Skip to content

feat(agent): BuildImage builds a repository at its commit with rootless BuildKit (part of #215) - #533

Merged
samuelmbabhazi merged 8 commits into
mainfrom
feat/215-build-image
Nov 27, 2026
Merged

samuelmbabhazi merged 8 commits into
mainfrom
feat/215-build-image

Conversation

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator

Part of #215 (M3.3), per ADR 0030 and ADR 0032 (#531). This adds the agent's BuildImage action. It builds on #532 (the build lane) and contains its commit until #532 merges. The base is main.

What changed

  • agent/internal/buildkit drives the rootless BuildKit daemon over its gRPC socket. It runs no process and never touches Docker.

    • The repository is fetched by BuildKit itself (llb.Git) over HTTPS at the commit, with llb.GitSubDir for the context.
    • The Git token is a session secret under a random name. The default header secret name gets a random name too, and is not served. A Dockerfile cannot guess either name.
    • It builds with BuildKit's Dockerfile frontend, and pushes target_ref with an auth session that answers credentials only for the target's registry host.
    • It answers containerimage.digest, checked against sha256:<64 hex>.
    • BuildKit's progress becomes plain lines: #3 [2/4] RUN …, the step's output, then #3 DONE, CACHED or ERROR: ….
  • actions/build.go validates every field before anything runs (SPEC row updated):

    • an HTTPS repository on a DNS name, without credentials, query or fragment;
    • a full commit hash;
    • relative path segments without . or ..;
    • bounded args;
    • a tag in the registry the push credentials are for, with credentials that have not expired;
    • a timeout from 1 minute to 2 hours (30 minutes by default). CPU, memory and disk are those of the BuildKit unit.

    The plan runs in journal.BuildLane and is retry-safe as a whole.

  • Output: each line is redacted (the Git token and the registry password), made valid UTF-8 and cut at 16 KiB, then handed to a BuildLines sink with the action id. The log stream comes next. Until then the agent drops the lines, and never writes them to its own log.

  • Failures get fixed texts: build_failed, build_timeout, builder_unavailable. The control plane maps them to reasons, the web UI labels them in English and French, and SPEC 3.4 lists them.

  • Wiring: build.socket in the agent's config, /run/shipkeep-build/buildkitd.sock by default; the installer sets the daemon up in a later PR. A control-plane-only machine refuses BuildImage.

  • Dependency: github.com/moby/buildkit v0.35.1. Its compiled dependencies are 55 modules, all Apache-2.0, MIT or BSD; no GPL-family license. The stripped static agent goes from 25.4 MB to 30.6 MB.

  • CI: the "Agent against Docker and Caddy" job starts BuildKit 0.35.1 (pinned by digest) and a registry, and runs TestRealBuildKit….

How it was tested

  • Unit:
    • the push, the request built and the build lane;
    • malicious inputs that never reach BuildKit (46 cases): plain HTTP, SSH, file://, credentials, query or fragment in the URL, IP and localhost hosts, traversal raw and encoded, newline injection, short or uppercase commits, a commit that is an option, control characters in the token, absolute or traversing paths, backslashes, bad arg names and values, NUL, oversized values, too many args, targets on Docker Hub, elsewhere, by digest or without a tag, missing, expired or mismatched credentials, timeouts too short, too long or negative, oversized limits;
    • redaction, the UTF-8 fix and the 16 KiB bound;
    • each failure's fixed text, never BuildKit's message (which can quote a secret);
    • control-plane-only machines and agents without a builder.
  • Real BuildKit (TestRealBuildKitBuildsAndPushesARepositoryAtItsCommit): I ran it locally against moby/buildkit:v0.35.1 and registry:3.1.2 on the host's Docker.
    • BuildKit fetched this repository from GitHub at this branch's pushed commit and built agent/internal/buildkit/testdata/app with a build argument;
    • its RUN step found no Docker socket;
    • it pushed, and the registry's Docker-Content-Digest for the tag equals the digest the build answered. The run took 10 s.
  • Go and TypeScript checks: go test ./agent/... ./lib/... and golangci-lint are clean. The control plane fleet tests (173) and the web reason labels pass.

Security considerations

  • New action handler (security-review). Validation comes first and is tested with malicious input. The token and the registry password never appear in a URL, an argument, the journal, the disk or the output.
  • What a build can reach depends on the installer (next PR): buildkitd runs as shipkeep-build, which is not in the docker group, behind the nftables rule of ADR 0030. The test only shows that a build step sees no Docker socket in BuildKit's own sandbox.
  • Failure texts are fixed: BuildKit's errors, which can quote a command line, never reach the control plane.

)

ADR 0032: each lane has its own executor gate. Operations of a lane run one at a time, two lanes side by side, so a long build leaves the server's other actions free. The default lane holds every existing action.

Signed-off-by: samuel mbabhazi <[email protected]>
…ss BuildKit (part of #215)

ADR 0030, 0032: the action is validated field by field, runs in the build lane, fetches the repository over HTTPS with its token as a session secret under a random name, builds with BuildKit's Dockerfile frontend, pushes with the grant for the target's registry only, and answers the digest. Failures have fixed texts; the output is redacted and bounded, and goes to the log stream in the next step.

Signed-off-by: samuel mbabhazi <[email protected]>
…with a real BuildKit

The three fixed texts of BuildImage become reasons (build_failed, build_timeout, builder_unavailable), labelled in the web UI and in French. The agent job starts BuildKit 0.35.1 and a registry and builds this repository at the commit under test.

Signed-off-by: samuel mbabhazi <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 27, 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 51 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 1362f04 and f8a21d3.

Files ignored due to path filters: 5

  • agent/go.sum is excluded by !**/*.sum
  • apps/api/openapi.json is excluded by !apps/api/openapi.json
  • cli/go.sum is excluded by !**/*.sum
  • lib/go.sum is excluded by !**/*.sum
  • packages/api-client/src/gen/openapi.ts is excluded by !**/gen/**, !packages/api-client/src/gen/**
Files selected for processing: 22

  • .github/workflows/ci.yml
  • agent/go.mod
  • agent/internal/actions/build.go
  • agent/internal/actions/build_test.go
  • agent/internal/actions/dispatcher.go
  • agent/internal/actions/docker.go
  • agent/internal/actions/registry.go
  • agent/internal/agent/gateway.go
  • agent/internal/buildkit/buildkit.go
  • agent/internal/buildkit/printer.go
  • agent/internal/buildkit/real_buildkit_test.go
  • agent/internal/buildkit/testdata/app/Dockerfile
  • agent/internal/buildkit/testdata/app/greeting.txt
  • agent/internal/config/config.go
  • apps/api/src/modules/fleet/domain/agent-action.spec.ts
  • apps/api/src/modules/fleet/domain/agent-action.ts
  • apps/web/src/app/delivery/agent-action-rows.spec.ts
  • apps/web/src/app/delivery/agent-action-rows.ts
  • apps/web/src/app/ui/fr.ts
  • cli/go.mod
  • docs/SPEC.md
  • lib/go.mod
  • 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

…as nobody

go work sync and go mod tidy record BuildKit's dependency graph in agent/go.mod and give cli and lib the versions the workspace selects, which the license scan reads; Semgrep wants a non-root USER in the test Dockerfile.

Signed-off-by: samuel mbabhazi <[email protected]>
@samuelmbabhazi
samuelmbabhazi merged commit 79412a3 into main Nov 27, 2026
27 checks passed
@samuelmbabhazi
samuelmbabhazi deleted the feat/215-build-image branch November 27, 2026 11:37
samuelmbabhazi added a commit that referenced this pull request Nov 27, 2026
…yment (part of #215) (#534)

Part of #215 (M3.3), per ADR 0032 (#531). A build's output now reaches
the control plane. **It builds on #533 (BuildImage), and through it on
#532 (the build lane)**, and contains their commits until they merge;
the base is `main`.

## What changed

- **`logs.proto`** — `LogEntry.action_id` (6): the action whose output
the line is, `container` then empty. Backward compatible: today's
control plane drops such an entry and keeps the rest of the batch
(checked).
- **Agent**:
- `logship.BuildOutput` is the build's line sink. A build writes to it
without ever waiting. It keeps up to 8192 lines and 8 MiB, the oldest
dropped first.
- The shipper relays these lines in the same batches as the containers'
lines, numbered.
- A line is forgotten only once its batch is acknowledged. A stream that
fails before then sends it again on the next one, so delivery is at
least once.
  - No cursor is written for build lines.
- **Control plane**:
  - An entry is a container's line or an action's output, never both.
- `MetricsTargets.buildsOnNode` keeps only `buildImage` actions queued
on that very node with a deployment key `d:<deployment>:…`, and returns
their deployment's application, environment and project.
- Such lines are written with `instance` and `stream` set to `build`,
plus `deployment`.
- The application's log search adds `-stream:=build`, so build lines
never mix with the application's. I checked the LogsQL on a real
VictoriaLogs v1.54.
- **SPEC** documents the labels and the agent's bounds.

Reading build output back (a route for the deployment page) and the page
itself (#265) come next.

## How it was tested

- **Go**:
  - lines are tagged with the action and carry no container;
  - nothing is forgotten before its acknowledgement;
  - a line is resent on the next stream after a failed one;
  - the 8192-line and 8 MiB bounds drop the oldest first;
  - writing never blocks with nobody reading.
  
`go test -race ./agent/internal/logship/` and `golangci-lint` are clean.
- **TypeScript unit**:
- entries with both, neither, a malformed id or an injected id are
refused;
  - a line of a build the node was not given is dropped;
  - a build line never comes back through an application search;
- the ingest asks only for the actions named, and writes the
deployment's labels.
- **Integration, PostgreSQL** (`build-output.integration.spec.ts`): a
build queued on another node, a pull of the same deployment, a build
without a deployment key and an unknown id are all refused; only the
right build is kept. The fleet and observability integration suites show
only the known environment failures.
- **VictoriaLogs v1.54**, run on the host's Docker: `-stream:=build` and
`deployment:="…"` select what is expected.

## Security considerations

- An agent can label lines only through an action the control plane
queued on that node: a forged or foreign action id is dropped.
- No name the agent sends becomes a label. The build's own secrets are
redacted on the agent (#533).
- The buffer is bounded, and a build never waits for the stream.

---------

Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi added a commit that referenced this pull request Nov 27, 2026
… then deploys the image (part of #215) (#537)

Part of #215 (M3.3), per ADR 0030. This connects the pieces already
merged: the registry and its grants (#529, #530), the agent's
`BuildImage` (#533) and the build lane (#532). A Git application with a
Dockerfile now builds when it deploys, and its replicas run the image
that was built.

## What changed

- **Configuration**: an application whose configuration is a
repository's may use `build.type: dockerfile`. Railpack and Nixpacks are
still refused with `unsupported_build_type` (new text, in the web UI and
in French). An application created from an image still runs an image.
- **Release**:
- `releaseDraft(config, { repository })` plans a build. Its image is
`<control plane host>/<organization>/<application>:<release number>`
(`builtImage`), set once the store knows the number;
- `repositoryPath` reads paths the way the agent does: `./api/` → `api`,
`.` → the root;
  - the commit was already kept (#527).
- **Planner** (`building` and `built` stages): the replicas are placed
first, then `build_image` runs on the first one's server, at the commit,
with the context, the Dockerfile and the args. Its digest becomes the
release's (`record_build`). A failed build gives its cause in words: its
output, its time limit, a server without a builder.
- **Runner**:
- the GitHub token is minted **outside any transaction**
(`RepositorySource.buildAccess`): read access to that one repository,
under its current name. If GitHub cannot be reached, the run waits and
tries again;
- the push grant (#529) is issued at enqueue time and lasts as long as
the action;
  - `release.image_built` is audited with the digest and the commit;
- every pull from the installation's registry carries a **pull-only
grant**.
- **Store**: an action's `buildImage.imageDigest` is read back, only if
it is a valid `sha256:` digest.
- **SPEC**: the build stage. Open question: the token is not revoked
when the build ends yet (it expires within the hour).

## How it was tested

- **Planner unit tests**:
- the full order, from `queued` through `building` and `built` to
`succeeded`;
- the exact build step (first replica's node, normalized paths, the
tag), with the default context and Dockerfile;
  - every replica pulls `<repository>@<built digest>`;
  - each failure cause and its text, with nothing deployed afterwards;
  - no digest, no commit, a release already built.
- **Agent action**: `BuildImage` carries the URL, the commit, the token
and the push grant, and round-trips through protobuf. A build without
its access is refused.
- **Integration** (`git-builds.integration.spec.ts`, PostgreSQL, fake
GitHub, real pipeline and token endpoint):
- the deploy creates `…/<app>:1`, and the build is the only action
queued;
  - the token is scoped to `repositoryIds: [777]`, `contents: read`;
- the push grant is accepted by the token endpoint for pull and push on
that repository;
  - after the agent's answer, the digest is recorded and audited;
- the pull goes to `<repo>@<digest>` with a grant that gets `pull` only;
- both grants are audited, and the token never appears in the audit log.
- **Suites**:
  - API: lint, typecheck, 411 unit tests;
- integration, all suites run: only the known environment failures
(PostgreSQL 18 error codes, specs that need a container runtime);
  - web: 398 tests.

## Security considerations

- **The token** is minted for one repository and read access, travels
only inside the encrypted action, and is never logged or audited. It is
not revoked yet (open question).
- **The grants**: pushing only for the build, only to the application's
repository, until the action's deadline. Servers only pull.
- **No GitHub call holds a database transaction.**

Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi added a commit that referenced this pull request Nov 27, 2026
…f its own (part of #215) (#536)

Part of #215 (M3.3), per ADR 0030. The server installer now sets up the
builder that `BuildImage` (#533) talks to. BuildKit comes from GitHub,
pinned, as decided on 2026-11-27.

## What changed (`deploy/install.sh`)

- **BuildKit v0.35.1**, the official release:
  - downloaded from `github.com` over HTTPS only, redirects included;
- checked against `buildkit_amd64_sha256` and `buildkit_arm64_sha256`,
written in this script, which the control plane already pins by its own
digest;
- only `buildkitd` and `buildkit-runc` are kept, in
`/usr/local/libexec/shipkeep-build` (root-owned).
- **From Ubuntu**: `rootlesskit` (whose AppArmor profile already allows
user namespaces, so no profile of our own), `slirp4netns`, `uidmap`, and
`git` (BuildKit's Git source needs it).
- **The `shipkeep-build` account**:
  - it is in no group that reaches Docker;
- it gets 65536 subordinate ids **after every range already given**:
Ubuntu's cloud images give 100000–165535 to `ubuntu`, which I found in
the lab;
  - the agent's account joins its group, to reach the socket.
- **`shipkeep-build.service`**:
- rootlesskit runs `buildkitd` with `--net=slirp4netns
--disable-host-loopback --copy-up=/etc`;
- the socket is `/run/shipkeep-build/buildkitd.sock` (0660,
`shipkeep-build` group);
- it runs in `shipkeep-build.slice` (MemoryMax 50 %, CPUWeight 50), with
`OOMScoreAdjust=1000`;
- `ExecStartPre=+nft --file /etc/shipkeep-egress.nft`, so the rule is
always loaded before it starts;
- `buildkitd.toml`: one rootless OCI worker, GC within 20 % of the disk,
15 % left free.
- **The `build` chain of `inet shipkeep_egress`**, matched on the
account's uid:
- allowed: the name servers of `/etc/resolv.conf` on port 53, and the
server's own addresses on **443 only**, its Caddy (which the registry
needs on a single machine);
- rejected: the server's other own addresses, and the egress proxy's
ranges plus IPv4-mapped addresses. A Go test keeps those ranges
identical.
- **Flows**:
  - fresh install: prepared, then the guard, then started;
- `--migrate yes` adds it to servers installed before (account checks
included);
  - a control-plane-only machine gets none;
- a single machine installed before builds has no migration yet (open
question in SPEC).
- **Docs**: INSTALL (requirements, the service, cleanup),
`deploy/README`, SPEC.

## How it was tested

On the rig: privileged Ubuntu 24.04 containers with systemd, on the
host's Docker.

- **Full installer main flow** on a fresh server (`--agent-file`, no
control plane): exit 0. `shipkeep-build`, `shipkeep-egress`, Docker and
Caddy are active, the socket is present, `shipkeep` is in the
`shipkeep-build` group, and the build chain is loaded. After a restart
of the machine everything comes back with the rule loaded.
- **`prepare_builder` and `start_builder`** on another fresh server:
download via GitHub's redirect, checksum, account, subordinate range
165536 (after `ubuntu`'s), units. Running them a second time adds
nothing and restarts cleanly.
- **A real rootless build** as `shipkeep-build`, through the agent's
BuildKit client: this repository fetched from GitHub at the commit,
built, pushed to a registry (before the rule).
- **Under the rule**:
  - plain-HTTP internet: reached;
- `169.254.169.254`, a private registry and the server's own port 22:
blocked;
  - DNS: works;
- BuildKit's own push to a private registry: refused (`dial tcp
192.168.64.3:5000: i/o timeout`), while the GitHub fetch still passes.
- **Socket access**: the agent's account builds through the socket, and
`nobody` is refused.
- **Automated**:
- `install_test.sh`: the build chain's exact rules and their order,
refused uids and name servers (injection, `$(id)`, names, braces),
`resolv_nameservers`, `subordinate_start`, the unit's settings (no
Docker, `--disable-host-loopback`), the pins;
  - Go `TestTheBuildRuleRefusesTheProxysRanges`;
  - shellcheck and golangci-lint are clean.

**Not covered here**: Ubuntu's restriction on unprivileged user
namespaces (`kernel.apparmor_restrict_unprivileged_userns`). The lab's
host does not have it, so rootlesskit's AppArmor profile is only
exercised on a real Ubuntu 24.04 VM, which is the v0.1 acceptance step.

## Security considerations

- A build cannot reach the Docker socket: the account is not in the
`docker` group, and the rootless sandbox maps no host path.
- Its network reaches only what the internet reaches. The 443 exception
only reaches the server's own Caddy, which serves public routes.
- What is downloaded at install time is pinned by digest inside the
pinned installer. A new external source at install time (github.com) is
the maintainer's choice.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Application servers can now build applications using an isolated build
service with bounded resource use and cache.
* Existing servers can add the build service through migration, except
machines that also host the control plane.
* **Documentation**
* Installation guidance now covers build-service setup, network
requirements, resource limits, troubleshooting, and cleanup.

<!-- 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 27, 2026
…#539)

Part of #265 (screen 15, "the build and release log of one deployment,
streamed while it runs").

## What changed

**API**
- `GET
…/applications/{applicationId}/deployments/{deploymentId}/build-output`
(`environment.read`, also open to API tokens with that permission)
answers one deployment's build output, oldest first: `kept`, and `lines`
with `time`, `line`, `truncated`.
- It reads the lines the control plane labelled with that deployment
(#534): `instance` and `stream` `build`, field `deployment`. By default
it starts an hour before the deployment started, because the agent
stamps lines with its own clock. A live view passes `from`, the exact
time of its last line, to the nanosecond. `limit` defaults to 500, which
is also the maximum.
- A deployment of another application is not found, checked in SQL
(`deployments.application_id`).
- Authorization follows the application's log search (#488): authorized
in a short transaction, the store read with no lock or transaction held,
then authorized again before any line leaves.

**Web**
- The "will appear here" note on the deployment page is replaced by a
**Build output** section under the timeline. It follows the "Full log"
block of design screen 15: a title, "Rootless BuildKit" on the right, a
mono block of at most 420 px, each line prefixed with its time.
- While the deployment runs, the section reads again every 3 s, and
twice more once it has finished. Each read starts 3 s before the last
line, because batches of one build may reach the store side by side. A
line read twice shows once.
- The view follows the end unless the reader scrolled up. It keeps the
last 8192 lines, as many as the agent holds for one build, and says so
when it drops older ones.
- An image deployment promises no build output. A deployment that runs a
release command says its output is not collected yet.
- The page says when the installation keeps no logs, and when the read
fails, with a Retry button.
- French translations added.

**Docs**: SPEC section 12 describes the route and the live view; section
8 points the timeline at it. The route/role matrix is regenerated.

## Why

#215 builds now run (#533, #537) and their output reaches VictoriaLogs
(#534), but nobody could see it. Without that, a failed build is a
failed deployment with no reason anyone can read.

## How it was tested

- Unit tests:
- the LogsQL query: exact time, injection attempts in each identifier,
records that are not build lines;
- the service: margin before the start, a deployment of another
application, no store, access withdrawn while the store answers;
  - the line merge: repeats, order, the 8192 bound;
- the page: live reads with `from`, a line read twice, reads stop after
the deployment finished, no log store, a read failure then Retry.
- Integration with PostgreSQL (`build-output-http.integration.spec.ts`):
  - viewer access, the exact query, `from` to the nanosecond;
  - a `from` with no offset, or in the future, is refused;
- an outsider, and a deployment under another application, get 404 and
the store is never asked.
- Mutation check: dropping the application filter from the SQL fails
that test.
- Chromium against the production build (`github.browser.spec.ts`): a
Git application with a Dockerfile is deployed on an enrolled server, and
its page shows the build output a fake log store answers, read again
while it runs. Checked under the production CSP and axe.
- Locally: web 404/404 unit tests, API 973/973 unit tests. Integration
469 passed; the only failures are the known local ones (PostgreSQL 18's
23001 ×3, and the metrics, S3 and Distribution suites, which need a
container runtime).

The diff is about 1100 lines excluding generated code, about half of it
tests.

## Security considerations

- Build lines are redacted by the agent before they leave the server
(#534): secret values, the Git token and the registry password. This
route only reads what was stored.
- Identifiers in the LogsQL query are validated as UUIDs. `from` must be
RFC 3339 with an offset, and enters the query only through the strict
nine-digit form, so no user text reaches the query.
- Access is `environment.read`, the same as application logs. Access is
checked again after the store answers, so a reader who loses access
during the read gets nothing.

## UI validation

Screenshots (desktop and mobile, English and French) were shared with
the maintainer. This PR waits for their validation before merging.

---------

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