| new file mode 100644 |
| index 000000000..1693b1690 |
| --- /dev/null |
| +++ b/internal/console/apibackups_test.go |
| @@ -0,0 +1,307 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "slices" |
| + "sort" |
| + "testing" |
| + "time" |
| + |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbreads" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/regionlabel" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +func backupsURL(fx *consoleFixture, app, host string) string { |
| + return fx.ts.URL + "/api/cli/apps/" + release.OpsAccount + "/" + app + "/instances/" + host + "/backups" |
| +} |
| + |
| +// untimedReplica is listedReplica with no times on its listing, which is |
| +// what makes PositionAndHistory answer the position with history unknown. |
| +type untimedReplica struct{ listedReplica } |
| + |
| +func (r *untimedReplica) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) { |
| + itr, err := r.listedReplica.LTXFiles(ctx, level, seek, useMetadata) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer itr.Close() |
| + var fs []*ltx.FileInfo |
| + for itr.Next() { |
| + f := *itr.Item() |
| + f.CreatedAt = time.Time{} |
| + fs = append(fs, &f) |
| + } |
| + return ltx.NewFileInfoSliceIterator(fs), nil |
| +} |
| + |
| +// backupsKeys is the sorted top-level key set of a JSON object, and the |
| +// object itself. |
| +func backupsKeys(t *testing.T, body string) ([]string, map[string]any) { |
| + t.Helper() |
| + var m map[string]any |
| + if err := json.Unmarshal([]byte(body), &m); err != nil { |
| + t.Fatalf("not a JSON object: %s: %v", body, err) |
| + } |
| + keys := make([]string, 0, len(m)) |
| + for k := range m { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + return keys, m |
| +} |
| + |
| +// TestAPIInstanceBackupsKeySets (P2-17): each class carries exactly its |
| +// keys and no others, read as a member through the door itself. |
| +func TestAPIInstanceBackupsKeySets(t *testing.T) { |
| + fx := dbFixture(t) |
| + here := fx.srv.cfg.Region // dbTestHost's record is homed here |
| + const untimed = "untimed.go.tito.io" |
| + onDisk := fx.srv.dbReplica |
| + fx.srv.dbReplica = func(ctx context.Context, prefix string) (replicaReader, error) { |
| + if prefix == "instances/"+untimed { |
| + return &untimedReplica{listedReplica{n: 2, at: time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)}}, nil |
| + } |
| + return onDisk(ctx, prefix) |
| + } |
| + for _, rec := range []provision.Record{ |
| + {Host: untimed, Region: here}, |
| + {Host: "born-ha.go.tito.io", Region: here, HA: true}, |
| + {Host: "awake.go.tito.io", Region: here, Hibernate: backupsNo()}, |
| + {Host: "svc.go.tito.io", Region: here, Kind: "service"}, |
| + {Host: "far.go.tito.io", Region: "uk"}, |
| + {Host: "pool.go.tito.io", Region: here, Pool: "shared"}, |
| + {Host: "fleet.go.tito.io", Region: "fleet/acme"}, |
| + {Host: "empty.go.tito.io", Region: here}, |
| + } { |
| + putDBRecord(t, fx.consoleFixture, rec) |
| + } |
| + fx.replicate(t, dbTestHost, 2) |
| + fx.replicate(t, "born-ha.go.tito.io", 1) |
| + |
| + far := regionlabel.ForCode("uk", fx.srv.regionHome(), fx.srv.regionNames()).Text |
| + for _, c := range []struct { |
| + host, class, reason, files string |
| + keys []string |
| + }{ |
| + {dbTestHost, "replicated", "", "not_copied", []string{"class", "copied_to", "files", "history_from"}}, |
| + {untimed, "replicated", "", "not_copied", []string{"class", "copied_to", "files"}}, |
| + {"born-ha.go.tito.io", "replicated", "", "not_shown", []string{"class", "copied_to", "files", "history_from"}}, |
| + {"awake.go.tito.io", "no_copy", "no_sleep", "not_copied", []string{"class", "files", "reason"}}, |
| + {"svc.go.tito.io", "no_copy", "not_instance", "not_copied", []string{"class", "files", "reason"}}, |
| + {"far.go.tito.io", "not_shown", "other_region", "not_copied", []string{"class", "files", "reason", "region"}}, |
| + {"pool.go.tito.io", "not_shown", "pooled", "not_copied", []string{"class", "files", "reason"}}, |
| + {"fleet.go.tito.io", "not_shown", "fleet", "not_copied", []string{"class", "files", "reason"}}, |
| + {"empty.go.tito.io", "not_shown", "nothing_replicated", "not_copied", []string{"class", "files", "reason"}}, |
| + } { |
| + t.Run(c.host, func(t *testing.T) { |
| + status, h, body := rawReq(t, http.MethodGet, backupsURL(fx.consoleFixture, "titogo", c.host), fx.member, "") |
| + if status != http.StatusOK || h.Get("Content-Type") != "application/json" { |
| + t.Fatalf("backups = %d %q %s, want 200 JSON", status, h.Get("Content-Type"), body) |
| + } |
| + keys, m := backupsKeys(t, body) |
| + if !slices.Equal(keys, c.keys) { |
| + t.Fatalf("keys = %v, want exactly %v: %s", keys, c.keys, body) |
| + } |
| + if m["class"] != c.class || m["files"] != c.files { |
| + t.Fatalf("class %v files %v, want %s and %s: %s", m["class"], m["files"], c.class, c.files, body) |
| + } |
| + if c.reason != "" && m["reason"] != c.reason { |
| + t.Fatalf("reason = %v, want %s", m["reason"], c.reason) |
| + } |
| + if c.reason == "other_region" && (m["region"] != far || far == "") { |
| + t.Fatalf("region = %v, want %q", m["region"], far) |
| + } |
| + if pos, ok := m["copied_to"]; ok { |
| + p, _ := pos.(map[string]any) |
| + pk := make([]string, 0, len(p)) |
| + for k := range p { |
| + pk = append(pk, k) |
| + } |
| + sort.Strings(pk) |
| + if !slices.Equal(pk, []string{"transaction", "written_at"}) { |
| + t.Fatalf("copied_to keys = %v, want exactly transaction and written_at: %s", pk, body) |
| + } |
| + if _, err := time.Parse(time.RFC3339Nano, p["written_at"].(string)); err != nil { |
| + t.Fatalf("written_at %v is not Go's time encoding: %v", p["written_at"], err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// backupsToken is serviceToken for every role, the two that are minted |
| +// with a scope included: deploy with a rung, run with a command. |
| +func backupsToken(t *testing.T, st *Store, accountID int64, name, app string, role svcrole.Role) string { |
| + t.Helper() |
| + var rungs []string |
| + var commands [][]string |
| + switch role { |
| + case svcrole.Deploy: |
| + rungs = []string{"edge"} |
| + case svcrole.Run: |
| + commands = [][]string{{"rake", "db:migrate"}} |
| + default: |
| + return serviceToken(t, st, accountID, name, app, role) |
| + } |
| + tok, err := st.NewServicePrincipalScoped(accountID, name, app, role, rungs, commands, "paul@example.test", time.Now()) |
| + if err != nil { |
| + t.Fatalf("mint %s %q: %v", role, name, err) |
| + } |
| + return tok |
| +} |
| + |
| +// TestAPIInstanceBackupsRoles (P-2): a member and the deploy, operate and |
| +// admin credentials of the app read the door; every other role meets the |
| +// role gate's 403 as cliGate writes it; a credential or member whose scope |
| +// does not reach the app meets the instance gate's byte-identical 404. |
| +func TestAPIInstanceBackupsRoles(t *testing.T) { |
| + fx := dbFixture(t) |
| + fx.replicate(t, dbTestHost, 1) |
| + u := backupsURL(fx.consoleFixture, "titogo", dbTestHost) |
| + if status, _, body := rawReq(t, http.MethodGet, u, fx.member, ""); status != http.StatusOK { |
| + t.Fatalf("member = %d %s, want 200", status, body) |
| + } |
| + |
| + for _, role := range []svcrole.Role{svcrole.Deploy, svcrole.Operate, svcrole.Admin} { |
| + tok := backupsToken(t, fx.st, OpsAccountID, "ok-"+string(role), "titogo", role) |
| + status, _, body := rawReq(t, http.MethodGet, u, tok, "") |
| + if status != http.StatusOK { |
| + t.Errorf("%s bound to titogo = %d %s, want 200", role, status, body) |
| + continue |
| + } |
| + if keys, m := backupsKeys(t, body); m["class"] != "replicated" || !slices.Contains(keys, "copied_to") { |
| + t.Errorf("%s bound to titogo = %s, want the replicated view", role, body) |
| + } |
| + } |
| + // An account-scoped operate or admin credential reaches every app of |
| + // its account, this one included. |
| + for _, role := range []svcrole.Role{svcrole.Operate, svcrole.Admin} { |
| + tok := serviceToken(t, fx.st, OpsAccountID, "acct-"+string(role), "", role) |
| + if status, _, body := rawReq(t, http.MethodGet, u, tok, ""); status != http.StatusOK { |
| + t.Errorf("account-scoped %s = %d %s, want 200", role, status, body) |
| + } |
| + } |
| + |
| + // Every other role: the role gate's 403, before the handler runs. |
| + for _, role := range svcrole.All() { |
| + if role == svcrole.Deploy || role == svcrole.Operate || role == svcrole.Admin { |
| + continue |
| + } |
| + tok := backupsToken(t, fx.st, OpsAccountID, "no-"+string(role), "titogo", role) |
| + status, h, body := rawReq(t, http.MethodGet, u, tok, "") |
| + want := `{"error":"this credential holds role \"` + string(role) + `\"; this door needs one of [admin deploy operate]"}` + "\n" |
| + if status != http.StatusForbidden || h.Get("Content-Type") != "application/json" || body != want { |
| + t.Errorf("%s = %d %q %q, want 403 %q", role, status, h.Get("Content-Type"), body, want) |
| + } |
| + } |
| + |
| + // Scope refusals: the instance gate's byte-identical 404. |
| + nf := canonicalNotFound(t) |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, role := range []svcrole.Role{svcrole.Deploy, svcrole.Operate, svcrole.Admin} { |
| + tok := backupsToken(t, fx.st, OpsAccountID, "elsewhere-"+string(role), "other", role) |
| + status, h, body := rawReq(t, http.MethodGet, u, tok, "") |
| + assertNotFound(t, string(role)+" bound to another app", nf, status, h, body) |
| + } |
| + // A deploy credential is never app-less: the gate's app binding is |
| + // required for it at the mint. |
| + if _, err := fx.st.NewServicePrincipalScoped(OpsAccountID, "loose-deploy", "", svcrole.Deploy, []string{"edge"}, nil, "paul@example.test", time.Now()); !errors.Is(err, ErrAccountScopedDeploy) { |
| + t.Fatalf("app-less deploy mint = %v, want ErrAccountScopedDeploy", err) |
| + } |
| + otherID := testAccountID() |
| + if err := fx.st.CreateAccount(otherID, accountSqid(otherID), "other-account", "sam@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(otherID, "titogo", "sam@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, role := range []svcrole.Role{svcrole.Operate, svcrole.Admin} { |
| + for _, app := range []string{"", "titogo"} { |
| + tok := serviceToken(t, fx.st, otherID, "foreign-"+string(role)+app, app, role) |
| + status, h, body := rawReq(t, http.MethodGet, u, tok, "") |
| + assertNotFound(t, "another account's "+string(role)+" (app "+app+")", nf, status, h, body) |
| + } |
| + } |
| + if err := fx.st.AddMember(otherID, "bob@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + stranger := cliToken(t, fx.consoleFixture, "bob@keymail.dev", "code-backups-stranger") |
| + status, h, body := rawReq(t, http.MethodGet, u, stranger, "") |
| + assertNotFound(t, "another account's member", nf, status, h, body) |
| +} |
| + |
| +// TestAPIInstanceBackupsBadHostAndMissing: a host that cannot name a record |
| +// and one that names none are the instance family's byte-identical 404. |
| +func TestAPIInstanceBackupsBadHostAndMissing(t *testing.T) { |
| + fx := dbFixture(t) |
| + nf := canonicalNotFound(t) |
| + for name, host := range map[string]string{ |
| + "bad shape": "..%2f..%2fchannels", |
| + "unknown host": "nobody.go.tito.io", |
| + } { |
| + status, h, body := rawReq(t, http.MethodGet, backupsURL(fx.consoleFixture, "titogo", host), fx.member, "") |
| + assertNotFound(t, name, nf, status, h, body) |
| + } |
| + if n := fx.opens.Load(); n != 0 { |
| + t.Fatalf("dbReplica opened %d times for refused hosts", n) |
| + } |
| +} |
| + |
| +// TestAPIInstanceBackupsOtherRegion: an instance homed in another region is |
| +// not_shown with that region's label, and `carlos db pull`'s forward for |
| +// the same host is still admitted (spec §1, R2-2): the door's region rule |
| +// is its own and never reaches db pull's path. |
| +func TestAPIInstanceBackupsOtherRegion(t *testing.T) { |
| + fx := newDBFFixture(t, true) |
| + fx.srv.dbf.pickup = 200 * time.Millisecond |
| + status, _, body := rawReq(t, http.MethodGet, backupsURL(fx.consoleFixture, "shop", dbfHost), fx.member, "") |
| + if status != http.StatusOK { |
| + t.Fatalf("backups = %d %s", status, body) |
| + } |
| + var v struct { |
| + Class, Reason, Region, Files string |
| + } |
| + if err := json.Unmarshal([]byte(body), &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + label := regionlabel.ForCode("uk", fx.srv.regionHome(), fx.srv.regionNames()).Text |
| + if v.Class != "not_shown" || v.Reason != "other_region" || v.Region != label || label == "" { |
| + t.Fatalf("backups = %s, want not_shown/other_region in %q", body, label) |
| + } |
| + |
| + // The list door still marks the host for forwarding... |
| + status, _, body = rawReq(t, http.MethodGet, fx.listURL(), fx.member, "") |
| + var mark dbdoor.ForwardBody |
| + if err := json.Unmarshal([]byte(body), &mark); err != nil || status != http.StatusConflict || mark.Forward != 1 || |
| + !slices.Contains(mark.ForwardOps, dbreads.OpPull) { |
| + t.Fatalf("list door = %d %s, want the forward marker offering pull", status, body) |
| + } |
| + // ...and the forwarded pull is admitted, not refused for residency. |
| + key, err := dbreads.NewReplyKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + res := fx.openRead(t, dbfHost, fx.member, dbreads.ReadBody{Op: dbreads.OpPull, ReplyKey: dbreads.EncodeReplyKey(key.PublicKey())}) |
| + if res.StatusCode != http.StatusOK { |
| + b, _ := io.ReadAll(res.Body) |
| + res.Body.Close() |
| + t.Fatalf("forwarded pull = %d %s, want admitted", res.StatusCode, b) |
| + } |
| + lines := readLines(t, res.Body) |
| + res.Body.Close() |
| + if len(lines) == 0 || lines[0].Admitted == "" { |
| + t.Fatalf("forwarded pull lines %+v, want an admitted read", lines) |
| + } |
| +} |