canary retire: CLI doors for unfollowed canary pointers (#1634)
The browser's Retire was the only way to delete a canary/<name> pointer,
so CLI-driven operators were stuck with lapsed canary rows in carlos
channels digests.
- handleRetireCanary's guard and delete become one shared core
(checkCanaryRetire, deleteRetiredCanary): follower check over registry,
records and box reports, the settle window, the app lock, the record
stamp recheck and the CAS delete. The browser door is unchanged.
- POST /api/cli/apps/{account}/{app}/canary/retire and carlos canary
retire: the same act for a member; closed to service credentials.
- POST /api/cli/system/channels/retire and carlos channels retire: a
platform operator retires a canary pointer of an app with no console
row. Refuses a live or trashed row, a trash marker, any instance record
and any follower (box reports see hand routes); rechecks under the lock;
canary/* only; platform audit row.
- The digests listing marks such lines no_app, and the CLI names the
retire command for their canary heads.
- canary rm's closing line names carlos canary retire.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+1,186
−156
canary.go+17 −8canary_retire.go+125 −0canary_retire_test.go+149 −0channels_digests.go+14 −0commands.go+5 −3internal/console/apidigests.go+35 −2internal/console/apilinks_test.go+6 −5internal/console/canary_retire.go+488 −0internal/console/canary_retire_test.go+307 −0internal/console/claim_invariant_fixtures_test.go+8 −0internal/console/claim_invariant_probes_nonapp_test.go+24 −0internal/console/linkedpolicy.go+1 −0internal/console/routedecls.go+6 −0internal/console/server.go+0 −138internal/console/testdata/claim-authority-sites.txt+1 −0
diff --git a/canary.go b/canary.go| index fc2365337..7f4ea3a8a 100644 |
| --- a/canary.go |
| +++ b/canary.go |
| @@ -41,6 +41,7 @@ const canaryUsage = `usage: carlos canary [deploy] --app <a> [--name <n>] [--ver |
| [--mail submit] [--timeout 120s] <files-or-site-dir> |
| carlos canary ls --app <a> |
| carlos canary rm --app <a> --name <n> |
| + carlos canary retire --app <a> --name <n> |
| Ships a version and serves it on its own host, following its own canary/<name> |
| channel, without touching what the app's other instances serve. The bare form |
| @@ -64,7 +65,10 @@ been on one still enters the pipeline as a fresh build, so canarying and then |
| promoting to edge is the ordinary path, not a bypass. |
| Canaries carry a seven-day lease, refreshed by every re-promote. "canary ls" |
| -shows what is left of it.` |
| +shows what is left of it. An expired lease only warns: it deletes nothing. |
| + |
| +"canary rm" deletes the canary's instance. "canary retire" then deletes its |
| +channel, once nothing has followed it for 15 minutes. Shipped releases stay.` |
| // canaryWatchEvery is how often the deploy leg re-probes the canary host. |
| // The same 2s deploy.go uses — and it is not a coincidence that canary/* |
| @@ -86,7 +90,7 @@ func canaryCommand() *clireg.Node { |
| return &clireg.Node{ |
| Name: "canary", |
| Audience: cust, |
| - Children: []*clireg.Node{list, remove, raw("deploy", cust, runCanaryDeploy)}, |
| + Children: []*clireg.Node{list, remove, rawErr("retire", cust, runCanaryRetire), raw("deploy", cust, runCanaryDeploy)}, |
| Default: "deploy", |
| DefaultOn: clireg.OnAbsent | clireg.OnFlag | clireg.OnWord, |
| } |
| @@ -748,14 +752,19 @@ func runCanaryList(args []string) { |
| // ---- carlos canary rm ----------------------------------------------------- |
| +// textCanaryRemovedChannel is canary rm's closing line (#1634). Not yet |
| +// through copy review. |
| +const textCanaryRemovedChannel = "%s still exists, followed by nothing. To delete it, run carlos canary retire --app %s --name %s after 15 minutes" |
| + |
| // runCanaryRemove deletes a canary's instance record — its host stops being |
| // served and its process goes away. |
| // |
| -// It does NOT delete the channel pointer, because the platform has no such |
| -// operation: a pointer is a signed object in the deployment bucket, and |
| -// canary/<name> simply stops being followed by anything and lapses at the end |
| -// of its lease. Saying so is the point — a command that let a member believe |
| -// the channel was gone would be lying about what it did, and the next |
| +// It does NOT delete the channel pointer: canary/<name> stays, followed by |
| +// nothing, and its lease running out deletes nothing either (the lease is a |
| +// nag, never enforcement). `carlos canary retire` deletes the pointer once |
| +// the app has been still for the settle window (#1634), so the closing line |
| +// names it. Saying so is the point — a command that let a member believe the |
| +// channel was gone would be lying about what it did, and the next |
| // `carlos channels` would contradict it. |
| func runCanaryRemove(args []string) { |
| fs := flag.NewFlagSet("canary rm", flag.ExitOnError) |
| @@ -792,7 +801,7 @@ func runCanaryRemove(args []string) { |
| log.Fatalf("canary rm: delete %s: %v", rec.Host, err) |
| } |
| fmt.Fprintf(stdout, "%s %s\n", colorFor(stdout).ok("removed"), rec.Host) |
| - mutedf(stdout, "%s itself remains and lapses at the end of its lease — nothing follows it now\n", channel) |
| + mutedf(stdout, textCanaryRemovedChannel+"\n", channel, app2, canary) |
| } |
| // ---- refusals ------------------------------------------------------------- |
diff --git a/canary_retire.go b/canary_retire.go| new file mode 100644 |
| index 000000000..57cdc4879 |
| --- /dev/null |
| +++ b/canary_retire.go |
| @@ -0,0 +1,125 @@ |
| +package main |
| + |
| +// `carlos canary retire` and `carlos channels retire` (#1634): deleting a |
| +// canary/<name> channel pointer that nothing follows, through a console. |
| +// The console does every check (no follower by registry, record or box |
| +// report; the app still for 15 minutes; the pointer unchanged since it was |
| +// read) and deletes only the pointer, never a shipped release. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| +) |
| + |
| +// Not yet through copy review. |
| +const ( |
| + textCanaryRetired = "%s's pointer is gone. Its releases are kept" |
| + textCanaryRetireNeedName = "carlos canary retire: --name <n> is required" |
| + textRetireNeedsConsole = "carlos %s works through a console, and this shell is in direct bucket mode. Unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then run carlos auth login --console <url>" |
| + textChannelsRetireUsage = "usage: carlos channels retire --account-id <sqid> --app <a> canary/<name>" |
| + textChannelsRetired = "%s of %s/%s: its pointer is gone. Its releases are kept" |
| +) |
| + |
| +// canaryRetire asks the console to retire canary/<name> of app, and |
| +// answers the channel it retired. |
| +func (s *apiSession) canaryRetire(ctx context.Context, a apiAcct, app, name string) (string, error) { |
| + status, body, err := s.postJSON(ctx, apiPath(a, app, "/canary/retire"), map[string]string{"name": name}) |
| + if err != nil { |
| + return "", err |
| + } |
| + if status != http.StatusOK { |
| + return "", apiErrorFromBody(status, body) |
| + } |
| + var out struct { |
| + Channel string `json:"channel"` |
| + } |
| + if err := json.Unmarshal(body, &out); err != nil || out.Channel == "" { |
| + return "", errors.New("canary retire: unreadable response") |
| + } |
| + return out.Channel, nil |
| +} |
| + |
| +// systemChannelRetire asks the console to retire channel of acct/app, an |
| +// app the console has no row for (the operator door). |
| +func (s *apiSession) systemChannelRetire(ctx context.Context, acct, app, channel string) error { |
| + status, body, err := s.postJSON(ctx, "/api/cli/system/channels/retire", |
| + map[string]string{"account": acct, "app": app, "channel": channel}) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return apiErrorFromBody(status, body) |
| + } |
| + return nil |
| +} |
| + |
| +// runCanaryRetire is `carlos canary retire --app <a> --name <n>`: the |
| +// console's Retire button, from the CLI. canary rm deletes the instance; |
| +// this deletes the channel it followed, once nothing does. |
| +func runCanaryRetire(args []string) error { |
| + fs := flag.NewFlagSet("canary retire", flag.ExitOnError) |
| + app := appFlag(fs, "app the canary belongs to") |
| + name := fs.String("name", "", "canary to retire") |
| + acctRaw, acctIDRaw, _ := accountFlags(fs) |
| + consoleFlag := consoleOption(fs, "console to retire through (default: the only logged-in one)") |
| + fs.Usage = flagUsage(fs, canaryUsage) |
| + fs.Parse(args) |
| + canary := strings.TrimSpace(*name) |
| + if canary == "" || fs.NArg() != 0 { |
| + return errors.New(textCanaryRetireNeedName + "\n\n" + canaryUsage) |
| + } |
| + sess, err := resolveMode(*consoleFlag) |
| + if err != nil { |
| + return err |
| + } |
| + if sess == nil { |
| + return fmt.Errorf(textRetireNeedsConsole, "canary retire") |
| + } |
| + printUsing(stdout, sess) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + app2 := resolvedApp(sess, acct, *app, canaryUsage) |
| + channel, err := sess.canaryRetire(context.Background(), acct, app2, canary) |
| + if err != nil { |
| + return err |
| + } |
| + fmt.Fprintf(stdout, "%s %s\n", colorFor(stdout).ok("retired"), channel) |
| + mutedf(stdout, textCanaryRetired, channel) |
| + return nil |
| +} |
| + |
| +// runChannelsRetire is `carlos channels retire --account-id <sqid> --app |
| +// <a> canary/<name>`: a platform operator retires a canary pointer of an |
| +// app the console has no row for (the repair listing names such a line "no |
| +// app on this console"). The console refuses an app it has, one in the |
| +// trash, one with instance records, and any channel outside canary/*. |
| +func runChannelsRetire(args []string) error { |
| + fs := flag.NewFlagSet("channels retire", flag.ExitOnError) |
| + acct := fs.String("account-id", "", "the account's sqid, as the repair listing prints it") |
| + app := fs.String("app", "", "the app, as the repair listing prints it") |
| + consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)") |
| + fs.Usage = flagUsage(fs, "") |
| + fs.Parse(args) |
| + if *acct == "" || *app == "" || fs.NArg() != 1 { |
| + return errors.New(textChannelsRetireUsage) |
| + } |
| + channel := fs.Arg(0) |
| + sess, err := resolveMode(*consoleFlag) |
| + if err != nil { |
| + return err |
| + } |
| + if sess == nil { |
| + return fmt.Errorf(textRetireNeedsConsole, "channels retire") |
| + } |
| + printUsing(stdout, sess) |
| + if err := sess.systemChannelRetire(context.Background(), *acct, *app, channel); err != nil { |
| + return err |
| + } |
| + fmt.Fprintf(stdout, "%s %s\n", colorFor(stdout).ok("retired"), channel) |
| + mutedf(stdout, textChannelsRetired, channel, *acct, *app) |
| + return nil |
| +} |
diff --git a/canary_retire_test.go b/canary_retire_test.go| new file mode 100644 |
| index 000000000..5185cb18e |
| --- /dev/null |
| +++ b/canary_retire_test.go |
| @@ -0,0 +1,149 @@ |
| +package main |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// `carlos canary retire` posts the name to the member door and prints the |
| +// channel the console retired; a refusal comes back as the command's error, |
| +// in the console's words, and prints no success line. |
| +func TestCanaryRetireAPIMode(t *testing.T) { |
| + useTempCredentials(t) |
| + clearDeploymentEnv(t) |
| + path := "/api/cli/apps/" + apiTestAccount + "/shop/canary/retire" |
| + var posted []map[string]string |
| + refuse := false |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != path || r.Method != http.MethodPost { |
| + t.Errorf("request = %s %s", r.Method, r.URL.Path) |
| + } |
| + var b map[string]string |
| + json.NewDecoder(r.Body).Decode(&b) |
| + posted = append(posted, b) |
| + if refuse { |
| + w.WriteHeader(http.StatusConflict) |
| + json.NewEncoder(w).Encode(map[string]string{"error": "canary rc still has a host (eu.shop.example.com) following it"}) |
| + return |
| + } |
| + json.NewEncoder(w).Encode(map[string]string{"result": "retired", "channel": "canary/rc"}) |
| + })) |
| + defer ts.Close() |
| + loginTo(t, ts.URL, "vicky@keymail.dev") |
| + out := captureStdout(t) |
| + |
| + if err := runCanaryRetire([]string{"--app", "shop", "--account", apiTestAccount, "--name", "rc"}); err != nil { |
| + t.Fatalf("retire: %v", err) |
| + } |
| + if len(posted) != 1 || posted[0]["name"] != "rc" { |
| + t.Fatalf("posted %v", posted) |
| + } |
| + if want := fmt.Sprintf(textCanaryRetired, "canary/rc"); !strings.Contains(out.String(), want) { |
| + t.Fatalf("output lacks %q:\n%s", want, out.String()) |
| + } |
| + |
| + out.Reset() |
| + refuse = true |
| + err := runCanaryRetire([]string{"--app", "shop", "--account", apiTestAccount, "--name", "rc"}) |
| + if err == nil || !strings.Contains(err.Error(), "still has a host (eu.shop.example.com)") { |
| + t.Fatalf("a refused retire = %v", err) |
| + } |
| + if strings.Contains(out.String(), "retired") { |
| + t.Fatalf("a refused retire printed success:\n%s", out.String()) |
| + } |
| + |
| + posted = nil |
| + if err := runCanaryRetire([]string{"--app", "shop", "--account", apiTestAccount}); err == nil || !strings.Contains(err.Error(), textCanaryRetireNeedName) { |
| + t.Fatalf("retire with no --name = %v", err) |
| + } |
| + if len(posted) != 0 { |
| + t.Fatalf("retire with no --name posted %v", posted) |
| + } |
| +} |
| + |
| +// Direct bucket mode has no console to check followers, so both verbs |
| +// refuse rather than touch the bucket. |
| +func TestRetireVerbsRefuseDirectBucketMode(t *testing.T) { |
| + useTempCredentials(t) |
| + clearDeploymentEnv(t) |
| + t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| + if err := runCanaryRetire([]string{"--app", "shop", "--name", "rc"}); err == nil || !strings.Contains(err.Error(), "direct bucket mode") { |
| + t.Fatalf("canary retire in direct bucket mode = %v", err) |
| + } |
| + if err := runChannelsRetire([]string{"--account-id", "bab", "--app", "old", "canary/rc"}); err == nil || !strings.Contains(err.Error(), "direct bucket mode") { |
| + t.Fatalf("channels retire in direct bucket mode = %v", err) |
| + } |
| +} |
| + |
| +// `carlos channels retire` posts account, app and channel to the operator |
| +// door, exactly as the repair listing's line names them. |
| +func TestChannelsRetireAPIMode(t *testing.T) { |
| + useTempCredentials(t) |
| + clearDeploymentEnv(t) |
| + var posted map[string]string |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/api/cli/system/channels/retire" || r.Method != http.MethodPost { |
| + t.Errorf("request = %s %s", r.Method, r.URL.Path) |
| + } |
| + json.NewDecoder(r.Body).Decode(&posted) |
| + json.NewEncoder(w).Encode(map[string]string{"result": "retired", "channel": "canary/old"}) |
| + })) |
| + defer ts.Close() |
| + loginTo(t, ts.URL, "vicky@keymail.dev") |
| + out := captureStdout(t) |
| + |
| + if err := runChannelsRetire([]string{"--account-id", "bab", "--app", "old", "canary/old"}); err != nil { |
| + t.Fatalf("retire: %v", err) |
| + } |
| + want := map[string]string{"account": "bab", "app": "old", "channel": "canary/old"} |
| + if fmt.Sprint(posted) != fmt.Sprint(want) { |
| + t.Fatalf("posted %v, want %v", posted, want) |
| + } |
| + if line := fmt.Sprintf(textChannelsRetired, "canary/old", "bab", "old"); !strings.Contains(out.String(), line) { |
| + t.Fatalf("output lacks %q:\n%s", line, out.String()) |
| + } |
| + posted = nil |
| + for _, args := range [][]string{ |
| + {"--app", "old", "canary/old"}, |
| + {"--account-id", "bab", "canary/old"}, |
| + {"--account-id", "bab", "--app", "old"}, |
| + } { |
| + if err := runChannelsRetire(args); err == nil || err.Error() != textChannelsRetireUsage { |
| + t.Fatalf("channels retire %v = %v, want the usage", args, err) |
| + } |
| + } |
| + if posted != nil { |
| + t.Fatalf("an incomplete retire posted %v", posted) |
| + } |
| +} |
| + |
| +// The repair listing names the operator door for a canary head of an app |
| +// the console has no row for, and only for that: a record line or a |
| +// non-canary head of such an app keeps its repair. |
| +func TestRepairCellNamesTheRetireForNoAppCanaries(t *testing.T) { |
| + head := apiDigestRepair{Account: "bab", App: "old", Channel: "canary/rc", Version: "v1", NoRecord: true, NoApp: true} |
| + if got, want := repairCell(head), fmt.Sprintf(textRepairNoApp, "bab", "old", "canary/rc"); got != want { |
| + t.Fatalf("no-app canary head = %q, want %q", got, want) |
| + } |
| + if !strings.HasPrefix(repairCell(head), "no app on this console: carlos channels retire --account-id bab --app old canary/rc") { |
| + t.Fatalf("the line does not name the command to run: %q", repairCell(head)) |
| + } |
| + stable := head |
| + stable.Channel = "stable" |
| + if got := repairCell(stable); got != textRepairNoRecord { |
| + t.Fatalf("no-app stable head = %q, want the ordinary repair", got) |
| + } |
| + rec := apiDigestRepair{Account: "bab", App: "old", Version: "v1", Record: true, NoApp: true} |
| + if got := repairCell(rec); got != textRepairRecordUnbound { |
| + t.Fatalf("no-app record line = %q, want the ordinary repair", got) |
| + } |
| + live := head |
| + live.NoApp = false |
| + if got := repairCell(live); got != textRepairNoRecord { |
| + t.Fatalf("a canary head of an app with a row = %q", got) |
| + } |
| +} |
diff --git a/channels_digests.go b/channels_digests.go| index 6df405694..9aa3a9bf4 100644 |
| --- a/channels_digests.go |
| +++ b/channels_digests.go |
| @@ -63,6 +63,10 @@ const ( |
| textRepairUnknown = "this console does not list repairs: upgrade it, or ask the bucket directly" |
| ) |
| +// A canary head of an app the console has no row for (#1634). Not yet |
| +// through copy review. |
| +const textRepairNoApp = "no app on this console: carlos channels retire --account-id %s --app %s %s" |
| + |
| // apiDigestRepair is a channel whose head a fresh or replaced box would |
| // refuse: Unbound (not bound to its account: the pointer names none, or the |
| // key grant it was signed under names none) or NoRecord (no digest and no |
| @@ -86,6 +90,10 @@ type apiDigestRepair struct { |
| NoBuild bool `json:"no_build,omitempty"` |
| Grant string `json:"grant,omitempty"` |
| GrantMintedAt string `json:"grant_minted_at,omitempty"` |
| + // NoApp is a line of an app the console has no row for, live or in the |
| + // trash (#1634); an older console, and the direct-store report, never |
| + // set it. |
| + NoApp bool `json:"no_app,omitempty"` |
| } |
| // apiPointerDigests is the pointer-digest report: the console's, or one |
| @@ -102,8 +110,14 @@ type apiPointerDigests struct { |
| // account first, since an unbound pointer is refused before its bytes are. |
| // A record is repaired by authorizing its version: promoting a head's |
| // version again writes no record. |
| +// |
| +// A canary head of an app the console has no row for names the operator |
| +// door that retires it instead: nobody can promote or authorize for an app |
| +// with no row, and a canary nothing follows needs no repair, only removing. |
| func repairCell(r apiDigestRepair) string { |
| switch { |
| + case r.NoApp && !r.Record && strings.HasPrefix(r.Channel, release.RungCanary+"/"): |
| + return fmt.Sprintf(textRepairNoApp, r.Account, r.App, r.Channel) |
| case r.Record && r.Unread: |
| return fmt.Sprintf(textRepairRecordRetry, r.Error) |
| case r.Record && r.NoBuild: |
diff --git a/commands.go b/commands.go| index 20777fdfc..62763010b 100644 |
| --- a/commands.go |
| +++ b/commands.go |
| @@ -303,9 +303,9 @@ func runRegistryChildTop(args []string) { |
| } |
| } |
| -// channelsCommand is `carlos channels`, moved from main's switch: two |
| -// sub-verbs, resign and digests (#253), and bare `carlos channels` (any |
| -// other word or flag too) still lists, the `carlos releases retention` |
| +// channelsCommand is `carlos channels`, moved from main's switch: three |
| +// sub-verbs, resign and digests (#253) and retire (#1634), and bare |
| +// `carlos channels` (any other word or flag too) still lists, the `carlos releases retention` |
| // precedent. The sub-verbs returned from main() before the update hint, so |
| // they skip it. |
| func channelsCommand() *clireg.Node { |
| @@ -318,6 +318,8 @@ func channelsCommand() *clireg.Node { |
| // digests' on|off counts only as its first argument |
| // (runChannelsDigests): an enum positional of this raw leaf. |
| noHint(rawErr("digests", clireg.Operator, runChannelsDigests)), |
| + // retire: a canary pointer of an app with no console row (#1634). |
| + noHint(rawErr("retire", clireg.Operator, runChannelsRetire)), |
| }, |
| DefaultLeaf: &clireg.Node{Audience: cust, Run: clireg.RawArgs(runChannels)}, |
| DefaultOn: clireg.OnAbsent | clireg.OnFlag | clireg.OnWord, |
diff --git a/internal/console/apidigests.go b/internal/console/apidigests.go| index 1c3cff878..072f3f6b0 100644 |
| --- a/internal/console/apidigests.go |
| +++ b/internal/console/apidigests.go |
| @@ -307,6 +307,11 @@ type digestRepRow struct { |
| NoBuild bool `json:"no_build,omitempty"` |
| Grant string `json:"grant,omitempty"` |
| GrantMintedAt string `json:"grant_minted_at,omitempty"` |
| + // NoApp is a line of an app this console has no row for, live or in |
| + // the trash: shipped straight to the bucket and never adopted, or left |
| + // by a purge that did not finish (#1634). The CLI names the operator |
| + // door that retires such an app's canary pointers. |
| + NoApp bool `json:"no_app,omitempty"` |
| } |
| // grantMinted is a grant's mint time on the wire, or "" for no grant. |
| @@ -343,7 +348,9 @@ func (s *Server) walkDigestAccount(ctx context.Context, sqid string, bucketOnly |
| row.Error = fmt.Sprintf(textBucketListApps, sqid, err) |
| return wk |
| } |
| + noApp := s.digestNoApp(ctx, sqid, bucketOnly) |
| for _, app := range apps { |
| + orphan := noApp(app) |
| states, _, err := release.DigestReport(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app) |
| if err != nil { |
| row.Error = err.Error() |
| @@ -365,7 +372,7 @@ func (s *Server) walkDigestAccount(ctx context.Context, sqid string, bucketOnly |
| } |
| if st.Err == "" && st.NeedsRepair() { |
| wk.repairs = append(wk.repairs, digestRepRow{Account: sqid, App: app, Channel: st.Channel, Version: st.Version, Unbound: st.Unbound, NoRecord: st.NoRecord, |
| - Grant: st.Grant, GrantMintedAt: grantMinted(st.Grant, st.GrantMintedAt)}) |
| + Grant: st.Grant, GrantMintedAt: grantMinted(st.Grant, st.GrantMintedAt), NoApp: orphan}) |
| } |
| } |
| // Every record a box refuses, whichever head names its version: one |
| @@ -381,8 +388,34 @@ func (s *Server) walkDigestAccount(ctx context.Context, sqid string, bucketOnly |
| row.Error = rec.Err |
| } |
| wk.repairs = append(wk.repairs, digestRepRow{Account: sqid, App: app, Version: rec.Version, Record: true, Error: rec.Err, |
| - Unread: rec.Unread, NoBuild: rec.NoBuild, Grant: rec.Grant, GrantMintedAt: grantMinted(rec.Grant, rec.GrantMintedAt)}) |
| + Unread: rec.Unread, NoBuild: rec.NoBuild, Grant: rec.Grant, GrantMintedAt: grantMinted(rec.Grant, rec.GrantMintedAt), NoApp: orphan}) |
| } |
| } |
| return wk |
| } |
| + |
| +// digestNoApp answers, per app of the account sqid, whether this console |
| +// has no row for it, live or trashed (digestRepRow.NoApp). An account the |
| +// console does not have has no app rows. A lookup that fails answers false: |
| +// the label only adds a hint, and a wrong one would send an operator to a |
| +// door that refuses anyway. |
| +func (s *Server) digestNoApp(ctx context.Context, sqid string, bucketOnly bool) func(app string) bool { |
| + if bucketOnly { |
| + return func(string) bool { return true } |
| + } |
| + a, err := s.store.AccountBySqid(sqid) |
| + if err != nil || a == nil { |
| + if err != nil { |
| + log.Printf("console: pointer digests: account %s: %v", sqid, err) |
| + } |
| + return func(string) bool { return false } |
| + } |
| + return func(app string) bool { |
| + live, err := s.store.HasAppInContext(ctx, a.ID, app) |
| + if err != nil || live { |
| + return false |
| + } |
| + trashed, err := s.store.HasTrashedAppInContext(ctx, a.ID, app) |
| + return err == nil && !trashed |
| + } |
| +} |
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go| index a03d4c98e..135455892 100644 |
| --- a/internal/console/apilinks_test.go |
| +++ b/internal/console/apilinks_test.go |
| @@ -495,11 +495,12 @@ var linkedBodyAppDoors = map[string]string{ |
| "POST /a/{sqid}/domains/buy/check": "the app only travels on to step 2's preselection; the search writes nothing", |
| "POST /a/{sqid}/fleets/{fleet}/place": "placeAppTarget refuses a linked app with LD-C11", |
| // Cannot act on a linked app. |
| - "POST /a/{sqid}/trash/restore": "acts only on a trashed row; linked rows are never trashed", |
| - "POST /a/{sqid}/trash/delete": "acts only on a trashed row; linked rows are never trashed", |
| - "POST /a/{sqid}/services/new": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| - "POST /api/cli/services/{account}": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| - "POST /api/cli/link/publications": "the home console's own publish of a home app through its link; no serving-side app", |
| + "POST /a/{sqid}/trash/restore": "acts only on a trashed row; linked rows are never trashed", |
| + "POST /a/{sqid}/trash/delete": "acts only on a trashed row; linked rows are never trashed", |
| + "POST /a/{sqid}/services/new": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| + "POST /api/cli/services/{account}": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| + "POST /api/cli/link/publications": "the home console's own publish of a home app through its link; no serving-side app", |
| + "POST /api/cli/system/channels/retire": "acts only on an app with no row, live or trashed (orphanRefusal, asked again under the app lock); a linked app is a live row", |
| } |
| // TestLinkedPolicyCoversBodyAppDoors finds every declared non-link route |
diff --git a/internal/console/canary_retire.go b/internal/console/canary_retire.go| new file mode 100644 |
| index 000000000..5adb673bf |
| --- /dev/null |
| +++ b/internal/console/canary_retire.go |
| @@ -0,0 +1,488 @@ |
| +package console |
| + |
| +// Retiring a canary: deleting a canary/<name> channel pointer that nothing |
| +// follows (#1634). Three doors share one guard and one delete: |
| +// |
| +// - the browser's Retire button on an app's Releases tab |
| +// (handleRetireCanary); |
| +// - `carlos canary retire`, the same act for a member over the CLI API |
| +// (handleAPIRetireCanary); |
| +// - `carlos channels retire`, a platform operator's door for a canary |
| +// pointer left in the bucket under an app this console has no row for |
| +// (handleAPISystemRetireChannel): an app shipped straight to the bucket |
| +// and never adopted, or one whose purge did not finish. |
| +// |
| +// Shipped releases are never touched: a retire un-points, it never deletes |
| +// bits. Every door fails CLOSED: "could not check who follows this channel" |
| +// never reads as "nobody does". |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "maps" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The CLI doors' answers (#1634). Not yet through copy review. |
| +const ( |
| + textRetireBadName = "%q is not a canary name" |
| + textRetireBadChannel = "%q is not a canary channel: only canary/<name> channels can be retired" |
| + textRetireNoBucket = "no deployment bucket on this host, so this console cannot retire a canary" |
| + textRetireNoCanary = "%s has no canary named %s" |
| + textRetireFollowed = "canary %s still has a host (%s) following it. Delete that instance or move it to another channel, then retire the canary" |
| + textRetireUnsettled = "%s was not retired: an instance of %s changed in the last 15 minutes, a box has not reported, or the canary changed while it was checked. Nothing was deleted. Try again in 15 minutes" |
| + textRetireCheck = "could not check what follows %s, so nothing was deleted. Try again" |
| + textRetireStore = "could not read the deployment bucket, so nothing was deleted. Try again" |
| + textRetireFailed = "retiring %s failed, so it may still be there. Try again" |
| + textRetireHasApp = "%s/%s is an app on this console: carlos canary retire --account %s --app %s --name %s" |
| + textRetireTrashed = "%s/%s is in the trash: restore it and retire the canary, or let the purge remove it" |
| + textRetireHasRecords = "%s/%s still has instance records in the deployment bucket, so its channels are not retired here" |
| + textRetireActivity = "retired canary %s (cli)" |
| +) |
| + |
| +// errNoCanary is checkCanaryRetire's answer when the channel has no pointer. |
| +var errNoCanary = errors.New("no such canary") |
| + |
| +// canaryFollowedError is checkCanaryRetire's answer when a host follows the |
| +// channel: retiring the pointer would strand it. |
| +type canaryFollowedError struct{ host string } |
| + |
| +func (e *canaryFollowedError) Error() string { return "host " + e.host + " follows the channel" } |
| + |
| +// canaryPointerReadError is checkCanaryRetire's answer when the pointer |
| +// itself could not be read. |
| +type canaryPointerReadError struct{ err error } |
| + |
| +func (e *canaryPointerReadError) Error() string { return "read the canary pointer: " + e.err.Error() } |
| +func (e *canaryPointerReadError) Unwrap() error { return e.err } |
| + |
| +// canaryRetireCheck is what a retire read before any confirmation: the |
| +// app's record stamps, compared again under the app lock, and the pointer's |
| +// key and ETag, deleted only if still exactly that revision. |
| +type canaryRetireCheck struct { |
| + acct, app, channel string |
| + key, etag string |
| + before map[string]time.Time |
| +} |
| + |
| +// validRetireChannel reports whether channel is canary/<name> for a name |
| +// the store could hold: one segment, release.ValidChannel's alphabet. |
| +func validRetireChannel(channel string) bool { |
| + name, ok := strings.CutPrefix(channel, release.RungCanary+"/") |
| + return ok && name != "" && !strings.Contains(name, "/") && release.ValidChannel(channel) |
| +} |
| + |
| +// checkCanaryRetire is the guard every retire door asks first. It takes the |
| +// app's record stamps, then the channel's followers (channelHosts: the |
| +// console box's registry, every instance and sidecar record, and the settle |
| +// rule over box reports and recent changes), then reads the pointer. |
| +// |
| +// Its answers: a *canaryFollowedError, errNoCanary, a |
| +// *canaryPointerReadError, an error wrapping errRetireUnsettled, or any |
| +// other error for a check that could not be made. Every one refuses. |
| +func (s *Server) checkCanaryRetire(ctx context.Context, acct, app, channel string) (*canaryRetireCheck, error) { |
| + checkCtx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| + // The app's records as they stand before the check, compared again just |
| + // before the delete: the check itself runs without the app lock, so a |
| + // record created, changed or deleted in between refuses the retire |
| + // (recordStamps). |
| + before, err := s.recordStamps(checkCtx, acct, app) |
| + var hosts []string |
| + if err == nil { |
| + hosts, err = s.channelHosts(checkCtx, acct, app, channel) |
| + } |
| + cancel() |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(hosts) > 0 { |
| + return nil, &canaryFollowedError{host: hosts[0]} |
| + } |
| + readCtx, cancelRead := context.WithTimeout(ctx, 15*time.Second) |
| + defer cancelRead() |
| + key := release.ChannelKey(acct, app, channel) |
| + _, etag, err := s.cfg.Releases.Get(readCtx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, errNoCanary |
| + } |
| + if err != nil { |
| + return nil, &canaryPointerReadError{err: err} |
| + } |
| + return &canaryRetireCheck{acct: acct, app: app, channel: channel, key: key, etag: etag, before: before}, nil |
| +} |
| + |
| +// deleteRetiredCanary deletes the pointer c read, under the app lock, inside |
| +// mutate (the door's app mutation). recheck, when not nil, runs under the |
| +// lock first: the operator door asks there again that the app has no row. |
| +// A change to the app's records or to the pointer since the check is an |
| +// error wrapping errRetireUnsettled, and nothing is deleted. |
| +func (s *Server) deleteRetiredCanary(ctx context.Context, c *canaryRetireCheck, mutate func(context.Context, func(context.Context) error) error, recheck func(context.Context) error) error { |
| + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| + defer cancel() |
| + // The app lock from the re-list through the delete: every console |
| + // record write holds it too (recordlock.go), so a follower created or |
| + // moved onto this channel lands before the re-list, which refuses, or |
| + // after the pointer is gone (#407). |
| + unlockApp := s.lockApp(c.acct, c.app) |
| + defer unlockApp() |
| + return mutate(ctx, func(ctx context.Context) error { |
| + if h := s.retireBeforeDeleteHook; h != nil { |
| + h() |
| + } |
| + if recheck != nil { |
| + if err := recheck(ctx); err != nil { |
| + return err |
| + } |
| + } |
| + after, err := s.recordStamps(ctx, c.acct, c.app) |
| + if err != nil { |
| + return err |
| + } |
| + if !maps.Equal(c.before, after) { |
| + return fmt.Errorf("%w: the app's records changed during the check", errRetireUnsettled) |
| + } |
| + // The pointer must still be the one read above: a promotion or a |
| + // removal meanwhile refuses. |
| + if _, cur, gerr := s.cfg.Releases.Get(ctx, c.key); gerr != nil || cur != c.etag { |
| + if gerr != nil && !errors.Is(gerr, os.ErrNotExist) { |
| + return gerr |
| + } |
| + return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| + } |
| + // Delete exactly the pointer read above: a promotion since then |
| + // conflicts, and the retire is refused rather than deleting bytes |
| + // this check never saw. |
| + if err := release.DeleteIfMatch(ctx, s.cfg.Releases, c.key, c.etag); err != nil { |
| + if errors.Is(err, release.ErrCASConflict) { |
| + return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| + } |
| + return err |
| + } |
| + // No console record write lands between the comparison above and |
| + // this delete: each holds the app lock held here. One that waited |
| + // lands after it, on a channel with no pointer: the same as creating |
| + // an instance on a channel nobody has promoted, which the create |
| + // door allows. No restore is attempted: the store cannot tell |
| + // "deleted the revision read" from "already gone", so putting bytes |
| + // back could resurrect a pointer someone else removed. |
| + return nil |
| + }) |
| +} |
| + |
| +// appRetireMutation is deleteRetiredCanary's mutate for an app this console |
| +// has: the door's ordinary app mutation. |
| +func (s *Server) appRetireMutation(acct *Account, app string) func(context.Context, func(context.Context) error) error { |
| + return func(ctx context.Context, fn func(context.Context) error) error { |
| + return s.appMutation(ctx, acct, app, "canary-retire", fn) |
| + } |
| +} |
| + |
| +// orphanRetireMutation is deleteRetiredCanary's mutate for an app this |
| +// console has no row for: no demo claim can hold an app with no row, so |
| +// the bucket's app mutation alone, as the relay's per-app walks take it. |
| +func (s *Server) orphanRetireMutation(acct, app string) func(context.Context, func(context.Context) error) error { |
| + return func(ctx context.Context, fn func(context.Context) error) error { |
| + return release.WithAppMutation(ctx, s.cfg.Releases, acct, app, "canary-retire-orphan", fn) |
| + } |
| +} |
| + |
| +// handleRetireCanary removes a canary's channel pointer from the browser. |
| +// Shipped releases are untouched: retirement un-points, it never deletes |
| +// bits. |
| +func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, acct, role, app, ok := s.accountApp(w, r) |
| + if !ok { |
| + return |
| + } |
| + if !csrfFormOK(r, raw) { |
| + s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| + return |
| + } |
| + if s.refuseAppNoBucket(w, r) { |
| + return |
| + } |
| + if s.cfg.Key == nil { |
| + s.renderMessage(w, r, http.StatusServiceUnavailable, "Promotions disabled", |
| + "No signing key on this host — the console is running read-only.") |
| + return |
| + } |
| + back := func(kind, msg string) { |
| + s.setFlash(w, kind, msg) |
| + dest := "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) |
| + if tab := releaseBackTab(r); tab != "" { |
| + dest += "/" + tab |
| + } |
| + http.Redirect(w, r, dest, http.StatusSeeOther) |
| + } |
| + name := strings.ToLower(strings.TrimSpace(r.FormValue("name"))) |
| + if !canaryNameRe.MatchString(name) { |
| + back("err", "Invalid canary name.") |
| + return |
| + } |
| + channel := "canary/" + name |
| + // A canary with followers is load-bearing: retiring its pointer would |
| + // strand every host on it. Fail CLOSED on a registry error: an "I |
| + // couldn't check" must never be read as "nobody follows this channel". |
| + chk, err := s.checkCanaryRetire(r.Context(), acct.Sqid, app, channel) |
| + var followed *canaryFollowedError |
| + var readErr *canaryPointerReadError |
| + switch { |
| + case err == nil: |
| + case errors.Is(err, errRetireUnsettled): |
| + // Nobody follows the channel by any record, but the app changed too |
| + // recently (or a box still serves a host with no record) for that |
| + // to be the whole story yet. |
| + log.Printf("console: retire %s %s: %v", app, channel, err) |
| + back("err", "Could not verify no hosts follow this channel — try again.") |
| + return |
| + case errors.As(err, &followed): |
| + back("err", "Canary "+name+" still has a host ("+followed.host+") following it — remove or repoint that route first.") |
| + return |
| + case errors.Is(err, errNoCanary): |
| + back("err", "No canary named "+name+" here.") |
| + return |
| + case errors.As(err, &readErr): |
| + back("err", "Could not read the release store. Please try again.") |
| + return |
| + default: |
| + log.Printf("console: retire %s %s: check followers: %v", app, channel, err) |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", |
| + "Could not verify no hosts follow this channel — try again.") |
| + return |
| + } |
| + if !confirmed(r) { |
| + s.confirmRetireCanary(w, r, addr, raw, acct, role, app, name) |
| + return |
| + } |
| + err = s.deleteRetiredCanary(r.Context(), chk, s.appRetireMutation(acct, app), nil) |
| + if errors.Is(err, errRetireUnsettled) { |
| + log.Printf("console: retire %s %s: %v", app, channel, err) |
| + back("err", "Could not verify no hosts follow this channel — try again.") |
| + return |
| + } |
| + if err != nil { |
| + log.Printf("console: retire %s %s: %v", app, channel, err) |
| + back("err", "Retiring the canary failed: "+err.Error()) |
| + return |
| + } |
| + s.auditActivity(acct, app, addr, Activity{Action: "canary-retire", TargetType: "channel", Target: "canary/" + name, Detail: "retired canary " + name}) |
| + back("ok", "Retired canary "+name+" — its channel pointer is gone; shipped releases are untouched.") |
| +} |
| + |
| +// writeRetireRefusal answers a CLI door's refused check or delete, and |
| +// reports whether err was one (nil is not). |
| +func writeRetireRefusal(w http.ResponseWriter, err error, acct, app, channel string) bool { |
| + var followed *canaryFollowedError |
| + var readErr *canaryPointerReadError |
| + name := strings.TrimPrefix(channel, release.RungCanary+"/") |
| + switch { |
| + case err == nil: |
| + return false |
| + case errors.As(err, &followed): |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(textRetireFollowed, name, followed.host)) |
| + case errors.Is(err, errRetireUnsettled): |
| + log.Printf("console: api retire %s/%s %s: %v", acct, app, channel, err) |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(textRetireUnsettled, channel, app)) |
| + case errors.Is(err, errNoCanary): |
| + jsonError(w, http.StatusNotFound, fmt.Sprintf(textRetireNoCanary, app, name)) |
| + case errors.As(err, &readErr): |
| + log.Printf("console: api retire %s/%s %s: %v", acct, app, channel, err) |
| + jsonError(w, http.StatusBadGateway, textRetireStore) |
| + default: |
| + log.Printf("console: api retire %s/%s %s: %v", acct, app, channel, err) |
| + jsonError(w, http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, channel)) |
| + } |
| + return true |
| +} |
| + |
| +// handleAPIRetireCanary is POST /api/cli/apps/{account}/{app}/canary/retire, |
| +// `carlos canary retire` (#1634): the browser's Retire for a member over the |
| +// CLI. It is closed to service credentials, like resign: deleting a pointer |
| +// is a person's act. The body names the canary ({"name": "x"} for |
| +// canary/x); the console checks and deletes in one request, since the CLI |
| +// has no confirmation card and the guard refuses while anything follows. |
| +func (s *Server) handleAPIRetireCanary(w http.ResponseWriter, r *http.Request) { |
| + addr, acct, app, ok := s.apiAccountApp(w, r) |
| + if !ok { |
| + return |
| + } |
| + p, _ := principalFrom(r.Context()) |
| + if !s.allowWrite(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, textTooManyRequests) |
| + return |
| + } |
| + var req struct { |
| + Name string `json:"name"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + channel := release.RungCanary + "/" + req.Name |
| + if !validRetireChannel(channel) { |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(textRetireBadName, req.Name)) |
| + return |
| + } |
| + if s.cfg.Releases == nil { |
| + jsonError(w, http.StatusServiceUnavailable, textRetireNoBucket) |
| + return |
| + } |
| + if len(s.cfg.Key) == 0 { |
| + jsonError(w, http.StatusServiceUnavailable, textNoReleaseKey) |
| + return |
| + } |
| + chk, err := s.checkCanaryRetire(r.Context(), acct.Sqid, app, channel) |
| + if writeRetireRefusal(w, err, acct.Sqid, app, channel) { |
| + return |
| + } |
| + err = s.deleteRetiredCanary(r.Context(), chk, s.appRetireMutation(acct, app), nil) |
| + if errors.Is(err, errRetireUnsettled) { |
| + writeRetireRefusal(w, err, acct.Sqid, app, channel) |
| + return |
| + } |
| + if err != nil { |
| + log.Printf("console: api retire %s/%s %s: %v", acct.Sqid, app, channel, err) |
| + jsonError(w, http.StatusBadGateway, fmt.Sprintf(textRetireFailed, channel)) |
| + return |
| + } |
| + s.auditActivity(acct, app, addr, Activity{Action: "canary-retire", TargetType: "channel", Target: channel, |
| + Detail: fmt.Sprintf(textRetireActivity, req.Name)}) |
| + writeJSON(w, http.StatusOK, map[string]string{"result": "retired", "channel": channel}) |
| +} |
| + |
| +// errNoAppRow is the operator door's recheck failing: the app gained a |
| +// console row, a trash marker or a record while the retire was checked. |
| +var errNoAppRow = errors.New("the app is no longer without a row") |
| + |
| +// orphanRefusal is the operator door's precondition: acct/app has no live |
| +// or trashed console row, no trash marker and no instance or sidecar |
| +// record. It answers the refusal's status and sentence, or 0 when the app |
| +// is an orphan. Anything it cannot read refuses. |
| +func (s *Server) orphanRefusal(ctx context.Context, acct, app, name string) (int, string, error) { |
| + a, err := s.store.AccountBySqid(acct) |
| + if err != nil { |
| + return http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, release.RungCanary+"/"+name), err |
| + } |
| + if a != nil { |
| + live, err := s.store.HasAppInContext(ctx, a.ID, app) |
| + if err != nil { |
| + return http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, release.RungCanary+"/"+name), err |
| + } |
| + if live { |
| + return http.StatusConflict, fmt.Sprintf(textRetireHasApp, acct, app, acct, app, name), nil |
| + } |
| + trashed, err := s.store.HasTrashedAppInContext(ctx, a.ID, app) |
| + if err != nil { |
| + return http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, release.RungCanary+"/"+name), err |
| + } |
| + if trashed { |
| + return http.StatusConflict, fmt.Sprintf(textRetireTrashed, acct, app), nil |
| + } |
| + } |
| + tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, acct, app) |
| + if err != nil { |
| + return http.StatusBadGateway, textRetireStore, err |
| + } |
| + if tomb != nil { |
| + return http.StatusConflict, fmt.Sprintf(textRetireTrashed, acct, app), nil |
| + } |
| + stamps, err := s.recordStamps(ctx, acct, app) |
| + if err != nil { |
| + return http.StatusBadGateway, textRetireStore, err |
| + } |
| + if len(stamps) > 0 { |
| + return http.StatusConflict, fmt.Sprintf(textRetireHasRecords, acct, app), nil |
| + } |
| + return 0, "", nil |
| +} |
| + |
| +// handleAPISystemRetireChannel is POST /api/cli/system/channels/retire, |
| +// `carlos channels retire --account-id <sqid> --app <a> canary/<name>` |
| +// (#1634): a platform operator retires a canary pointer of an app this |
| +// console has no row for, which no member door can reach. canary/* only: a |
| +// bucket-only app's other channels may still be served by hand routes, |
| +// and retiring those is not what this door is for. |
| +// |
| +// It refuses an app with a live or trashed console row (the member door |
| +// and the trash own those), a trash marker in the bucket, any instance or |
| +// sidecar record, and any follower by registry or box report (the same |
| +// guard as the member door, whose box-report rule sees hand routes). It |
| +// asks the row and marker again under the app lock, deletes with CAS, and |
| +// writes a platform audit row. |
| +func (s *Server) handleAPISystemRetireChannel(w http.ResponseWriter, r *http.Request) { |
| + addr, _, ok := s.apiSystemRoller(w, r) |
| + if !ok { |
| + return |
| + } |
| + if !s.systemBucket(w) { |
| + return |
| + } |
| + p, _ := principalFrom(r.Context()) |
| + if !s.allowWrite(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, textTooManyRequests) |
| + return |
| + } |
| + var req struct { |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Channel string `json:"channel"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + if !release.ValidAccount(req.Account) || !release.ValidApp(req.App) { |
| + jsonError(w, http.StatusBadRequest, "name an account sqid and an app") |
| + return |
| + } |
| + if !validRetireChannel(req.Channel) { |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(textRetireBadChannel, req.Channel)) |
| + return |
| + } |
| + if len(s.cfg.Key) == 0 { |
| + jsonError(w, http.StatusServiceUnavailable, textNoReleaseKey) |
| + return |
| + } |
| + acct, app, channel := req.Account, req.App, req.Channel |
| + name := strings.TrimPrefix(channel, release.RungCanary+"/") |
| + ctx := r.Context() |
| + if status, msg, err := s.orphanRefusal(ctx, acct, app, name); status != 0 { |
| + if err != nil { |
| + log.Printf("console: api system retire %s/%s %s: %v", acct, app, channel, err) |
| + } |
| + jsonError(w, status, msg) |
| + return |
| + } |
| + chk, err := s.checkCanaryRetire(ctx, acct, app, channel) |
| + if writeRetireRefusal(w, err, acct, app, channel) { |
| + return |
| + } |
| + mutate := s.orphanRetireMutation(acct, app) |
| + recheck := func(ctx context.Context) error { |
| + if status, _, err := s.orphanRefusal(ctx, acct, app, name); status != 0 { |
| + if err != nil { |
| + return err |
| + } |
| + return fmt.Errorf("%w: %w", errRetireUnsettled, errNoAppRow) |
| + } |
| + return nil |
| + } |
| + err = s.deleteRetiredCanary(ctx, chk, mutate, recheck) |
| + if errors.Is(err, errRetireUnsettled) { |
| + writeRetireRefusal(w, err, acct, app, channel) |
| + return |
| + } |
| + if err != nil { |
| + log.Printf("console: api system retire %s/%s %s: %v", acct, app, channel, err) |
| + jsonError(w, http.StatusBadGateway, fmt.Sprintf(textRetireFailed, channel)) |
| + return |
| + } |
| + s.auditSystem(addr, "canary-retire-orphan", fmt.Sprintf("retired %s of %s/%s, an app with no row on this console (cli)", channel, acct, app)) |
| + writeJSON(w, http.StatusOK, map[string]string{"result": "retired", "channel": channel}) |
| +} |
diff --git a/internal/console/canary_retire_test.go b/internal/console/canary_retire_test.go| new file mode 100644 |
| index 000000000..d76ed4dff |
| --- /dev/null |
| +++ b/internal/console/canary_retire_test.go |
| @@ -0,0 +1,307 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// The CLI retire doors (#1634): `carlos canary retire` for a member, and |
| +// `carlos channels retire` for an operator retiring a canary pointer of an |
| +// app the console has no row for. |
| + |
| +func retireURL(tb *twoBoxes, app string) string { |
| + return tb.fx.ts.URL + "/api/cli/apps/" + tb.sqid + "/" + app + "/canary/retire" |
| +} |
| + |
| +func orphanRetireURL(tb *twoBoxes) string { |
| + return tb.fx.ts.URL + "/api/cli/system/channels/retire" |
| +} |
| + |
| +func pointerExists(t *testing.T, tb *twoBoxes, app, channel string) bool { |
| + t.Helper() |
| + _, _, err := tb.fx.rel.Get(context.Background(), release.ChannelKey(tb.sqid, app, channel)) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + return err == nil |
| +} |
| + |
| +// settledApp leaves shop with one instance on stable on box B, reported and |
| +// older than the settle window, so a retire's guard can say "nobody". |
| +func settledApp(t *testing.T, tb *twoBoxes) { |
| + t.Helper() |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| +} |
| + |
| +// The member door: refused while a host follows the canary, refused while |
| +// the app has not settled, then it deletes the pointer and only the |
| +// pointer, writes the activity row, and a second retire is a 404. |
| +func TestAPIRetireCanary(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v5", "canary/next") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + |
| + status, _, out := rawReq(t, http.MethodPost, retireURL(tb, "shop"), tb.token, `{"name":"rc"}`) |
| + if status != http.StatusConflict || !strings.Contains(out, "still has a host ("+remoteHost+") following it") { |
| + t.Fatalf("retire with a remote follower = %d %s", status, out) |
| + } |
| + if !pointerExists(t, tb, "shop", "canary/rc") { |
| + t.Fatal("a followed canary was retired") |
| + } |
| + |
| + // Moved off the canary just now: no record names it, but the app has |
| + // not been still for the window. |
| + if status, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, tb.sqid, "shop")+"/"+remoteHost+"/channel", tb.token, |
| + `{"channel":"canary/next"}`); status != http.StatusOK { |
| + t.Fatalf("channel move = %d %s", status, out) |
| + } |
| + if err := tb.regB.SetVersions(remoteHost, "v5", "v4"); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + status, _, out = rawReq(t, http.MethodPost, retireURL(tb, "shop"), tb.token, `{"name":"rc"}`) |
| + if status != http.StatusConflict || !strings.Contains(out, "Nothing was deleted") || !pointerExists(t, tb, "shop", "canary/rc") { |
| + t.Fatalf("retire right after a channel change = %d %s", status, out) |
| + } |
| + |
| + ageRecords(t, tb) |
| + status, _, out = rawReq(t, http.MethodPost, retireURL(tb, "shop"), tb.token, `{"name":"rc"}`) |
| + if status != http.StatusOK || !strings.Contains(out, `"channel":"canary/rc"`) { |
| + t.Fatalf("retire once the app was still = %d %s", status, out) |
| + } |
| + if pointerExists(t, tb, "shop", "canary/rc") { |
| + t.Fatal("the canary pointer is still there") |
| + } |
| + if _, err := release.GetManifest(context.Background(), tb.fx.rel, tb.sqid, "shop", "v4"); err != nil { |
| + t.Fatalf("retire touched a shipped release: %v", err) |
| + } |
| + ev, err := tb.fx.st.Events(5151, "shop", 10) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(ev) == 0 || ev[0].Action != "canary-retire" { |
| + t.Fatalf("no canary-retire activity row: %+v", ev) |
| + } |
| + |
| + status, _, out = rawReq(t, http.MethodPost, retireURL(tb, "shop"), tb.token, `{"name":"rc"}`) |
| + if status != http.StatusNotFound || !strings.Contains(out, "shop has no canary named rc") { |
| + t.Fatalf("retire of a canary that is gone = %d %s", status, out) |
| + } |
| + for _, bad := range []string{``, `a/b`, `..`, `has space`} { |
| + body, _ := json.Marshal(map[string]string{"name": bad}) |
| + if status, _, out := rawReq(t, http.MethodPost, retireURL(tb, "shop"), tb.token, string(body)); status != http.StatusBadRequest { |
| + t.Fatalf("retire of name %q = %d %s, want 400", bad, status, out) |
| + } |
| + } |
| +} |
| + |
| +// A record that will not read could be a follower: the member door fails |
| +// closed with a 500, and the pointer stays. |
| +func TestAPIRetireCanaryFailsClosed(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + settledApp(t, tb) |
| + if _, err := tb.fx.rel.Put(context.Background(), provision.RecordKey(tb.sqid, "shop", "broken.shop.example.com"), []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, _, out := rawReq(t, http.MethodPost, retireURL(tb, "shop"), tb.token, `{"name":"rc"}`) |
| + if status != http.StatusInternalServerError || !strings.Contains(out, "nothing was deleted") { |
| + t.Fatalf("retire with an unreadable record = %d %s", status, out) |
| + } |
| + if !pointerExists(t, tb, "shop", "canary/rc") { |
| + t.Fatal("the pointer went although the check could not be made") |
| + } |
| +} |
| + |
| +// The operator door: an app with no console row ("old", shipped straight |
| +// to the bucket) loses its canary pointer only when no box reports a host |
| +// of it (a hand route), and then only that pointer; the platform audit |
| +// names it. |
| +func TestAPISystemRetireChannel(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "canary/rc") |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "stable") |
| + body := `{"account":"` + tb.sqid + `","app":"old","channel":"canary/rc"}` |
| + |
| + // A hand route of "old" on box B, which no record names: the box |
| + // report holds the retire. |
| + if err := tb.regB.Upsert(registry.Route{Host: "hand.old.example.com", Kind: "instance", App: "old", Account: tb.sqid, |
| + Channel: "canary/rc", Version: "v1", Provisioned: true, Hibernate: true, Status: "ready", |
| + Socket: "/run/carlos/hand-old.sock"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, body) |
| + if status != http.StatusConflict || !strings.Contains(out, "a box has not reported") || !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatalf("orphan retire with a hand route on box B = %d %s", status, out) |
| + } |
| + |
| + if err := tb.regB.Delete("hand.old.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + status, _, out = rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, body) |
| + if status != http.StatusOK { |
| + t.Fatalf("orphan retire = %d %s", status, out) |
| + } |
| + if pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatal("the orphan's canary pointer is still there") |
| + } |
| + if !pointerExists(t, tb, "old", "stable") { |
| + t.Fatal("the orphan retire took another channel with it") |
| + } |
| + if _, err := release.GetManifest(context.Background(), tb.fx.rel, tb.sqid, "old", "v1"); err != nil { |
| + t.Fatalf("orphan retire touched a shipped release: %v", err) |
| + } |
| + found := false |
| + for _, e := range roleAudits(t, tb.fx) { |
| + found = found || (e.Action == "canary-retire-orphan" && strings.Contains(e.Detail, "canary/rc of "+tb.sqid+"/old")) |
| + } |
| + if !found { |
| + t.Fatal("no platform audit row for the orphan retire") |
| + } |
| +} |
| + |
| +// Every refusal of the operator door, each leaving the pointer in place: a |
| +// channel outside canary/*, an app the console has (the member door's), an |
| +// app in the trash, an app with instance records, and a member who is not |
| +// a platform operator. |
| +func TestAPISystemRetireChannelRefusals(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + ctx := context.Background() |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + for _, app := range []string{"old", "binned", "recorded"} { |
| + shipAndPromote(t, tb.fx, tb.sqid, app, "v1", "canary/rc") |
| + } |
| + if err := release.TrashApp(ctx, tb.fx.rel, tb.sqid, "binned", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.CreateRecord(ctx, tb.fx.rel, provision.Record{Schema: 1, Host: "x.recorded.example.com", Slug: "x", |
| + App: "recorded", Account: tb.sqid, Pool: "shop", Region: "uk", Channel: "stable", CreatedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + post := func(token, app, channel string) (int, string) { |
| + body, _ := json.Marshal(map[string]string{"account": tb.sqid, "app": app, "channel": channel}) |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), token, string(body)) |
| + return status, out |
| + } |
| + cases := []struct { |
| + app, channel string |
| + status int |
| + says string |
| + }{ |
| + {"old", "stable", http.StatusBadRequest, "is not a canary channel"}, |
| + {"shop", "canary/rc", http.StatusConflict, "carlos canary retire --account " + tb.sqid + " --app shop --name rc"}, |
| + {"binned", "canary/rc", http.StatusConflict, "is in the trash"}, |
| + {"recorded", "canary/rc", http.StatusConflict, "still has instance records"}, |
| + } |
| + for _, c := range cases { |
| + status, out := post(tb.token, c.app, c.channel) |
| + if status != c.status || !strings.Contains(out, c.says) { |
| + t.Fatalf("orphan retire of %s %s = %d %s, want %d saying %q", c.app, c.channel, status, out, c.status, c.says) |
| + } |
| + } |
| + for _, app := range []string{"shop", "binned", "recorded"} { |
| + if !pointerExists(t, tb, app, "canary/rc") { |
| + t.Fatalf("a refused retire deleted %s's canary/rc", app) |
| + } |
| + } |
| + member := cliToken(t, tb.fx, "alice@keymail.dev", "code-orphan-member") |
| + if status, out := post(member, "old", "canary/rc"); status != http.StatusNotFound { |
| + t.Fatalf("orphan retire by a non-operator = %d %s, want 404", status, out) |
| + } |
| + if !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatal("a non-operator retired the orphan's canary") |
| + } |
| +} |
| + |
| +// A console row created for the app while the retire was being checked |
| +// (an owner adopting the name) refuses the delete under the lock. |
| +func TestAPISystemRetireChannelRefusesAnAppCreatedDuringTheCheck(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "canary/rc") |
| + tb.fx.srv.retireBeforeDeleteHook = func() { |
| + if _, err := tb.fx.st.CreateAppIn(5151, "old", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, |
| + `{"account":"`+tb.sqid+`","app":"old","channel":"canary/rc"}`) |
| + if status != http.StatusConflict || !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatalf("orphan retire with an app created during the check = %d %s", status, out) |
| + } |
| +} |
| + |
| +// The repair listing marks a line of an app the console has no row for |
| +// (no_app), so the CLI can name the operator door; an app with a row is |
| +// not marked. |
| +func TestSystemDigestsDoorMarksAppsWithNoRow(t *testing.T) { |
| + fx := newDigestsFixture(t) |
| + ctx := context.Background() |
| + unbound := func(acct, app, channel string) { |
| + t.Helper() |
| + legacy := release.ChannelPointer{Schema: 1, App: app, Channel: channel, Version: "v1", PromotedAt: time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)} |
| + payload, _ := json.MarshalIndent(legacy, "", " ") |
| + b64 := base64.StdEncoding.EncodeToString(payload) |
| + wire, _ := json.Marshal(map[string]string{"payload": b64, "sig": base64.StdEncoding.EncodeToString(ed25519.Sign(fx.priv, []byte(b64)))}) |
| + key := release.ChannelKey(acct, app, channel) |
| + _, etag, _ := fx.store.Get(ctx, key) |
| + if _, err := fx.store.Put(ctx, key, wire, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + unbound(release.OpsAccount, "km", "canary/x") |
| + unbound(release.OpsAccount, "direct", "canary/y") |
| + unbound("zqx", "shop", "canary/z") |
| + st, out := getRaw(t, fx.ts.URL+"/api/cli/system/pointer-digests", fx.operator) |
| + if st != http.StatusOK { |
| + t.Fatalf("report: %d %s", st, out) |
| + } |
| + var rep struct { |
| + Repairs []struct { |
| + Account, App, Channel string |
| + NoApp bool `json:"no_app"` |
| + } `json:"repairs"` |
| + } |
| + if err := json.Unmarshal([]byte(out), &rep); err != nil { |
| + t.Fatalf("report body %s: %v", out, err) |
| + } |
| + got := map[string]bool{} |
| + for _, r := range rep.Repairs { |
| + got[r.Account+"/"+r.App+"/"+r.Channel] = r.NoApp |
| + } |
| + want := map[string]bool{ |
| + release.OpsAccount + "/km/canary/x": false, |
| + release.OpsAccount + "/direct/canary/y": true, |
| + "zqx/shop/canary/z": true, |
| + } |
| + for k, v := range want { |
| + if noApp, ok := got[k]; !ok || noApp != v { |
| + t.Fatalf("%s: listed %v, no_app %v; want no_app %v\n%s", k, ok, noApp, v, out) |
| + } |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index e39414b5c..9e4c5c9e2 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1725,6 +1725,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route POST /api/cli/system/antivirus": claimNonApp("the deployment scanning switch (system/antivirus.json)"), |
| "route POST /api/cli/system/layout": claimNonApp("the deployment layout intent (control/layout.json)"), |
| "route POST /api/cli/system/activation/cancel": claimNonApp("cancels an unpublished system activation"), |
| + "route POST /api/cli/system/channels/retire": claimNonApp("operator retire of a canary pointer of an app with no console row; the delete runs inside the bucket's own app mutation (release.WithAppMutation), classified exactly by the mutation boundary"), |
| "route POST /api/cli/system/pointer-digests": claimNonApp("operator switch: writes or removes each account's root-signed pointer digest marker (releases/<acct>/pointer-digests), classified exactly by the mutation boundary"), |
| "route POST /api/cli/system/hold": claimNonApp("rewrites the platform system pointer's per-box update holds"), |
| "route POST /api/cli/system/hold/release": claimNonApp("removes a per-box update hold from the platform system pointer"), |
| @@ -2369,6 +2370,13 @@ var claimFixtures = map[string]claimFixture{ |
| apps: claimRefs("bab/titogo"), |
| do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/retention", `{"keep": 50}`), |
| }}, |
| + "route POST /api/cli/apps/{account}/{app}/canary/retire": {door: &claimDoor{ |
| + apps: claimRefs("bab/kass"), |
| + setup: func(t *testing.T, cx *claimCase) { |
| + cx.mustForm(t, "/a/bab/apps/kass/canary", "name", "rc", "version", "v1") |
| + }, |
| + do: claimAPI(http.MethodPost, "/api/cli/apps/bab/kass/canary/retire", `{"name":"rc"}`), |
| + }}, |
| "route POST /api/cli/apps/{account}/{app}/channels/resign": {door: &claimDoor{ |
| apps: claimRefs("bab/kass"), |
| setup: func(t *testing.T, cx *claimCase) { cx.resignPlan(t, "canary/x") }, |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 4c1538820..bf554ea6e 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -10,6 +10,7 @@ import ( |
| "database/sql" |
| "encoding/json" |
| "errors" |
| + "os" |
| "fmt" |
| "github.com/carlosframework/platform/internal/hostactors" |
| "net/http" |
| @@ -1324,6 +1325,29 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + // An app shipped straight to the bucket under bab with no console row: |
| + // its canary pointer is the one the operator door may retire (#1634). |
| + "route POST /api/cli/system/channels/retire": { |
| + setup: func(t *testing.T, cx *claimCase) { |
| + ctx := context.Background() |
| + m := release.Manifest{Schema: 1, App: "orphan", Version: "v1", Kind: "binary", BuiltAt: "2026-10-01T10:00:00Z", |
| + Artifacts: map[string]release.Artifact{"linux-amd64": {File: "orphan"}}} |
| + if err := release.Ship(ctx, cx.rel, "bab", m, map[string][]byte{"linux-amd64": []byte("binary v1")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.Promote(ctx, cx.rel, cx.priv, "bab", "orphan", "canary/old", "v1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + do: claimAPIReply(http.MethodPost, "/api/cli/system/channels/retire", `{"account":"bab","app":"orphan","channel":"canary/old"}`), |
| + body: []string{`"channel":"canary/old"`}, |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + if _, _, err := cx.rel.Get(context.Background(), release.ChannelKey("bab", "orphan", "canary/old")); !errors.Is(err, os.ErrNotExist) { |
| + return "the orphan's canary/old pointer is still there" |
| + } |
| + return "" |
| + }, |
| + }, |
| "route POST /api/cli/system/pointer-digests": { |
| do: claimAPIReply(http.MethodPost, "/api/cli/system/pointer-digests", `{"on":true,"accounts":["bab"]}`), |
| body: []string{`"account":"bab","on":true`}, |
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go| index 083d415c6..feb92b6fa 100644 |
| --- a/internal/console/linkedpolicy.go |
| +++ b/internal/console/linkedpolicy.go |
| @@ -155,6 +155,7 @@ var linkedPolicies = map[string]linkedPolicy{ |
| "POST /api/cli/apps/{account}/{app}/promote": linkedRefuse, |
| "POST /api/cli/apps/{account}/{app}/rollback": linkedRefuse, |
| "POST /api/cli/apps/{account}/{app}/channels/resign": linkedRefuse, |
| + "POST /api/cli/apps/{account}/{app}/canary/retire": linkedRefuse, |
| "GET /api/cli/apps/{account}/{app}/releases/{version}/authorize": linkedRefuse, |
| "POST /api/cli/apps/{account}/{app}/releases/{version}/authorize": linkedRefuse, |
| "POST /api/cli/apps/{account}/{app}/releases": linkedRefuse, |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index e86f527f1..e0616af22 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -572,6 +572,9 @@ var routeDecls = []routeDecl{ |
| // manifest digests the console then signs into the channel's pointer, so |
| // no credential reaches it. |
| {Pattern: "POST /api/cli/apps/{account}/{app}/channels/resign", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIChannelResign}, |
| + // `carlos canary retire` (#1634): the browser's Retire over the CLI. A |
| + // person's act, like resign: closed to every service credential. |
| + {Pattern: "POST /api/cli/apps/{account}/{app}/canary/retire", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIRetireCanary}, |
| // `carlos releases authorize` (settings spec §4.1): GET shows a build's |
| // digests, POST signs a promotion record for the digest a person |
| // confirmed. A credential the app holds never vouches for a build. |
| @@ -1298,6 +1301,9 @@ var routeDecls = []routeDecl{ |
| {Pattern: "GET /api/cli/system/hosts-used/status", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIHostsUsedStatus}, |
| {Pattern: "GET /api/cli/system/pointer-digests", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemPointerDigests}, |
| {Pattern: "POST /api/cli/system/pointer-digests", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemPointerDigests}, |
| + // `carlos channels retire` (#1634): a canary pointer of an app with no |
| + // row on this console. apiSystemRoller, like pointer digests. |
| + {Pattern: "POST /api/cli/system/channels/retire", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemRetireChannel}, |
| // The anonymous demos (apidemo.go): registered on a console with demos |
| // on or one in demo box mode (gateDemo). |
diff --git a/internal/console/server.go b/internal/console/server.go| index 8d737cdcb..dae16932b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -18,7 +18,6 @@ import ( |
| "html/template" |
| "io" |
| "log" |
| - "maps" |
| "math" |
| mrand "math/rand/v2" |
| "net" |
| @@ -6751,143 +6750,6 @@ func attachCommands(app, channel, domain, appsDomain, sqid string, absent bool) |
| return create, enable |
| } |
| -// handleRetireCanary removes a canary's channel pointer. Shipped releases |
| -// are untouched — retirement un-points, it never deletes bits. |
| -func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| - addr, raw, acct, role, app, ok := s.accountApp(w, r) |
| - if !ok { |
| - return |
| - } |
| - if !csrfFormOK(r, raw) { |
| - s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| - return |
| - } |
| - if s.refuseAppNoBucket(w, r) { |
| - return |
| - } |
| - if s.cfg.Key == nil { |
| - s.renderMessage(w, r, http.StatusServiceUnavailable, "Promotions disabled", |
| - "No signing key on this host — the console is running read-only.") |
| - return |
| - } |
| - back := func(kind, msg string) { |
| - s.setFlash(w, kind, msg) |
| - dest := "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) |
| - if tab := releaseBackTab(r); tab != "" { |
| - dest += "/" + tab |
| - } |
| - http.Redirect(w, r, dest, http.StatusSeeOther) |
| - } |
| - name := strings.ToLower(strings.TrimSpace(r.FormValue("name"))) |
| - if !canaryNameRe.MatchString(name) { |
| - back("err", "Invalid canary name.") |
| - return |
| - } |
| - channel := "canary/" + name |
| - // A canary with followers is load-bearing: retiring its pointer would |
| - // strand every host on it. Fail CLOSED on a registry error — an "I |
| - // couldn't check" must never be read as "nobody follows this channel". |
| - checkCtx, cancelCheck := context.WithTimeout(r.Context(), 15*time.Second) |
| - // The app's records as they stand before the check, compared again just |
| - // before the delete: the check itself runs without the app lock, so a |
| - // record created, changed or deleted in between refuses the retire |
| - // (recordStamps). |
| - before, err := s.recordStamps(checkCtx, acct.Sqid, app) |
| - var hosts []string |
| - if err == nil { |
| - hosts, err = s.channelHosts(checkCtx, acct.Sqid, app, channel) |
| - } |
| - cancelCheck() |
| - if errors.Is(err, errRetireUnsettled) { |
| - // Nobody follows the channel by any record, but the app changed too |
| - // recently (or a box still serves a host with no record) for that |
| - // to be the whole story yet. |
| - log.Printf("console: retire %s %s: %v", app, channel, err) |
| - back("err", "Could not verify no hosts follow this channel — try again.") |
| - return |
| - } |
| - if err != nil { |
| - log.Printf("console: retire %s %s: check followers: %v", app, channel, err) |
| - s.renderMessage(w, r, http.StatusInternalServerError, "Error", |
| - "Could not verify no hosts follow this channel — try again.") |
| - return |
| - } |
| - if len(hosts) > 0 { |
| - back("err", "Canary "+name+" still has a host ("+hosts[0]+") following it — remove or repoint that route first.") |
| - return |
| - } |
| - ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| - defer cancel() |
| - key := release.ChannelKey(acct.Sqid, app, channel) |
| - _, pointerETag, err := s.cfg.Releases.Get(ctx, key) |
| - if errors.Is(err, os.ErrNotExist) { |
| - back("err", "No canary named "+name+" here.") |
| - return |
| - } else if err != nil { |
| - back("err", "Could not read the release store. Please try again.") |
| - return |
| - } |
| - if !confirmed(r) { |
| - s.confirmRetireCanary(w, r, addr, raw, acct, role, app, name) |
| - return |
| - } |
| - // The app lock from the re-list through the delete: every console |
| - // record write holds it too (recordlock.go), so a follower created or |
| - // moved onto this channel lands before the re-list, which refuses, or |
| - // after the pointer is gone (#407). |
| - unlockApp := s.lockApp(acct.Sqid, app) |
| - err = s.appMutation(ctx, acct, app, "canary-retire", func(ctx context.Context) error { |
| - if h := s.retireBeforeDeleteHook; h != nil { |
| - h() |
| - } |
| - after, err := s.recordStamps(ctx, acct.Sqid, app) |
| - if err != nil { |
| - return err |
| - } |
| - if !maps.Equal(before, after) { |
| - return fmt.Errorf("%w: the app's records changed during the check", errRetireUnsettled) |
| - } |
| - // The pointer must still be the one read above: a promotion or a |
| - // removal meanwhile refuses. |
| - if _, cur, gerr := s.cfg.Releases.Get(ctx, key); gerr != nil || cur != pointerETag { |
| - if gerr != nil && !errors.Is(gerr, os.ErrNotExist) { |
| - return gerr |
| - } |
| - return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| - } |
| - // Delete exactly the pointer read above: a promotion since then |
| - // conflicts, and the retire is refused rather than deleting bytes |
| - // this check never saw. |
| - if err := release.DeleteIfMatch(ctx, s.cfg.Releases, key, pointerETag); err != nil { |
| - if errors.Is(err, release.ErrCASConflict) { |
| - return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| - } |
| - return err |
| - } |
| - // No console record write lands between the comparison above and |
| - // this delete: each holds the app lock held here. One that waited |
| - // lands after it, on a channel with no pointer: the same as creating |
| - // an instance on a channel nobody has promoted, which the create |
| - // door allows. No restore is attempted: the store cannot tell |
| - // "deleted the revision read" from "already gone", so putting bytes |
| - // back could resurrect a pointer someone else removed. |
| - return nil |
| - }) |
| - unlockApp() |
| - if errors.Is(err, errRetireUnsettled) { |
| - log.Printf("console: retire %s %s: %v", app, channel, err) |
| - back("err", "Could not verify no hosts follow this channel — try again.") |
| - return |
| - } |
| - if err != nil { |
| - log.Printf("console: retire %s %s: %v", app, channel, err) |
| - back("err", "Retiring the canary failed: "+err.Error()) |
| - return |
| - } |
| - s.auditActivity(acct, app, addr, Activity{Action: "canary-retire", TargetType: "channel", Target: "canary/" + name, Detail: "retired canary " + name}) |
| - back("ok", "Retired canary "+name+" — its channel pointer is gone; shipped releases are untouched.") |
| -} |
| - |
| // promoteChannelOptions is the per-row promote select's option list. |
| // |
| // For a pipelined app (pipe != nil), it's the pipeline's own declared |
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt| index c21243ba7..3a603a14f 100644 |
| --- a/internal/console/testdata/claim-authority-sites.txt |
| +++ b/internal/console/testdata/claim-authority-sites.txt |
| @@ -72,6 +72,7 @@ claim_app_admission.go|initializeBackfillClaimAppAdmission|w.EnrollBackfillApp(c |
| claim_app_admission.go|reserveClaimAppAdmission|w.EnrollNewApp(ctx, acct.Sqid, app) |
| claim_app_enroll.go|insertClaimAppRow|s.claimEnrollmentContext(ctx, acct, app, appID) |
| claim_app_enroll.go|insertClaimAppRow|w.EnrollNewApp(ctx, acct.Sqid, app) |
| +canary_retire.go|orphanRetireMutation|release.WithAppMutation(ctx, s.cfg.Releases, acct, app, "canary-retire-orphan", fn) |
| claim_app_mutation.go|claimAppCall|release.WithAppMutation(ctx, s.cfg.Releases, acct.Sqid, app, action, func(callCtx context.Context) error { var callErr error result, callErr = call(callCtx) return callErr }) |
| claim_create.go|beginClaimCreate|a.Control.RegisterStart(ctx, acct.Sqid, app, appID, id, registration, time.Now()) |
| claim_mail_admitter.go|AcquireClaimMailGate|g.w.AcquireMailGate(ctx, hostops.MailGateOwner(owner), hostops.MailGateScope(scope)) |