Repository navigation
feat(agent): Docker exec calls for interactive sessions (part of #232) - #453
Merged
Merged
Conversation
Create, start with the daemon's hijacked connection, resize and inspect an exec. The multiplexed output is read frame by frame, refusing invalid headers and frames over 1 MiB. Tested against a fake daemon and a real Docker. 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 9 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. |
This was referenced Nov 24, 2026
…ag, and end with their context From review: Docker's default detach sequence is replaced by one a terminal user does not type; CreateExec returns the instance with its terminal flag, which StartExec repeats; the start's context bounds the session; Next returns at most max bytes in both modes and refuses no room; errors keep their cause. Signed-off-by: samuel mbabhazi <[email protected]>
Collaborator
Author
|
An independent review of this PR (high effort, while CodeRabbit is rate limited) raised seven points, all fixed in ca90c66:
|
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 24, 2026
#454) Part of #232 (M6.1), the agent's side of container exec (SPEC 3.1 and 3.3). Stacked on #453, which adds the Docker calls. The gateway relay and the WebSocket route come next. Until they exist, the control plane sends no `ExecSession` and its gateway still answers `Unimplemented` to `ExecStream`. ## What changed - **`exec_session` handler** (`agent/internal/actions/exec.go`). It is registered only with `WithExec`, and the agent's gateway wiring passes it. - **Validation before anything runs:** - a container reference in the existing grammar; - a session id that is a UUIDv7; - argv of 1 to 64 non-empty UTF-8 entries without NUL, each at most 4 KiB, and 16 KiB in all; - a user that is a name or uid, with an optional group; - a time limit between 1 second and 4 hours. - **The session itself.** It runs only in a managed container (`sk.managed`), never on the host (rule 3). The handler creates the exec, opens an `ExecStream` on the current gateway session, sends `ExecOpen{session_id}`, then starts the exec. - **Frames.** - Output goes out as stdout and stderr frames of at most 32 KiB, from a single goroutine, since a stream's sends are not safe concurrently. - Stdin, resizes (1 to 1000 on each side, others ignored) and `ExecClose` come in. `ExecClose` either closes stdin and keeps the output, or kills the session. - **How a session ends.** It sends one last frame: - `ExecExit` with Docker's exit code; - or one of three fixed texts: `time limit reached`, `session closed` (a kill, or the stream ended) or `session failed`. Docker's messages are never sent. - **Journal.** It is one step that is not retry-safe. After an agent restart the journal finds it uncertain and compensates, so a session never resumes. - **`gateway.Streams`.** Opens RPCs beside `Connect` on the current session's connection. A stream ends with that connection. - **SPEC 3.3**, the `ExecSession` row: the exact bounds, and the limit below. ## How it was tested - **Unit tests,** `go test -race`: - 22 malicious inputs are refused at planning, including path traversal, injection characters, NUL bytes, invalid UTF-8, oversized values and invalid durations, and nothing is created; - the users that must pass, pass; - output, stderr and the exit code reach the stream; - stdin and resize are forwarded, out-of-bounds sizes are ignored, and closing stdin keeps the output; - a kill ends the session; - the end of the stream ends the session; - the time limit ends the session and closes the connection; - large output is split into 32 KiB frames; - a foreign container is refused before any exec or stream exists; - no stream means no start; - a failed start sends only the fixed text; - the handler is registered only when configured. - **Real Docker 29,** `-tags integration`, `TestRealExecSessionRunsInAManagedContainer`. It runs the action through the dispatcher in a busybox container that the agent's own actions created. The test plays the control plane's side of the stream. It checks stdin, the separate stdout and stderr, and exit code 4. - `go test ./agent/...` passes, and `golangci-lint` reports 0 issues, with and without the `integration` tag. ## Security considerations - The argv is passed to Docker as an array, with no shell. The container must carry `sk.managed=true`, so a foreign container is refused. - All input is bounded. Frames from the control plane are applied only within bounds. - Error frames carry fixed texts, never daemon output. - **Known limit, in SPEC 3.3:** Docker has no API to stop an exec's process. A command that ignores the end of its stdin can outlive its session until it exits or its container stops. A TTY session's shell gets SIGHUP when its connection closes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added interactive execution sessions for managed, running containers, with support for sending input, receiving output, resizing the terminal, and setting a time limit. * Sessions can continue after the action that starts them has completed, and end when the agent stops or the session limit is reached. * **Documentation** * Clarified container, command, user, and session-limit requirements, along with session behavior and lifecycle. <!-- 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
…455) 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 - RBAC: a developer may exec only on unprotected environments (SPEC 7, already in the domain policy). Missing protection metadata denies. - The argv is passed to the agent as an array, and the agent validates it again (#454). No shell is involved. - No secret value reaches the audit log or the response. --------- Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 25, 2026
#459) Part of #232 (M6.1). The agent reads a container's log lines, which the `ShipLogs` stream of ADR 0029 will send (#458 is the contract). This PR is stacked on #453 and reuses its frame reader for Docker's multiplexed stream. ## What changed `docker.Client.FollowLogs(ctx, ref, since, emit)` is in `agent/internal/docker/logs.go`. - It reads `GET /containers/{ref}/logs` with `follow`, `stdout`, `stderr`, `timestamps` and `since` (seconds and nanoseconds). It uses the client without a response-header timeout, and returns when the container stops (the output ends), when ctx ends, or when `emit` fails. - A `LogLine` has its stream (stdout or stderr), Docker's timestamp and the text without its newline (and a trailing `\r`). `Truncated` tells whether the line was cut. - Lines: - **Split lines.** Docker splits lines longer than its 16 KiB buffer. Each part has its own timestamp, and the line has the first one. Parts are joined per stream, so stderr in between does not mix in. - **Size.** A line is cut at 16 KiB on a character boundary, and sent as soon as it is full: the rest, up to its newline, is dropped, so a progress bar that never writes a newline still shows. Each byte that is not UTF-8 becomes U+FFFD (ADR 0029), and the line is cut again on a rune boundary if replacements made it longer. A line without a final newline is emitted when the container stops. - **Resume.** Each line carries `Resume`, the time to read again from once it is kept: its own time, or the start of a line of the other stream still being joined, whose first part reading from the later time would lose. - **Several lines in one message** each keep the message's timestamp. - Refusals: - A frame without a valid timestamp is dropped, never shown as a line. - A container with a terminal is refused (`raw-stream`). The agent never creates one, and its output does not tell the streams apart. - Errors carry the status only, never the daemon's text. ## How it was tested - **Fake daemon:** the cases above, the `since` query, an oversized frame, an `emit` that fails and stops the read, 404 and other statuses. - **Real Docker 29,** `-tags integration`, `TestRealFollowLogsResumesFromACursor`: a busybox container writes `one`, `two` on stderr, a 20,000-byte line and `three`. - All four lines arrive, and the long line is cut to exactly 16 KiB and marked as cut. - Following again from the long line's timestamp, as after an outage, gives that line and `three`. That is the at-least-once delivery the ADR describes. - `golangci-lint` reports 0 issues, with and without the `integration` tag. ## Security considerations - Container output is untrusted. Frame sizes are bounded before allocating (1 MiB, from #453), lines at 16 KiB, and the text is made valid UTF-8 before it goes anywhere. - Secret redaction (ADR 0029) comes with the shipping PR, which knows the container's secret names. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added support for following Docker container logs, with stdout and stderr lines, timestamps, and resume points. * Long log lines are safely truncated, and incomplete lines are emitted when the stream ends. * **Bug Fixes** * Improved error messages for Docker exec output and log streams, including clearer handling of missing containers and interrupted reads. <!-- 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 first piece of container exec, which needs no decision (SPEC 3.1 and 3.3 specify it). It adds the Docker Engine calls only. The
ExecSessionhandler, theExecStreamclient, the gateway relay and the WebSocket route come in the next PRs.What changed
agent/internal/docker/exec.go:CreateExec(ref, {Argv, TTY, User}). Creates an exec attached to stdin, stdout and stderr. The command is an argument vector, never a shell string. The container reference is one escaped path segment. The id Docker returns must be 64 hex characters.StartExec(id, tty).101, as the Docker CLI does:net/httpwould not hand the connection back.Exec.Writesends to stdin,CloseStdinhalf-closes the connection, andCloseends it.Nextreads the output. A TTY session is one raw stream. Otherwise, Docker's multiplexed frames are read one by one.ResizeExecandInspectExec. They take a validated exec id. Inspection givesRunning,ExitCodeandPid.Client. It keeps its Unix socket dialer for the start.How it was tested
go test -tags integration -run '^TestReal' ./agent/internal/docker/:stty sizeafter a resize to 123×45;golangci-lint, with and without theintegrationtag, reports 0 issues.Security considerations
sh -c "id; rm -rf /"and checks that the script stays one argv entry.ExecSessionhandler in the next PR.