Skip to content

feat(api): open an exec session in a running replica (part of #232) - #455

Merged
samuelmbabhazi merged 8 commits into
mainfrom
feat/232-exec-sessions-api
Nov 25, 2026
Merged

samuelmbabhazi merged 8 commits into
mainfrom
feat/232-exec-sessions-api

Conversation

@samuelmbabhazi

@samuelmbabhazi samuelmbabhazi commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

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 ExecStream comes 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):
    • Sessions only: API tokens cannot open one until a client of their own joins sessions. It also keeps the token picker unchanged.
    • The body is optional: replica (1), argv (["sh"]), tty (true) and minutes (1 to 240, default 30). class-validator checks it first, and the domain checks the agent's byte bounds again (SPEC 3.3).
    • It picks the replica's running container, preferring the newest release during a rollout. A replica without one answers 409 replica_not_running.
    • It queues the node an ExecSession action, with exec:<session id> as idempotency key and the time limit as deadline.
    • It answers 201 with id, nodeId, attachBy (one minute), endsAt and websocketPath.
  • Audit exec.session.opened:
    • It records the program and the number of its arguments only, never the arguments, which can carry what a person typed. A test checks that a password in the argv stays out of the event.
    • It is published in the same tenant transaction as the action.
    • The session becomes joinable only after that transaction commits.
  • 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).
  • The deployments ActionQueue port: origin is now optional, since an exec session belongs to no deployment. AgentActions already accepted that.
  • SPEC 8: the route. The generated openapi.json, API client and route-role matrix are updated.

How it was tested

  • Domain:
    • the defaults;
    • every invalid field, named in the error: replica, minutes, empty, NUL, lone-surrogate, too many, oversized arguments, and multibyte length;
    • the audited command.
  • Service:
    • the action, the event and their order;
    • the registry's expiry;
    • the choice of replica during a rollout;
    • refusals that queue and audit nothing: not running, denied, unknown application, invalid input;
    • a failed commit leaves nothing joinable.
  • audit-coverage.spec.ts lists the event, and route-role-matrix.spec.ts gives container.exec@environment the same roles as deploy.run, since the fixture's environments are protected.
  • vitest --project api: 775 tests pass.
  • The integration route matrix runs in CI: the route answers 400 to allowed actors with an invalid application id, and 404 to the others.

Security considerations

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]>
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between f608af5 and dd83206.

Files ignored due to path filters: 3

  • apps/api/openapi.json is excluded by !apps/api/openapi.json
  • docs/generated/route-role-matrix.md is excluded by !**/generated/**, !docs/generated/**
  • packages/api-client/src/gen/openapi.ts is excluded by !**/gen/**, !packages/api-client/src/gen/**
Files selected for processing: 14

  • apps/api/src/audit-coverage.spec.ts
  • apps/api/src/modules/deployments/application/deployment-pipeline.spec.ts
  • apps/api/src/modules/deployments/application/exec-sessions.spec.ts
  • apps/api/src/modules/deployments/application/exec-sessions.ts
  • apps/api/src/modules/deployments/application/ports.ts
  • apps/api/src/modules/deployments/deployments.module.ts
  • apps/api/src/modules/deployments/domain/exec-session.spec.ts
  • apps/api/src/modules/deployments/domain/exec-session.ts
  • apps/api/src/modules/deployments/interface/exec-session.controller.ts
  • apps/api/src/modules/deployments/interface/exec-session.dto.ts
  • apps/api/src/modules/fleet/application/exec-relay.ts
  • apps/api/src/modules/fleet/fleet.module.ts
  • apps/api/src/route-role-matrix.spec.ts
  • docs/SPEC.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

The gateway's ExecStream joins sessions there, and fleet cannot import deployments.

Signed-off-by: samuel mbabhazi <[email protected]>
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]>
@samuelmbabhazi

Copy link
Copy Markdown
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.

@samuelmbabhazi
samuelmbabhazi merged commit 962dbf1 into main Nov 25, 2026
25 checks passed
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant