app-region-set: Astra round 1 fixes
The request's app incarnation is captured at resolution and checked again under the app lock and, in the store, under the name lock purge and rename hold. A member who is a deployment operator keeps operator authority by account name. A console with no named home refuses the change. The CLI and docs no longer say the region decides where a pooled app's instances start (Luna pass 3). The closed-door count and the record-write census take the two new doors. Round 1 findings and the round 2 brief committed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+277
−27
apps_region_cmd.go+1 −1apps_region_cmd_e2e_test.go+1 −1docs/site/cli.md+1 −1docs/superpowers/notes/copy-app-region-set.md+3 −0docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md+60 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md+39 −1docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md+12 −1internal/console/appregionset.go+36 −17internal/console/appregionset_test.go+76 −0internal/console/store.go+10 −0internal/console/svcroutes_test.go+2 −2internal/provision/app_region_set_census_test.go+33 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-app-region-set.tsv+2 −2
CI passed — run details
diff --git a/apps_region_cmd.go b/apps_region_cmd.go| index dd392f1db..1b3cb82e0 100644 |
| --- a/apps_region_cmd.go |
| +++ b/apps_region_cmd.go |
| @@ -26,7 +26,7 @@ const ( |
| appsRegionUsage = "usage: carlos apps region --app <name> [--set <region>] [--account <sqid|name>] [--account-id <sqid>] [--console <origin>]" |
| appsRegionFlagSet = "the region where this app's new instances start. existing instances stay where they are. only account owners and deployment operators can change it" |
| // AR-32: app, label |
| - appsRegionShow = "%s's region is %s. new instances start there." |
| + appsRegionShow = "%s's region is %s. for apps not using a pool, new instances start there; pooled apps start new instances in the home region" |
| // AR-33: app, fleet name |
| appsRegionShowFleet = "%s runs on your fleet %s, which decides where its instances run." |
| // AR-34: app, old label, new label, new label |
diff --git a/apps_region_cmd_e2e_test.go b/apps_region_cmd_e2e_test.go| index fc530c65a..454c00410 100644 |
| --- a/apps_region_cmd_e2e_test.go |
| +++ b/apps_region_cmd_e2e_test.go |
| @@ -117,7 +117,7 @@ func TestAppsRegionThroughTheConsole(t *testing.T) { |
| before := "home1." + labelsDomain |
| e.out(t, runInstancesCreate, "-app", "shop", "-account", "ops", "-host", before) |
| - if got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops"); got != "shop's region is Dublin (ie). new instances start there.\n" { |
| + if got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops"); got != "shop's region is Dublin (ie). for apps not using a pool, new instances start there; pooled apps start new instances in the home region\n" { |
| t.Fatalf("apps region:\n%q", got) |
| } |
| got := e.out(t, runAppsRegion, "--app", "shop", "--account", "ops", "--set", "uk") |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 71aab8d9d..08d959a04 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -193,7 +193,7 @@ carlos apps region --app hello |
| carlos apps region --app hello --set uk |
| ``` |
| -An app's region is only where its new instances start. Changing it moves nothing: instances that already exist stay where they are, and only instances created afterwards start in the new region. Use `carlos move` to move one that exists. The new region must be one the platform offers, able to start instances now, and allowed for this app's instances. An app on a fleet is refused because the fleet decides where its instances run. Use `carlos apps place` instead. The command also refuses an app whose instances start in a pool or an app in the Trash. Account owners and deployment operators can change the region with this command or in the Region section of the app's settings in the console. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` must name the app's current region. |
| +An app's region sets where its new instances start, except for apps whose instances start in a pool. Those instances start in the home region instead. Changing the region moves nothing: existing instances stay where they are, and only instances created afterwards start in the new region when the app uses its region. Use `carlos move` to move one that exists. The new region must be one the platform offers, able to start instances now, and allowed for this app's instances. An app on a fleet is refused because the fleet decides where its instances run. Use `carlos apps place` instead. The command also refuses an app whose instances start in a pool because the app's region does not decide where its new instances start. It also refuses an app in the Trash. Account owners and deployment operators can change the region with this command. In the console, the Region control is on the app's settings page, which only account members can open. Owners and deployment operators who are members can use the control. A deployment operator who is not a member must use the command. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` must name the app's current region. |
| `carlos apps set` changes how the app's running instances take a new build: |
diff --git a/docs/superpowers/notes/copy-app-region-set.md b/docs/superpowers/notes/copy-app-region-set.md| index 467188840..7cf3da359 100644 |
| --- a/docs/superpowers/notes/copy-app-region-set.md |
| +++ b/docs/superpowers/notes/copy-app-region-set.md |
| @@ -27,6 +27,7 @@ Every new human string of branch `app-region-set`: changing an existing app's re |
| | AR-19 | door refusal, printed by the CLI as "apps region: <text>" | code, reason text (R-*) | region %s can't take new instances right now (%s), so the app's region was not changed. | |
| | AR-20 | door refusal, printed by the CLI as "apps region: <text>" | code | could not confirm that region %s can take new instances, so the app's region was not changed. Try again. | |
| | AR-21 | door refusal, printed by the CLI as "apps region: <text>" | | changing an app's region is not supported on a console with host claims on | |
| +| AR-22 | door refusal, printed by the CLI as "apps region: <text>" | | this console names no home region (CONSOLE_HOME_REGION is unset), so an app's region cannot be changed | |
| | AR-30 | usage line | | usage: carlos apps region --app <name> [--set <region>] [--account <sqid\|name>] [--account-id <sqid>] [--console <origin>] | |
| | AR-31 | flag help for --set | | the region this app's new instances start in. existing instances stay where they are. account owners and deployment operators only | |
| | AR-32 | CLI line | app, region label | %s's region is %s. new instances start there. | |
| @@ -40,3 +41,5 @@ Every new human string of branch `app-region-set`: changing an existing app's re |
| | AR-41 | docs (docs/site/cli.md) | | `carlos apps region` shows an app's region, and `--set` changes it: | |
| | AR-42 | docs (docs/site/cli.md) | | An app's region is only where its new instances start. Changing it moves nothing: instances that already exist stay where they are, and only instances created afterwards start in the new region. Use carlos move to move one that exists. The new region must be one the platform offers and can start instances in now, and one the app's instances may use. An app on a fleet is refused, because the fleet decides where its instances run; use `carlos apps place` instead. So is an app whose instances start in a pool, and an app in the Trash. Account owners and deployment operators can change the region, here or in the Region section of the app's settings in the console. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` has to name the new region. | |
| | AR-43 | docs (docs/site/cli.md) | | That is the region the app has now, after any `carlos apps region --set`, and deploy never moves an instance to match it. | |
| + |
| +Drafts as first sent to Luna; the applied text is in docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md (pass 3 revises AR-32 and AR-42 and adds AR-22). |
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md| new file mode 100644 |
| index 000000000..ce4c87e02 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md |
| @@ -0,0 +1,60 @@ |
| +Reviewed round 1 of 3 at `f686d3d5e26efd000f144e10a94318f96a7f65e5` against `origin/main` (`b1d00ca7d84dd2c158151469f9fd40283707e33b`). No files changed. |
| + |
| +1. **P1 — Tests: the closed-route test necessarily fails.** |
| + The two additions at [svcroutes_test.go:260](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:260) increase `closedDoors` from 64 to 66. [Line 1103](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/svcroutes_test.go:1103) still requires `seen == 64`. Even when every authorization refusal succeeds, the test fails its final assertion. I verified both list counts directly from the Git revisions. |
| + **Fix:** update the expected count and its explanatory message to include both region routes, then run this targeted test. |
| + **Fault family:** the security-route inventory and its executable assertion must agree. |
| + |
| +2. **P1 — Write identity: an in-flight request can change a replacement app.** |
| + [appRegionApp](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:148) checks existence without capturing an incarnation. The first incarnation read occurs at [appregionset.go:311](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:311), after request parsing, remote reads and policy validation. |
| + |
| + If `shop` is renamed away or purged and recreated during that interval, the handler captures the replacement’s incarnation and writes its region. The SQL comparison succeeds because it compares against the replacement it just read. Earlier policy checks can also belong to the previous app. |
| + |
| + Furthermore, [SetAppRegion](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1705) ignores `AppIncarnation.freed`, comparing only second-resolution `created_at`. An in-memory check using the exact SQL confirmed that replacing a row with the same timestamp permits the stale update. |
| + |
| + **Fix:** capture the incarnation when resolving the app, then compare the complete identity under the existing app/name locking discipline before validation and commit. Preserve identity through the write. Add controlled rename/recreate and same-second replacement tests. |
| + **Fault family:** a mutation must affect the app incarnation the request originally resolved. |
| + |
| +3. **P2 — Authorization: operator permission is lost on two supported paths.** |
| + The browser handler calls `accountApp` at [appregionset.go:394](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:394). Its underlying [account gate](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:2696) searches memberships only. An ops owner or listed system operator who is not a member receives 404 before CSRF or operator authorization is checked. They also cannot reach the Settings control. |
| + |
| + Separately, an operator who is an ordinary member and addresses the API by account name falls through to [appregionset.go:139](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:139), which requires ownership and forgets their operator status. The equivalent sqid request succeeds. |
| + |
| + **Fix:** retain operator authority through account resolution; implement the browser’s session → CSRF → owner/operator gate and provide access to the advertised control. Add browser tests for both operator kinds without membership, and API tests for the name fallback. |
| + **Fault family:** equivalent authorized requests must retain the same owner-or-operator permission. |
| + |
| +4. **P2 — CLI output: stored region is presented as effective placement for pooled apps.** |
| + [apps_region_cmd.go:106](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:106) always prints “new instances start there” for a non-fleet app. GET returns the stored region without reading pool policy. An app storing `uk` with a pooled manifest therefore reports London, although [regiondefault.go:70](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/regiondefault.go:70) explicitly makes its no-region pooled creates use the home. |
| + |
| + **Fix:** describe GET’s result as the stored app region and qualify its applicability. Preserve the zero-bucket-read GET budget. Add a pooled-app output case and correct the equivalent documentation claim. |
| + **Fault family:** stored defaults must not be presented as effective placement when another policy overrides them. |
| + |
| +5. **P2 — Configuration: an unnamed home makes the change one-way.** |
| + [appregionset.go:253](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:253) rejects an empty value but permits an eligible non-home code without requiring `HomeRegion`. With no named home, [explicitChoices](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/regionclaim.go:83) omits the home, and [homeRegionIn](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/apiinstancemove.go:312) cannot map any nonempty input to it. |
| + |
| + Consequently, a console with eligible `uk` boxes and no `CONSOLE_HOME_REGION` can change an app to `uk`, but neither this command nor an explicit instance-region value can select the home afterward. |
| + |
| + **Fix:** require a named home before accepting a non-home default, while retaining the approved switch-off behavior when the home is named. Test this configuration explicitly. |
| + **Fault family:** every stored non-home default must leave the home explicitly selectable. |
| + |
| +No P3 findings. |
| + |
| +The shared authentication code refuses expired/revoked tokens and every service role before account resolution. Ordinary non-members retain the standard 404, and API Trash details follow account authorization. Existing-instance readers do not move or rewrite records; seeded creates use the same defaulting path. The migration preserves `region_set_at` through the rebuild, and rollback to main remains structurally compatible. GET and the added page controls introduce no bucket reads or polling. |
| + |
| +The new tests cover ordinary owner/member behavior, several refusals, unchanged existing instances and deploy-region behavior. They do not cover the replacement races or operator paths above. Go tests could not start because the read-only sandbox prevented creation of Go’s work directory; this is a validation limitation, not a test result. `git diff --check` passed. |
| + |
| +Census verdicts for the reviewed tip: |
| + |
| +| Unit or envelope | Verdict and evidence | |
| +|---|---| |
| +| `Server.NewServer` | **Approve.** [server.go:1738](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:1738): route registration only; existing read basis unchanged. | |
| +| `Store.NonHomeAppRegions` | **Approve.** [store.go:1725](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:1725): same console-owned query, with a later discrepancy cutoff. | |
| +| `Store.migrate` | **Approve.** [store.go:574](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:574): additive column through existing execution sites. | |
| +| `Store.migrateAppsKey` | **Approve.** [store.go:715](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:715), [store.go:734](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/store.go:734): preserves the new column in the existing transactional rebuild. | |
| +| Template `external` unit | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): embedded form markup and CSRF field; no new read. | |
| +| `.` envelope | **Approve.** [apps.go:156](/home/paulca/amadan.net/carlos/platform-app-region/apps.go:156), [apps_region_cmd.go:55](/home/paulca/amadan.net/carlos/platform-app-region/apps_region_cmd.go:55): CLI dispatch, authenticated API calls and formatting; no new root execution or filesystem authority. | |
| +| `internal/console` envelope | **Approve.** [appregionset.go:116](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:116), [appregionset.go:246](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/appregionset.go:246), [server.go:4440](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/server.go:4440): existing configured stores and validated region vocabulary; host-claim writes refused. The correctness findings above do not introduce a new root-read target or weaken the recorded root-read basis. | |
| +| `internal/console/templates` envelope | **Approve.** [app_settings.html:25](/home/paulca/amadan.net/carlos/platform-app-region/internal/console/templates/app_settings.html:25): same embedded-template boundary. | |
| +| `internal/regionlabel` envelope | **Approve.** [regionlabel.go:81](/home/paulca/amadan.net/carlos/platform-app-region/internal/regionlabel/regionlabel.go:81): sorts keys from an existing in-memory map; no I/O. | |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md| index 86c7516fe..08a9080c6 100644 |
| --- a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md |
| +++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-APP-REGION-SET.md |
| @@ -1,4 +1,4 @@ |
| -# Review brief: branch app-region-set (carlos apps region), round 1 of 3 |
| +# Review brief: branch app-region-set (carlos apps region), round 2 of 3 |
| Repo carlos/platform, branch `app-region-set`, commit named in the prompt |
| (the commit that adds this brief). |
| @@ -118,6 +118,44 @@ something, with evidence): |
| follow anything from a tenant-, app- or box-writable path or input, or |
| a check the basis relies on is weakened. |
| +## Round 2 |
| + |
| +Earlier rounds: round 1, `docs/superpowers/specs/CODEX-FINDINGS-APP-REGION-SET.md` |
| +(Astra, at f686d3d5; 2 P1, 3 P2; census approved). The round number counts |
| +every earlier review of this change. |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings. The verdict covers everything |
| +outstanding, earlier rounds included. The builder's dispositions: |
| + |
| +1. P1 closed-door count: the test now expects 66 and names the two |
| + region doors (svcroutes_test.go). |
| +2. P1 write identity: the API resolves the incarnation with the app |
| + (`appRegionApp`); the browser captures it right after its gates; |
| + `setAppRegion` re-reads it under `lockApp` and compares the whole |
| + `AppIncarnation`; `Store.SetAppRegion` takes the name lock that purge |
| + and rename hold, compares the whole incarnation again under it, then |
| + writes pinned to created_at and the region read. Test: |
| + `TestAppRegionSetRefusesAReplacedApp` (same-second purge and re-create). |
| +3. P2 operator paths: the member path keeps operator authority |
| + (`principalPlatformOperator`), tested by name in the API and in the |
| + browser (`TestAppRegionSetMemberOperator`). Ruling: the browser control |
| + serves members only (owners and member operators), because every |
| + account page is a member page; an operator who is no member uses the |
| + CLI. The docs now say so. |
| +4. P2 pooled display: AR-32 and the docs (Luna pass 3) no longer claim the |
| + region decides where a pooled app's instances start; GET still reads |
| + no bucket object. |
| +5. P2 unnamed home: refused up front (AR-22) when the console names no |
| + home region; `TestAppRegionSetNeedsANamedHome`. |
| + |
| +CI at f686d3d5 also failed the record-write census (two re-pinned route |
| +registrations); `internal/provision/app_region_set_census_test.go` layers |
| +the two new digests. Census: the root-read overlay was re-proposed under |
| +the same name (the console and root envelopes re-pinned); give the |
| +envelope verdicts again for the changed code. |
| + |
| ## Severity |
| - **P1**: unsafe, would not compile, a test fails, or it would not work. |
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md b/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md| index 29023b4f7..9aab9ea44 100644 |
| --- a/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md |
| +++ b/docs/superpowers/specs/LUNA-COPY-RESULT-APP-REGION-SET.md |
| @@ -57,4 +57,15 @@ The brief asked for full stops on form labels and buttons by mistake, so Luna's |
| **Flags** |
| -- None. |
| \ No newline at end of file |
| +- None. |
| +## Pass 3 (after Astra round 1: AR-22 new, AR-32 and AR-42 revised) |
| + |
| +| key | new | why | |
| +|---|---|---| |
| +| AR-22 | this console names no home region (CONSOLE_HOME_REGION is unset), so an app's region cannot be changed | added the missing refusal reason | |
| +| AR-32 | %s's region is %s. for apps not using a pool, new instances start there; pooled apps start new instances in the home region | avoids claiming the region always controls new instances | |
| +| AR-42 | An app's region sets where its new instances start, except for apps whose instances start in a pool. Those instances start in the home region instead. Changing the region moves nothing: existing instances stay where they are, and only instances created afterwards start in the new region when the app uses its region. Use `carlos move` to move one that exists. The new region must be one the platform offers, able to start instances now, and allowed for this app's instances. An app on a fleet is refused because the fleet decides where its instances run. Use `carlos apps place` instead. The command also refuses an app whose instances start in a pool because the app's region does not decide where its new instances start. It also refuses an app in the Trash. Account owners and deployment operators can change the region with this command. In the console, the Region control is on the app's settings page, which only account members can open. Owners and deployment operators who are members can use the control. A deployment operator who is not a member must use the command. The console records who changed it, from what and to what, in the app's activity. After a change, `carlos deploy --region` must name the app's current region. | corrected pooled-app behavior and console access rules | |
| + |
| +**Flags** |
| + |
| +- The overlap check could not reach its service because network/DNS access was blocked. No files were edited. |
| \ No newline at end of file |
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go| index 65e3b1caf..aaa53a431 100644 |
| --- a/internal/console/appregionset.go |
| +++ b/internal/console/appregionset.go |
| @@ -52,6 +52,7 @@ type appRegionSetCopyStrings struct { |
| NotAllowed string // AR-7: code, list |
| NotAllowedNone string // AR-7b: code |
| ClaimOff string // AR-21 |
| + NoHome string // AR-22 |
| Unavailable string // AR-19: code, reason text (R-*) |
| Unconfirmed string // AR-20: code |
| Changed string // AR-8 |
| @@ -78,6 +79,7 @@ var appRegionSetCopy = appRegionSetCopyStrings{ |
| NotAllowed: "region %s cannot be used by this app's instances. allowed: %s", |
| NotAllowedNone: "region %s cannot be used by this app's instances, and none of the regions this app can use is offered right now", |
| ClaimOff: "changing an app's region is not supported on a console with host claims on", |
| + NoHome: "this console names no home region (CONSOLE_HOME_REGION is unset), so an app's region cannot be changed", |
| Unavailable: "region %s can't start new instances right now (%s), so the app's region was not changed", |
| Unconfirmed: "could not confirm that region %s can start new instances, so the app's region was not changed. try again", |
| Changed: "this app's region changed while this ran. run it again", |
| @@ -136,25 +138,26 @@ func (s *Server) appRegionCaller(w http.ResponseWriter, r *http.Request, write b |
| if !ok { |
| return "", nil, false |
| } |
| - if write && acct.Role != RoleOwner { |
| + if write && acct.Role != RoleOwner && !s.principalPlatformOperator(p) { |
| jsonError(w, http.StatusForbidden, appRegionSetCopy.NotOwner) |
| return "", nil, false |
| } |
| return p.Address, acct, true |
| } |
| -// appRegionApp is the {app} half: a live app, or the Trash refusal for a |
| -// trashed one (the caller may already see the Trash), else the bare 404. |
| -func (s *Server) appRegionApp(w http.ResponseWriter, r *http.Request, acct *Account) (string, bool) { |
| +// appRegionApp is the {app} half: a live app and the incarnation the |
| +// request found, or the Trash refusal for a trashed one (the caller may |
| +// already see the Trash), else the bare 404. |
| +func (s *Server) appRegionApp(w http.ResponseWriter, r *http.Request, acct *Account) (string, AppIncarnation, bool) { |
| app := r.PathValue("app") |
| - live, err := s.store.HasAppIn(acct.ID, app) |
| + inc, live, err := s.store.AppIncarnationContext(r.Context(), acct.ID, app) |
| if err != nil { |
| log.Printf("console: app region %s/%s: has app: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusInternalServerError, msgAppRegionUnreadable) |
| - return "", false |
| + return "", AppIncarnation{}, false |
| } |
| if live { |
| - return app, true |
| + return app, inc, true |
| } |
| trashed, err := s.store.HasTrashedAppIn(acct.ID, app) |
| if err != nil { |
| @@ -162,10 +165,10 @@ func (s *Server) appRegionApp(w http.ResponseWriter, r *http.Request, acct *Acco |
| } |
| if err == nil && trashed { |
| jsonError(w, http.StatusConflict, fmt.Sprintf(appRegionSetCopy.InTrash, app)) |
| - return "", false |
| + return "", AppIncarnation{}, false |
| } |
| http.NotFound(w, r) |
| - return "", false |
| + return "", AppIncarnation{}, false |
| } |
| // handleAPIAppRegionGet is GET /api/cli/apps/{account}/{app}/region: the |
| @@ -176,7 +179,7 @@ func (s *Server) handleAPIAppRegionGet(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - app, ok := s.appRegionApp(w, r, acct) |
| + app, _, ok := s.appRegionApp(w, r, acct) |
| if !ok { |
| return |
| } |
| @@ -214,7 +217,7 @@ func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| - app, ok := s.appRegionApp(w, r, acct) |
| + app, inc, ok := s.appRegionApp(w, r, acct) |
| if !ok { |
| return |
| } |
| @@ -231,7 +234,7 @@ func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) |
| defer cancel() |
| - v, ref := s.setAppRegion(ctx, acct, app, req.Region, addr, "cli") |
| + v, ref := s.setAppRegion(ctx, acct, app, inc, req.Region, addr, "cli") |
| if ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| @@ -240,16 +243,23 @@ func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| } |
| // setAppRegion is both doors' mechanism. Every refusal is checked before |
| -// the write; the write holds the app lock and lands on the incarnation and |
| +// the write. found is the incarnation the request resolved: the write holds |
| +// the app lock (which a rename, purge, trash or create also takes), checks |
| +// that the name still names that incarnation, and lands on it and the |
| // region it read, or not at all. via is appended to the audit line ("cli" |
| // or "" for the browser). |
| -func (s *Server) setAppRegion(ctx context.Context, acct *Account, app, raw, addr, via string) (appRegionView, *doorRefusal) { |
| +func (s *Server) setAppRegion(ctx context.Context, acct *Account, app string, found AppIncarnation, raw, addr, via string) (appRegionView, *doorRefusal) { |
| // A host-claim console gates every app-row write through a claim |
| // operation, and this one has none: refused before anything is read |
| // (host claims are shelved; claimRenameUnsupportedMsg is the precedent). |
| if s.cfg.HostClaim { |
| return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.ClaimOff} |
| } |
| + // With no home named, the home has no code to choose, so a change away |
| + // from it could never be undone here. |
| + if s.regionHome() == "" { |
| + return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.NoHome} |
| + } |
| raw = strings.TrimSpace(raw) |
| if raw == "" { |
| return appRegionView{}, &doorRefusal{http.StatusBadRequest, appRegionSetCopy.NoRegion} |
| @@ -313,7 +323,7 @@ func (s *Server) setAppRegion(ctx context.Context, acct *Account, app, raw, addr |
| log.Printf("console: app region %s/%s: incarnation: %v", acct.Sqid, app, err) |
| return appRegionView{}, &doorRefusal{http.StatusInternalServerError, appRegionSetCopy.WriteFailed} |
| } |
| - if !live { |
| + if !live || inc != found { |
| return appRegionView{}, &doorRefusal{http.StatusConflict, appRegionSetCopy.Changed} |
| } |
| from, fromSource, err := s.store.AppRegion(acct.ID, app) |
| @@ -382,7 +392,8 @@ func (s *Server) appRegionPageChoices() []regionOption { |
| func (p page) AppRegionSetCopy() appRegionSetCopyStrings { return appRegionSetCopy } |
| // canSetAppRegion is the browser's form of the rule: an owner, or a |
| -// deployment operator. |
| +// deployment operator. The browser reaches only accounts the person is a |
| +// member of (accountApp), so an operator who is no member uses the CLI. |
| func (s *Server) canSetAppRegion(addr, role string) bool { |
| return role == RoleOwner || s.platformOperator(addr) |
| } |
| @@ -413,7 +424,15 @@ func (s *Server) handleAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) |
| defer cancel() |
| - v, ref := s.setAppRegion(ctx, acct, app, r.FormValue("region"), addr, "") |
| + found, live, err := s.store.AppIncarnationContext(ctx, acct.ID, app) |
| + if err != nil || !live { |
| + if err != nil { |
| + log.Printf("console: app region %s/%s: incarnation: %v", acct.Sqid, app, err) |
| + } |
| + back("err", sentenceCase(appRegionSetCopy.Changed)) |
| + return |
| + } |
| + v, ref := s.setAppRegion(ctx, acct, app, found, r.FormValue("region"), addr, "") |
| if ref != nil { |
| back("err", sentenceCase(ref.Msg)) |
| return |
diff --git a/internal/console/appregionset_test.go b/internal/console/appregionset_test.go| index 105b1dd33..06b8e2f53 100644 |
| --- a/internal/console/appregionset_test.go |
| +++ b/internal/console/appregionset_test.go |
| @@ -458,3 +458,79 @@ func equalSnapshots(a, b map[string]string) bool { |
| } |
| return true |
| } |
| + |
| +// A deployment operator who is an ordinary member keeps operator authority |
| +// when naming the account by name (the member path), in the API and in the |
| +// browser. |
| +func TestAppRegionSetMemberOperator(t *testing.T) { |
| + fx := newAppRegionFx(t) |
| + fx.srv.cfg.SystemOperators = []string{arMember} |
| + member := cliToken(t, fx.consoleFixture, arMember, "code-ar-member") |
| + st, _, out := rawReq(t, http.MethodPut, fx.ts.URL+"/api/cli/apps/"+url.PathEscape("Shop Co")+"/shop/region", member, `{"region":"uk"}`) |
| + if st != http.StatusOK { |
| + t.Fatalf("member operator by name = %d %s", st, out) |
| + } |
| + c, csrf := signInAs(t, fx.consoleFixture, arMember, "code-ar-member-web") |
| + if _, _, body := get(t, c, fx.ts.URL+"/a/"+arSqid+"/apps/shop/settings"); !strings.Contains(body, appRegionSetCopy.ControlButton) { |
| + t.Fatal("a member operator does not see the region control") |
| + } |
| + if st, _, _ := postForm(t, c, fx.ts.URL+"/a/"+arSqid+"/apps/shop/region", url.Values{"csrf": {csrf}, "region": {"ie"}}); st != http.StatusSeeOther { |
| + t.Fatalf("member operator post = %d", st) |
| + } |
| + if r, _ := fx.stored(t, "shop"); r != "" { |
| + t.Fatalf("stored %q after the member operator's post, want the home", r) |
| + } |
| +} |
| + |
| +// A request that resolved one incarnation never writes another: the app is |
| +// purged and created again under the same name in the same second between |
| +// the request's resolution and its write. |
| +func TestAppRegionSetRefusesAReplacedApp(t *testing.T) { |
| + fx := newAppRegionFx(t) |
| + ctx := context.Background() |
| + created := time.Unix(1_700_000_000, 0) |
| + if _, err := fx.st.CreateAppIn(42, "cart", arOwner, created); err != nil { |
| + t.Fatal(err) |
| + } |
| + found, ok, err := fx.st.AppIncarnationContext(ctx, 42, "cart") |
| + if err != nil || !ok { |
| + t.Fatal(ok, err) |
| + } |
| + if err := fx.st.TrashAppRow(42, "cart", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.PurgeAppRow(42, "cart"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(42, "cart", arOwner, created); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, ref := fx.srv.setAppRegion(ctx, fx.acct, "cart", found, "uk", arOwner, "cli") |
| + if ref == nil || ref.Status != http.StatusConflict || ref.Msg != appRegionSetCopy.Changed { |
| + t.Fatalf("refusal = %+v, want the 409 changed sentence", ref) |
| + } |
| + // The store's own check, under the name lock, refuses it too. |
| + if ok, err := fx.st.SetAppRegion(ctx, 42, "cart", found, "", "uk", time.Now()); err != nil || ok { |
| + t.Fatalf("store write with the replaced incarnation = %v %v, want false", ok, err) |
| + } |
| + if r, _ := fx.stored(t, "cart"); r != "" { |
| + t.Fatalf("the replacement's region became %q", r) |
| + } |
| +} |
| + |
| +// With no home region named, the change is refused: the home could not be |
| +// chosen again afterwards. |
| +func TestAppRegionSetNeedsANamedHome(t *testing.T) { |
| + fx := newAppRegionFx(t) |
| + fx.srv.cfg.HomeRegion = "" |
| + owner := cliToken(t, fx.consoleFixture, arOwner, "code-ar-owner") |
| + st, out := fx.put(t, owner, "shop", "uk") |
| + var e struct{ Error string } |
| + json.Unmarshal([]byte(out), &e) |
| + if st != http.StatusConflict || e.Error != appRegionSetCopy.NoHome { |
| + t.Fatalf("no home = %d %s", st, out) |
| + } |
| + if r, _ := fx.stored(t, "shop"); r != "" { |
| + t.Fatalf("stored %q", r) |
| + } |
| +} |
diff --git a/internal/console/store.go b/internal/console/store.go| index a73d38883..90da15618 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -1702,7 +1702,17 @@ func (s *Store) AppRegion(accountID int64, app string) (region, source string, e |
| // vocabulary ("" is the home). The source becomes "changed" and |
| // region_set_at the time of the change. Nothing else reads the row's region |
| // to place an existing instance, so no instance moves. |
| +// |
| +// It holds the name's lock (apppolicy_names.go), which a purge and a |
| +// rename hold while they free the name, and compares the whole incarnation |
| +// under it, so a same-second replacement cannot pass for the app it |
| +// replaced. |
| func (s *Store) SetAppRegion(ctx context.Context, accountID int64, app string, inc AppIncarnation, from, to string, now time.Time) (ok bool, err error) { |
| + defer s.lockAppNames(appNameKey{accountID, app})() |
| + cur, live, err := s.AppIncarnationContext(ctx, accountID, app) |
| + if err != nil || !live || cur != inc { |
| + return false, err |
| + } |
| res, err := s.db.ExecContext(ctx, `UPDATE apps SET region = ?, region_source = 'changed', region_set_at = ? |
| WHERE account_id = ? AND app = ? AND deleted_at = 0 AND created_at = ? AND region = ?`, |
| to, now.Unix(), accountID, app, inc.createdAt, from) |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index bbee0a8e7..56f023174 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -1100,8 +1100,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 64 { |
| - t.Errorf("walked %d closed doors, want all %d (and 64 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)", |
| + if seen != len(closedDoors) || seen != 66 { |
| + t.Errorf("walked %d closed doors, want all %d (and 66 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)", |
| seen, len(closedDoors)) |
| } |
| } |
diff --git a/internal/provision/app_region_set_census_test.go b/internal/provision/app_region_set_census_test.go| new file mode 100644 |
| index 000000000..25b8a91c8 |
| --- /dev/null |
| +++ b/internal/provision/app_region_set_census_test.go |
| @@ -0,0 +1,33 @@ |
| +package provision |
| + |
| +// Record-write census entries for branch app-region-set (carlos apps |
| +// region: changing an app's stored region, the default for its new |
| +// instances), layered on regionLabelsWriteCensusInventory (main's newest at |
| +// the branch point b1d00ca7). Reviewed by the branch author; the root-read |
| +// card is docs/superpowers/notes/census-proposal-app-region-set.md. No |
| +// record write is added anywhere and no class or site kind changes: the |
| +// change writes the console's own apps row in SQLite, never a record. |
| +// - Server.registerCLIRoutes: registers GET and PUT |
| +// /api/cli/apps/{account}/{app}/region (appregionset.go). Same |
| +// "instances" and "sidecars" literals: still key-site. |
| +// - NewServer: registers POST /a/{sqid}/apps/{app}/region. Same |
| +// "instances" literal: still key-site. |
| +func appRegionSetWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), regionLabelsWriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "390e86260d25e9bf4968d5268a3d4842656c6594cbd497397302ece8b61e3a26"}, |
| + {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "b9b22ee5933f80618afa83e46c228632af67a7d2e5a15d3dae4a11dddff4bf77"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 9ba7acb51..e166f61ba 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := regionLabelsWriteCensusInventory() |
| + inventory := appRegionSetWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-app-region-set.tsv b/internal/provision/testdata/plan14-root-reads-app-region-set.tsv| index 36cf3f0fc..3d845424e 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-app-region-set.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-app-region-set.tsv |
| @@ -10,7 +10,7 @@ internal/console/store.go Store.NonHomeAppRegions legacy accepted-legacy accepte |
| internal/console/store.go Store.migrate legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: adds the three account/app-scoped lifetime intent tables and apps.lifetime at unarmed store boot, then backfills missing lifetimes;rev3=census-ruling-plans-4d-lapse;basis=adds the additive account_plans.lapse_since and account_plans.disabled columns and calls migratePlanLapse last, which creates the console's own plan_lapse_items table (plans 4d). No read added; the new store units are the plans-4d-units decision.;rev3=census-ruling-plans-6-checkout;basis=calls migrateBilling last, after main's migratePlanLapse, which creates the console's own billing tables (plans 6a, its own decision row); no read added here;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328/#329 plan 1 Task 9: calls migrateAppPolicy (a new unit: CREATE TABLE IF NOT EXISTS app_policy_revisions, the console's own table) before migratePlanLapse. The same two Exec sites; no read added here.;rev3=census-ruling-app-region-set;basis=adds the additive apps.region_set_at column (INTEGER NOT NULL DEFAULT 0) to the ALTER list; the same two Exec sites; no read added file:Exec@13226,file:Exec@20688 9cce47c664c920211c5f9ef290164c1b34962a2106f6a9bc7b797fcc4d71092a |
| internal/console/store.go Store.migrateAppsKey legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=console.service user carlos-console, J4 root-input: copies apps into the composite-key schema while preserving existing lifetimes and minting only missing ids;rev3=census-ruling-app-region-set;basis=carries region_set_at across the apps rebuild (column list and INSERT ... SELECT); console-owned table only; no read added file:Exec@2425,file:QueryRow@65 a6d4f9c819c32c9d311e793e3de0cbd9aa4f387fbaf3ca85b0e03d732a93182f |
| internal/console/templates/app_settings.html external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-design-edge-rate-limit-358;basis=the Settings page gains a Rate limit section: per instance host, a form of four numbers (busy at, per address while busy, backstop rate, backstop burst) and a reset form, both posting to /a/{sqid}/apps/{app}/ratelimit with the CSRF token, and the record's path rules listed read-only; embedded and rendered by the console (carlos-console), as before; no read added;rev3=census-ruling-console-ux-nav;basis=adds the Placement section (the existing POST /place form, moved from app_instances) and the Errors and analytics section; Advanced folds into General; link texts reworded; markup only; no read added;rev3=census-ruling-region-labels;basis=General gains a Region section (RC-18a, RC-18d, RC-19, RL-S1, or the unread sentence); the placement form's button reads Change fleet (RC-14); markup only; no read added;rev3=census-ruling-app-region-set;basis=the General Region section gains, for an owner or a deployment operator, a select of region codes and a Change region button posting to /a/{sqid}/apps/{app}/region with the CSRF token, and a note; markup only; no read added file:external@0 9a9cd510dbd50d7362db8355ecca9226eaf2c05dc89fe46ac33aa22abb33fca9 |
| -@coverage . 35092e4af1e6da9b70857f55eb1aaa26751c06e31020f5b100ffdf27eeed8fda |
| -@coverage internal/console f81dbf9f4361baa298d7da0f87777d82b42e946bfbbe09680ed21af69ffb19ad |
| +@coverage . fc29f7b37d6a5b150c9d5955b40300da7a8e7b830e41ff8dc7e0f4633d94f00f |
| +@coverage internal/console d3116f625665419a5503b481761fe60c81b86d8a9191fbf605ec6c32438ccef4 |
| @coverage internal/console/templates 31b5a71a123d232e2f36cd8032b5ff8d9f43c1474f203c81b2dd1852aeedc6e7 |
| @coverage internal/regionlabel a4cc5a2ff624a1aa3215c711302c7dc68d2bdca9853eadc372f31a8c99113872 |