File
Blob: integrations/shared_config_test.go
| 1 | package integrations |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/tls" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "os" |
| 14 | "os/exec" |
| 15 | "path/filepath" |
| 16 | "slices" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "go.miragespace.co/specter/acme" |
| 21 | dnscmd "go.miragespace.co/specter/cmd/dns" |
| 22 | servercmd "go.miragespace.co/specter/cmd/server" |
| 23 | "go.miragespace.co/specter/config" |
| 24 | |
| 25 | "github.com/miekg/dns" |
| 26 | "github.com/stretchr/testify/require" |
| 27 | "github.com/urfave/cli/v3" |
| 28 | "go.uber.org/zap" |
| 29 | ) |
| 30 | |
| 31 | // A child process lets the fixture crash a physical server and restart it |
| 32 | // without depending on graceful Chord departure. |
| 33 | func TestIntegrationSharedConfigProcess(t *testing.T) { |
| 34 | if os.Getenv("SPECTER_SHARED_CONFIG_CHILD") != "1" { |
| 35 | t.Skip("subprocess helper") |
| 36 | } |
| 37 | separator := slices.Index(os.Args, "--") |
| 38 | require.GreaterOrEqual(t, separator, 0) |
| 39 | args := os.Args[separator+1:] |
| 40 | require.NotEmpty(t, args) |
| 41 | var command *cli.Command |
| 42 | switch args[0] { |
| 43 | case "server": |
| 44 | command = servercmd.Generate() |
| 45 | case "dns": |
| 46 | command = dnscmd.Generate() |
| 47 | default: |
| 48 | t.Fatalf("unknown integration command %q", args[0]) |
| 49 | } |
| 50 | config := zap.NewProductionConfig() |
| 51 | config.Level = zap.NewAtomicLevelAt(zap.DebugLevel) |
| 52 | config.DisableStacktrace = true |
| 53 | logger, err := config.Build() |
| 54 | require.NoError(t, err) |
| 55 | app, _ := compileApp(command) |
| 56 | app.Metadata["apexOverride"] = serverApex |
| 57 | app.Writer = io.Discard |
| 58 | app.Before = func(ctx context.Context, cmd *cli.Command) (context.Context, error) { |
| 59 | cmd.Root().Metadata["logger"] = logger |
| 60 | return ctx, nil |
| 61 | } |
| 62 | require.NoError(t, app.Run(t.Context(), append([]string{"specter"}, args...))) |
| 63 | } |
| 64 | |
| 65 | type sharedConfigProcess struct { |
| 66 | command *exec.Cmd |
| 67 | output bytes.Buffer |
| 68 | done chan struct{} |
| 69 | err error |
| 70 | } |
| 71 | |
| 72 | func startSharedConfigProcess(t *testing.T, args ...string) *sharedConfigProcess { |
| 73 | t.Helper() |
| 74 | p := &sharedConfigProcess{done: make(chan struct{})} |
| 75 | p.command = exec.Command(os.Args[0], append([]string{"-test.run=^TestIntegrationSharedConfigProcess$", "-test.timeout=150s", "--"}, args...)...) |
| 76 | p.command.Env = append(os.Environ(), "SPECTER_SHARED_CONFIG_CHILD=1", "DOH=false") |
| 77 | p.command.Stdout = &p.output |
| 78 | p.command.Stderr = &p.output |
| 79 | require.NoError(t, p.command.Start()) |
| 80 | go func() { |
| 81 | p.err = p.command.Wait() |
| 82 | close(p.done) |
| 83 | }() |
| 84 | t.Cleanup(func() { |
| 85 | p.stop(t) |
| 86 | if t.Failed() { |
| 87 | t.Logf("%s: %s", p.command.String(), p.output.String()) |
| 88 | } |
| 89 | }) |
| 90 | return p |
| 91 | } |
| 92 | |
| 93 | func (p *sharedConfigProcess) running(t *testing.T) { |
| 94 | t.Helper() |
| 95 | select { |
| 96 | case <-p.done: |
| 97 | t.Fatalf("integration process exited: %v\n%s", p.err, p.output.String()) |
| 98 | default: |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | func (p *sharedConfigProcess) stop(t *testing.T) { |
| 103 | t.Helper() |
| 104 | select { |
| 105 | case <-p.done: |
| 106 | return |
| 107 | default: |
| 108 | } |
| 109 | err := p.command.Process.Kill() |
| 110 | if !errors.Is(err, os.ErrProcessDone) { |
| 111 | require.NoError(t, err) |
| 112 | } |
| 113 | select { |
| 114 | case <-p.done: |
| 115 | case <-time.After(10 * time.Second): |
| 116 | t.Fatal("integration process did not stop") |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | func sharedConfigListenAddress(t *testing.T) string { |
| 121 | t.Helper() |
| 122 | tcp, err := net.Listen("tcp", "127.0.0.1:0") |
| 123 | require.NoError(t, err) |
| 124 | defer tcp.Close() |
| 125 | address := tcp.Addr().String() |
| 126 | udp, err := net.ListenPacket("udp", address) |
| 127 | require.NoError(t, err) |
| 128 | require.NoError(t, udp.Close()) |
| 129 | return address |
| 130 | } |
| 131 | |
| 132 | type sharedConfigNode struct { |
| 133 | dataDir string |
| 134 | address string |
| 135 | http string |
| 136 | rpc string |
| 137 | process *sharedConfigProcess |
| 138 | client *http.Client |
| 139 | } |
| 140 | |
| 141 | func newSharedConfigNode(t *testing.T) *sharedConfigNode { |
| 142 | t.Helper() |
| 143 | transport := &http.Transport{TLSClientConfig: &tls.Config{ServerName: serverApex, InsecureSkipVerify: true}} |
| 144 | n := &sharedConfigNode{ |
| 145 | dataDir: t.TempDir(), |
| 146 | address: sharedConfigListenAddress(t), |
| 147 | http: sharedConfigListenAddress(t), |
| 148 | rpc: sharedConfigListenAddress(t), |
| 149 | client: &http.Client{Transport: transport, Timeout: 2 * time.Second}, |
| 150 | } |
| 151 | t.Cleanup(transport.CloseIdleConnections) |
| 152 | return n |
| 153 | } |
| 154 | |
| 155 | func (n *sharedConfigNode) start(t *testing.T, join string) { |
| 156 | t.Helper() |
| 157 | _, httpPort, err := net.SplitHostPort(n.http) |
| 158 | require.NoError(t, err) |
| 159 | args := []string{"server", "--cert-dir", "../certs", "--data-dir", n.dataDir, |
| 160 | "--listen", n.address, "--advertise", n.address, "--listen-http", httpPort, |
| 161 | "--listen-rpc", "tcp://" + n.rpc, "--apex", serverApex, "--virtual", "2", |
| 162 | "--kv-provider", "memory", |
| 163 | "--auth_user", "shared-config", "--auth_pass", "shared-config"} |
| 164 | if join != "" { |
| 165 | args = append(args, "--join", join) |
| 166 | } |
| 167 | n.process = startSharedConfigProcess(t, args...) |
| 168 | } |
| 169 | |
| 170 | func (n *sharedConfigNode) restart(t *testing.T, join string) { |
| 171 | t.Helper() |
| 172 | n.start(t, join) |
| 173 | // Match service-manager recovery: a peer may retain the crashed server's |
| 174 | // QUIC connection until its idle timeout, causing an early join to fail. |
| 175 | // Retry exited startups, then check configuration catch-up separately. |
| 176 | require.Eventually(t, func() bool { |
| 177 | select { |
| 178 | case <-n.process.done: |
| 179 | n.start(t, join) |
| 180 | return false |
| 181 | default: |
| 182 | } |
| 183 | _, status, err := n.request(t.Context(), http.MethodGet, nil) |
| 184 | return err == nil && status == http.StatusOK |
| 185 | }, 45*time.Second, time.Second, "server %s did not restart", n.address) |
| 186 | } |
| 187 | |
| 188 | type sharedDNSResponse struct { |
| 189 | Version string `json:"version"` |
| 190 | Config acme.DNSConfig `json:"config"` |
| 191 | Server struct { |
| 192 | ID string `json:"id"` |
| 193 | Address string `json:"address"` |
| 194 | } `json:"server"` |
| 195 | } |
| 196 | |
| 197 | func (n *sharedConfigNode) request(ctx context.Context, method string, body []byte) (sharedDNSResponse, int, error) { |
| 198 | var result sharedDNSResponse |
| 199 | request, err := http.NewRequestWithContext(ctx, method, "https://"+n.address+"/_internal/api/config/dns", bytes.NewReader(body)) |
| 200 | if err != nil { |
| 201 | return result, 0, err |
| 202 | } |
| 203 | request.Host = serverApex |
| 204 | request.SetBasicAuth("shared-config", "shared-config") |
| 205 | request.Header.Set("Content-Type", "application/json") |
| 206 | response, err := n.client.Do(request) |
| 207 | if err != nil { |
| 208 | return result, 0, err |
| 209 | } |
| 210 | defer response.Body.Close() |
| 211 | err = json.NewDecoder(response.Body).Decode(&result) |
| 212 | return result, response.StatusCode, err |
| 213 | } |
| 214 | |
| 215 | func (n *sharedConfigNode) waitVersion(t *testing.T, record config.Record) { |
| 216 | t.Helper() |
| 217 | var lastErr error |
| 218 | var status int |
| 219 | var result sharedDNSResponse |
| 220 | require.Eventually(t, func() bool { |
| 221 | n.process.running(t) |
| 222 | result, status, lastErr = n.request(t.Context(), http.MethodGet, nil) |
| 223 | return lastErr == nil && status == http.StatusOK && result.Version == record.Token() |
| 224 | }, 30*time.Second, 100*time.Millisecond, "server %s did not reach %s", n.address, record.Token()) |
| 225 | dnsConfig, err := acme.DecodeDNSConfig(record, "") |
| 226 | require.NoError(t, err) |
| 227 | require.Equal(t, dnsConfig, result.Config) |
| 228 | require.Equal(t, n.address, result.Server.Address) |
| 229 | require.NotEmpty(t, result.Server.ID) |
| 230 | } |
| 231 | |
| 232 | func (n *sharedConfigNode) put(t *testing.T, expected config.Record, dnsConfig acme.DNSConfig) config.Record { |
| 233 | t.Helper() |
| 234 | body, err := json.Marshal(struct { |
| 235 | ExpectedVersion string `json:"expected_version"` |
| 236 | Config acme.DNSConfig `json:"config"` |
| 237 | }{expected.Token(), dnsConfig}) |
| 238 | require.NoError(t, err) |
| 239 | result, status, err := n.request(t.Context(), http.MethodPut, body) |
| 240 | require.NoError(t, err) |
| 241 | require.Equal(t, http.StatusOK, status) |
| 242 | record, err := config.NewClient("http://"+n.rpc, n.client).Get(t.Context(), acme.DNSConfigName) |
| 243 | require.NoError(t, err) |
| 244 | require.Equal(t, expected.Version.Revision+1, record.Version.Revision) |
| 245 | require.Equal(t, record.Token(), result.Version) |
| 246 | require.Equal(t, dnsConfig, result.Config) |
| 247 | return record |
| 248 | } |
| 249 | |
| 250 | func waitSharedDNS(t *testing.T, process *sharedConfigProcess, address, network string, config acme.DNSConfig, revision uint64) { |
| 251 | t.Helper() |
| 252 | client := &dns.Client{Net: network, Timeout: time.Second} |
| 253 | require.Eventually(t, func() bool { |
| 254 | process.running(t) |
| 255 | for _, kind := range []uint16{dns.TypeSOA, dns.TypeA} { |
| 256 | name := config.Zone |
| 257 | if kind == dns.TypeA { |
| 258 | name = config.Nameservers[0].Host |
| 259 | } |
| 260 | message := new(dns.Msg) |
| 261 | message.SetQuestion(name, kind) |
| 262 | response, _, err := client.ExchangeContext(t.Context(), message, address) |
| 263 | if err != nil || response.Rcode != dns.RcodeSuccess || !response.Authoritative || len(response.Answer) != 1 { |
| 264 | return false |
| 265 | } |
| 266 | switch answer := response.Answer[0].(type) { |
| 267 | case *dns.SOA: |
| 268 | if answer.Serial != uint32(revision) || answer.Ns != config.Nameservers[0].Host { |
| 269 | return false |
| 270 | } |
| 271 | case *dns.A: |
| 272 | if !slices.Contains(config.Nameservers[0].Addresses, answer.A.String()) { |
| 273 | return false |
| 274 | } |
| 275 | default: |
| 276 | return false |
| 277 | } |
| 278 | } |
| 279 | return true |
| 280 | }, 15*time.Second, 100*time.Millisecond, "%s DNS did not activate revision %d", network, revision) |
| 281 | } |
| 282 | |
| 283 | func TestIntegrationSharedConfig(t *testing.T) { |
| 284 | if os.Getenv("GO_INTEGRATION_TUNNEL") == "" { |
| 285 | t.Skip("set GO_INTEGRATION_TUNNEL=1") |
| 286 | } |
| 287 | nodes := []*sharedConfigNode{newSharedConfigNode(t), newSharedConfigNode(t), newSharedConfigNode(t)} |
| 288 | initial := acme.DNSConfig{ |
| 289 | Zone: "shared.test.", |
| 290 | Nameservers: []acme.DNSNameserver{{Host: "ns.shared.test.", Addresses: []string{"192.0.2.1", "2001:db8::1"}}}, |
| 291 | } |
| 292 | value, err := json.Marshal(initial) |
| 293 | require.NoError(t, err) |
| 294 | record, err := config.NewRecord(acme.DNSConfigName, acme.DNSConfigSchema, 1, value) |
| 295 | require.NoError(t, err) |
| 296 | // A future consumer's binary payload must survive without any DNS decoding. |
| 297 | opaque, err := config.NewRecord("future.example/opaque", 37, 1, []byte{0, 255, 128, 10, 42}) |
| 298 | require.NoError(t, err) |
| 299 | // Start empty replicas before initialization, as during a first rollout. |
| 300 | for i, node := range nodes { |
| 301 | join := "" |
| 302 | if i > 0 { |
| 303 | join = nodes[0].address |
| 304 | _, err := os.Stat(filepath.Join(node.dataDir, "config", config.FileName)) |
| 305 | require.ErrorIs(t, err, os.ErrNotExist, "only the first physical server is initialized") |
| 306 | } |
| 307 | node.start(t, join) |
| 308 | require.Eventually(t, func() bool { |
| 309 | node.process.running(t) |
| 310 | response, status, err := node.request(t.Context(), http.MethodGet, nil) |
| 311 | return err == nil && status == http.StatusOK && response.Version == "" |
| 312 | }, 10*time.Second, 100*time.Millisecond, "server %s did not start with an empty replica", node.address) |
| 313 | } |
| 314 | // A separate process can populate the first database while its server runs. |
| 315 | require.NoError(t, config.Init(filepath.Join(nodes[0].dataDir, "config"), []config.Record{record, opaque})) |
| 316 | for _, node := range nodes { |
| 317 | node.waitVersion(t, record) |
| 318 | } |
| 319 | |
| 320 | dnsAddress := sharedConfigListenAddress(t) |
| 321 | // Existing launcher flags must not override the shared DNS document. |
| 322 | dnsProcess := startSharedConfigProcess(t, "dns", "--listen", dnsAddress, "--rpc", "tcp://"+nodes[2].rpc, |
| 323 | "--acme", "acme://admin@example.com@shared.test", "--acme-ns", "old.shared.test/192.0.2.99") |
| 324 | for _, network := range []string{"udp", "tcp"} { |
| 325 | waitSharedDNS(t, dnsProcess, dnsAddress, network, initial, record.Version.Revision) |
| 326 | } |
| 327 | |
| 328 | edited := acme.DNSConfig{ |
| 329 | Zone: initial.Zone, |
| 330 | Nameservers: []acme.DNSNameserver{{Host: "updated.shared.test.", Addresses: []string{"192.0.2.2", "2001:db8::2"}}}, |
| 331 | } |
| 332 | record = nodes[1].put(t, record, edited) |
| 333 | for _, node := range nodes { |
| 334 | node.waitVersion(t, record) |
| 335 | } |
| 336 | waitSharedDNS(t, dnsProcess, dnsAddress, "udp", edited, record.Version.Revision) |
| 337 | |
| 338 | // Stop the original source abruptly, and inspect its durable full replica. |
| 339 | nodes[0].process.stop(t) |
| 340 | store, err := config.Open(filepath.Join(nodes[0].dataDir, "config")) |
| 341 | require.NoError(t, err) |
| 342 | persisted, found, err := store.Get(acme.DNSConfigName) |
| 343 | require.NoError(t, err) |
| 344 | require.True(t, found) |
| 345 | require.Equal(t, record, persisted) |
| 346 | require.NoError(t, store.Close()) |
| 347 | |
| 348 | edited.Nameservers[0].Addresses = []string{"192.0.2.3", "2001:db8::3"} |
| 349 | record = nodes[1].put(t, record, edited) |
| 350 | nodes[2].waitVersion(t, record) |
| 351 | waitSharedDNS(t, dnsProcess, dnsAddress, "udp", edited, record.Version.Revision) |
| 352 | |
| 353 | // A restarted server retains its old copy and repairs it from a live peer. |
| 354 | nodes[0].restart(t, nodes[1].address) |
| 355 | nodes[0].waitVersion(t, record) |
| 356 | for _, node := range nodes { |
| 357 | node.process.stop(t) |
| 358 | store, err := config.Open(filepath.Join(node.dataDir, "config")) |
| 359 | require.NoError(t, err) |
| 360 | records, err := store.Snapshot() |
| 361 | require.NoError(t, err) |
| 362 | require.ElementsMatch(t, []config.Record{record, opaque}, records, "every physical node owns a complete durable copy") |
| 363 | require.NoError(t, store.Close()) |
| 364 | for vnode := range 2 { |
| 365 | _, err := os.Stat(filepath.Join(node.dataDir, fmt.Sprint(vnode), "config")) |
| 366 | require.ErrorIs(t, err, os.ErrNotExist, "virtual nodes must not own shared configuration replicas") |
| 367 | } |
| 368 | } |
| 369 | } |