deploy: a Publish credential can give a static app its first host
GET .../instances now admits Publish, so carlos deploy with a Publish credential gets past its first read. POST .../platform-host (Publish only, plus Admin) creates the app's static record at <app>.<sqid>.<apps-domain>; the caller sends a channel and a message and nothing else (strict body). The door writes nothing itself (Astra r1-4). It reads the app's manifest read-only (readEnableManifest) and hands the instance-create handler a body it builds, plus, when the app has no manifest, a default manifest in memory through a context value that only instanceManifest reads. Every write is the create handler's, after its own refusals and under its own locks, so a refused request leaves the manifest, audit rows and control/serial alone. No manifest is ever written: reconcile serves a manifest-less record. The door also refuses a channel whose head is not a static site (422, new copy row host.not_static, pending copy review): the create handler has no such check for a static record. instances-manifest stays shut to every role. mintPlatformHost falls back to the new door when the manifest door answers 403; a 404 from it (an older console) leaves the 403 standing. The claim census covers the door; claimDoor gains opts so its console has a home region, as a claim console in production has.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+624
−10
deploy.go+27 −8deploy_platformhost.go+38 −0deploy_test.go+62 −0docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md+3 −0internal/console/apiinstances.go+6 −0internal/console/apiplatformhost.go+126 −0internal/console/apiplatformhost_test.go+333 −0internal/console/claim_invariant_fixtures_test.go+11 −0internal/console/claim_invariant_test.go+4 −1internal/console/platform_copy.go+2 −0internal/console/routedecls.go+11 −1internal/console/testdata/claim-routes.txt+1 −0
diff --git a/deploy.go b/deploy.go| index 1ef7d5b35..2ebe10d9e 100644 |
| --- a/deploy.go |
| +++ b/deploy.go |
| @@ -1083,17 +1083,36 @@ var errNoStaticHost = errors.New("no static host") |
| // stays right regardless: this caller has already resolved the channel it is |
| // about to promote to, and a record minted on a different one would serve |
| // something else. |
| +// |
| +// A service credential meets the manifest door's 403 (that door is |
| +// person-only), and takes the platform-host door instead (platform accounts |
| +// spec §6.3): the same record, with no manifest written. A console that |
| +// predates that door answers it 404, and the 403 stands. |
| func mintPlatformHost(ctx context.Context, sess *apiSession, acct apiAcct, app, channel string, messages ...string) (apiInstanceRecord, error) { |
| m, err := sess.instancesEnable(ctx, acct, app, nil, nil, nil) |
| - if err != nil { |
| - return apiInstanceRecord{}, err |
| - } |
| - // No environment: the app's apex serves its default config bundle, which |
| - // is exactly right — this is the app's primary host, the one every other |
| - // bundle's origin values are written to name. |
| - rec, err := sess.instanceCreate(ctx, acct, app, app+"."+m.Domain, "", channel, "static", "", nil, nil, nil, firstMutationMessage(messages)) |
| - if err != nil { |
| + var rec apiInstanceRecord |
| + var denied *enableError |
| + switch { |
| + case errors.As(err, &denied) && denied.status == http.StatusForbidden: |
| + var hostErr error |
| + rec, hostErr = sess.platformHost(ctx, acct, app, channel, firstMutationMessage(messages)) |
| + var missing *enableError |
| + if errors.As(hostErr, &missing) && missing.status == http.StatusNotFound { |
| + return apiInstanceRecord{}, err |
| + } |
| + if hostErr != nil { |
| + return apiInstanceRecord{}, hostErr |
| + } |
| + case err != nil: |
| return apiInstanceRecord{}, err |
| + default: |
| + // No environment: the app's apex serves its default config bundle, |
| + // which is exactly right — this is the app's primary host, the one |
| + // every other bundle's origin values are written to name. |
| + rec, err = sess.instanceCreate(ctx, acct, app, app+"."+m.Domain, "", channel, "static", "", nil, nil, nil, firstMutationMessage(messages)) |
| + if err != nil { |
| + return apiInstanceRecord{}, err |
| + } |
| } |
| fmt.Fprintf(stdout, "%s %s (static, channel %s)\n", |
| colorFor(stdout).ok("minted"), rec.Host, rec.Channel) |
diff --git a/deploy_platformhost.go b/deploy_platformhost.go| new file mode 100644 |
| index 000000000..0873385b4 |
| --- /dev/null |
| +++ b/deploy_platformhost.go |
| @@ -0,0 +1,38 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| +) |
| + |
| +// platformHost asks the console's platform-host door (platform accounts |
| +// spec §6.3) to give app its first host, <app>.<sqid>.<apps-domain>, as a |
| +// static record on channel: the service credential's way to the host a |
| +// person gets through the instances-manifest door, which is person-only. |
| +// The door's answer is the create door's, so the record decodes the same. |
| +// |
| +// A refusal is an *enableError: it carries the status, so mintPlatformHost |
| +// can tell an older console (404) from a real refusal, and runDeploy's |
| +// enableUnavailable reads this door's "no platform host here" answers (503 |
| +// no apps domain, 409 an instance domain an operator pinned) as it reads |
| +// the manifest door's. |
| +func (s *apiSession) platformHost(ctx context.Context, a apiAcct, app, channel, message string) (apiInstanceRecord, error) { |
| + in := struct { |
| + Channel string `json:"channel"` |
| + Message string `json:"message,omitempty"` |
| + }{channel, message} |
| + status, body, err := s.postJSON(ctx, apiPath(a, app, "/platform-host"), in) |
| + if err != nil { |
| + return apiInstanceRecord{}, err |
| + } |
| + if status != http.StatusCreated { |
| + return apiInstanceRecord{}, &enableError{status: status, msg: apiErrorFromBody(status, body).Error()} |
| + } |
| + var out apiInstanceRecord |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + return apiInstanceRecord{}, fmt.Errorf("platform host: unreadable response: %w", err) |
| + } |
| + return out, nil |
| +} |
diff --git a/deploy_test.go b/deploy_test.go| index 11c24a9d2..376caa951 100644 |
| --- a/deploy_test.go |
| +++ b/deploy_test.go |
| @@ -13,6 +13,7 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "reflect" |
| "strings" |
| "sync" |
| "sync/atomic" |
| @@ -1841,6 +1842,67 @@ func TestMintPlatformHostForbiddenIsNotUnavailable(t *testing.T) { |
| } |
| } |
| +// A service credential meets the manifest door's 403 (it is person-only), |
| +// and the mint falls back to the platform-host door: the same record and |
| +// the same "minted" line, with nothing but the channel and the message sent. |
| +func TestMintPlatformHostFallsBackForAServiceCredential(t *testing.T) { |
| + var sent map[string]any |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch { |
| + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/apps/bab/mysite/instances-manifest"): |
| + w.WriteHeader(http.StatusForbidden) |
| + io.WriteString(w, `{"error":"this credential holds role \"publish\"; this door needs one of []"}`) |
| + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/apps/bab/mysite/platform-host"): |
| + if err := json.NewDecoder(r.Body).Decode(&sent); err != nil { |
| + t.Errorf("decode platform-host: %v", err) |
| + } |
| + w.WriteHeader(http.StatusCreated) |
| + io.WriteString(w, `{"host":"mysite.bab.oncarlos.test","kind":"static","channel":"edge"}`) |
| + default: |
| + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) |
| + w.WriteHeader(http.StatusTeapot) |
| + } |
| + })) |
| + defer ts.Close() |
| + |
| + out := captureStdout(t) |
| + rec, err := mintPlatformHost(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "mysite", "edge", "publish the new site") |
| + if err != nil { |
| + t.Fatalf("mintPlatformHost: %v", err) |
| + } |
| + if rec.Host != "mysite.bab.oncarlos.test" || rec.Kind != "static" || rec.Channel != "edge" { |
| + t.Fatalf("record = %+v, want the platform-host door's", rec) |
| + } |
| + if want := map[string]any{"channel": "edge", "message": "publish the new site"}; !reflect.DeepEqual(sent, want) { |
| + t.Fatalf("platform-host body = %#v, want %#v", sent, want) |
| + } |
| + if got := out.String(); got != "minted mysite.bab.oncarlos.test (static, channel edge)\n" { |
| + t.Fatalf("stdout = %q, want the minted line", got) |
| + } |
| +} |
| + |
| +// A console from before the platform-host door answers it 404: the |
| +// manifest door's 403 is the refusal that stands, unchanged. |
| +func TestMintPlatformHostOnAnOlderConsole(t *testing.T) { |
| + const refusal = `this credential holds role "publish"; this door needs one of []` |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch { |
| + case strings.HasSuffix(r.URL.Path, "/instances-manifest"): |
| + w.WriteHeader(http.StatusForbidden) |
| + json.NewEncoder(w).Encode(map[string]string{"error": refusal}) |
| + default: |
| + http.NotFound(w, r) |
| + } |
| + })) |
| + defer ts.Close() |
| + |
| + _, err := mintPlatformHost(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "mysite", "edge") |
| + var denied *enableError |
| + if !errors.As(err, &denied) || denied.status != http.StatusForbidden || err.Error() != refusal { |
| + t.Fatalf("err = %v, want the manifest door's 403 %q", err, refusal) |
| + } |
| +} |
| + |
| // ---- the build probe: watching the app's own report, not the edge's header -- |
| // TestWatchProbeMatchesAWholeToken: the probe body must carry the build as a |
diff --git a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md| index 8e80c6164..990e7abd6 100644 |
| --- a/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md |
| +++ b/docs/superpowers/plans/2026-11-19-platform-accounts-1-platform-layer.md |
| @@ -1241,6 +1241,7 @@ Every row is pending copy review (Task 15). `%s`/`%d` are filled as named. CLI e |
| | cred.role | a customer credential is publish for the whole account, or deploy for one app with its rungs | |
| | cred.ttl | a customer credential lasts from 1 minute to 24 hours | |
| | cred.failed | could not mint the credential. try again | |
| +| host.not_static | channel %s serves %s, which isn’t a static site, so it can’t be given a static host | |
| | svc.platform_app | a platform credential works for the whole platform account, so it takes no --app | |
| | svc.not_platform | only a platform account can hold a platform credential. an operator grants that with carlos accounts platform | |
| @@ -1364,6 +1365,8 @@ Task 1's UX pass (2026-11-19) changed the text of `ValueByOn`, `LabelPlans`, `La |
| Task 11 added, all pending copy review: `FlagCreateRef` (`--ref` on `customers create`, where it is also what makes a retry safe: create is idempotent only on the ref, Task 8), `CreateRetry` (the last lines of `carlos platform`'s usage, which is otherwise command syntax), `HelpLine` (`platform`'s line in `carlos help`, under "Your deployment" after `services`; Task 11 follow-up), and `SqidRequired`/`SqidInvalid` (the CLI's refusal of a missing or malformed `--platform` or `--customer` before anything is sent, `%s` the flag; worded as the existing `--account` refusals in `store.go`). |
| +Task 12 added `host.not_static` (pending copy review): the platform-host door's 422 for a channel whose head is a release that is not a static site, filled with the channel and that release's version. The brief listed this refusal among the door's witnesses, but the create handler has no such check for a static record (`staticHeadRefusal` refuses only an instance on a static head), so the door makes it, read-only, before delegating. |
| + |
| Task 6 added `ReasonRequired` (the CLI's refusal of `--grant` or `--revoke` without `--reason`, before anything is sent; the text of the console's `grant.reason`), `ReasonAlone` (its refusal of `--reason` with neither, pending copy review; Task 6 fix round 1) and `Usage` (the `platform` line in `carlos accounts`' usage). |
| Cap names in usage reuse the approved `cliPlanCopyLimit*` labels (apps and instances, object storage, emails a day, bandwidth a month, awake hours a month); `CapPDF` is the one new label. |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 552fca003..3fb00647b 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -164,6 +164,12 @@ func (s *Server) instanceManifest(ctx context.Context, w http.ResponseWriter, ac |
| case err == nil: |
| return m, true |
| case errors.Is(err, os.ErrNotExist): |
| + // The platform-host door's default manifest (apiplatformhost.go): |
| + // admission for this one request, never written. Read here and |
| + // nowhere else. |
| + if dm, ok := ctx.Value(defaultManifestKey{}).(*provision.Manifest); ok && dm != nil { |
| + return dm, true |
| + } |
| // Membership (or binding) is already proven, so this may name its |
| // cause and the operator act that fixes it. |
| jsonError(w, http.StatusConflict, |
diff --git a/internal/console/apiplatformhost.go b/internal/console/apiplatformhost.go| new file mode 100644 |
| index 000000000..3d87e139a |
| --- /dev/null |
| +++ b/internal/console/apiplatformhost.go |
| @@ -0,0 +1,126 @@ |
| +package console |
| + |
| +// The platform-host door (platform accounts spec §6.3, plan D3): |
| +// POST /api/cli/apps/{account}/{app}/platform-host gives a static app its |
| +// first host, <app>.<sqid>.<apps-domain>, for a Publish credential. A person |
| +// gets that host from `carlos deploy --kind static` through the |
| +// instances-manifest door and then the create door; the manifest door stays |
| +// person-only (policyDoors pins it), so a service credential's deploy comes |
| +// here instead. |
| +// |
| +// The door performs no write of its own (Astra r1-4). It hands the |
| +// instance-create handler a body it builds itself (the host, kind static, |
| +// and the caller's channel and message: nothing else is the caller's to |
| +// choose) and, when the app has no instances manifest, a default manifest |
| +// in memory through the request's context. Every write is then the create |
| +// handler's, after its own refusals (the service control-plane refusal, |
| +// lifetimes, the host suffix, the caps) and under its own locks: a refused |
| +// request leaves the manifest, the audit trail and control/serial as they |
| +// were. No manifest is written at all: reconcile serves a record whose app |
| +// has none ("the manifest only governs the API door", provision/reconcile.go), |
| +// as it always has for the domains door's static first route. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// defaultManifestKey carries the platform-host door's in-memory manifest to |
| +// instanceManifest, its only reader (TestDefaultManifestKeyIsReadOnlyByInstanceManifest). |
| +type defaultManifestKey struct{} |
| + |
| +// withDefaultManifest is ctx carrying m as the manifest instanceManifest |
| +// answers when the app has none in the bucket. handleAPIPlatformHost is its |
| +// only caller. |
| +func withDefaultManifest(ctx context.Context, m *provision.Manifest) context.Context { |
| + return context.WithValue(ctx, defaultManifestKey{}, m) |
| +} |
| + |
| +// platformHostRequest is the door's whole body: unknown fields are refused, |
| +// so a caller cannot name a host, a kind or anything else. |
| +type platformHostRequest struct { |
| + Channel string `json:"channel"` |
| + Message string `json:"message"` |
| +} |
| + |
| +// handleAPIPlatformHost answers POST .../platform-host with exactly the |
| +// create door's answer. In order: the account and app (the family's |
| +// byte-identical 404), the body (strict; the channel is required and |
| +// checked as the enable door checks it), the channel's head (a head that is |
| +// not a static site is refused, and one that cannot be read refuses too), |
| +// the platform domain (instancesDomain) and the app's manifest |
| +// (readEnableManifest, read-only: an absent one is the default, with a |
| +// born-HA app's pool and regions bound in memory), then the create handler. |
| +func (s *Server) handleAPIPlatformHost(w http.ResponseWriter, r *http.Request) { |
| + _, acct, app, ok := s.apiAccountApp(w, r) |
| + if !ok { |
| + return |
| + } |
| + var req platformHostRequest |
| + if !readJSONStrictLimit(w, r, &req, 8<<10) { |
| + return |
| + } |
| + if !release.ValidChannel(req.Channel) { |
| + jsonError(w, http.StatusBadRequest, "invalid channel name") |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| + defer cancel() |
| + if ref := s.platformHostHeadRefusal(ctx, acct, app, req.Channel); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + domain, ref := s.instancesDomain(acct) |
| + if ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + m, _, absent, ref := s.readEnableManifest(ctx, acct, app, domain) |
| + if ref != nil { |
| + writeHARefusal(w, ref) |
| + return |
| + } |
| + // A map of strings always marshals. |
| + body, _ := json.Marshal(map[string]string{ |
| + "host": app + "." + m.Domain, "kind": "static", "channel": req.Channel, "message": req.Message, |
| + }) |
| + createCtx := r.Context() |
| + if absent { |
| + createCtx = withDefaultManifest(createCtx, m) |
| + } |
| + create := r.Clone(createCtx) |
| + create.Body = io.NopCloser(bytes.NewReader(body)) |
| + create.ContentLength = int64(len(body)) |
| + // apiAccountApp above already wrote this request's plan warnings; the |
| + // create handler's own gate would add each one a second time. |
| + create.Header.Del(planWarningsAccept) |
| + s.handleAPIInstanceCreate(w, create) |
| +} |
| + |
| +// platformHostHeadRefusal refuses a channel whose head is a release that is |
| +// not a static site: the edge serves a static route only from a static |
| +// release (internal/edge/static.go), so the host would be minted serving |
| +// nothing. The create handler asks the reverse question only |
| +// (staticHeadRefusal: an instance on a static head). A channel with nothing |
| +// on it yet passes: a first deploy mints the host before it ships. A head |
| +// that cannot be read refuses, at 502. |
| +func (s *Server) platformHostHeadRefusal(ctx context.Context, acct *Account, app, channel string) *doorRefusal { |
| + head, err := s.readChannelHeadChecked(ctx, acct.Sqid, app, channel) |
| + switch { |
| + case err != nil: |
| + log.Printf("console: platform host %s/%s: read channel %s: %v", acct.Sqid, app, channel, err) |
| + return &doorRefusal{Status: http.StatusBadGateway, Msg: rootfsReleasesUnreadableMsg} |
| + case head != nil && head.Manifest.Kind != "static": |
| + return &doorRefusal{Status: http.StatusUnprocessableEntity, |
| + Msg: fmt.Sprintf(platformCopy["host.not_static"], channel, head.Version)} |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/apiplatformhost_test.go b/internal/console/apiplatformhost_test.go| new file mode 100644 |
| index 000000000..fcc02af02 |
| --- /dev/null |
| +++ b/internal/console/apiplatformhost_test.go |
| @@ -0,0 +1,333 @@ |
| +package console |
| + |
| +// The platform-host door (apiplatformhost.go, platform accounts spec §6.3): |
| +// a Publish credential gives a static app its first host. The door writes |
| +// nothing of its own (Astra r1-4): every write is the instance-create |
| +// handler's, so a refused request leaves the manifest, the audit trail and |
| +// the serial as they were. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +// platformHostFixture is the ops account with a platform apps domain and a |
| +// fresh app, site, that has no instances manifest and no records. |
| +func platformHostFixture(t *testing.T) *consoleFixture { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.AppsDomain = "oncarlos.test" |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "site", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + return fx |
| +} |
| + |
| +func platformHostURL(fx *consoleFixture, app string) string { |
| + return fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/" + app + "/platform-host" |
| +} |
| + |
| +func platformHostOf(fx *consoleFixture, app string) string { |
| + return app + "." + fx.sqid + ".oncarlos.test" |
| +} |
| + |
| +// manifestAbsent reports whether app has no instances manifest. |
| +func manifestAbsent(t *testing.T, fx *consoleFixture, app string) bool { |
| + t.Helper() |
| + _, err := provision.GetManifest(context.Background(), fx.rel, fx.sqid, app) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("read the manifest: %v", err) |
| + } |
| + return errors.Is(err, os.ErrNotExist) |
| +} |
| + |
| +func TestPublishCredentialListsInstances(t *testing.T) { |
| + fx := platformHostFixture(t) |
| + tok := serviceToken(t, fx.st, OpsAccountID, "ci", "", svcrole.Publish) |
| + status, _, out := rawReq(t, http.MethodGet, instancesURL(fx, fx.sqid, "site"), tok, "") |
| + if status != http.StatusOK { |
| + t.Fatalf("publish lists instances = %d %s, want 200", status, out) |
| + } |
| +} |
| + |
| +func TestPlatformHostDoorMintsTheAppsStaticHost(t *testing.T) { |
| + fx := platformHostFixture(t) |
| + tok := serviceToken(t, fx.st, OpsAccountID, "ci", "", svcrole.Publish) |
| + status, _, out := rawReq(t, http.MethodPost, platformHostURL(fx, "site"), tok, `{"channel":"edge","message":"first host"}`) |
| + if status != http.StatusCreated { |
| + t.Fatalf("platform-host = %d %s, want 201", status, out) |
| + } |
| + host := platformHostOf(fx, "site") |
| + var reply provision.Record |
| + if err := json.Unmarshal([]byte(out), &reply); err != nil { |
| + t.Fatal(err) |
| + } |
| + if reply.Host != host || reply.Kind != "static" || reply.Channel != "edge" { |
| + t.Fatalf("reply = %+v, want the create door's record for %s, static on edge", reply, host) |
| + } |
| + rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "site", host) |
| + if err != nil { |
| + t.Fatalf("record: %v", err) |
| + } |
| + if rec.Kind != "static" || rec.Channel != "edge" || rec.Host != host { |
| + t.Fatalf("record = %+v, want static at %s on edge", rec, host) |
| + } |
| + if !manifestAbsent(t, fx, "site") { |
| + t.Fatal("the door wrote an instances manifest; it must write none (Astra r1-4)") |
| + } |
| +} |
| + |
| +// The reconcile.go contract the door stands on: a record whose app has no |
| +// instances manifest is served all the same ("the manifest only governs the |
| +// API door"). |
| +func TestPlatformHostRecordServesWithoutAManifest(t *testing.T) { |
| + fx := platformHostFixture(t) |
| + tok := serviceToken(t, fx.st, OpsAccountID, "ci", "", svcrole.Publish) |
| + if status, _, out := rawReq(t, http.MethodPost, platformHostURL(fx, "site"), tok, `{"channel":"edge"}`); status != http.StatusCreated { |
| + t.Fatalf("platform-host = %d %s", status, out) |
| + } |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if err := provision.Reconcile(context.Background(), fx.rel, reg, |
| + provision.ReconcileConfig{DataDir: t.TempDir()}); err != nil { |
| + t.Fatalf("reconcile: %v", err) |
| + } |
| + host := platformHostOf(fx, "site") |
| + got, err := reg.Get(host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got == nil { |
| + t.Fatal("the record never became a route: a manifest-less record must still serve") |
| + } |
| + if got.Kind != "static" || got.Channel != "edge" || got.App != "site" || got.Account != fx.sqid { |
| + t.Fatalf("route = %+v, want site's static route on edge", *got) |
| + } |
| + if !manifestAbsent(t, fx, "site") { |
| + t.Fatal("an instances manifest appeared") |
| + } |
| +} |
| + |
| +func TestPlatformHostDoorLeavesAnExistingManifestAlone(t *testing.T) { |
| + fx := platformHostFixture(t) |
| + m := provision.Manifest{Schema: 1, App: "site", Domain: fx.sqid + ".oncarlos.test", Channel: "beta"} |
| + if err := provision.PutManifest(context.Background(), fx.rel, fx.sqid, "site", m); err != nil { |
| + t.Fatal(err) |
| + } |
| + key := provision.ManifestKey(fx.sqid, "site") |
| + before, etagBefore, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tok := serviceToken(t, fx.st, OpsAccountID, "ci", "", svcrole.Publish) |
| + if status, _, out := rawReq(t, http.MethodPost, platformHostURL(fx, "site"), tok, `{"channel":"edge"}`); status != http.StatusCreated { |
| + t.Fatalf("platform-host = %d %s", status, out) |
| + } |
| + after, etagAfter, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if string(after) != string(before) || etagAfter != etagBefore { |
| + t.Fatalf("the manifest changed:\n before %s (%s)\n after %s (%s)", before, etagBefore, after, etagAfter) |
| + } |
| + rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "site", platformHostOf(fx, "site")) |
| + if err != nil || rec.Channel != "edge" || rec.Kind != "static" { |
| + t.Fatalf("record = %+v, %v; want static on the channel sent", rec, err) |
| + } |
| +} |
| + |
| +func TestPlatformHostDoorRoles(t *testing.T) { |
| + for _, tc := range []struct { |
| + role svcrole.Role |
| + want int |
| + }{ |
| + {svcrole.Publish, http.StatusCreated}, |
| + {svcrole.Admin, http.StatusCreated}, |
| + {svcrole.Deploy, http.StatusForbidden}, |
| + {svcrole.Instance, http.StatusForbidden}, |
| + {svcrole.Operate, http.StatusForbidden}, |
| + } { |
| + t.Run(string(tc.role), func(t *testing.T) { |
| + fx := platformHostFixture(t) |
| + var tok string |
| + switch tc.role { |
| + case svcrole.Deploy: |
| + var err error |
| + tok, err = fx.st.NewServicePrincipalScoped(OpsAccountID, "ci", "site", svcrole.Deploy, []string{"edge"}, nil, "paul@keymail.dev", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + case svcrole.Instance: |
| + tok = serviceToken(t, fx.st, OpsAccountID, "ci", "site", tc.role) |
| + default: |
| + tok = serviceToken(t, fx.st, OpsAccountID, "ci", "", tc.role) |
| + } |
| + status, _, out := rawReq(t, http.MethodPost, platformHostURL(fx, "site"), tok, `{"channel":"edge"}`) |
| + if status != tc.want || (tc.want == http.StatusForbidden && !strings.Contains(out, "this door needs one of")) { |
| + t.Fatalf("%s at platform-host = %d %s, want %d", tc.role, status, out, tc.want) |
| + } |
| + _, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "site", platformHostOf(fx, "site")) |
| + if wrote := err == nil; wrote != (tc.want == http.StatusCreated) { |
| + t.Fatalf("%s: record written = %v, want %v", tc.role, wrote, tc.want == http.StatusCreated) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// platformHostState is what a refused request must leave as it was: the |
| +// manifest's absence, the app's audit rows and control/serial. |
| +type platformHostState struct { |
| + manifestAbsent bool |
| + events []Event |
| + serial, etag string |
| +} |
| + |
| +func platformHostSnapshot(t *testing.T, fx *consoleFixture) platformHostState { |
| + t.Helper() |
| + events, err := fx.st.EventsContext(context.Background(), OpsAccountID, "site", 1000) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + st := platformHostState{manifestAbsent: manifestAbsent(t, fx, "site"), events: events} |
| + b, etag, err := fx.rel.Get(context.Background(), "control/serial") |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + case err != nil: |
| + t.Fatal(err) |
| + default: |
| + st.serial, st.etag = string(b), etag |
| + } |
| + return st |
| +} |
| + |
| +func TestPlatformHostDoorRefusalsWriteNothing(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + setup func(t *testing.T, fx *consoleFixture) |
| + body string |
| + want int |
| + msg string // a substring of the refusal |
| + }{ |
| + {name: "control plane", want: http.StatusForbidden, msg: "site is the control plane", body: `{"channel":"edge"}`, |
| + setup: func(t *testing.T, fx *consoleFixture) { |
| + if err := fx.st.SetAppControlPlane(OpsAccountID, "site", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {name: "bad channel", want: http.StatusBadRequest, msg: "invalid channel name", body: `{"channel":"Not A Channel"}`}, |
| + {name: "no channel", want: http.StatusBadRequest, msg: "invalid channel name", body: `{}`}, |
| + {name: "a field it does not take", want: http.StatusBadRequest, msg: `unknown field \"host\"`, body: `{"channel":"edge","host":"other.bab.oncarlos.test"}`}, |
| + {name: "channel head not static", want: http.StatusUnprocessableEntity, msg: "channel edge serves v1, which isn’t a static site", body: `{"channel":"edge"}`, |
| + setup: func(t *testing.T, fx *consoleFixture) { |
| + shipVersion(t, fx, "site", "v1") |
| + seedChannel(t, fx, "site", "edge", "v1") |
| + }}, |
| + {name: "running things cap", want: http.StatusConflict, msg: `"code":"cap"`, body: `{"channel":"edge"}`, |
| + setup: func(t *testing.T, fx *consoleFixture) { atRunningCap(t, fx, 3) }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fx := platformHostFixture(t) |
| + if tc.setup != nil { |
| + tc.setup(t, fx) |
| + } |
| + tok := serviceToken(t, fx.st, OpsAccountID, "ci", "", svcrole.Publish) |
| + before := platformHostSnapshot(t, fx) |
| + if !before.manifestAbsent { |
| + t.Fatal("setup wrote a manifest") |
| + } |
| + status, _, out := rawReq(t, http.MethodPost, platformHostURL(fx, "site"), tok, tc.body) |
| + if status != tc.want || !strings.Contains(out, tc.msg) { |
| + t.Fatalf("platform-host = %d %s, want %d with %s", status, out, tc.want, tc.msg) |
| + } |
| + after := platformHostSnapshot(t, fx) |
| + if !after.manifestAbsent { |
| + t.Error("a refused request wrote an instances manifest") |
| + } |
| + if !reflect.DeepEqual(after.events, before.events) { |
| + t.Errorf("a refused request wrote audit rows:\n before %+v\n after %+v", before.events, after.events) |
| + } |
| + if after.serial != before.serial || after.etag != before.etag { |
| + t.Errorf("a refused request bumped control/serial: %q (%s) -> %q (%s)", before.serial, before.etag, after.serial, after.etag) |
| + } |
| + if _, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "site", platformHostOf(fx, "site")); err == nil { |
| + t.Error("a refused request wrote a record") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestDefaultManifestKeyIsReadOnlyByInstanceManifest: the in-memory default |
| +// manifest is admission for one request, so exactly two places may touch |
| +// its key: apiplatformhost.go, which declares it and sets it |
| +// (withDefaultManifest, called only by handleAPIPlatformHost), and |
| +// instanceManifest, which reads it. Any other reader would let the absent |
| +// manifest's stand-in govern something it was never checked for. |
| +func TestDefaultManifestKeyIsReadOnlyByInstanceManifest(t *testing.T) { |
| + files, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fset := token.NewFileSet() |
| + var keyAt, setterAt []string |
| + for _, f := range files { |
| + if strings.HasSuffix(f, "_test.go") { |
| + continue |
| + } |
| + file, err := parser.ParseFile(fset, f, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, decl := range file.Decls { |
| + where := f + ":<top level>" |
| + if fn, ok := decl.(*ast.FuncDecl); ok { |
| + where = f + ":" + fn.Name.Name |
| + } |
| + ast.Inspect(decl, func(n ast.Node) bool { |
| + id, ok := n.(*ast.Ident) |
| + if !ok { |
| + return true |
| + } |
| + switch id.Name { |
| + case "defaultManifestKey": |
| + if !slices.Contains(keyAt, where) { |
| + keyAt = append(keyAt, where) |
| + } |
| + case "withDefaultManifest": |
| + if !slices.Contains(setterAt, where) { |
| + setterAt = append(setterAt, where) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + slices.Sort(keyAt) |
| + slices.Sort(setterAt) |
| + wantKey := []string{"apiinstances.go:instanceManifest", "apiplatformhost.go:<top level>", "apiplatformhost.go:withDefaultManifest"} |
| + if !reflect.DeepEqual(keyAt, wantKey) { |
| + t.Errorf("defaultManifestKey appears in %q, want only %q", keyAt, wantKey) |
| + } |
| + wantSetter := []string{"apiplatformhost.go:handleAPIPlatformHost", "apiplatformhost.go:withDefaultManifest"} |
| + if !reflect.DeepEqual(setterAt, wantSetter) { |
| + t.Errorf("withDefaultManifest appears in %q, want only its declaration and handleAPIPlatformHost: %q", setterAt, wantSetter) |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index e59a357eb..0941cc97c 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1803,6 +1803,17 @@ var claimFixtures = map[string]claimFixture{ |
| setup: func(t *testing.T, cx *claimCase) { cx.instanceWorld(t) }, |
| do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/instances", `{"host":"acme.go.tito.io","region":"ie"}`), |
| }}, |
| + // The platform-host door (apiplatformhost.go) is the create door with a |
| + // body it builds itself: titogo has no instances manifest here, so the |
| + // create runs on the door's in-memory default and claims titogo's |
| + // static platform host under the create's own admission. The body names |
| + // no region, so the record is the home region's: the console is given |
| + // one, as a claim console in production has. |
| + "route POST /api/cli/apps/{account}/{app}/platform-host": {door: &claimDoor{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/platform-host", `{"channel":"site"}`), |
| + opts: []func(*Config){func(c *Config) { c.HomeRegion = "ie" }}, |
| + }}, |
| "route POST /api/cli/apps/{account}/{app}/instances/{host}/channel": {door: &claimDoor{ |
| apps: claimRefs("bab/titogo"), |
| setup: func(t *testing.T, cx *claimCase) { |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 10ec5f335..7698e0fa8 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -178,6 +178,9 @@ type claimDoor struct { |
| // rejected probe (bad session, CSRF or id) leaves the world unchanged, so |
| // it fails the open check however it answered. |
| check func(t *testing.T, cx *claimCase, open bool) string |
| + // opts, when set, configure the door's console beyond the world's |
| + // defaults (a home region, for a create that names no region). |
| + opts []func(*Config) |
| } |
| // claimWindow is what one measured request left behind. |
| @@ -489,7 +492,7 @@ func claimFixtureCensus(entries []claimEntry, fixtures map[string]claimFixture) |
| // writers the open run reached. |
| func runClaimDoor(t *testing.T, d *claimDoor, opts ...func(*Config)) ([]string, []string) { |
| t.Helper() |
| - cx := newClaimCaseWith(t, opts...) |
| + cx := newClaimCaseWith(t, append(slices.Clone(opts), d.opts...)...) |
| if d.setup != nil { |
| d.setup(t, cx) |
| } |
diff --git a/internal/console/platform_copy.go b/internal/console/platform_copy.go| index 053119938..43fb3aed2 100644 |
| --- a/internal/console/platform_copy.go |
| +++ b/internal/console/platform_copy.go |
| @@ -40,6 +40,8 @@ var platformCopy = map[string]string{ |
| "cred.ttl": "a customer credential lasts from 1 minute to 24 hours", |
| "cred.failed": "could not mint the credential. try again", |
| + "host.not_static": "channel %s serves %s, which isn’t a static site, so it can’t be given a static host", |
| + |
| "svc.platform_app": "a platform credential works for the whole platform account, so it takes no --app", |
| "svc.not_platform": "only a platform account can hold a platform credential. an operator grants that with carlos accounts platform", |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index beaa8e46e..f977f5270 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -610,7 +610,17 @@ var routeDecls = []routeDecl{ |
| // while the handler refuses is a registration that lies. As at the mint |
| // door, the ANSWER a credential gets here moves from 401 to 403. |
| {Pattern: "PUT /api/cli/apps/{account}/{app}/instances-manifest", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIInstanceEnable}, |
| - {Pattern: "GET /api/cli/apps/{account}/{app}/instances", Kind: kindCLIScoped, Allow: svcrole.Allow(svcrole.Instance, svcrole.Deploy), Target: scopeList, Handler: (*Server).handleAPIInstanceList}, |
| + // Publish reads the records of an app it already deploys and manages |
| + // hostnames for: `carlos deploy` lists them before anything else |
| + // (platform accounts spec §6.3). |
| + {Pattern: "GET /api/cli/apps/{account}/{app}/instances", Kind: kindCLIScoped, Allow: svcrole.Allow(svcrole.Instance, svcrole.Deploy, svcrole.Publish), Target: scopeList, Handler: (*Server).handleAPIInstanceList}, |
| + // A static app's first host for a Publish credential (apiplatformhost.go, |
| + // platform accounts spec §6.3): the host `carlos deploy --kind static` |
| + // mints for a person through the manifest door above, which stays shut |
| + // to every role. Narrow: the caller names a channel and a message, and |
| + // the door writes nothing itself; the create handler below does every |
| + // write, after its own refusals. |
| + {Pattern: "POST /api/cli/apps/{account}/{app}/platform-host", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Publish), Handler: (*Server).handleAPIPlatformHost}, |
| // The armed-regions answer for consumer pickers (issue #346) — the |
| // same gate and role as the list beside it; see handleAPIRegions. |
| {Pattern: "GET /api/cli/apps/{account}/{app}/regions", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Instance, svcrole.Deploy), Handler: (*Server).handleAPIRegions}, |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index fd62c40f0..e64b59611 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -325,6 +325,7 @@ route POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/append |
| route POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/blobs |
| route POST /api/cli/apps/{account}/{app}/pdf/{route...} |
| route POST /api/cli/apps/{account}/{app}/place |
| +route POST /api/cli/apps/{account}/{app}/platform-host |
| route POST /api/cli/apps/{account}/{app}/promote |
| route POST /api/cli/apps/{account}/{app}/regions/guess |
| route POST /api/cli/apps/{account}/{app}/relay |