Repository navigation
feat(api): open an exec session in a running replica (part of #232) - #455
Merged
Merged
Conversation
POST …/exec-sessions checks container.exec (protected environments: their administrators only), picks the replica's running container, queues its agent an ExecSession and audits exec.session.opened with the program and argument count only. The session waits in memory for the browser and the agent to join it. Signed-off-by: samuel mbabhazi <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 53 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
The gateway's ExecStream joins sessions there, and fleet cannot import deployments. Signed-off-by: samuel mbabhazi <[email protected]>
This was referenced Nov 24, 2026
From review: the agent action's deadline is the join window, not the session's end; a replica must have been seen running in the last two minutes; a person may have 4 sessions waiting and an organization 32; the audited program is cut by code points; the argv bound fits the request body cap. Signed-off-by: samuel mbabhazi <[email protected]>
Collaborator
Author
|
An independent review of this PR (high effort, while CodeRabbit is rate limited) raised six points. They are fixed in c5d93fe, and carried into #456 and #457.
|
The port's origin is optional now; the spec says so. Signed-off-by: samuel mbabhazi <[email protected]>
A lab run found it: the default replica 1 named no container of a one-replica application, and 0 was refused. Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 25, 2026
…t of #232) (#456) Part of #232 (M6.1): the control plane relays an exec session between the agent and the browser. Stacked on #455, which opens sessions. The browser's WebSocket endpoint comes next. Until then, no browser can join, so a session ends as `not_joined` after a minute. ## What changed - **`fleet/application/exec-relay.ts`**: one `ExecRelay` per session, kept by `ExecSessionRegistry`. The registry now lives in fleet, because the gateway joins it and fleet cannot import deployments. - **Rendezvous.** The agent of the session's node and the person who opened it each join once. A wrong node, a wrong organization, a wrong person or a second join gets `undefined`. If both have not joined within a minute, the session ends as `not_joined`. - **Frames.** - Output and the exit or error go to the browser once both sides are there, so the first prompt is never lost. - The browser's stdin, resize and close frames wait for the agent, at most 256 of them, past which the session ends as `flooded`. - **End.** The session ends once: - at the agent's exit, or at its error frame: the agent's fixed texts map to `time_limit`, `closed` or `failed`, and any other text gives `failed`; - when a side leaves; - on a frame out of order. Unless the command exited, the last frame to the agent is `ExecClose{kill: true}`. The browser's connection is closed. - **Audit.** `exec.session.ended`, with the session's person as actor and the reason, the exit code (or null) and the duration. It is written in its own tenant transaction. Nothing waits on that write, so a failed write is logged with identifiers only. - **`fleet/interface/exec-stream.ts`** and the gateway: - `ExecStream` replaces its `Unimplemented` stub. It still sits behind the shared mTLS and database identity guard, with the 24-hour stream deadline of `Connect`. - The first frame must be `ExecOpen`, otherwise `INVALID_ARGUMENT`. - An unknown, foreign, expired or already joined session gets `NOT_FOUND`, the same answer for each. - **`ExecSession`** now carries `projectId` and `environmentId`, for the audit payload. - **SPEC 3.1:** the relay's rules. ## How it was tested - **`exec-relay.spec.ts`:** - frames both ways and the audited exit; - only the right node or person can join, each once; - the minute's timeout, with fake timers; - a browser that leaves stops the command; - the agent's texts map to reasons, and other text maps to `failed`; - a flood ends the session; - a failed audit write still ends the session. - **`exec-stream.spec.ts`:** - `INVALID_ARGUMENT` without an open; - `NOT_FOUND` for an unknown session and for another node of the organization; - output reaches the browser and stdin reaches the agent, until the exit ends both; - a second open ends the session with a kill. - **`gateway.integration.spec.ts`** (CI, real TLS gateway and PostgreSQL): an enrolled agent naming an unknown session gets `NOT_FOUND`. A client without a certificate still gets `UNAUTHENTICATED`. - `vitest --project api`: 785 tests pass. ESLint is clean on the new files. ## Security considerations - A session is bound to one node of one organization and one person, and each side joins once. - The refusals say nothing about why. - The frames from the browser are bounded in number. The gateway's 64 KiB message cap still applies. - Output is relayed as it came and never logged. - The audit records the end, never the session's content. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added interactive exec sessions for running application replicas, including browser-to-agent terminal streaming, configurable command options, and session duration. * Added access checks, session limits, replica availability checks, and audit events for session activity. * **Documentation** * Documented exec session setup, validation, streaming behavior, and session-ending conditions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 25, 2026
…#232) (#457) Part of #232 (M6.1): the browser's side of an exec session. This completes the path from the browser through the API and the agent into the container. It is stacked on #456 (relay), which sits on #455 (opening a session). The terminal in the web UI comes next. ## What changed - **`ExecSocket`** (`deployments/interface/exec-socket.ts`) takes the HTTP server's upgrades for `/api/v1/exec/{id}` (a UUIDv7). Any other path gets 404. - **`401`:** - the `Origin` is not `API_PUBLIC_URL`'s, or `Sec-Fetch-Site` is `cross-site`. A cookie goes with every request to this origin, so this check stops cross-site WebSocket hijacking; - no valid sign-in cookie, or a session that `SessionCommands.authenticate` refuses. - **`404`, whatever the reason:** - the session is unknown; - it belongs to another person; - it no longer waits; - the person no longer holds `container.exec` on its environment, checked again at join time. - A second join of the same session is upgraded, then closed with `4404`. - **Messages** are at most 64 KiB (`maxPayload`). - To the browser: output as binary, with the stream in the first byte (1 for stdout, 2 for stderr). Then `{"type":"exit","code":n}`, or `{"type":"end","reason":…}` with the mapped reason only, never the agent's text. - From the browser: binary messages are stdin. Text messages are `resize` (integers from 1 to 1000) or `close` (`kill` a boolean). Anything else is ignored, including prototype keys. - **Sign-in.** It is checked again every minute with `assertLive`, so signing out or changing one's password ends the session (`signed_out`, a new end reason). - Writes resolve when the socket has taken the frame, so a slow browser slows the agent's stream instead of buffering without bound. - **`IdentityModule`** exports `SessionCommands`. - **Dependency:** `ws` 8.22.0 (MIT) and `@types/ws` 8.18.2 (MIT). Both were already in the lockfile as transitive dependencies, so no new package is downloaded. - **SPEC 3.1:** the WebSocket's rules. **THREAT_MODEL:** the exec session's bindings and the origin check. ## How it was tested `exec-socket.spec.ts`, with a real HTTP server and a real `ws` client: - refusals: - another origin, no cookie, or a refused sign-in gets `401`; - an unknown session, a path traversal, a query string, another person, or no permission gets `404`; - none of them takes the session; - a full session: - binary stdin and a JSON resize reach the agent's side; - output reaches the browser with its stream byte; - the exit closes the WebSocket with 1000 and is audited `exited`; - a second connection is closed with 4404, and the browser leaving makes the relay send `ExecClose{kill: true}`, audited `browser_left`; - message parsing: malformed JSON, out-of-range or fractional sizes, wrong types, unknown types and `__proto__` are ignored; - an agent error with arbitrary text reaches the browser as `failed` only. `vitest --project api`: 790 tests pass, and ESLint is clean. ## Security considerations - Cross-site WebSocket hijacking: the origin check comes before any session lookup. - Every refusal after sign-in is the same 404, so it says nothing about other people's sessions. - Permission is checked when the session opens and again when the browser joins. The sign-in is checked every minute. - Input from the browser is bounded and typed. Output from the container is relayed as bytes, and never logged or parsed. - Not covered yet: a per-network limit on failed upgrade attempts, like the one `IdentityGuard` applies to cookies. Each failed attempt costs one session lookup, like any API request with a bad cookie. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added browser-based interactive container sessions, including input, output, and terminal resizing. * Sessions now end when sign-in or required access is revoked, with a reason communicated to the browser. * Added safeguards for session access, connection attempts, and message sizes. * **Documentation** * Updated agent protocol and security documentation with interactive session requirements. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 25, 2026
… (part of #232) (#468) Part of #232 (M6.1); closes #477: the application page's Logs and Terminal tabs on real data, replacing the samples they showed. Stacked on #457, the exec WebSocket; retarget to `main` once #457 is merged. The maintainer validated the screens on desktop and phone on 2026-11-25, from captures of a lab installation. ## What changed - **Logs tab** (`logs-panel.ts`, `logs-view.ts`): - the replicas' output, newest first, from `GET …/applications/{id}/logs` (#463); - filters All, stdout and stderr, and a text search (a substring, matched with its case); - a live view that asks again every 3 s while the tab is shown, and not at all without a log store. It reads forward from shortly before its newest line, oldest first, page after page (`order=oldest`, up to 5 pages a tick), so a burst between two ticks is not skipped. Each tick waits for the previous read to end. - Lines are merged without repeats. Times are shown in the viewer's time zone. On a phone, the time, replica and stream sit above the line at full width. - An installation without a log store says that it keeps no logs. - **Terminal tab** (`terminal-panel.ts`, `terminal-view.ts`): - a command line in the first replica (r0), over the exec WebSocket (`/api/v1/exec/{id}`, #457): Connect, then one command per line; - output bounded: a line keeps its first 4096 characters and is marked with ` …` past them, dropping the rest up to its newline, and the screen keeps at most 2000 lines and 1 Mi characters, the newest first (#477); - stdout and stderr shown apart, stderr in rose, and Disconnect; - the notice that the session is recorded in the audit log and that no SSH port is open. - **Shared tab bar** (`shell/tabs.ts`): on a narrow screen it scrolls to keep the open tab in view, for example when a link opens `?tab=terminal`. - **CSP**: `connect-src` adds `wss://` for the API's own host only (`socketOrigin()`), so the terminal's WebSocket can connect. - **`DeliveryApi`** gains `logs()` and `openExecSession()`. French translations are in `fr.ts`. - **API, logs route** (found in review): `from` written in UTC with up to nine digits of fraction now goes into the LogsQL query as written (`fromExact`), so a live view can read forward from a line's exact time. A `Date` cut it to milliseconds and stalled on bursts. - **After review:** - each live read starts three seconds before the newest line, so lines another server sent late still show; - only a submitted search applies; - a terminal left while connecting joins nothing; - the header reads "shell connected", the one text change from the validated captures. ## How it was tested - Web unit tests (55 files): log merging, keys, times, the forward reading (page after page from the last line, its bound, and a full page that does not move), terminal frames, and the tab bar's scroll. - `nx typecheck lint test` for web and API, and the browser suite (Chromium against the production build, 28 tests), which enforces the CSP. - **Lab** (control plane 0.1.0-lab.26, agent 0.1.0-lab.27, an nginx application): - the Logs tab showed the replica's real lines, and the search found them; - the Terminal ran `echo`, `ls` and `nginx -v` in the container, with stderr apart. ## Security considerations - The terminal goes through the agent and its typed exec action, and it is audited, as #455 to #457 describe. No new route. - The CSP opens WebSockets to the API's own origin only. - Log lines arrive already redacted by the agent (ADR 0029). The panel renders them as text and never as HTML. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added live application logs with stream filters, text search, pause/resume, and retryable error handling. * Added an interactive terminal for running commands in an application replica. * Kept the active tab visible when navigating a narrow tab bar. * **Bug Fixes** * Improved log updates to include recently delayed entries and support precise UTC time filters. * Allowed WebSocket connections from the configured public URL. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: samuel mbabhazi <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #232 (M6.1). This is the control plane's first piece of container exec: opening a session. The relay between the browser's WebSocket and the agent's
ExecStreamcomes in the next PR, so a session opened now expires after a minute with nothing joined. The agent side is #453 and #454.What changed
POST …/applications/{applicationId}/exec-sessions(container.exec@ environment):replica(1),argv(["sh"]),tty(true) andminutes(1 to 240, default 30). class-validator checks it first, and the domain checks the agent's byte bounds again (SPEC 3.3).409 replica_not_running.ExecSessionaction, withexec:<session id>as idempotency key and the time limit as deadline.201withid,nodeId,attachBy(one minute),endsAtandwebsocketPath.exec.session.opened:ExecSessionRegistry(fleet module, where the gateway will join it) holds sessions in memory until both sides join. A session lives as long as its two connections, which both reach this API process, so a restart ends it (the SPEC says so).ActionQueueport:originis now optional, since an exec session belongs to no deployment.AgentActionsalready accepted that.openapi.json, API client and route-role matrix are updated.How it was tested
audit-coverage.spec.tslists the event, androute-role-matrix.spec.tsgivescontainer.exec@environmentthe same roles asdeploy.run, since the fixture's environments are protected.vitest --project api: 775 tests pass.Security considerations