Skip to content

feat(agent): Docker exec calls for interactive sessions (part of #232) - #453

Merged
samuelmbabhazi merged 3 commits into
mainfrom
feat/232-docker-exec
Nov 24, 2026
Merged

samuelmbabhazi merged 3 commits into
mainfrom
feat/232-docker-exec

Conversation

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator

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 ExecSession handler, the ExecStream client, 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).
    • Writes the start request on a connection of its own and takes it over once Docker answers 101, as the Docker CLI does: net/http would not hand the connection back.
    • The context bounds the start only.
    • On a refusal, only the status is reported, never the daemon's text.
  • Exec.
    • Write sends to stdin, CloseStdin half-closes the connection, and Close ends it.
    • Next reads the output. A TTY session is one raw stream. Otherwise, Docker's multiplexed frames are read one by one.
    • A frame is refused when its stream byte is not 1 or 2, when its padding is not zero, when it is over 1 MiB, or when it is truncated.
  • ResizeExec and InspectExec. They take a validated exec id. Inspection gives Running, ExitCode and Pid.
  • Client. It keeps its Unix socket dialer for the start.

How it was tested

  • Unit tests against a fake daemon. They check:
    • the argument vector is sent unchanged;
    • an invalid exec id is refused;
    • stdin goes through and stdout stays apart from stderr, including after stdin is closed;
    • a TTY session is one raw stream;
    • a refusal reports the status without the daemon's text;
    • the start stops with its context;
    • malformed frames are refused;
    • resize and inspect work.
  • Real Docker 29, go test -tags integration -run '^TestReal' ./agent/internal/docker/:
    • stdin and the two output streams, with exit code 7 read back;
    • stty size after a resize to 123×45;
    • creation is refused in a stopped container.
  • CI. The integration job now runs this package too.
  • golangci-lint, with and without the integration tag, reports 0 issues.

Security considerations

  • The argument vector reaches the daemon unchanged and no shell is involved. A test sends sh -c "id; rm -rf /" and checks that the script stays one argv entry.
  • Output from the container is untrusted. Frame headers are validated and sizes are bounded before allocating.
  • The checks that the container is managed, that the user holds the permission, and the time limit belong to the ExecSession handler in the next PR.
  • Docker has no API to stop an exec'd process. A command that outlives its connection keeps running until it exits or the container restarts. The handler PR documents this limit.

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]>
@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 9 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 4948888 and 6ca0d82.

Files selected for processing: 5

  • .github/workflows/ci.yml
  • agent/internal/docker/client.go
  • agent/internal/docker/exec.go
  • agent/internal/docker/exec_test.go
  • agent/internal/docker/real_exec_test.go
  • 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

…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]>
@samuelmbabhazi

Copy link
Copy Markdown
Collaborator Author

An independent review of this PR (high effort, while CodeRabbit is rate limited) raised seven points, all fixed in ca90c66:

  • Docker's default detach sequence (important). ctrl-p ctrl-q would have cut a terminal session short, and ctrl-p was held back until the next key. The create now sets DetachKeys to ctrl-\\,ctrl-],ctrl-\\,ctrl-],ctrl-\\, since Docker cannot turn the sequence off. A real-Docker test sends ctrl-p ctrl-q and checks that the shell is still attached.
  • The TTY flag was given twice (important). CreateExec now returns an ExecInstance{ID, TTY}, and StartExec takes it, so the two can no longer disagree.
  • The context is now held for the whole session (nit). The StartExec context bounds the session, and Next and Write return when it ends (rule: context on every call that can block). The AfterFunc is always released, and a cancelled start reports ctx.Err(). A test covers it.
  • Next(max) now refuses no room, never wraps a nil error, retries a read of zero bytes, and returns at most max bytes without a TTY as well, keeping the rest of a frame. A test covers it.
  • Error wrapping. The truncated-frame and CloseStdin errors now keep their cause.

go test -race, golangci-lint (0 issues, with and without integration) and the four real-Docker tests pass.

@samuelmbabhazi
samuelmbabhazi merged commit ac29b5f into main Nov 24, 2026
25 checks passed
@samuelmbabhazi
samuelmbabhazi deleted the feat/232-docker-exec branch November 24, 2026 21:24
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]>
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