| new file mode 100644 |
| index 000000000..822b867e8 |
| --- /dev/null |
| +++ b/internal/console/restore_door_test.go |
| @@ -0,0 +1,789 @@ |
| +package console |
| + |
| +// The restore door (instance restore #658, plan Task 6; spec §3). Driven |
| +// through the real create and delete doors of a claims-off console with |
| +// lifetimes on and the history active (newProofFx: one.shop.example.com |
| +// created with its origin, then deleted), over the ltStore bucket and the |
| +// stagingStore data bucket, with the leftover rail reading real litestream |
| +// replicas on disk. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// doorFx is a proofFx whose leftover rail reads replicas under root. |
| +type doorFx struct { |
| + *proofFx |
| + root string |
| +} |
| + |
| +// doorOver gives p's console a replica root for the leftover rail and the |
| +// instances prefix, as a deployment with a data bucket has. |
| +func doorOver(t *testing.T, p *proofFx) *doorFx { |
| + t.Helper() |
| + root := t.TempDir() |
| + srv := p.fx.srv |
| + srv.cfg.HibernatePrefix = "instances" |
| + srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) { |
| + return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil |
| + } |
| + return &doorFx{proofFx: p, root: root} |
| +} |
| + |
| +// newDoorFx is the eligible state: ltOne created and deleted through the |
| +// doors. |
| +func newDoorFx(t *testing.T) *doorFx { |
| + t.Helper() |
| + return doorOver(t, newProofFx(t)) |
| +} |
| + |
| +func restoreBody(extra string) string { |
| + return `{"host":"` + ltOne + `","restore":true` + extra + `}` |
| +} |
| + |
| +func ordinaryBody(extra string) string { |
| + return `{"host":"` + ltOne + `"` + extra + `}` |
| +} |
| + |
| +// post sends body to the owner's instance door. |
| +func (d *doorFx) post(t *testing.T, body string) (int, string) { |
| + t.Helper() |
| + code, _, out := rawReq(t, http.MethodPost, instancesURL(d.fx, "bab", ltApp), d.member, body) |
| + return code, out |
| +} |
| + |
| +func (d *doorFx) restore(t *testing.T, extra string) (int, string) { |
| + t.Helper() |
| + return d.post(t, restoreBody(extra)) |
| +} |
| + |
| +// async sends body to url without blocking; the answer arrives on the channel. |
| +func (d *doorFx) async(url, body string) <-chan rdAnswer { |
| + done := make(chan rdAnswer, 1) |
| + go func() { done <- rdDo(http.MethodPost, url, d.member, body) }() |
| + return done |
| +} |
| + |
| +func (d *doorFx) url() string { return instancesURL(d.fx, "bab", ltApp) } |
| + |
| +// leaveReplica writes a real litestream replica where the deleted record's |
| +// activator left it: instances/<host>. |
| +func (d *doorFx) leaveReplica(t *testing.T) { |
| + t.Helper() |
| + dbdoortest.Replicate(t, filepath.Join(d.root, activator.HibernatePrefix("instances", ltOne)), 1) |
| +} |
| + |
| +// requireAnswer fails unless the door answered status with msg as its error. |
| +func requireAnswer(t *testing.T, code int, out string, status int, msg, what string) { |
| + t.Helper() |
| + if code != status || ltErr(out) != msg { |
| + t.Fatalf("%s = %d %s, want %d %q", what, code, out, status, msg) |
| + } |
| +} |
| + |
| +// requireNoRestoreWrite: the only allocation of ltOne is the origin, and no |
| +// record stands under the key. |
| +func (d *doorFx) requireNoRestoreWrite(t *testing.T, allocs int) { |
| + t.Helper() |
| + if rows := allocRows(t, d.fx.st, ltOne); len(rows) != allocs { |
| + t.Fatalf("allocations of %s = %+v, want %d", ltOne, rows, allocs) |
| + } |
| +} |
| + |
| +func (d *doorFx) requireNoRecord(t *testing.T) { |
| + t.Helper() |
| + if raw, _ := rawOf(t, d.fx.rel, ltApp, ltOne); raw != nil { |
| + t.Fatalf("a record stands under %s: %s", ltOne, raw) |
| + } |
| +} |
| + |
| +// requireRestored: the door answered 201 with "restore": true; the record |
| +// under the key is the deleted one's host and region at incarnation n; and |
| +// the newest allocation carries restore_of naming the newest retirement, |
| +// and no origin. |
| +func (d *doorFx) requireRestored(t *testing.T, code int, out string, n uint64) provision.Record { |
| + t.Helper() |
| + if code != http.StatusCreated { |
| + t.Fatalf("restore = %d %s, want 201", code, out) |
| + } |
| + var reply map[string]any |
| + if err := json.Unmarshal([]byte(out), &reply); err != nil { |
| + t.Fatalf("restore answer %s: %v", out, err) |
| + } |
| + if reply["restore"] != true { |
| + t.Fatalf("restore answer %s, want \"restore\": true", out) |
| + } |
| + raw, _ := rawOf(t, d.fx.rel, ltApp, ltOne) |
| + if raw == nil { |
| + t.Fatal("no record after a 201 restore") |
| + } |
| + rec := decodeRec(t, raw) |
| + deleted := d.deleted(t) |
| + if rec.Host != deleted.Host || rec.Region != deleted.Region || rec.Incarnation != n || rec.Retired { |
| + t.Fatalf("restored record = host %q region %q incarnation %d retired %v, want %q %q %d live", |
| + rec.Host, rec.Region, rec.Incarnation, rec.Retired, deleted.Host, deleted.Region, n) |
| + } |
| + if reply["host"] != rec.Host { |
| + t.Fatalf("restore answer names %v, want %s", reply["host"], rec.Host) |
| + } |
| + rows := lineage(t, d.fx.st, ltOne) |
| + last := rows[len(rows)-1] |
| + e := evidenceOf(t, d.fx.st, ltOne) |
| + if last.Incarnation != n || last.RestoreOf != e.OpID || last.RestoreOrigin || last.State != lifetimeCommitted { |
| + t.Fatalf("the restore's allocation = %+v, want committed at %d, restore_of %s, no origin", last, n, e.OpID) |
| + } |
| + return rec |
| +} |
| + |
| +// parkFirst holds the first create of ltOne that reaches stage until the |
| +// gate opens; every later one passes. |
| +func parkFirst(t *testing.T, stage string) *pauseGate { |
| + t.Helper() |
| + g := newPauseGate() |
| + var first atomic.Bool |
| + h := func(s, host string) { |
| + if s != stage || host != ltOne || !first.CompareAndSwap(false, true) { |
| + return |
| + } |
| + close(g.entered) |
| + select { |
| + case <-g.release: |
| + case <-time.After(10 * time.Second): |
| + t.Errorf("timed out releasing the create parked at %s", stage) |
| + } |
| + } |
| + instanceCreateHook.Store(&h) |
| + t.Cleanup(func() { |
| + g.open() |
| + instanceCreateHook.Store(nil) |
| + }) |
| + return g |
| +} |
| + |
| +func awaitAnswer(t *testing.T, ch <-chan rdAnswer, what string) rdAnswer { |
| + t.Helper() |
| + a := await(t, ch, what) |
| + if a.err != nil { |
| + t.Fatalf("%s: %v", what, a.err) |
| + } |
| + return a |
| +} |
| + |
| +func TestRestoreRoundTrip(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.leaveReplica(t) // the deleted instance's replica rows, keyed by host alone |
| + code, out := d.restore(t, "") |
| + d.requireRestored(t, code, out, 2) |
| + if rows := lineage(t, d.fx.st, ltOne); len(rows) != 2 || !rows[0].RestoreOrigin { |
| + t.Fatalf("lineage = %+v, want the origin then the restore", rows) |
| + } |
| + slot, _ := slotOf(t, d.fx.rel, ltOne) |
| + if slot == nil || slot.Incarnation != 2 || slot.State != provision.SlotLive || slot.Account != "bab" || slot.App != ltApp { |
| + t.Fatalf("slot = %+v, want live at 2 for bab/%s", slot, ltApp) |
| + } |
| +} |
| + |
| +// TestRestoreTwice (Review Focus 4): delete, restore, delete, restore. |
| +func TestRestoreTwice(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, out := d.restore(t, "") |
| + d.requireRestored(t, code, out, 2) |
| + if code, body := d.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent { |
| + t.Fatalf("second delete = %d %s", code, body) |
| + } |
| + requireRetired(t, d.fx.rel, ltApp, ltOne, 2) |
| + code, out = d.restore(t, "") |
| + d.requireRestored(t, code, out, 3) |
| + if rows := lineage(t, d.fx.st, ltOne); len(rows) != 3 { |
| + t.Fatalf("lineage = %+v, want the origin and two restores", rows) |
| + } |
| +} |
| + |
| +// TestRestoreRetriedAfterSuccess (Review Focus 2): the retry of a restore |
| +// that succeeded gets the create's duplicate answer, not R8. |
| +func TestRestoreRetriedAfterSuccess(t *testing.T) { |
| + d := newDoorFx(t) |
| + _, _ = d.restore(t, "") // the response is lost |
| + code, out := d.restore(t, "") |
| + requireAnswer(t, code, out, http.StatusConflict, msgInstanceExists(ltOne), "the retried restore") |
| + d.requireNoRestoreWrite(t, 2) |
| + if rec := decodeRec(t, mustRaw(t, d)); rec.Incarnation != 2 { |
| + t.Fatalf("record at %d, want the first restore's 2", rec.Incarnation) |
| + } |
| +} |
| + |
| +func mustRaw(t *testing.T, d *doorFx) []byte { |
| + t.Helper() |
| + raw, _ := rawOf(t, d.fx.rel, ltApp, ltOne) |
| + if raw == nil { |
| + t.Fatal("no record") |
| + } |
| + return raw |
| +} |
| + |
| +// TestRestoreRecordAppearsBetweenEvaluations: a record lands after the |
| +// early proof; the deciding one, under the locks, answers the duplicate. |
| +func TestRestoreRecordAppearsBetweenEvaluations(t *testing.T) { |
| + d := newDoorFx(t) |
| + g := parkFirst(t, instanceCreateAfterRestoreProof) |
| + ch := d.async(d.url(), restoreBody("")) |
| + await(t, g.entered, "the restore past its early proof") |
| + d.reviveRecord(t) |
| + g.open() |
| + a := awaitAnswer(t, ch, "the restore") |
| + requireAnswer(t, a.code, a.out, http.StatusConflict, msgInstanceExists(ltOne), "the restore") |
| + d.requireNoRestoreWrite(t, 1) |
| + if raw := mustRaw(t, d); string(raw) != string(d.recBefore) { |
| + t.Fatalf("the record that landed was changed: %s", raw) |
| + } |
| +} |
| + |
| +// TestRestorePendingAppearsBetweenEvaluations: something for the host goes |
| +// pending after the early proof; the deciding one answers R1 and writes no |
| +// allocation. |
| +func TestRestorePendingAppearsBetweenEvaluations(t *testing.T) { |
| + t.Run("another restore's allocation, pending with no record", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + g := parkFirst(t, instanceCreateAfterRestoreProof) |
| + ch := d.async(d.url(), restoreBody("")) |
| + await(t, g.entered, "the first restore past its early proof") |
| + d.bucket.setHook(failNth("put", provision.HostIncarnationKey(ltOne), 1, false)) |
| + code, out := d.restore(t, "") |
| + d.bucket.setHook(nil) |
| + requireAnswer(t, code, out, http.StatusBadGateway, msgLifetimeCreatePending, "the second restore") |
| + d.requireNoRecord(t) |
| + rows := allocRows(t, d.fx.st, ltOne) |
| + if len(rows) != 2 || rows[1].State != lifetimePending { |
| + t.Fatalf("allocations = %+v, want the origin and one pending", rows) |
| + } |
| + g.open() |
| + a := awaitAnswer(t, ch, "the first restore") |
| + requireAnswer(t, a.code, a.out, http.StatusServiceUnavailable, msgRestoreUnchecked(ltOne), "the first restore") |
| + d.requireNoRestoreWrite(t, 2) |
| + d.requireNoRecord(t) |
| + }) |
| + t.Run("a completed restore whose delete is pending before N1", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + g := parkFirst(t, instanceCreateAfterRestoreProof) |
| + ch := d.async(d.url(), restoreBody("")) |
| + await(t, g.entered, "the first restore past its early proof") |
| + code, out := d.restore(t, "") |
| + d.requireRestored(t, code, out, 2) |
| + d.pendingRetire(t, "begin") |
| + raw := mustRaw(t, d) |
| + g.open() |
| + a := awaitAnswer(t, ch, "the first restore") |
| + requireAnswer(t, a.code, a.out, http.StatusServiceUnavailable, msgRestoreUnchecked(ltOne), "the first restore") |
| + d.requireNoRestoreWrite(t, 2) |
| + if now := mustRaw(t, d); string(now) != string(raw) { |
| + t.Fatalf("the record changed under a pending delete: %s", now) |
| + } |
| + }) |
| +} |
| + |
| +// newUKDoorFx is newDoorFx on a console in uk whose home is ie: ltOne |
| +// created in uk through the door, then deleted. |
| +func newUKDoorFx(t *testing.T) *doorFx { |
| + t.Helper() |
| + l := newLtOn(t) |
| + srv := l.fx.srv |
| + srv.cfg.Region, srv.cfg.HomeRegion = "uk", "ie" |
| + forceHostsState(t, srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"region:uk"}}) |
| + if code, _, out := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, ordinaryBody(`,"region":"uk"`)); code != http.StatusCreated { |
| + t.Fatalf("create in uk = %d %s", code, out) |
| + } |
| + recBefore, _ := rawOf(t, l.fx.rel, ltApp, ltOne) |
| + if code, body := l.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent { |
| + t.Fatalf("delete = %d %s", code, body) |
| + } |
| + data := &stagingStore{DirStore: release.NewDirStore(t.TempDir())} |
| + srv.cfg.SeedData, srv.cfg.HibernateBucket = data, "data-test" |
| + acct := l.acct(t) |
| + life, err := l.fx.st.AppLife(acct.ID, ltApp) |
| + if err != nil || life == nil { |
| + t.Fatalf("apps row: %+v %v", life, err) |
| + } |
| + return doorOver(t, &proofFx{ltOn: l, data: data, recBefore: recBefore, |
| + ask: restoreAsk{Account: acct.Sqid, AccountID: acct.ID, App: ltApp, Lifetime: life.Lifetime, Host: ltOne}}) |
| +} |
| + |
| +// TestRestoreRegion (Review Focus 5). |
| +func TestRestoreRegion(t *testing.T) { |
| + for _, c := range []struct{ name, extra string }{ |
| + {"no region", ""}, |
| + {"the home region named", `,"region":"ie"`}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, out := d.restore(t, c.extra) |
| + d.requireRestored(t, code, out, 2) |
| + }) |
| + } |
| + // A console outside the home restores what it holds, and only that. |
| + for _, c := range []struct{ name, extra string }{ |
| + {"a uk console, no region", ""}, |
| + {"a uk console, its own region named", `,"region":"uk"`}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + d := newUKDoorFx(t) |
| + code, out := d.restore(t, c.extra) |
| + if rec := d.requireRestored(t, code, out, 2); rec.Region != "uk" { |
| + t.Fatalf("restored into %q, want uk", rec.Region) |
| + } |
| + }) |
| + } |
| + t.Run("a uk console, the home region named", func(t *testing.T) { |
| + d := newUKDoorFx(t) |
| + code, out := d.restore(t, `,"region":"ie"`) |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreRegion(ltOne, "uk"), "a restore naming ie on uk") |
| + d.requireNoRecord(t) |
| + }) |
| + t.Run("another region", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, out := d.restore(t, `,"region":"uk"`) |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreRegion(ltOne, "ie"), "a restore naming uk") |
| + d.requireNoRestoreWrite(t, 1) |
| + d.requireNoRecord(t) |
| + }) |
| + t.Run("the app's default region elsewhere", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.fx.srv.appRegionOf = func(int64, string) (string, string, error) { return "uk", "", nil } |
| + code, out := d.restore(t, "") |
| + if rec := d.requireRestored(t, code, out, 2); rec.Region != "" { |
| + t.Fatalf("restored into %q, want the stored body's home region", rec.Region) |
| + } |
| + }) |
| +} |
| + |
| +// TestRestoreRefusesPlacedApp: a fleet placement or a manifest pool, gained |
| +// after the delete, is R7. |
| +func TestRestoreRefusesPlacedApp(t *testing.T) { |
| + t.Run("fleet placement", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + // Written directly: the placement door refuses a change while the |
| + // history is active (fleets.go). |
| + if err := d.fx.st.SetAppPlacement(d.ask.AccountID, ltApp, "fleet/acme"); err != nil { |
| + t.Fatal(err) |
| + } |
| + code, out := d.restore(t, "") |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "a restore on a placed app") |
| + d.requireNoRecord(t) |
| + }) |
| + t.Run("manifest pool", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + enableInstances(t, d.fx, ltApp, provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable", Pool: "p1"}) |
| + code, out := d.restore(t, "") |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "a restore on a pooled app") |
| + d.requireNoRecord(t) |
| + }) |
| +} |
| + |
| +// TestRestoreKeepsRegionPolicy: the manifest's allow-list still applies, |
| +// with the ordinary create's own refusal. |
| +func TestRestoreKeepsRegionPolicy(t *testing.T) { |
| + d := newDoorFx(t) |
| + enableInstances(t, d.fx, ltApp, provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable", Regions: []string{"uk"}}) |
| + code, out := d.restore(t, "") |
| + ordCode, _, ordOut := rawReq(t, http.MethodPost, d.url(), d.member, `{"host":"`+ltFresh+`"}`) |
| + if ordCode != http.StatusBadRequest || !strings.Contains(ordOut, "not one this app runs in") { |
| + t.Fatalf("fixture: an ordinary create = %d %s, want the region refusal", ordCode, ordOut) |
| + } |
| + if code != ordCode || out != ordOut { |
| + t.Fatalf("restore = %d %s, want the ordinary create's %d %s", code, out, ordCode, ordOut) |
| + } |
| + d.requireNoRecord(t) |
| +} |
| + |
| +// TestRestoreStaticKindRefused: a static or service restore is R7 at the |
| +// door, and the core's deciding call cannot be skipped by a record that is |
| +// not a data kind. |
| +func TestRestoreStaticKindRefused(t *testing.T) { |
| + for _, extra := range []string{`,"kind":"static"`, `,"kind":"service","addrs":["127.0.0.1:9000"]`} { |
| + t.Run(extra, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, out := d.restore(t, extra) |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "the restore") |
| + d.requireNoRecord(t) |
| + d.requireNoRestoreWrite(t, 1) |
| + }) |
| + } |
| + t.Run("the core, a static record", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + rec := d.deleted(t) |
| + rec.Kind = "static" |
| + ctx := withRestore(onCtx(t, d.fx.srv), d.ask) |
| + _, err := d.fx.srv.createRecordWithLifetime(ctx, rec, d.ask.Lifetime) |
| + var used *hostsUsedError |
| + if !errors.As(err, &used) || used.ref.Status != http.StatusConflict || used.ref.Msg != msgRestoreNotPlain(ltOne) { |
| + t.Fatalf("the core's static restore = %v, want R7", err) |
| + } |
| + d.requireNoRecord(t) |
| + d.requireNoRestoreWrite(t, 1) |
| + }) |
| +} |
| + |
| +// TestRestoreStagingRefused: any object under moves/<host>/ is R6, a |
| +// listing error R1, and staging that appears after the early proof is R6 |
| +// from the deciding one. |
| +func TestRestoreStagingRefused(t *testing.T) { |
| + for _, key := range []string{"moves/" + ltOne + "/build-state.json", "moves/" + ltOne + "/0000/0000000000000001-0000000000000001.ltx"} { |
| + t.Run(key, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.stage(t, key) |
| + code, out := d.restore(t, "") |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreStaging(ltOne), "the restore") |
| + d.requireNoRecord(t) |
| + }) |
| + } |
| + t.Run("a listing error", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.data.fail = errBucketDown |
| + code, out := d.restore(t, "") |
| + requireAnswer(t, code, out, http.StatusServiceUnavailable, msgRestoreUnchecked(ltOne), "the restore") |
| + d.requireNoRecord(t) |
| + }) |
| + t.Run("staging between the evaluations", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + g := parkFirst(t, instanceCreateAfterRestoreProof) |
| + ch := d.async(d.url(), restoreBody("")) |
| + await(t, g.entered, "the restore past its early proof") |
| + d.stage(t, "moves/"+ltOne+"/build-state.json") |
| + g.open() |
| + a := awaitAnswer(t, ch, "the restore") |
| + requireAnswer(t, a.code, a.out, http.StatusConflict, msgRestoreStaging(ltOne), "the restore") |
| + d.requireNoRecord(t) |
| + d.requireNoRestoreWrite(t, 1) |
| + }) |
| +} |
| + |
| +// TestRestoreSkipsLeftoverRailOnlyForOwnReplica: the rail does not refuse |
| +// a restore over the host's own replica; an ordinary create over the same |
| +// leftovers is refused by it as before. |
| +func TestRestoreSkipsLeftoverRailOnlyForOwnReplica(t *testing.T) { |
| + t.Run("restore", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.leaveReplica(t) |
| + code, out := d.restore(t, "") |
| + d.requireRestored(t, code, out, 2) |
| + }) |
| + t.Run("ordinary create", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.leaveReplica(t) |
| + code, out := d.post(t, ordinaryBody("")) |
| + requireAnswer(t, code, out, http.StatusConflict, |
| + ltOne+" still holds data from a deleted instance. Choose another address, or ask an operator to purge it.", "the ordinary create") |
| + d.requireNoRecord(t) |
| + }) |
| +} |
| + |
| +// stranger is someone else asking for ltOne: another account, or another |
| +// app of this one, each with its own app named on shop.example.com. |
| +type stranger struct { |
| + name string |
| + url func(t *testing.T, d *doorFx) string |
| +} |
| + |
| +var strangers = []stranger{ |
| + {"another account", func(t *testing.T, d *doorFx) string { |
| + t.Helper() |
| + id := testAccountID() |
| + sqid := accountSqid(id) |
| + now := time.Now() |
| + if err := d.fx.st.CreateAccount(id, sqid, "other", "sam@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := d.fx.st.AddMember(id, "alice@keymail.dev", RoleMember, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.fx.st.CreateAppIn(id, ltApp, "sam@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(context.Background(), d.fx.rel, sqid, ltApp, |
| + provision.Manifest{Schema: 1, App: ltApp, Domain: "shop.example.com", Channel: "stable"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return instancesURL(d.fx, sqid, ltApp) |
| + }}, |
| + {"another app", func(t *testing.T, d *doorFx) string { |
| + t.Helper() |
| + if _, err := d.fx.st.CreateAppIn(OpsAccountID, "blog", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + enableInstances(t, d.fx, "blog", provision.Manifest{Schema: 1, App: "blog", Domain: "shop.example.com", Channel: "stable"}) |
| + return instancesURL(d.fx, "bab", "blog") |
| + }}, |
| +} |
| + |
| +// eligibilitySetups are four states that refuse the owner's restore: a |
| +// region named elsewhere, a move's staging, a retirement with no body, and |
| +// a lineage row of an older app lifetime. extra is the body's addition. |
| +var eligibilitySetups = []struct { |
| + name, extra, class string |
| + apply func(t *testing.T, d *doorFx) |
| +}{ |
| + {"a conflicting region", `,"region":"uk"`, "R5", func(*testing.T, *doorFx) {}}, |
| + {"staging", "", "R6", func(t *testing.T, d *doorFx) { d.stage(t, "moves/"+ltOne+"/build-state.json") }}, |
| + {"a missing body", "", "R8", func(t *testing.T, d *doorFx) { |
| + d.exec(t, `UPDATE record_retirements SET record_body = NULL WHERE host = ?`, ltOne) |
| + }}, |
| + {"an older app lifetime", "", "R4", func(t *testing.T, d *doorFx) { |
| + d.exec(t, `UPDATE host_allocations SET app_lifetime = 'feedfacefeedface' WHERE host = ?`, ltOne) |
| + }}, |
| +} |
| + |
| +// TestRestoreForeignOwnerSeesOnlyS1: another owner's restore answers the |
| +// exact bytes another owner's ordinary create gets (S1), whatever else is |
| +// wrong with it. |
| +func TestRestoreForeignOwnerSeesOnlyS1(t *testing.T) { |
| + for _, who := range strangers { |
| + for _, c := range eligibilitySetups { |
| + t.Run(who.name+", "+c.name, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + url := who.url(t, d) |
| + s1Code, _, s1 := rawReq(t, http.MethodPost, url, d.member, ordinaryBody("")) |
| + requireAnswer(t, s1Code, s1, http.StatusConflict, msgHostUsed(ltOne), "the stranger's ordinary create") |
| + c.apply(t, d) |
| + code, _, out := rawReq(t, http.MethodPost, url, d.member, restoreBody(c.extra)) |
| + if code != s1Code || out != s1 { |
| + t.Fatalf("the stranger's restore = %d %s, want S1's bytes %d %s", code, out, s1Code, s1) |
| + } |
| + d.requireNoRestoreWrite(t, 1) |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// TestRestoreOwnerSeesDetail: the rightful owner gets the detailed answer. |
| +func TestRestoreOwnerSeesDetail(t *testing.T) { |
| + msgs := map[string]string{ |
| + "R4": msgRestoreEarlierApp(ltOne, ltApp), |
| + "R5": msgRestoreRegion(ltOne, "ie"), |
| + "R6": msgRestoreStaging(ltOne), |
| + "R8": msgRestoreTooOld(ltOne), |
| + } |
| + for _, c := range eligibilitySetups { |
| + t.Run(c.name, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + c.apply(t, d) |
| + code, out := d.restore(t, c.extra) |
| + requireAnswer(t, code, out, http.StatusConflict, msgs[c.class], c.class) |
| + d.requireNoRestoreWrite(t, 1) |
| + }) |
| + } |
| + t.Run("R2", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + forceHostsState(t, d.fx.srv, provision.HostsState{Mode: provision.HostsModeIncomplete}) |
| + code, out := d.restore(t, "") |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreUnavailable(ltOne), "R2") |
| + d.requireNoRecord(t) |
| + }) |
| + t.Run("R7", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, out := d.restore(t, `,"kind":"static"`) |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreNotPlain(ltOne), "R7") |
| + d.requireNoRecord(t) |
| + }) |
| +} |
| + |
| +// TestOrdinaryCreateHintsRestore: C2 for the owner when a restore would |
| +// pass; S1 for anyone else, and for the owner when it would not. |
| +func TestOrdinaryCreateHintsRestore(t *testing.T) { |
| + t.Run("the owner", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, out := d.post(t, ordinaryBody("")) |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreHint(ltOne), "the owner's ordinary create") |
| + d.requireNoRestoreWrite(t, 1) |
| + d.requireNoRecord(t) |
| + }) |
| + for _, who := range strangers { |
| + t.Run(who.name, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, _, out := rawReq(t, http.MethodPost, who.url(t, d), d.member, ordinaryBody("")) |
| + requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the stranger's ordinary create") |
| + }) |
| + } |
| + t.Run("the owner, staging holding only build-state.json", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.stage(t, "moves/"+ltOne+"/build-state.json") |
| + code, out := d.post(t, ordinaryBody("")) |
| + requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the owner's ordinary create") |
| + }) |
| + t.Run("the owner, the staging list failing", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.data.fail = errBucketDown |
| + code, out := d.post(t, ordinaryBody("")) |
| + requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the owner's ordinary create") |
| + }) |
| +} |
| + |
| +// TestRestoreRacesOrdinaryCreate (Review Focus 1): one wins, the other |
| +// answers its normal refusal, and there is never a second record. |
| +func TestRestoreRacesOrdinaryCreate(t *testing.T) { |
| + requireOneRestore := func(t *testing.T, d *doorFx) { |
| + t.Helper() |
| + if rec := decodeRec(t, mustRaw(t, d)); rec.Incarnation != 2 { |
| + t.Fatalf("record at %d, want the restore's 2", rec.Incarnation) |
| + } |
| + d.requireNoRestoreWrite(t, 2) |
| + } |
| + t.Run("the ordinary create inside the restore's window", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + g := parkFirst(t, instanceCreateAfterRestoreProof) |
| + ch := d.async(d.url(), restoreBody("")) |
| + await(t, g.entered, "the restore past its early proof") |
| + code, out := d.post(t, ordinaryBody("")) |
| + requireAnswer(t, code, out, http.StatusConflict, msgRestoreHint(ltOne), "the ordinary create") |
| + g.open() |
| + a := awaitAnswer(t, ch, "the restore") |
| + d.requireRestored(t, a.code, a.out, 2) |
| + requireOneRestore(t, d) |
| + }) |
| + t.Run("the restore inside the ordinary create's window", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + g := parkFirst(t, instanceCreateAfterClaimCheck) |
| + ch := d.async(d.url(), ordinaryBody("")) |
| + await(t, g.entered, "the ordinary create past its claim check") |
| + code, out := d.restore(t, "") |
| + d.requireRestored(t, code, out, 2) |
| + g.open() |
| + a := awaitAnswer(t, ch, "the ordinary create") |
| + requireAnswer(t, a.code, a.out, http.StatusConflict, msgInstanceExists(ltOne), "the ordinary create") |
| + requireOneRestore(t, d) |
| + }) |
| + for i := 0; i < 3; i++ { |
| + t.Run("together", func(t *testing.T) { |
| + d := newDoorFx(t) |
| + restore := d.async(d.url(), restoreBody("")) |
| + ordinary := d.async(d.url(), ordinaryBody("")) |
| + r, o := awaitAnswer(t, restore, "the restore"), awaitAnswer(t, ordinary, "the ordinary create") |
| + d.requireRestored(t, r.code, r.out, 2) |
| + if msg := ltErr(o.out); o.code != http.StatusConflict || (msg != msgRestoreHint(ltOne) && msg != msgInstanceExists(ltOne)) { |
| + t.Fatalf("the ordinary create = %d %s, want C2 or the duplicate", o.code, o.out) |
| + } |
| + requireOneRestore(t, d) |
| + }) |
| + } |
| +} |
| + |
| +// TestRestoreAfterLegacyLineageRefused (spec §8): a hostname first created |
| +// with lifetimes off has no origin, and an app purged and recreated under |
| +// the same name is another lifetime: never restored. |
| +func TestRestoreAfterLegacyLineageRefused(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + bucket := <Store{Store: l.fx.rel} |
| + l.fx.srv.cfg.Releases = bucket |
| + forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive}) |
| + if code, out := createAs(t, l, `{"host":"`+ltOne+`"}`); code != http.StatusCreated { |
| + t.Fatalf("legacy create = %d %s", code, out) |
| + } |
| + turnLifetimesOn(t, l.fx.srv, l.clock) |
| + on := ltOn{lifetimesFx: l, bucket: bucket} |
| + if code, body := on.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent { |
| + t.Fatalf("delete = %d %s", code, body) |
| + } |
| + data := &stagingStore{DirStore: release.NewDirStore(t.TempDir())} |
| + l.fx.srv.cfg.SeedData, l.fx.srv.cfg.HibernateBucket, l.fx.srv.cfg.HomeRegion = data, "data-test", "ie" |
| + d := doorOver(t, &proofFx{ltOn: on, data: data}) |
| + refusedAsOld := func(what string) { |
| + t.Helper() |
| + code, out := d.restore(t, "") |
| + if msg := ltErr(out); code != http.StatusConflict || (msg != msgRestoreTooOld(ltOne) && msg != msgRestoreEarlierApp(ltOne, ltApp)) { |
| + t.Fatalf("%s = %d %s, want R4 or R8", what, code, out) |
| + } |
| + d.requireNoRecord(t) |
| + } |
| + refusedAsOld("the restore of a legacy lineage") |
| + now := time.Now() |
| + if err := l.fx.st.TrashAppRow(OpsAccountID, ltApp, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := l.fx.st.PurgeAppRow(OpsAccountID, ltApp); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := l.fx.st.CreateAppIn(OpsAccountID, ltApp, "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedAsOld("the restore into a recreated app") |
| +} |
| + |
| +// TestRestoreAfterManagedEnrolment: a managed fleet's enrolment moves the |
| +// history's @mode.At after the create; the restore still passes. |
| +func TestRestoreAfterManagedEnrolment(t *testing.T) { |
| + p := newProofBase(t) |
| + ctx := context.Background() |
| + before, _, err := provision.ReadHostsState(ctx, p.fx.rel) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(2 * time.Millisecond) |
| + if err := p.fx.srv.admitManagedHistory(ctx, registry.Fleet{Name: "production", Account: "bab", Managed: true, Bucket: "bucket"}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + after, _, err := provision.ReadHostsState(ctx, p.fx.rel) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !after.At.After(before.At) || after.Mode != provision.HostsModeActive { |
| + t.Fatalf("history after enrolment = %+v, before %+v: want active with @mode.At moved", after, before) |
| + } |
| + if code, body := p.del(t, ltOne); code != http.StatusOK && code != http.StatusNoContent { |
| + t.Fatalf("delete = %d %s", code, body) |
| + } |
| + d := doorOver(t, p) |
| + code, out := d.restore(t, "") |
| + d.requireRestored(t, code, out, 2) |
| +} |
| + |
| +// TestCreateWithoutRestoreUnchanged: a create with no restore, or with |
| +// "restore": false, is today's create. A fresh host never asks the proof |
| +// (nothing lists the staging prefix), its allocation carries the origin and |
| +// no restore_of, and its answer has no "restore" key. The existing S1, S4, |
| +// S5, leftover-rail and lock-order witnesses run unmodified (Step 4). |
| +func TestCreateWithoutRestoreUnchanged(t *testing.T) { |
| + for _, extra := range []string{"", `,"restore":false`} { |
| + t.Run("fresh"+extra, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + code, _, out := rawReq(t, http.MethodPost, d.url(), d.member, `{"host":"`+ltFresh+`"`+extra+`}`) |
| + if code != http.StatusCreated { |
| + t.Fatalf("create = %d %s", code, out) |
| + } |
| + var reply map[string]any |
| + if err := json.Unmarshal([]byte(out), &reply); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := reply["restore"]; ok { |
| + t.Fatalf("an ordinary create's answer carries restore: %s", out) |
| + } |
| + if len(d.data.listed) != 0 { |
| + t.Fatalf("an ordinary create of a fresh host listed %q", d.data.listed) |
| + } |
| + rows := lineage(t, d.fx.st, ltFresh) |
| + if len(rows) != 1 || !rows[0].RestoreOrigin || rows[0].RestoreOf != "" { |
| + t.Fatalf("lineage of %s = %+v, want one origin row", ltFresh, rows) |
| + } |
| + }) |
| + t.Run("a host another owner marked"+extra, func(t *testing.T) { |
| + d := newDoorFx(t) |
| + d.setMark(t, provision.HostUse{Host: ltOne, Account: "zzz", App: "gone", Kind: "instance", Source: "test"}) |
| + code, out := d.post(t, ordinaryBody(extra)) |
| + requireAnswer(t, code, out, http.StatusConflict, msgHostUsed(ltOne), "the create") |
| + d.requireNoRestoreWrite(t, 1) |
| + }) |
| + } |
| +} |