package console import ( "context" "encoding/json" "fmt" "net/http" "net/url" "os" "path/filepath" "strings" "sync" "testing" "time" "github.com/carlosframework/platform/internal/registry" "github.com/carlosframework/platform/internal/release" "github.com/carlosframework/platform/internal/svcrole" ) func temporaryFixture(t *testing.T) (*consoleFixture, string) { t.Helper() fx := newConsoleFixture(t) fx.srv.cfg.TemporaryApps = true return fx, cliToken(t, fx, "paul@keymail.dev", "code-"+strings.ReplaceAll(t.Name(), "/", "-")) } func createTemporary(t *testing.T, fx *consoleFixture, token, name string, ttl int64) (int, map[string]any) { t.Helper() return postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new-temporary", map[string]any{"name": name, "ttl_seconds": ttl}, token) } func TestTemporaryRouteIsOffUntilSwitchedOn(t *testing.T) { fx := newConsoleFixture(t) token := cliToken(t, fx, "paul@keymail.dev", "code-temp-off") status, h, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new-temporary", token, `{"name":"tmp-docs"}`) assertNotFound(t, "feature off", canonicalNotFound(t), status, h, body) if l := lifeOf(t, fx, "tmp-docs"); l != nil { t.Fatal("the switched-off route created a row") } } func TestTemporaryCreateSetsTheExpiryInTheClaim(t *testing.T) { fx, token := temporaryFixture(t) before := time.Now() status, out := createTemporary(t, fx, token, "tmp-docs", 0) if status != http.StatusOK { t.Fatalf("create = %d %v", status, out) } exp, err := time.Parse(time.RFC3339, str(t, out, "expires_at")) if err != nil { t.Fatalf("expires_at %q: %v", out["expires_at"], err) } if d := exp.Sub(before); d < temporaryTTLDefault-time.Minute || d > temporaryTTLDefault+time.Minute { t.Fatalf("default expiry is %v away, want 7 days", d) } if l := lifeOf(t, fx, "tmp-docs"); l == nil || l.ExpiresAt != exp.Unix() { t.Fatalf("row = %+v, want expires_at %d", l, exp.Unix()) } if p, err := release.GetPipeline(t.Context(), fx.rel, fx.pub, fx.sqid, "tmp-docs"); err != nil || p == nil { t.Fatalf("a new temporary app gets the default pipeline like any new app: %v %v", p, err) } } // Review Focus 1. func TestTemporaryTTLBounds(t *testing.T) { for secs, ok := range map[int64]bool{ 0: true, 3599: false, 3600: true, 2592000: true, 2592001: false, -1: false, 1 << 62: false, } { if _, err := temporaryTTL(secs, true); (err == nil) != ok { t.Errorf("temporaryTTL(%d) = %v, want ok=%v", secs, err, ok) } } if _, err := temporaryTTL(0, false); err == nil { t.Error("ttl 0 is only the default at create, never for carlos apps ttl") } fx, token := temporaryFixture(t) if status, _ := createTemporary(t, fx, token, "tmp-short", 3599); status != http.StatusBadRequest { t.Fatalf("ttl 3599 = %d, want 400", status) } if status, _ := createTemporary(t, fx, token, "tmp-huge", 1<<62); status != http.StatusBadRequest { t.Fatalf("ttl 1<<62 = %d, want 400", status) } if l := lifeOf(t, fx, "tmp-huge"); l != nil { t.Fatal("a refused ttl created a row") } } // Review Focus 2. func TestTemporaryCreateNameShapes(t *testing.T) { fx, token := temporaryFixture(t) for _, name := range []string{"docs", "tmp-", "tmp-abc-", "tmp-" + strings.Repeat("a", 29), "tmp_docs"} { if status, out := createTemporary(t, fx, token, name, 0); status != http.StatusBadRequest { t.Errorf("name %q = %d %v, want 400", name, status, out) } } if status, out := createTemporary(t, fx, token, " TMP-Docs ", 0); status != http.StatusOK || out["app"] != "tmp-docs" { t.Fatalf("TMP-Docs = %d %v, want 200 creating tmp-docs", status, out) } } func TestTemporaryCreateRefusesUnknownFields(t *testing.T) { fx, token := temporaryFixture(t) status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new-temporary", map[string]any{"name": "tmp-cp", "control_plane": true}, token) if status != http.StatusBadRequest || !strings.Contains(str(t, out, "error"), "control_plane") { t.Fatalf("control_plane on /new-temporary = %d %v, want 400 naming the field", status, out) } } // Spec §9: any key under the prefix refuses, including a manifest with no // channel pointer, and the owner role does not exempt it (paul owns ops). func TestTemporaryCreateRefusesAnyKeyUnderThePrefix(t *testing.T) { fx, token := temporaryFixture(t) if _, err := fx.rel.Put(t.Context(), "apps/"+fx.sqid+"/tmp-shipped/releases/v1/manifest.json", []byte(`{}`), ""); err != nil { t.Fatal(err) } status, out := createTemporary(t, fx, token, "tmp-shipped", 0) if status != http.StatusConflict || out["code"] != "name_taken" { t.Fatalf("create over an unpromoted release = %d %v, want 409 name_taken", status, out) } if l := lifeOf(t, fx, "tmp-shipped"); l != nil { t.Fatal("the owner adopted release history into a temporary app") } } // Spec §3 (astra 5.1): a route-only service of the same account and app, with // no row and no bucket objects, refuses. Another account's route does not. func TestTemporaryCreateRefusesARouteOfTheSameAccount(t *testing.T) { fx, token := temporaryFixture(t) reg, err := registry.Open(fx.regPath) if err != nil { t.Fatal(err) } for _, rt := range []registry.Route{ {Host: "svc.example.com", Kind: "service", Status: "ready", App: "tmp-svc", Account: fx.sqid, Addr: "127.0.0.1:9"}, {Host: "other.example.com", Kind: "service", Status: "ready", App: "tmp-other", Account: "bzz", Addr: "127.0.0.1:9"}, } { if err := reg.Upsert(rt); err != nil { t.Fatal(err) } } if status, out := createTemporary(t, fx, token, "tmp-svc", 0); status != http.StatusConflict { t.Fatalf("same-account route = %d %v, want 409", status, out) } if status, out := createTemporary(t, fx, token, "tmp-other", 0); status != http.StatusOK { t.Fatalf("another account's route = %d %v, want 200", status, out) } } // "Could not check" is not "no routes". func TestTemporaryCreateRefusesWhenTheRegistryCannotBeRead(t *testing.T) { fx, token := temporaryFixture(t) notADir := filepath.Join(t.TempDir(), "file") if err := os.WriteFile(notADir, []byte("x"), 0o600); err != nil { t.Fatal(err) } fx.srv.cfg.Registry = filepath.Join(notADir, "registry.db") if status, out := createTemporary(t, fx, token, "tmp-blind", 0); status != http.StatusBadGateway { t.Fatalf("unreadable registry = %d %v, want 502", status, out) } if l := lifeOf(t, fx, "tmp-blind"); l != nil { t.Fatal("created without checking the routes") } } // Spec §9: the cap refuses the 21st and is exact under concurrent creates. func TestTemporaryCapIsExactUnderConcurrentCreates(t *testing.T) { fx, token := temporaryFixture(t) now := time.Now() for i := 0; i < 18; i++ { if ok, err := fx.st.CreateTemporaryAppIn(OpsAccountID, fmt.Sprintf("tmp-seed%02d", i), "paul@keymail.dev", now, now.Add(time.Hour)); err != nil || !ok { t.Fatal(ok, err) } } var wg sync.WaitGroup statuses := make([]int, 5) for i := range statuses { wg.Add(1) go func(i int) { defer wg.Done() statuses[i], _ = createTemporary(t, fx, token, fmt.Sprintf("tmp-race%d", i), 0) }(i) } wg.Wait() won := 0 for _, s := range statuses { if s == http.StatusOK { won++ } } if won != 2 { t.Fatalf("statuses = %v, want exactly 2 of 5 to fit under the cap of 20", statuses) } live, _ := fx.st.LiveTemporaryApps(OpsAccountID) if len(live) != temporaryAppCap { t.Fatalf("%d live temporary apps, want %d", len(live), temporaryAppCap) } status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new-temporary", map[string]any{"name": "tmp-21st"}, token) msg := str(t, out, "error") if status != http.StatusConflict || out["code"] != "cap" || !strings.Contains(msg, "tmp-seed00") { t.Fatalf("21st = %d %v, want 409 cap listing each app with its expiry", status, out) } } // Review Focus 5. func TestAppScopedServiceCannotClaimATemporaryApp(t *testing.T) { fx := newConsoleFixture(t) fx.srv.cfg.TemporaryApps = true u := fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/new-temporary" appTok := serviceToken(t, fx.st, OpsAccountID, "kass-ci", "kass", svcrole.Publish) status, h, body := rawReq(t, http.MethodPost, u, appTok, `{"name":"tmp-ci"}`) assertNotFound(t, "app-scoped credential claiming a temporary app", canonicalNotFound(t), status, h, body) if l := lifeOf(t, fx, "tmp-ci"); l != nil { t.Fatal("an app-scoped credential claimed a temporary app") } acctTok := serviceToken(t, fx.st, OpsAccountID, "pages", "", svcrole.Publish) if status, _, body := rawReq(t, http.MethodPost, u, acctTok, `{"name":"tmp-ci"}`); status != http.StatusOK { t.Fatalf("account-scoped Publish credential = %d %s, want 200", status, body) } } func TestTemporaryCreateHasOwnBudget(t *testing.T) { fx, token := temporaryFixture(t) // Attempts, not successes, spend the budget (cliCreateBurst's rule): // past the live cap of 20 these are 409s, and they still count. for i := 0; i < cliTemporaryCreateBurst; i++ { status, out := createTemporary(t, fx, token, fmt.Sprintf("tmp-b%d", i), 0) if status == http.StatusTooManyRequests { t.Fatalf("temporary attempt %d refused by the rate limit: %v", i, out) } } if status, out := createTemporary(t, fx, token, "tmp-over", 0); status != http.StatusTooManyRequests { t.Fatalf("attempt %d = %d %v, want 429", cliTemporaryCreateBurst+1, status, out) } // The permanent budget is untouched by all of that. status, out := postJSON(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/new", map[string]any{"name": "permanent-one"}, token) if status == http.StatusTooManyRequests { t.Fatalf("/new refused after temporary creates: %v; the budgets must be separate", out) } } func appURL(fx *consoleFixture, app, tail string) string { return fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/" + app + tail } func TestKeepMakesATemporaryAppPermanent(t *testing.T) { fx, token := temporaryFixture(t) tempApp(t, fx, "tmp-a", time.Now().Add(time.Hour)) status, out := postJSON(t, appURL(fx, "tmp-a", "/keep"), map[string]string{}, token) if status != http.StatusOK || out["app"] != "tmp-a" || out["expires_at"] != nil { t.Fatalf("keep = %d %v, want 200 with expires_at null", status, out) } if l := lifeOf(t, fx, "tmp-a"); l.Temporary() { t.Fatalf("row = %+v, want permanent", l) } } func TestTTLMovesTheExpiry(t *testing.T) { fx, token := temporaryFixture(t) tempApp(t, fx, "tmp-a", time.Now().Add(time.Hour)) before := time.Now() status, out := postJSON(t, appURL(fx, "tmp-a", "/ttl"), map[string]int64{"ttl_seconds": 5 * 86400}, token) if status != http.StatusOK { t.Fatalf("ttl = %d %v", status, out) } exp, _ := time.Parse(time.RFC3339, str(t, out, "expires_at")) if d := exp.Sub(before); d < 5*24*time.Hour-time.Minute || d > 5*24*time.Hour+time.Minute { t.Fatalf("expiry is %v away, want 5 days", d) } if l := lifeOf(t, fx, "tmp-a"); l.ExpiresAt != exp.Unix() { t.Fatalf("row = %+v", l) } } // Review Focus 4. func TestTTLAndKeepRefuseWhatTheyCannotChange(t *testing.T) { fx, token := temporaryFixture(t) for _, tail := range []string{"/keep", "/ttl"} { status, out := postJSON(t, appURL(fx, "kass", tail), map[string]int64{"ttl_seconds": 86400}, token) if status != http.StatusConflict { t.Errorf("%s on a permanent app = %d %v, want 409", tail, status, out) } } if l := lifeOf(t, fx, "kass"); l.Temporary() { t.Fatal("a door made a permanent app temporary") } tempApp(t, fx, "tmp-a", time.Now().Add(time.Hour)) if status, _ := postJSON(t, appURL(fx, "tmp-a", "/ttl"), map[string]int64{"ttl_seconds": 3599}, token); status != http.StatusBadRequest { t.Errorf("ttl 3599 = %d, want 400", status) } if status, _ := postJSON(t, appURL(fx, "tmp-a", "/ttl"), map[string]int64{}, token); status != http.StatusBadRequest { t.Errorf("ttl with no ttl_seconds = %d, want 400", status) } fx.st.TrashAppRow(OpsAccountID, "tmp-a", time.Now()) trashed := *lifeOf(t, fx, "tmp-a") // The live-app gate's answer is http.NotFound's plain text, not JSON, so // these go through rawReq (apiinstances_test.go:42): postJSON's doJSON // fails the test on any body that does not decode (authcli_test.go:62). for _, tail := range []string{"/keep", "/ttl"} { status, h, body := rawReq(t, http.MethodPost, appURL(fx, "tmp-a", tail), token, `{"ttl_seconds":86400}`) assertNotFound(t, tail+" on a trashed app", canonicalNotFound(t), status, h, body) } if l := lifeOf(t, fx, "tmp-a"); l == nil || *l != trashed { t.Fatalf("row = %+v after refused keep/ttl, want unchanged %+v", l, trashed) } } // Spec §9 "failure at step 4 followed by a keep": the marker is written and // the row is live and expired. Keep settles first, finds the app in the // Trash, and refuses; the row is left trashed with the 3-day window. func TestKeepAfterAFailedExpiryStepFourIsRefused(t *testing.T) { fx, token := temporaryFixture(t) at := time.Now().Truncate(time.Second).Add(-time.Minute) tempApp(t, fx, "tmp-a", at) if err := release.TrashApp(context.Background(), fx.rel, fx.sqid, "tmp-a", expiryActor, at); err != nil { t.Fatal(err) } status, out := postJSON(t, appURL(fx, "tmp-a", "/keep"), map[string]string{}, token) if status != http.StatusConflict || !strings.Contains(str(t, out, "error"), "carlos apps restore") { t.Fatalf("keep = %d %v, want 409 pointing at carlos apps restore", status, out) } if l := lifeOf(t, fx, "tmp-a"); l.DeletedAt != at.Unix() || l.PurgeAfter != at.Unix()+72*3600 || !l.Temporary() { t.Fatalf("row = %+v, want trashed at the marker's clock with the 3-day window, still temporary", l) } } // Spec §9 "/list": trashed apps shown; the accounts listing's []string // unchanged; service-principal filtering matches. func TestListShowsTheTrashAndFiltersServices(t *testing.T) { fx, token := temporaryFixture(t) now := time.Now().Truncate(time.Second) tempApp(t, fx, "tmp-live", now.Add(3*24*time.Hour)) tempApp(t, fx, "tmp-gone", now.Add(time.Hour)) fx.st.TrashAppRow(OpsAccountID, "tmp-gone", now) fx.st.TrashAppRow(OpsAccountID, "kass", now) list := func(tok string) map[string]map[string]any { t.Helper() status, body := getRaw(t, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/list", tok) if status != http.StatusOK { t.Fatalf("list = %d %s", status, body) } var rows []map[string]any if err := json.Unmarshal([]byte(body), &rows); err != nil { t.Fatalf("list is not a JSON array: %v\n%s", err, body) } out := map[string]map[string]any{} for _, r := range rows { out[r["app"].(string)] = r } return out } rows := list(token) if len(rows) != 3 { t.Fatalf("list = %v, want tmp-live, tmp-gone and kass", rows) } if r := rows["tmp-live"]; r["deleted_at"] != nil || r["purge_after"] != nil || r["expires_at"] != now.Add(3*24*time.Hour).UTC().Format(time.RFC3339) { t.Errorf("tmp-live = %v", r) } if r := rows["tmp-gone"]; r["purge_after"] != now.Add(72*time.Hour).UTC().Format(time.RFC3339) { t.Errorf("tmp-gone = %v, want purge_after 3 days after the trash", r) } if r := rows["kass"]; r["purge_after"] != now.Add(30*24*time.Hour).UTC().Format(time.RFC3339) || r["expires_at"] != nil { t.Errorf("kass = %v, want purge_after 30 days after the trash", r) } // The accounts listing keeps its []string of LIVE names. _, accts := getJSON(t, fx.ts.URL+"/api/cli/apps", token) for _, a := range accts["accounts"].([]any) { for _, name := range a.(map[string]any)["apps"].([]any) { if _, ok := name.(string); !ok || name == "kass" || name == "tmp-gone" { t.Errorf("accounts listing apps = %v, want live names only, as strings", a) } } } // An app-scoped service sees only its app. svc := serviceToken(t, fx.st, OpsAccountID, "live-ci", "tmp-live", svcrole.Publish) if rows := list(svc); len(rows) != 1 || rows["tmp-live"] == nil { t.Errorf("app-scoped list = %v, want only tmp-live", rows) } } func TestBrowserKeepButton(t *testing.T) { fx := newConsoleFixture(t) tempApp(t, fx, "tmp-a", time.Now().Add(time.Hour)) c, csrf := signInAs(t, fx, "paul@keymail.dev", "code-keep-button") if _, _, page := get(t, c, fx.u("/apps/tmp-a")); !strings.Contains(page, fx.path("/apps/tmp-a/keep")) { t.Fatal("the app page of a temporary app has no Keep form") } if _, _, page := get(t, c, fx.u("/apps/kass")); strings.Contains(page, "/apps/kass/keep") { t.Fatal("a permanent app shows a Keep form") } status, _, _ := postForm(t, c, fx.u("/apps/tmp-a/keep"), url.Values{"csrf": {csrf}}) if status != http.StatusSeeOther { t.Fatalf("keep = %d, want 303", status) } if l := lifeOf(t, fx, "tmp-a"); l.Temporary() { t.Fatal("the Keep button did not keep") } } // Review carryover from Task 8: keepApp and setAppTTL must take the SAME // s.lockApp key the expiry pass and the trash doors use, settle first, and // only then act. Proved here with real lock contention, not sequencing: the // test holds the app's lock, lets the request queue on it, writes the trash // marker the expiry pass's first steps would have written, and only then // releases. The queued keep/ttl must find the trash when it finally gets the // lock and refuse, never a stale live row read before it waited. func TestKeepAndTTLRecheckAfterTheLock(t *testing.T) { race := func(t *testing.T, fx *consoleFixture, app string, request func() int, change func()) int { t.Helper() unlock := fx.srv.lockApp(fx.sqid, app) done := make(chan int, 1) go func() { done <- request() }() waitForWaiter(t, &fx.srv.appLocks, fx.sqid+"/"+app) change() unlock() return <-done } t.Run("keep queued while the expiry pass trashes it", func(t *testing.T) { fx, token := temporaryFixture(t) at := time.Now().Truncate(time.Second).Add(-time.Minute) tempApp(t, fx, "tmp-a", at) status := race(t, fx, "tmp-a", func() int { st, _ := postJSON(t, appURL(fx, "tmp-a", "/keep"), map[string]string{}, token) return st }, func() { if err := release.TrashApp(context.Background(), fx.rel, fx.sqid, "tmp-a", expiryActor, at); err != nil { t.Error(err) } }) if status != http.StatusConflict { t.Fatalf("keep queued behind a trash = %d, want 409", status) } if l := lifeOf(t, fx, "tmp-a"); !l.Trashed() || !l.Temporary() { t.Fatalf("row = %+v, want trashed, still temporary: the queued keep must not have won", l) } }) t.Run("ttl queued while the expiry pass trashes it", func(t *testing.T) { fx, token := temporaryFixture(t) at := time.Now().Truncate(time.Second).Add(-time.Minute) tempApp(t, fx, "tmp-b", at) status := race(t, fx, "tmp-b", func() int { st, _ := postJSON(t, appURL(fx, "tmp-b", "/ttl"), map[string]int64{"ttl_seconds": 86400}, token) return st }, func() { if err := release.TrashApp(context.Background(), fx.rel, fx.sqid, "tmp-b", expiryActor, at); err != nil { t.Error(err) } }) if status != http.StatusConflict { t.Fatalf("ttl queued behind a trash = %d, want 409", status) } if l := lifeOf(t, fx, "tmp-b"); !l.Trashed() || l.ExpiresAt != at.Unix() { t.Fatalf("row = %+v, want trashed with its original expiry: the queued ttl must not have won", l) } }) }