Skip to content

[M1.4a1] Agent action dispatch with journaled, validated execution - #147

Merged
samuelmbabhazi merged 4 commits into
mainfrom
feat/m1.4a1-agent-action-dispatch
Nov 5, 2026
Merged

samuelmbabhazi merged 4 commits into
mainfrom
feat/m1.4a1-agent-action-dispatch

Conversation

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator

Part of #134.

What changed

M1.4a1: the agent side of action dispatch.

  • agent/internal/actions.Dispatcher.
    • Validates each ActionRequest before journaling anything:
      • the action id must be a UUIDv7;
      • the idempotency key must match [A-Za-z0-9._:-]{1,128};
      • the action kind must be registered;
      • the lease epoch must be the node's;
      • the deadline must be present and in the future;
      • the handler's own validation must pass.
    • A rejected request gets exactly one FAILED update with a fixed, redacted message.
    • It then runs the handler's versioned plan through journal.Store.Execute, under the request deadline, and sends an ActionUpdate on every transition plus a final one with the mapped ActionResult.
    • The payload hash covers only the action message, so redelivery with the same key returns the journaled outcome without re-executing. The same key with a different payload is refused.
    • Cancel cancels a running action's context, and the journal compensates per its plan.
  • actions.Registry(). Empty for now: every kind is answered "not supported" until handlers land with their own malicious-input tests (M1.4b, M1.4c, M1.5).
  • gateway.Runner:
    • forwards ActionRequest frames to the handler on the agent's lifetime, not the stream's, so a dropped connection never interrupts an action;
    • serializes updates onto the stream and applies CancelAction;
    • still refuses other frames (routing, peers, leases) instead of pretending to apply them;
    • Run waits for in-flight actions before returning. Receivers became pointers.
  • Agent. The dispatcher is wired to the journal store and the enrolled lease epoch.
  • Docs. SPEC 3.4 describes dispatch. The PLAN splits M1.4a into a1 (agent, this PR) and a2 (control-plane queue).

How it was tested

Everything runs locally: pure-Go SQLite, a real TLS test gateway.

  • Dispatcher with the real journal:
    • a successful action reports progress and its result;
    • redelivery does not re-run the step;
    • a payload conflict is refused;
    • 10 rejection cases (SQL injection in the id, path traversal and an oversized key, missing or unhandled action, stale epoch, expired or missing deadline, an invalid payload) give one failure each, nothing journaled, no step run and no input echoed;
    • cancellation stops a blocked step.
  • Runner over real TLS: an action delivered by the gateway produces RUNNING then SUCCEEDED updates on the stream, and a CancelAction reaches the handler.
  • go test -race ./agent/..., golangci-lint (0 issues) and the local gate pass.

Security considerations

  • The closed action list holds: an empty registry means nothing runs.
  • Validation happens before any journal write or side effect.
  • Error texts are fixed and never echo request content.

@samuelmbabhazi
samuelmbabhazi merged commit 57f05ce into main Nov 5, 2026
1 of 10 checks passed
@samuelmbabhazi
samuelmbabhazi deleted the feat/m1.4a1-agent-action-dispatch branch November 5, 2026 19:36
samuelmbabhazi added a commit that referenced this pull request Nov 5, 2026
Closes #134 (with #147).

## What changed

M1.4a2: the control-plane side of action dispatch.

- **`agent_actions` table.**
- Forced tenant RLS, a composite foreign key to the node (cascade), and
an idempotency key unique per node.
- CHECK constraints on kind, key, state, epoch and attempts. The runtime
role gets SELECT, INSERT and UPDATE; `assertTenantDatabaseRole` now
covers 11 tables.
- The action message is stored encrypted with `EnvelopeService`: scope
`organization:<id>`, purpose bound to the action id.
- **`AgentActions` service:**
- `enqueue` validates the kind against the proto catalog, the key
grammar and a deadline within 24 h, and requires a node that has not
been removed. It stamps the node's lease epoch, is idempotent per key
(including a concurrent insert) and audits `fleet.action.queued`.
- `deliverable` first expires overdue actions (audited as
`fleet.action.expired`), then returns the node's unfinished actions not
yet sent on this stream as `ActionRequest`s.
- `record` applies an agent `ActionUpdate` only to that node's own
non-terminal action. Terminal states never change again, and each
terminal state is audited as `fleet.action.<state>` with the node as
actor. The step and error are bounded, and the result is stored as JSON.
- **`NodeStream`.** After Hello, each poll (at most every second) sends
unfinished actions once per stream, and the stream accepts
`actionUpdate` frames. A new stream redelivers everything unfinished;
the agent journal (#147) replays known keys.
- **Docs.** The SPEC describes delivery, and the PLAN ticks M1.4a.

## How it was tested

- Unit tests: a stream test delivers an action once (welcome, then
actionRequest) and records the agent's update. Existing stream tests are
updated. API tests (218) and the local gate pass.
- New TLS integration case in `gateway.integration.spec.ts`:
- an action queued for a really enrolled node is delivered with its key
and kind, and redelivered on a new stream after a dropped connection;
  - RUNNING then SUCCEEDED updates move it to `succeeded`;
  - the audit shows queued then succeeded;
  - re-enqueueing the same key returns the same action;
  - the stored payload does not contain the plaintext.
- **Not run locally:** the integration tests (no Docker). They run in
CI-1.

## Security considerations

- Payloads are encrypted at rest.
- A node can only update its own actions, through its authenticated
identity and RLS.
- Final states are immutable.
- Delivery stays inside the closed action list.

---------

Signed-off-by: Samuel Mbabhazi <[email protected]>
samuelmbabhazi added a commit that referenced this pull request Nov 5, 2026
…149)

Part of #135.

## What changed

M1.4b1: the agent can ensure networks and volumes and pull pinned
images. These are the first real handlers behind the #147 dispatcher.

- **`agent/internal/docker`.** A minimal typed Docker Engine API client
instead of the Go SDK: no new dependency, and a much smaller surface.
It:
  - talks only to the local `unix://` socket, with API `v1.47` pinned;
- exposes only the needed calls: network list and create, volume
inspect, create and remove, image inspect and pull;
  - uses typed JSON bodies and path-escaped names;
  - caps responses at 1 MiB and pull streams at 100k lines;
  - reports errors by status code only, never the daemon's text;
- matches networks by exact name (the Engine's inspect endpoint also
accepts id prefixes);
  - detects pull failures from in-stream `error` objects.
- **Handlers** (`actions.DockerHandlers`):
- `ensure_network` and `ensure_volume`: name grammar
`^sk-[a-z0-9-]{1,60}$`; create with `sk.managed=true`; adopt an existing
resource only if it carries that label (a same-named unmanaged resource
is refused); never delete to compensate.
- `ensure_volume` labels: at most 16; keys match
`[a-z0-9][a-z0-9._-]{0,62}`; the `sk.` namespace is reserved; values are
printable and at most 256 bytes.
- `pull_image`: digest-pinned references only (`repo@sha256:<64 hex>`,
lowercase, optional registry host and port, at most 512 bytes). Optional
credentials must be for the image's own registry, unexpired and bounded;
the password stays a `secret.String`. The step is skipped when the exact
repo@digest is already present, and the digest is checked after the
pull.
- **Wiring.** The agent builds the client from `docker.host` and
registers the handlers.
- **Docs.** SPEC 3.3 describes the client and the managed-label rule.
CLAUDE.md rule 1 points to the client. The PLAN splits M1.4b (b2: Go
confirmation verifier and `RemoveVolume`).

## How it was tested

Everything runs locally, without Docker.

- Handlers through the real dispatcher and journal with a fake engine:
  - create once and refuse foreign resources;
- pull with scoped credentials, then skip the pull when the image is
present;
  - labels preserved, and the managed label added.
- Malicious-input table, 34 cases:
- names: traversal, upper case, injection, oversize, `host`/`bridge`,
newline;
- images: tags, `latest`, upper case, short digest, traversal, appended
flags, oversize;
  - credentials: expired, other registry, Docker Hub;
  - labels: reserved key, control characters, too many.
- Each gets the fixed `invalid action input` error and never reaches the
daemon.
- A fuzz target over the name and image validators, run for 20 s (about
290k executions) with no finding.
- Client against a fake daemon on a Unix socket: exact network names
over substring filters, a 404 mapped to not-found, daemon text not
leaked, a pull stream error detected, non-unix hosts refused.
- `go test -race ./agent/...`, `golangci-lint` (0 issues) and the local
gate pass.
- **Not run locally:** a real Docker daemon. Integration against Docker
comes with CI-1.

## Security considerations

- No shell anywhere.
- Every input is validated before the journal and the daemon.
- Only Shipkeep-labelled resources are touched.
- Registry passwords are wrapped and scoped.
- Daemon errors never leak to the control plane.

---------

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