console: audit refused interactive-session attempts (rootfs plan 6)
Paul's ruling, 2026-10-31: every refusal the session door gives a caller it has placed in the account writes one interactive-refused row through auditActivity, before the upgrade (the HTTP answer) and after it (End refused, admission refusals included). TargetType instance, Target the host; Detail JSON: the requested argv or process, the HTTP status before the upgrade, the refusal code and the sentence sent. The row is the console's own database: no store request is added. No row for an unauthenticated request (401 at the auth layer), the person and membership 404s, or a host-claim console's C35, whose app SQL write would be admitted through the claim's bucket objects. Plan Task 10 step 5 and its test comment now cite the ruling.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+386
−25
docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md+2 −2internal/console/apiinteractive.go+58 −22internal/console/apiinteractive_refused_test.go+324 −0internal/console/apiinteractive_test.go+2 −1
diff --git a/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md b/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md| index 75d2e3ffc..01ffa76ef 100644 |
| --- a/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md |
| +++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md |
| @@ -1292,7 +1292,7 @@ After the upgrade: |
| 2. Read the `Open` frame within `OpenWait`. It must pass `Normalized().Check()`, else End refused RFS-6-C36. A `console` process resolves to the argv of `Processes["console"]` in the manifest of the version the record's channel serves, else End refused RFS-6-C33. (Rev 2, Astra R1 P1-2: the resolved argv is used only for this check and the audit row. `hubSession.open` keeps the `Open` exactly as received, `Process: "console"` and no argv, and that is what the box gets, so root runs the declared process with its own env and working directory.) |
| 3. Mint the id and the token, and **reserve the session in the hub** (`s.interactive.reserve(sess)`, finding 10). From here until step 6, every failure releases the reservation (`release(id)`, deferred and disarmed by a successful `activate`), and the steps' store calls run under a context bounded by `interactive.OpenWait`, so a reservation never outlives its admission. |
| 4. Sign the grant (Attach is `interactive.AttachURL(s.cfg.Origin, id)`) and `Put` it at `GrantKey`. |
| -5. Admit on the record (`Console: s.bootID`, `PickupBy: now+60s`, `Live: func(st provision.InteractiveState) bool { return s.interactive.live(st, s.bootID) }`). Because the id is already reserved, any other admission on this console that reads this marker, from the moment the CAS lands, finds it live and is refused with RFS-6-C32; a session of another console boot is dead by `Console`, as before. A refusal deletes the grant, releases the reservation, writes no audit row and ends with its sentence. |
| +5. Admit on the record (`Console: s.bootID`, `PickupBy: now+60s`, `Live: func(st provision.InteractiveState) bool { return s.interactive.live(st, s.bootID) }`). Because the id is already reserved, any other admission on this console that reads this marker, from the moment the CAS lands, finds it live and is refused with RFS-6-C32; a session of another console boot is dead by `Console`, as before. A refusal deletes the grant, releases the reservation and ends with its sentence. (Paul's ruling, 2026-10-31, superseding "writes no audit row": every refusal of a caller the door has placed in the account, before the upgrade or after it, writes one `interactive-refused` audit row through `s.auditActivity`, `TargetType` instance, `Target` the host, `Detail` JSON: the requested argv or process, the HTTP status before the upgrade, the refusal code and the sentence sent. It is the console's own database, so no store request is added. An unauthenticated request stays unlogged: the auth layer answers 401 before the door. So do the person and membership 404s, which have not placed the caller in an account, and a host-claim console's RFS-6-C35, where an app's SQL write is admitted through the claim's bucket objects.) |
| 6. `activate(id)` (the hub's `afterAdmit` seam runs just before it), bump the serial, write the `interactive-start` audit row (`Detail` JSON: id, argv, process, version), and send Status `waiting`. |
| 7. Wait for the box until `PickupBy`, else End expired, ending as below. |
| 8. The CLI closing before the box attaches ends the session as cancelled. |
| @@ -1302,7 +1302,7 @@ Every end after step 6 clears the marker by `InteractiveClear(id)`, deletes the |
| - [ ] **Step 1: Write the failing tests** (real `Server`, `httptest`, `DirStore`, a WebSocket client from `interactive.Dial`) |
| ```go |
| -func TestInteractiveRefusalsInOrder(t *testing.T) // one sub-test per refusal 1-11, each asserting status and exact sentence, and that nothing was written: no record change, no grant object, no audit row, no serial bump |
| +func TestInteractiveRefusalsInOrder(t *testing.T) // one sub-test per refusal 1-11, each asserting status and exact sentence, and that nothing was written: no record change, no grant object, no interactive-start or interactive-end row, no serial bump. Each writes its one interactive-refused row (Paul's ruling, 2026-10-31; TestEveryRefusalWritesOneRefusedRow) |
| func TestInteractiveAdmitsAFleetInstance(t *testing.T) // a rootfs record on fleet/home: admitted (waiting); a carlos run on the same record is still refused with the fleet sentence (until Task 16) |
| func TestInteractiveRefusedWhenTheAppDisallows(t *testing.T) // C9, console half: setting off -> 409 RFS-6-C27; turning it on admits the same request |
| func TestInteractiveAdmitsAndWaits(t *testing.T) // record has the marker with Console == bootID; grant verifies under ReleasePub with Attach == origin+"/api/box/interactive/"+id; audit interactive-start; first frame Status waiting |
diff --git a/internal/console/apiinteractive.go b/internal/console/apiinteractive.go| index ab5a06d74..6f320691b 100644 |
| --- a/internal/console/apiinteractive.go |
| +++ b/internal/console/apiinteractive.go |
| @@ -81,6 +81,13 @@ type interactiveDoor struct { |
| // rate (429), no bucket or no key (503), the host's shape or no record |
| // (404), the record's class, a move, the app's setting, an uncommitted |
| // import and a live session (409). Then the WebSocket. |
| +// |
| +// Every refusal after membership is proved writes one interactive-refused |
| +// row (Paul's ruling, 2026-10-31), here before the upgrade and in |
| +// refuseSession after it. The person and membership 404s write none: the |
| +// door has not placed the caller in the account, and an unauthenticated |
| +// request never reaches the door (the auth layer's 401). Nor does the |
| +// host-claim console's refusal (see there). |
| func (s *Server) handleAPIInteractive(w http.ResponseWriter, r *http.Request) { |
| p, ok := principalFrom(r.Context()) |
| if !ok || p.Kind != PrincipalUser { |
| @@ -91,70 +98,78 @@ func (s *Server) handleAPIInteractive(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + host := r.PathValue("host") |
| + door := interactiveDoor{acct: acct, app: app, host: host, by: actor} |
| + refuse := func(status int, msg string) { |
| + s.auditInteractiveRefused(door, interactive.Open{}, status, "", msg) |
| + jsonError(w, status, msg) |
| + } |
| if s.cfg.HostClaim { |
| + // No row: on a host-claim console an app's SQL write is admitted |
| + // through the claim's own bucket objects, and the ruling adds no |
| + // store request (the claim invariant: a refusal writes nothing). |
| jsonError(w, http.StatusConflict, claimInteractiveUnsupportedMsg) |
| return |
| } |
| if !s.cli.instances.allow(hashToken(bearer(r)), time.Now()) { |
| - jsonError(w, http.StatusTooManyRequests, runTooManyMsg) |
| + refuse(http.StatusTooManyRequests, runTooManyMsg) |
| return |
| } |
| if s.cfg.Releases == nil { |
| - jsonError(w, http.StatusServiceUnavailable, interactiveFailedMsg) |
| + refuse(http.StatusServiceUnavailable, interactiveFailedMsg) |
| return |
| } |
| if s.cfg.Key == nil { |
| - jsonError(w, http.StatusServiceUnavailable, interactiveNoKeyMsg) |
| + refuse(http.StatusServiceUnavailable, interactiveNoKeyMsg) |
| return |
| } |
| ctx := r.Context() |
| - host := r.PathValue("host") |
| notInstance := fmt.Sprintf("%s is not an instance of %s", host, app) |
| if !provision.ValidHostShape(host) { |
| - jsonError(w, http.StatusNotFound, notInstance) |
| + refuse(http.StatusNotFound, notInstance) |
| return |
| } |
| rec, _, err := s.readRecord(ctx, acct.Sqid, app, host) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| - jsonError(w, http.StatusNotFound, notInstance) |
| + refuse(http.StatusNotFound, notInstance) |
| return |
| case err != nil: |
| log.Printf("console: api interactive %s/%s/%s: read record: %v", acct.Sqid, app, host, err) |
| - jsonError(w, http.StatusBadGateway, interactiveFailedMsg) |
| + refuse(http.StatusBadGateway, interactiveFailedMsg) |
| return |
| } |
| if msg := instanceClassRefusal(*rec); msg != "" { |
| - jsonError(w, http.StatusConflict, msg) |
| + refuse(http.StatusConflict, msg) |
| return |
| } |
| if rec.Move != nil { |
| - jsonError(w, http.StatusConflict, runMovingMsg(host)) |
| + refuse(http.StatusConflict, runMovingMsg(host)) |
| return |
| } |
| // The setting lives in the default bundle only (appconfig.GetInteractive). |
| on, err := appconfig.GetInteractive(ctx, s.cfg.Releases, acct.Sqid, app) |
| if err != nil { |
| log.Printf("console: api interactive %s/%s: read the setting: %v", acct.Sqid, app, err) |
| - jsonError(w, http.StatusBadGateway, interactiveFailedMsg) |
| + refuse(http.StatusBadGateway, interactiveFailedMsg) |
| return |
| } |
| if !on { |
| - jsonError(w, http.StatusConflict, fmt.Sprintf(interactiveOffMsg, app, app)) |
| + refuse(http.StatusConflict, fmt.Sprintf(interactiveOffMsg, app, app)) |
| return |
| } |
| if rec.ImportUncommitted() { |
| - jsonError(w, http.StatusConflict, runImportMsg(host)) |
| + refuse(http.StatusConflict, runImportMsg(host)) |
| return |
| } |
| if m := rec.Interactive; m != nil && s.interactive.live(*m, s.bootID) { |
| - jsonError(w, http.StatusConflict, fmt.Sprintf(interactiveBusyMsg, host, m.By)) |
| + refuse(http.StatusConflict, fmt.Sprintf(interactiveBusyMsg, host, m.By)) |
| return |
| } |
| if s.interactive.afterChecks != nil { |
| s.interactive.afterChecks() |
| } |
| - door := interactiveDoor{acct: acct, app: app, host: host, by: actor, rec: rec} |
| + door.rec = rec |
| interactive.NewServer(func(ws *websocket.Conn) { |
| s.serveInteractive(ctx, ws, door) |
| }).ServeHTTP(w, r) |
| @@ -178,7 +193,8 @@ func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d in |
| open, ok := receiveOpen(ws, h.openWait()) |
| if !ok { |
| - refuseSession(ws, interactive.End{Detail: interactiveMalformedMsg}) |
| + // An Open that did not pass Check is not recorded: it is unbounded. |
| + s.refuseSession(ws, d, interactive.Open{}, interactive.End{Detail: interactiveMalformedMsg}) |
| return |
| } |
| sess := &hubSession{acct: d.acct.Sqid, app: d.app, host: d.host, by: d.by, account: d.acct, |
| @@ -186,7 +202,7 @@ func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d in |
| if open.Process == release.ProcessConsole { |
| argv, version, refusal := s.resolveConsole(ctx, d) |
| if refusal != nil { |
| - refuseSession(ws, *refusal) |
| + s.refuseSession(ws, d, open, *refusal) |
| return |
| } |
| sess.argv, sess.version = argv, version |
| @@ -197,7 +213,7 @@ func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d in |
| inc, err := provision.Incarnation(d.rec.Account, d.rec.App, d.rec.Host, d.rec.CreatedAt) |
| if err != nil { |
| log.Printf("console: api interactive %s/%s/%s: incarnation: %v", d.acct.Sqid, d.app, d.host, err) |
| - refuseSession(ws, interactive.End{Detail: interactiveFailedMsg}) |
| + s.refuseSession(ws, d, open, interactive.End{Detail: interactiveFailedMsg}) |
| return |
| } |
| sess.incarnation = inc |
| @@ -208,7 +224,7 @@ func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d in |
| } |
| if err != nil { |
| log.Printf("console: api interactive %s/%s/%s: mint: %v", d.acct.Sqid, d.app, d.host, err) |
| - refuseSession(ws, interactive.End{Detail: interactiveFailedMsg}) |
| + s.refuseSession(ws, d, open, interactive.End{Detail: interactiveFailedMsg}) |
| return |
| } |
| sess.id = id |
| @@ -244,11 +260,11 @@ func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d in |
| // The gate would not admit the write (it is draining): nothing was |
| // written, and the reservation is released. |
| log.Printf("console: api interactive %s/%s/%s: %v", d.acct.Sqid, d.app, d.host, err) |
| - refuseSession(ws, interactive.End{Detail: interactiveFailedMsg}) |
| + s.refuseSession(ws, d, open, interactive.End{Detail: interactiveFailedMsg}) |
| return |
| } |
| if refusal != nil { |
| - refuseSession(ws, *refusal) |
| + s.refuseSession(ws, d, open, *refusal) |
| return |
| } |
| // The box's prompt pickup, best effort, as the console's other |
| @@ -598,12 +614,32 @@ func (s *Server) deleteGrant(ctx context.Context, sess *hubSession) error { |
| return nil |
| } |
| -// refuseSession ends a session that was never admitted with End refused. |
| -func refuseSession(ws *websocket.Conn, e interactive.End) { |
| +// refuseSession ends a session that was never admitted with End refused, |
| +// and writes its interactive-refused row: o is the Open as the CLI sent it |
| +// (zero when none passed Check). |
| +func (s *Server) refuseSession(ws *websocket.Conn, d interactiveDoor, o interactive.Open, e interactive.End) { |
| + s.auditInteractiveRefused(d, o, 0, e.Refused, e.Detail) |
| e.Reason, e.Ended = interactive.EndRefused, time.Now().UTC() |
| _ = sendSessionJSON(ws, interactive.KindEnd, e) |
| } |
| +// auditInteractiveRefused writes a refused attempt's one interactive-refused |
| +// row (Paul's ruling, 2026-10-31), in the console's own database: no store |
| +// request. Its detail is what was asked for (the Open's argv, or its process |
| +// for carlos console; nothing before the upgrade, when no Open has come), |
| +// the HTTP status of a refusal before the upgrade, the End's refusal code |
| +// after it, and the sentence the CLI got. |
| +func (s *Server) auditInteractiveRefused(d interactiveDoor, o interactive.Open, status int, refused, sentence string) { |
| + raw, _ := json.Marshal(struct { |
| + Argv []string `json:"argv,omitempty"` |
| + Process string `json:"process,omitempty"` |
| + Status int `json:"status,omitempty"` |
| + Refused string `json:"refused,omitempty"` |
| + Detail string `json:"detail"` |
| + }{o.Argv, o.Process, status, refused, sentence}) |
| + s.auditActivity(d.acct, d.app, d.by, Activity{Action: "interactive-refused", TargetType: "instance", Target: d.host, Detail: string(raw)}) |
| +} |
| + |
| func sendSession(ws *websocket.Conn, kind byte, payload []byte) error { |
| _ = ws.SetWriteDeadline(time.Now().Add(interactiveSendWait)) |
| return interactive.Send(ws, kind, payload) |
diff --git a/internal/console/apiinteractive_refused_test.go b/internal/console/apiinteractive_refused_test.go| new file mode 100644 |
| index 000000000..da042fc75 |
| --- /dev/null |
| +++ b/internal/console/apiinteractive_refused_test.go |
| @@ -0,0 +1,324 @@ |
| +package console |
| + |
| +// Refused session attempts are audited (Paul's ruling, 2026-10-31): every |
| +// refusal the session door gives a caller it has proved is a member of the |
| +// account writes one interactive-refused row, before the upgrade (an HTTP |
| +// answer) and after it (End refused). A caller the door cannot place in the |
| +// account (unauthenticated, a service credential, a stranger) writes none. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/interactive" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/runs" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +type ixRefusedDetail struct { |
| + Argv []string `json:"argv"` |
| + Process string `json:"process"` |
| + Status int `json:"status"` |
| + Refused string `json:"refused"` |
| + Detail string `json:"detail"` |
| +} |
| + |
| +func TestEveryRefusalWritesOneRefusedRow(t *testing.T) { |
| + errRead := errors.New("the bucket is unreachable") |
| + const liveID = "tty_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + argv := ixOpenArgv() |
| + console := interactive.Open{Schema: 1, Process: release.ProcessConsole, Term: "xterm-256color", Cols: 80, Rows: 24} |
| + rootfs := func(t *testing.T, fx *interactiveFx) { |
| + no := false |
| + ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "uk"}) |
| + } |
| + failGet := func(match func(fx *interactiveFx, key string) bool) func(*testing.T, *interactiveFx) { |
| + return func(t *testing.T, fx *interactiveFx) { |
| + fx.rel.(*deletableStore).setGetHook(func(_ context.Context, key string) error { |
| + if match(fx, key) { |
| + return errRead |
| + } |
| + return nil |
| + }) |
| + t.Cleanup(func() { fx.rel.(*deletableStore).setGetHook(nil) }) |
| + } |
| + } |
| + // afterChecks puts the record rec returns (none for nil) after the door's checks: it passes them, and |
| + // the admission's CAS reads rec. |
| + afterChecks := func(rec func(fx *interactiveFx) *provision.Record) func(*testing.T, *interactiveFx) { |
| + return func(t *testing.T, fx *interactiveFx) { |
| + fx.srv.interactive.afterChecks = func() { |
| + key := provision.RecordKey(fx.acct, "shop", ixHost) |
| + _, etag, err := fx.rel.Get(context.Background(), key) |
| + if err == nil { |
| + err = release.DeleteIfMatch(context.Background(), fx.rel, key, etag) |
| + } |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + if r := rec(fx); r != nil { |
| + putAcctShopRecord(t, fx, *r) |
| + } |
| + } |
| + } |
| + } |
| + busy := func(fx *interactiveFx) *provision.Record { |
| + fx.srv.interactive.reserve(&hubSession{id: liveID, acct: fx.acct, app: "shop", host: ixHost}) |
| + return &provision.Record{Host: ixHost, Channel: "stable", Region: "uk", |
| + Interactive: &provision.InteractiveState{ID: liveID, By: "bob@keymail.dev", Console: fx.srv.bootID, PickupBy: time.Now().Add(time.Minute)}} |
| + } |
| + |
| + for _, c := range []struct { |
| + name string |
| + host string |
| + setup func(*testing.T, *interactiveFx) |
| + lt bool // on the lifetimes fixture |
| + noRow bool // the one refusal that writes none |
| + open *interactive.Open // nil: refused before the upgrade |
| + status int // before the upgrade |
| + refused string // after it |
| + msg string |
| + argv []string |
| + process string |
| + }{ |
| + // Before the upgrade: the door's JSON errors, in its order. |
| + // A host-claim console's refusal writes no row: its app SQL writes |
| + // go through the claim's bucket objects (TestClaimConsoleMutationInvariant). |
| + {name: "host claims", setup: func(_ *testing.T, fx *interactiveFx) { fx.srv.cfg.HostClaim = true }, |
| + status: http.StatusConflict, msg: claimInteractiveUnsupportedMsg, noRow: true}, |
| + {name: "rate", setup: func(_ *testing.T, fx *interactiveFx) { |
| + fx.srv.cli.instances = newRateLimiter(1, cliRateWindow) |
| + fx.srv.cli.instances.allow(hashToken(fx.alice), time.Now()) |
| + }, status: http.StatusTooManyRequests, msg: runTooManyMsg}, |
| + {name: "no bucket", setup: func(t *testing.T, fx *interactiveFx) { |
| + rel := fx.srv.cfg.Releases |
| + fx.srv.cfg.Releases = nil |
| + t.Cleanup(func() { fx.srv.cfg.Releases = rel }) |
| + }, status: http.StatusServiceUnavailable, msg: interactiveFailedMsg}, |
| + {name: "no key", setup: func(_ *testing.T, fx *interactiveFx) { fx.srv.cfg.Key = nil }, |
| + status: http.StatusServiceUnavailable, msg: interactiveNoKeyMsg}, |
| + {name: "host shape", host: "Not_A_Host", status: http.StatusNotFound, msg: "Not_A_Host is not an instance of shop"}, |
| + {name: "no record", host: "other.example.com", status: http.StatusNotFound, msg: "other.example.com is not an instance of shop"}, |
| + {name: "record unreadable", setup: failGet(func(fx *interactiveFx, k string) bool { return k == provision.RecordKey(fx.acct, "shop", ixHost) }), |
| + status: http.StatusBadGateway, msg: interactiveFailedMsg}, |
| + {name: "class", setup: func(t *testing.T, fx *interactiveFx) { |
| + ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Pool: "shop"}) |
| + }, status: http.StatusConflict, msg: ixHost + " is a pooled instance. carlos run works on instances with a process of their own"}, |
| + {name: "moving", setup: func(t *testing.T, fx *interactiveFx) { |
| + ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Move: &provision.MoveState{ID: "mv_1", To: "ie"}}) |
| + }, status: http.StatusConflict, msg: runMovingMsg(ixHost)}, |
| + {name: "setting unreadable", setup: failGet(func(fx *interactiveFx, k string) bool { return k == appconfig.Key(fx.acct, "shop") }), |
| + status: http.StatusBadGateway, msg: interactiveFailedMsg}, |
| + {name: "setting off", setup: func(t *testing.T, fx *interactiveFx) { |
| + if code, out := fx.put(t, fx.owner, `{"interactive":false}`); code != http.StatusOK { |
| + t.Fatalf("owner off = %d %s", code, out) |
| + } |
| + }, status: http.StatusConflict, msg: "interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on"}, |
| + {name: "uncommitted import", setup: func(t *testing.T, fx *interactiveFx) { |
| + ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Seed: &provision.SeedSource{Kind: seeds.KindImport, State: seeds.StatePlaced}}) |
| + }, status: http.StatusConflict, msg: runImportMsg(ixHost)}, |
| + {name: "a live marker", setup: func(t *testing.T, fx *interactiveFx) { ixPutRecord(t, fx, *busy(fx)) }, |
| + status: http.StatusConflict, msg: ixHost + " already has an interactive session open, started by bob@keymail.dev"}, |
| + |
| + // After the upgrade: End refused. |
| + {name: "malformed open", open: &interactive.Open{Schema: 2, Argv: []string{"sh"}}, msg: interactiveMalformedMsg}, |
| + {name: "no console process", setup: func(t *testing.T, fx *interactiveFx) { |
| + rootfs(t, fx) |
| + shipShopRootfs(t, fx, "r1", nil) |
| + }, open: &console, process: release.ProcessConsole, |
| + msg: ixHost + " runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app shop --instance " + ixHost + " -- <command>"}, |
| + {name: "channel unreadable", setup: func(t *testing.T, fx *interactiveFx) { |
| + rootfs(t, fx) |
| + shipShopRootfs(t, fx, "r1", []string{"bin/rails", "console"}) |
| + failGet(func(fx *interactiveFx, k string) bool { return k == release.ChannelKey(fx.acct, "shop", "stable") })(t, fx) |
| + }, open: &console, process: release.ProcessConsole, msg: interactiveFailedMsg}, |
| + {name: "the gate drains", lt: true, setup: func(t *testing.T, fx *interactiveFx) { |
| + held, ok, _ := fx.srv.lifetimesAdmit(context.Background(), true) |
| + if !ok { |
| + t.Fatal("the test's legacy unit was not admitted") |
| + } |
| + t.Cleanup(held.done) |
| + ixCutover(t, fx) |
| + }, open: &argv, argv: argv.Argv, msg: interactiveFailedMsg}, |
| + {name: "admission: busy", setup: afterChecks(busy), open: &argv, argv: argv.Argv, refused: interactive.RefusedBusy, |
| + msg: ixHost + " already has an interactive session open, started by bob@keymail.dev"}, |
| + {name: "admission: moving", setup: afterChecks(func(*interactiveFx) *provision.Record { |
| + return &provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Move: &provision.MoveState{ID: "mv_1", To: "ie"}} |
| + }), open: &argv, argv: argv.Argv, msg: runMovingMsg(ixHost)}, |
| + {name: "admission: import", setup: afterChecks(func(*interactiveFx) *provision.Record { |
| + return &provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Seed: &provision.SeedSource{Kind: seeds.KindImport, State: seeds.StatePlaced}} |
| + }), open: &argv, argv: argv.Argv, refused: runs.RefusedImport, msg: runImportMsg(ixHost)}, |
| + {name: "admission: gone", setup: afterChecks(func(*interactiveFx) *provision.Record { return nil }), |
| + open: &argv, argv: argv.Argv, msg: ixHost + " is not an instance of shop"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + var fx *interactiveFx |
| + if c.lt { |
| + fx, _ = newIxLtFx(t, "code-ix-refused") |
| + } else { |
| + fx = newIxFx(t, "code-ix-refused") |
| + } |
| + if c.setup != nil { |
| + c.setup(t, fx) |
| + } |
| + host := c.host |
| + if host == "" { |
| + host = ixHost |
| + } |
| + if c.open == nil { |
| + code, _, out := ixGet(t, fx, host, fx.alice) |
| + if code != c.status || interactiveError(t, out) != c.msg { |
| + t.Fatalf("%d %s, want %d %q", code, out, c.status, c.msg) |
| + } |
| + } else { |
| + ws, err := ixDial(t, fx.ts.URL, fx.ixURL(host), fx.alice) |
| + if err != nil { |
| + t.Fatalf("dial: %v", err) |
| + } |
| + ixSendOpen(t, ws, *c.open) |
| + if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused || e.Refused != c.refused || e.Detail != c.msg { |
| + t.Fatalf("end %+v, want refused %q %q", e, c.refused, c.msg) |
| + } |
| + } |
| + // One row, and only one: give a second one time to land. |
| + time.Sleep(50 * time.Millisecond) |
| + evs := ixEvents(t, fx, "interactive-refused") |
| + if c.noRow { |
| + if len(evs) != 0 { |
| + t.Fatalf("rows %+v, want none", evs) |
| + } |
| + return |
| + } |
| + if len(evs) != 1 { |
| + t.Fatalf("%d interactive-refused rows, want 1: %+v", len(evs), evs) |
| + } |
| + ev := evs[0] |
| + if ev.Address != "alice@keymail.dev" || ev.TargetType != "instance" || ev.Target != host { |
| + t.Fatalf("row %+v, want alice on instance %s", ev, host) |
| + } |
| + var d ixRefusedDetail |
| + if err := json.Unmarshal([]byte(ev.Detail), &d); err != nil { |
| + t.Fatalf("detail %q: %v", ev.Detail, err) |
| + } |
| + want := ixRefusedDetail{Argv: c.argv, Process: c.process, Status: c.status, Refused: c.refused, Detail: c.msg} |
| + if strings.Join(d.Argv, "\x00") != strings.Join(want.Argv, "\x00") || d.Process != want.Process || |
| + d.Status != want.Status || d.Refused != want.Refused || d.Detail != want.Detail { |
| + t.Fatalf("detail %+v, want %+v", d, want) |
| + } |
| + if evs := append(ixEvents(t, fx, "interactive-start"), ixEvents(t, fx, "interactive-end")...); len(evs) != 0 { |
| + t.Fatalf("a refused attempt wrote %+v", evs) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestUnplacedCallersWriteNoRefusedRow: the door audits only a caller it has |
| +// placed in the account. No credential and a bad one get the auth layer's |
| +// 401; a service credential the mux's closed door; a stranger the |
| +// byte-identical 404. None of them writes a row. |
| +func TestUnplacedCallersWriteNoRefusedRow(t *testing.T) { |
| + fx := newIxFx(t, "code-ix-unplaced") |
| + stranger := cliToken(t, fx.consoleFixture, "mallory@keymail.dev", "code-ix-unplaced-stranger") |
| + svc := serviceToken(t, fx.st, fx.acctID, "ci-admin", "shop", "admin") |
| + for _, c := range []struct { |
| + name, token string |
| + status int |
| + }{ |
| + {"no credential", "", http.StatusUnauthorized}, |
| + {"a bad credential", "not-a-token", http.StatusUnauthorized}, |
| + {"a service credential", svc, http.StatusForbidden}, |
| + {"a stranger", stranger, http.StatusNotFound}, |
| + } { |
| + if code, _, out := ixGet(t, fx, ixHost, c.token); code != c.status { |
| + t.Errorf("%s: %d %s, want %d", c.name, code, out, c.status) |
| + } |
| + } |
| + evs, err := fx.st.Events(fx.acctID, "shop", 200) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, e := range evs { |
| + if strings.HasPrefix(e.Action, "interactive-") { |
| + t.Fatalf("an unplaced caller wrote %+v", e) |
| + } |
| + } |
| +} |
| + |
| +// TestARefusedAttemptAddsNoStoreRequest: the interactive-refused row is the |
| +// console's own database, never the bucket. A refused attempt makes the |
| +// store requests its checks always made, counted at the production |
| +// deployment store's wire as TestInteractiveRequestBudget counts a session |
| +// (whose counts the row leaves as they were: it has no refusal): these are |
| +// the counts from before refusals were audited. |
| +func TestARefusedAttemptAddsNoStoreRequest(t *testing.T) { |
| + type counts map[string]int |
| + for _, c := range []struct { |
| + name string |
| + open bool // refused after the upgrade |
| + want counts |
| + total int |
| + }{ |
| + {"before the upgrade", false, counts{"GET record": 1, "GET config": 1}, 2}, |
| + {"after the upgrade", true, counts{"GET record": 1, "GET config": 1, "GET channel": 1, "GET manifest": 1}, 4}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + lat := &perfLatency{} |
| + fx := newInteractiveFxWith(t, 7, "code-ix-refused-budget", consoleFixtureOptions{WithKey: true, S3: lat}) |
| + ixWorld(t, fx) |
| + no := false |
| + ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "uk"}) |
| + shipShopRootfs(t, fx, "r1", nil) |
| + if !c.open { |
| + if _, err := appconfig.SetInteractive(context.Background(), fx.rel, fx.acct, "shop", false); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var mu sync.Mutex |
| + var log []string |
| + lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) { |
| + mu.Lock() |
| + log = append(log, r.Method+" "+r.URL.Path) |
| + mu.Unlock() |
| + return 0, nil |
| + }) |
| + if c.open { |
| + ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), fx.alice) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ixSendOpen(t, ws, interactive.Open{Schema: 1, Process: release.ProcessConsole}) |
| + if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused { |
| + t.Fatalf("end %+v, want refused", e) |
| + } |
| + } else if code, _, out := ixGet(t, fx, ixHost, fx.alice); code != http.StatusConflict { |
| + t.Fatalf("%d %s, want 409", code, out) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + lat.Fake().OnRequest(nil) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + got := counts{} |
| + for _, l := range log { |
| + method, path, _ := strings.Cut(l, " ") |
| + got[method+" "+ixBudgetClass(path)]++ |
| + } |
| + if len(log) != c.total || !equalCounts(got, c.want) { |
| + sort.Strings(log) |
| + t.Fatalf("%d store requests, want %d:\n got %v\nwant %v\n%s", len(log), c.total, got, c.want, strings.Join(log, "\n")) |
| + } |
| + if n := len(ixEvents(t, fx, "interactive-refused")); n > 1 { |
| + t.Fatalf("%d interactive-refused rows", n) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/apiinteractive_test.go b/internal/console/apiinteractive_test.go| index 56d37a2b0..d274e850d 100644 |
| --- a/internal/console/apiinteractive_test.go |
| +++ b/internal/console/apiinteractive_test.go |
| @@ -305,7 +305,8 @@ func ixGet(t *testing.T, fx *interactiveFx, host, token string) (int, http.Heade |
| // TestInteractiveRefusalsInOrder walks the door's refusals 1 to 11 with every |
| // later one also failing, so each answer proves it comes before the rest; |
| -// then fixes it and goes on. Nothing is written by any of them. |
| +// then fixes it and goes on. Nothing is written by any of them but its |
| +// interactive-refused row (TestEveryRefusalWritesOneRefusedRow). |
| func TestInteractiveRefusalsInOrder(t *testing.T) { |
| fx := newInteractiveFx(t, 7, "code-ix-order") |
| t.Cleanup(func() { fx.srv.interactive.sessions.Wait() }) |