From 0f638c7c4ed0609bd055f019cfee23b0fe273739 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Fri, 13 Nov 2026 12:19:26 -0800 Subject: [PATCH] Wire triple-c-agent into the image, harden it, and prove Docker parity - Crate moves to container/triple-c-agent (inside the image build context); the Dockerfile's agent-build stage cross-compiles it on $BUILDPLATFORM for $TARGETARCH (verified: buildx arm64 and the classic builder with the app's build args both produce static binaries). The app's local build context embeds the crate's Cargo.toml, Cargo.lock and src/ only. - entrypoint.sh starts the agent from an env/cwd snapshot taken before the script exports or cd's anything (minus bash's own PWD/SHLVL/_), so execs see what `docker exec` would. - Agent: no TRIPLEC_AGENT_* setting reaches an exec; a token file others can read is refused (security review); upload symlink handling documented as deliberate parity (claude has passwordless sudo, so no boundary). - New ignored live test host::agent::live_tests runs every operation through ContainerTarget::Docker and ::Agent on the same real container and requires identical results. It caught a real divergence, now fixed in agent and spec: docker exec sets only HOME, never USER/LOGNAME. - CI runs the agent crate's tests in the preview test job. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/build-app-preview.yml | 13 + .gitignore | 2 +- CLAUDE.md | 10 + app/src-tauri/src/docker/image.rs | 8 + app/src-tauri/src/host/agent.rs | 2 + app/src-tauri/src/host/agent/live_tests.rs | 231 ++++++++++++++++++ container/.dockerignore | 2 + container/Dockerfile | 32 +++ container/entrypoint.sh | 20 +- .../triple-c-agent}/Cargo.lock | 0 .../triple-c-agent}/Cargo.toml | 0 {agent => container/triple-c-agent}/README.md | 36 ++- .../triple-c-agent}/src/attach.rs | 0 .../triple-c-agent}/src/exec.rs | 0 .../triple-c-agent}/src/files.rs | 9 + .../triple-c-agent}/src/lib.rs | 59 ++++- .../triple-c-agent}/src/main.rs | 0 .../triple-c-agent}/src/pty.rs | 0 .../triple-c-agent}/src/spawn.rs | 13 +- .../triple-c-agent}/src/tunnel.rs | 0 .../triple-c-agent}/src/users.rs | 0 .../triple-c-agent}/tests/protocol.rs | 7 +- .../2026-11-13-triple-c-agent-protocol.md | 5 +- 23 files changed, 430 insertions(+), 19 deletions(-) create mode 100644 app/src-tauri/src/host/agent/live_tests.rs create mode 100644 container/.dockerignore rename {agent => container/triple-c-agent}/Cargo.lock (100%) rename {agent => container/triple-c-agent}/Cargo.toml (100%) rename {agent => container/triple-c-agent}/README.md (64%) rename {agent => container/triple-c-agent}/src/attach.rs (100%) rename {agent => container/triple-c-agent}/src/exec.rs (100%) rename {agent => container/triple-c-agent}/src/files.rs (93%) rename {agent => container/triple-c-agent}/src/lib.rs (81%) rename {agent => container/triple-c-agent}/src/main.rs (100%) rename {agent => container/triple-c-agent}/src/pty.rs (100%) rename {agent => container/triple-c-agent}/src/spawn.rs (96%) rename {agent => container/triple-c-agent}/src/tunnel.rs (100%) rename {agent => container/triple-c-agent}/src/users.rs (100%) rename {agent => container/triple-c-agent}/tests/protocol.rs (99%) diff --git a/.gitea/workflows/build-app-preview.yml b/.gitea/workflows/build-app-preview.yml index f5942a8..392d902 100644 --- a/.gitea/workflows/build-app-preview.yml +++ b/.gitea/workflows/build-app-preview.yml @@ -84,6 +84,9 @@ on: - "app/**" - "VERSION" - ".gitea/workflows/build-app-preview.yml" + # The app embeds the agent's sources for its local image build, and the + # agent's own tests run in the `test` job below. + - "container/triple-c-agent/**" workflow_dispatch: jobs: @@ -332,6 +335,16 @@ jobs: export PATH="$HOME/.cargo/bin:$PATH" cargo test --locked + # The in-container agent is its own crate (container/triple-c-agent): a + # real server on loopback, exercised over HTTP/WebSocket as the current + # user. Its root-only test is #[ignore]d. The Docker-parity test against + # a real container lives in the app (host::agent::live_tests, ignored). + - name: Agent tests (cargo test) + working-directory: ./container/triple-c-agent + run: | + export PATH="$HOME/.cargo/bin:$PATH" + cargo test --locked + build-linux: runs-on: ubuntu-latest needs: [compute-version, create-release] diff --git a/.gitignore b/.gitignore index 59f33f5..acfd1df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ node_modules/ app/dist/ app/src-tauri/target/ -agent/target/ +container/triple-c-agent/target/ # Written by build.rs (tauri-build AppManifest); gen/schemas/acl-manifests.json is the # tracked, reviewable form of the same information. app/src-tauri/permissions/autogenerated/ diff --git a/CLAUDE.md b/CLAUDE.md index b5665ae..752b412 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -338,6 +338,16 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li subscription) is what flips a project whose container exits on its own to Stopped and emits `project-container-exited` with a `reason` (`exited` toasts; `found_stopped`, the first look of a run, is silent); `useProjectStatusEvents` applies it - **`triple-c-scheduler`** — Bash-based scheduled task system for recurring Claude Code invocations +- **`triple-c-agent/`** — the in-container agent (its own Rust crate; protocol in + `docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md`). Built static by the Dockerfile's + `agent-build` stage, started by `entrypoint.sh` **only when a token is configured**, last, as root + under a supervisor loop. **Its contract is Docker parity**: an `ExecSpec` must behave through the + agent exactly as through `docker exec`. Any change to exec semantics on either side is checked by + `host::agent::live_tests::the_agent_answers_exactly_as_docker_exec_does` (ignored; needs an image + with the agent — see the crate README). The token never stays in the environment: the entrypoint + moves it to a root-only file before anything runs, and the agent refuses a token file others can + read. The agent is started from an env/cwd snapshot taken at the top of the entrypoint so execs + see the container's configured env, not the script's. **`/home/claude` in the image is seed-only.** It is the mount point of the named volume `triple-c-home-{projectId}`, so after a project's *first* start the image's copy of that directory diff --git a/app/src-tauri/src/docker/image.rs b/app/src-tauri/src/docker/image.rs index 1471e01..9f5ddae 100644 --- a/app/src-tauri/src/docker/image.rs +++ b/app/src-tauri/src/docker/image.rs @@ -20,6 +20,11 @@ const PLAYWRIGHT_HEAL: &str = include_str!("../../../../container/triple-c-playw static MISSION_CONTROL_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/mission-control"); static SKILLS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/skills"); +// The agent crate's sources only — never the whole crate directory, which can +// hold a multi-hundred-megabyte `target/` from a local build. +const AGENT_CARGO_TOML: &str = include_str!("../../../../container/triple-c-agent/Cargo.toml"); +const AGENT_CARGO_LOCK: &str = include_str!("../../../../container/triple-c-agent/Cargo.lock"); +static AGENT_SRC_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/triple-c-agent/src"); pub async fn image_exists(image_name: &str) -> Result { let docker = get_docker()?; @@ -243,6 +248,9 @@ fn create_build_context() -> Result, std::io::Error> { append_embedded_dir(&mut archive, &MISSION_CONTROL_DIR, "mission-control")?; append_embedded_dir(&mut archive, &SKILLS_DIR, "skills")?; + append_file_to_archive(&mut archive, "triple-c-agent/Cargo.toml", AGENT_CARGO_TOML.as_bytes(), 0o644)?; + append_file_to_archive(&mut archive, "triple-c-agent/Cargo.lock", AGENT_CARGO_LOCK.as_bytes(), 0o644)?; + append_embedded_dir(&mut archive, &AGENT_SRC_DIR, "triple-c-agent/src")?; archive.finish()?; } diff --git a/app/src-tauri/src/host/agent.rs b/app/src-tauri/src/host/agent.rs index c246fa1..0c419a9 100644 --- a/app/src-tauri/src/host/agent.rs +++ b/app/src-tauri/src/host/agent.rs @@ -851,3 +851,5 @@ pub async fn is_running(ep: &AgentEndpoint) -> Result { #[cfg(test)] mod tests; +#[cfg(test)] +mod live_tests; diff --git a/app/src-tauri/src/host/agent/live_tests.rs b/app/src-tauri/src/host/agent/live_tests.rs new file mode 100644 index 0000000..96f36c8 --- /dev/null +++ b/app/src-tauri/src/host/agent/live_tests.rs @@ -0,0 +1,231 @@ +//! The real agent against `docker exec`, in one real container: every +//! operation goes through `ContainerTarget::Docker` and +//! `ContainerTarget::Agent` on the *same* container and must come back the +//! same. That is the agent protocol's whole requirement ("Docker parity is the +//! requirement"), checked end to end rather than against a fake. +//! +//! Needs a Docker daemon and an image whose entrypoint starts the agent: +//! `TRIPLEC_AGENT_E2E_IMAGE`, default `tc-agent-e2e:latest` (the sandbox image +//! plus this branch's `entrypoint.sh` and `triple-c-agent`). + +use super::*; +use crate::host::{ContainerTarget, ExecChunk, ExecSpec, OUTPUT_LIMIT_MARKER}; +use futures_util::StreamExt; +use std::process::Command; +use std::time::Duration; +use tokio::io::AsyncWriteExt; + +fn docker_cli(args: &[&str]) -> String { + let out = Command::new("docker").args(args).output().expect("docker cli"); + assert!(out.status.success(), "docker {:?}: {}", args, String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +fn sh(script: &str) -> Vec { + vec!["sh".into(), "-c".into(), script.into()] +} + +/// Drain an attached exec: (stdout, stderr). +async fn drain(exec: crate::host::AttachedExec) -> (String, String) { + let mut out = exec.output; + let (mut o, mut e) = (Vec::new(), Vec::new()); + let collect = async { + while let Some(chunk) = out.next().await { + match chunk { + Ok(ExecChunk::StdOut(b)) => o.extend_from_slice(&b), + Ok(ExecChunk::StdErr(b)) => e.extend_from_slice(&b), + Ok(ExecChunk::Other(_)) => {} + Err(_) => break, + } + } + }; + tokio::time::timeout(Duration::from_secs(20), collect).await.expect("attach output ended"); + (String::from_utf8_lossy(&o).into_owned(), String::from_utf8_lossy(&e).into_owned()) +} + +/// Fail with both answers side by side. +fn same(what: &str, docker: T, agent: T) -> Result<(), String> { + if docker == agent { + Ok(()) + } else { + Err(format!("{what} differs\n docker: {docker:?}\n agent: {agent:?}")) + } +} + +async fn parity(d: &ContainerTarget, a: &ContainerTarget) -> Result<(), String> { + // ── one-shot ───────────────────────────────────────────────────────────── + let script = sh("echo out1; echo err1 >&2; echo out2; exit 3"); + same( + "streams + exit code", + d.exec_oneshot_streams_as("claude", script.clone(), vec![]).await?, + a.exec_oneshot_streams_as("claude", script, vec![]).await?, + )?; + + for user in ["claude", "root"] { + let env = sh("env | sort"); + let strip = |s: String| -> String { + // `docker exec` inherits the container's configured env, which in + // this harness carries the agent's settings (the token included — + // the local-harness trade-off entrypoint.sh documents). The agent + // never passes its own settings on. + s.lines().filter(|l| !l.starts_with("TRIPLEC_AGENT_")).collect::>().join("\n") + }; + let (de, dc) = d.exec_oneshot_as(user, env.clone(), vec![]).await?; + let (ae, ac) = a.exec_oneshot_as(user, env, vec![]).await?; + same(&format!("environment as {user}"), (strip(de), dc), (strip(ae), ac))?; + } + + same("default working dir", d.exec_oneshot(vec!["pwd".into()]).await?, a.exec_oneshot(vec!["pwd".into()]).await?)?; + + let probe = sh("echo \"$FOO|$HOME|$USER|$(id -un)\""); + let env = vec!["FOO=bar".to_string(), "HOME=/tmp".to_string()]; + same( + "env overrides", + d.exec_oneshot_env_status(probe.clone(), env.clone()).await?, + a.exec_oneshot_env_status(probe, env).await?, + )?; + + same("user ids", d.user_ids().await, a.user_ids().await)?; + + let flood = sh("head -c 100000 /dev/zero"); + let de = d.exec_oneshot_limited("claude", flood.clone(), 1000).await.unwrap_err(); + let ae = a.exec_oneshot_limited("claude", flood, 1000).await.unwrap_err(); + if !de.starts_with(OUTPUT_LIMIT_MARKER) { + return Err(format!("docker limit error: {de}")); + } + same("output limit error", de, ae)?; + + let (_, dcode) = d.exec_oneshot_env_status(vec!["no-such-binary-tc".into()], vec![]).await?; + let (_, acode) = a.exec_oneshot_env_status(vec!["no-such-binary-tc".into()], vec![]).await?; + same("missing binary exit code", dcode, acode)?; + + // ── files ──────────────────────────────────────────────────────────────── + let ids = d.user_ids().await; + d.upload_bytes_with_ids("/tmp", "via-docker.txt", b"hello\n", 0o640, ids).await?; + a.upload_bytes_with_ids("/tmp", "via-agent.txt", b"hello\n", 0o640, ids).await?; + let stat = |n: &str| sh(&format!("stat -c '%a %u %g %s' /tmp/{n} && cat /tmp/{n}")); + same( + "uploaded file (mode, owner, size, content)", + d.exec_oneshot(stat("via-docker.txt")).await?, + a.exec_oneshot(stat("via-agent.txt")).await?, + )?; + + d.exec_oneshot(sh("rm -rf /tmp/arch && mkdir -p /tmp/arch/sub && echo x > /tmp/arch/x && echo y > /tmp/arch/sub/y")).await?; + let list = |t: &ContainerTarget| { + let mut s = t.download_archive("/tmp/arch"); + async move { + let mut bytes = Vec::new(); + while let Some(c) = s.next().await { + bytes.extend_from_slice(&c?); + } + let mut names: Vec<(String, Vec)> = tar::Archive::new(&bytes[..]) + .entries() + .map_err(|e| e.to_string())? + .map(|e| { + let mut e = e.unwrap(); + let name = e.path().unwrap().to_string_lossy().trim_end_matches('/').to_string(); + let mut data = Vec::new(); + std::io::Read::read_to_end(&mut e, &mut data).unwrap(); + (name, data) + }) + .collect(); + names.sort(); + Ok::<_, String>(names) + } + }; + same("archive members and contents", list(d).await?, list(a).await?)?; + + // ── attached ───────────────────────────────────────────────────────────── + for (label, t) in [("docker", d), ("agent", a)] { + let mut exec = t.attach_exec(vec!["head".into(), "-n1".into()], false).await?; + exec.input.write_all(b"ping\n").await.map_err(|e| e.to_string())?; + exec.input.flush().await.map_err(|e| e.to_string())?; + let id = exec.exec_id.clone(); + let (o, e) = drain(exec).await; + same(&format!("{label}: attach echo"), ("ping\n".to_string(), String::new()), (o, e))?; + same(&format!("{label}: attach exit"), Some(0), t.wait_exec_exit(&id).await)?; + } + + let mut sizes = Vec::new(); + for t in [d, a] { + let exec = t + .attach(ExecSpec::new(sh("sleep 1; stty size")).tty(true)) + .await?; + t.resize_exec(&exec.exec_id, 100, 40).await?; + let (o, _) = drain(exec).await; + sizes.push(o.trim().to_string()); + } + same("tty size after resize", sizes[0].clone(), sizes[1].clone())?; + same("tty size value", "40 100".to_string(), sizes[1].clone())?; + + // ── detached ───────────────────────────────────────────────────────────── + let mut codes = Vec::new(); + for t in [d, a] { + let id = t.exec_detached(ExecSpec::new(sh("sleep 0.3; exit 5"))).await?; + codes.push(t.wait_exec_exit(&id).await); + } + same("detached exit code", codes[0], codes[1])?; + + same("is_running", d.is_running().await?, a.is_running().await?)?; + Ok(()) +} + +#[tokio::test] +#[ignore = "needs a Docker daemon and an image whose entrypoint starts triple-c-agent (TRIPLEC_AGENT_E2E_IMAGE)"] +async fn the_agent_answers_exactly_as_docker_exec_does() { + let image = std::env::var("TRIPLEC_AGENT_E2E_IMAGE").unwrap_or_else(|_| "tc-agent-e2e:latest".into()); + let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()); + let name = format!("tc-agent-e2e-{}", uuid::Uuid::new_v4().simple()); + docker_cli(&[ + "run", "-d", "--name", &name, "-w", "/workspace", + "-e", &format!("TRIPLEC_AGENT_TOKEN={token}"), + // Docker forwards a published port to the container's own address, + // not its loopback, so the harness binds the agent wide *inside* the + // container and publishes it to the host's loopback only. + "-e", "TRIPLEC_AGENT_ADDR=0.0.0.0:47900", + "-p", "127.0.0.1::47900", + &image, + ]); + let outcome = async { + let mapped = docker_cli(&["port", &name, "47900/tcp"]); + let port: u16 = mapped.lines().next().and_then(|l| l.rsplit(':').next()).and_then(|p| p.parse().ok()) + .ok_or_else(|| format!("no published port in {mapped:?}"))?; + // Two ways in, because where *this test* runs decides which one routes: + // on the host (where the app runs) the published loopback port; from + // inside another container on the same daemon, the published port is + // on the host's loopback, not ours, but the container's bridge address + // is reachable. + let ip = docker_cli(&["inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}", &name]); + let mut candidates = vec![AgentEndpoint::loopback(port, token.clone())]; + for addr in ip.split_whitespace() { + let url = url::Url::parse(&format!("http://{addr}:47900/")).map_err(|e| e.to_string())?; + candidates.push(AgentEndpoint::new(url, token.clone())?); + } + let docker = ContainerTarget::docker(name.clone()); + + // The entrypoint starts the agent last, after setup (including a + // bounded `claude update`), so health is the readiness signal. + let mut agent = None; + 'wait: for _ in 0..240 { + for ep in &candidates { + let t = ContainerTarget::Agent(ep.clone()); + if t.is_running().await.unwrap_or(false) { + agent = Some(t); + break 'wait; + } + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + let Some(agent) = agent else { + return Err(format!("agent never answered on {candidates:?}; logs:\n{}", docker_cli(&["logs", "--tail", "40", &name]))); + }; + eprintln!("agent reached at {}", agent.id()); + parity(&docker, &agent).await + } + .await; + let logs = docker_cli(&["logs", "--tail", "20", &name]); + let _ = Command::new("docker").args(["rm", "-f", &name]).output(); + if let Err(e) = outcome { + panic!("{e}\n--- container log tail ---\n{logs}"); + } +} diff --git a/container/.dockerignore b/container/.dockerignore new file mode 100644 index 0000000..a9ea654 --- /dev/null +++ b/container/.dockerignore @@ -0,0 +1,2 @@ +# Build output of the agent crate must never enter the image build context. +triple-c-agent/target diff --git a/container/Dockerfile b/container/Dockerfile index 0a16ad5..84af9c7 100644 --- a/container/Dockerfile +++ b/container/Dockerfile @@ -1,3 +1,31 @@ +# ── triple-c-agent ───────────────────────────────────────────────────────── +# The in-container agent the AWS host reaches the container through +# (docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md). A static +# musl binary, so it needs nothing from the image below. +# +# The stage runs on the *build* machine's platform and cross-compiles for the +# target: CI builds amd64 and arm64 together, and compiling Rust for arm64 +# under QEMU is many times slower. BuildKit predefines BUILDPLATFORM and +# TARGETARCH; the app's local build (the classic builder) passes them itself +# (docker/image.rs, `local_build_args`), because there an empty `--platform=` +# fails the build. Pure-Rust dependencies only, so rust-lld links aarch64 +# with no C cross toolchain (see container/triple-c-agent/README.md). +ARG BUILDPLATFORM +FROM --platform=$BUILDPLATFORM rust:1.98-slim-bookworm AS agent-build +ARG TARGETARCH +RUN rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl +WORKDIR /src +COPY triple-c-agent/Cargo.toml triple-c-agent/Cargo.lock ./ +COPY triple-c-agent/src ./src +RUN case "$TARGETARCH" in \ + amd64) target=x86_64-unknown-linux-musl ;; \ + arm64) target=aarch64-unknown-linux-musl ;; \ + *) echo "triple-c-agent: unsupported TARGETARCH '$TARGETARCH'" >&2; exit 1 ;; \ + esac \ + && CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=rust-lld \ + cargo build --release --locked --target "$target" \ + && install -D -m 0755 "target/$target/release/triple-c-agent" /out/triple-c-agent + FROM ubuntu:24.04 # ── Provenance labels ──────────────────────────────────────────────────────── @@ -460,5 +488,9 @@ COPY triple-c-playwright-heal /usr/local/bin/triple-c-playwright-heal RUN chmod +x /usr/local/bin/triple-c-playwright-heal COPY triple-c-task-runner /usr/local/bin/triple-c-task-runner RUN chmod +x /usr/local/bin/triple-c-task-runner +# Root-owned in /usr/local/bin: entrypoint.sh starts it as root (only when a +# token is configured), and it rides the snapshot and migration like the other +# shims here. +COPY --from=agent-build /out/triple-c-agent /usr/local/bin/triple-c-agent ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] diff --git a/container/entrypoint.sh b/container/entrypoint.sh index 243e686..becf08f 100644 --- a/container/entrypoint.sh +++ b/container/entrypoint.sh @@ -22,7 +22,15 @@ # environment; the agent reads the file. A `docker exec` session still sees # the container's configured env — the local test harness passes it that way # and accepts that; on AWS nothing is started by `docker exec`. +# +# The agent also takes its exec environment and default working directory +# from how *it* was started, and execs must see what `docker exec` would: the +# container's configured env and WorkingDir, not whatever this script has +# exported or cd'd into by the time it gets to start_agent. So both are +# snapshotted here, before anything else runs, and the agent is started from +# the snapshot (`env -i`). The agent drops its own TRIPLEC_AGENT_* settings. # >>> agent_token +agent_cwd=$PWD if [ -n "${TRIPLEC_AGENT_TOKEN:-}" ]; then mkdir -p /run/triple-c chmod 700 /run/triple-c @@ -30,6 +38,13 @@ if [ -n "${TRIPLEC_AGENT_TOKEN:-}" ]; then unset TRIPLEC_AGENT_TOKEN export TRIPLEC_AGENT_TOKEN_FILE=/run/triple-c/agent-token fi +if [ -n "${TRIPLEC_AGENT_TOKEN_FILE:-}" ]; then + mkdir -p /run/triple-c + chmod 700 /run/triple-c + # Minus what bash itself exports (PWD, OLDPWD, SHLVL, `_`): those are this + # script's, not the container's, and `docker exec` has none of them. + ( umask 077; env -u PWD -u OLDPWD -u SHLVL -u _ -0 > /run/triple-c/agent-env ) +fi # <<< agent_token # ── UID/GID remapping ────────────────────────────────────────────────────── @@ -802,11 +817,14 @@ start_agent() { echo "triple-c-agent: token given but no agent binary in this image — not starting it" >&2 return 0 fi + local -a agent_env=() + [ -r /run/triple-c/agent-env ] && mapfile -d '' agent_env < /run/triple-c/agent-env ( trap '' HUP + cd "$agent_cwd" || cd / while :; do agent_started=$SECONDS - /usr/local/bin/triple-c-agent + env -i "${agent_env[@]}" /usr/local/bin/triple-c-agent echo "triple-c-agent exited ($?) — restarting" >&2 [ $((SECONDS - agent_started)) -ge 5 ] || sleep 5 done diff --git a/agent/Cargo.lock b/container/triple-c-agent/Cargo.lock similarity index 100% rename from agent/Cargo.lock rename to container/triple-c-agent/Cargo.lock diff --git a/agent/Cargo.toml b/container/triple-c-agent/Cargo.toml similarity index 100% rename from agent/Cargo.toml rename to container/triple-c-agent/Cargo.toml diff --git a/agent/README.md b/container/triple-c-agent/README.md similarity index 64% rename from agent/README.md rename to container/triple-c-agent/README.md index 01ab67a..3f72b76 100644 --- a/agent/README.md +++ b/container/triple-c-agent/README.md @@ -27,7 +27,7 @@ as itself and answers `403` for any other user. The tests rely on that. ## Tests ```bash -cd agent +cd container/triple-c-agent cargo test # everything, as the current user cargo clippy --all-targets # The root-only test (user switch + chown), as root: @@ -48,7 +48,7 @@ that comes with the toolchain. Verified with rustc 1.98.0: ```bash rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl -cd agent +cd container/triple-c-agent cargo build --release --target x86_64-unknown-linux-musl CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=rust-lld \ cargo build --release --target aarch64-unknown-linux-musl @@ -65,3 +65,35 @@ Check a build with `file `. It must say `statically linked` or `static-p Do not add a dependency that needs a C compiler (`ring`, `openssl-sys`, anything using `cc`). The aarch64 build would then need a cross C toolchain or `cargo-zigbuild`. TLS is out of scope for v1 anyway, because the transport is the SSM channel or loopback. + +In the image, `container/Dockerfile`'s `agent-build` stage does this on the build platform for +`$TARGETARCH`; the app's local build passes those build args itself (`docker/image.rs`). + +## Docker parity test + +The requirement is that every operation through the agent comes back exactly as it does through +`docker exec`. `app/src-tauri/src/host/agent/live_tests.rs` checks that in one real container, +running each operation through both `ContainerTarget::Docker` and `ContainerTarget::Agent` and +comparing. It needs an image whose entrypoint starts the agent. To build one from the published +sandbox image plus this branch's agent and entrypoint: + +```bash +cargo build --release --target x86_64-unknown-linux-musl # or aarch64, on an arm64 host +ctx=$(mktemp -d) +cp target/x86_64-unknown-linux-musl/release/triple-c-agent ../entrypoint.sh "$ctx"/ +cat > "$ctx/Dockerfile" <<'DOCKERFILE' +FROM ghcr.io/shadowdao/triple-c-sandbox:latest +COPY entrypoint.sh /usr/local/bin/entrypoint.sh +COPY triple-c-agent /usr/local/bin/triple-c-agent +RUN chmod 0755 /usr/local/bin/entrypoint.sh /usr/local/bin/triple-c-agent +DOCKERFILE +docker build -t tc-agent-e2e:latest "$ctx" + +cd ../../app/src-tauri +cargo test --lib the_agent_answers_exactly_as_docker_exec_does -- --ignored --nocapture +``` + +The test starts and removes its own container. It reaches the agent on the published loopback port +when run on the host, or on the container's bridge address when run from inside another container +on the same daemon. It has already caught one real divergence: `docker exec` sets only `HOME` for +the exec's user, never `USER`/`LOGNAME`. diff --git a/agent/src/attach.rs b/container/triple-c-agent/src/attach.rs similarity index 100% rename from agent/src/attach.rs rename to container/triple-c-agent/src/attach.rs diff --git a/agent/src/exec.rs b/container/triple-c-agent/src/exec.rs similarity index 100% rename from agent/src/exec.rs rename to container/triple-c-agent/src/exec.rs diff --git a/agent/src/files.rs b/container/triple-c-agent/src/files.rs similarity index 93% rename from agent/src/files.rs rename to container/triple-c-agent/src/files.rs index cac0cae..440639f 100644 --- a/agent/src/files.rs +++ b/container/triple-c-agent/src/files.rs @@ -81,6 +81,15 @@ pub async fn put_file( if euid != 0 && (uid != euid || gid != egid) { return error(StatusCode::FORBIDDEN, "the agent is not root and cannot chown to another user"); } + // `dir` is resolved following symlinks, and the write runs as root. That + // is deliberate parity, not an oversight: Docker's archive upload — what + // this replaces — also resolves symlinks inside the container. It is not + // a privilege boundary either: the `claude` user who could plant a + // symlink has passwordless sudo in this image (Dockerfile, sudoers.d), so + // redirecting a root write gains nothing `sudo` doesn't. The final + // component is still opened O_NOFOLLOW|O_CREAT|O_EXCL below, so an + // existing symlink *at* the name is replaced, never written through. + // Revisit with openat2(RESOLVE_NO_SYMLINKS) if that sudo ever goes. match std::fs::metadata(&q.dir) { Ok(m) if m.is_dir() => {} Ok(_) => return error(StatusCode::BAD_REQUEST, format!("{} is not a directory", q.dir)), diff --git a/agent/src/lib.rs b/container/triple-c-agent/src/lib.rs similarity index 81% rename from agent/src/lib.rs rename to container/triple-c-agent/src/lib.rs index 15c3df1..b705157 100644 --- a/agent/src/lib.rs +++ b/container/triple-c-agent/src/lib.rs @@ -80,7 +80,12 @@ impl Config { Ok(Config { token, default_cwd: std::env::current_dir()?, - base_env: std::env::vars_os().filter(|(k, _)| k != TOKEN_ENV).collect(), + // None of the agent's own settings (`TRIPLEC_AGENT_*`) reach an + // exec: the token is a secret, and the token-file path and listen + // address are the agent's business — `docker exec` sees neither. + base_env: std::env::vars_os() + .filter(|(k, _)| !k.to_string_lossy().starts_with("TRIPLEC_AGENT_")) + .collect(), max_file_bytes: MAX_DROP_BYTES, }) } @@ -102,8 +107,8 @@ pub fn load_token(env_token: Option, file: Option) -> Result< ), None => match file { Some(path) => ( - std::fs::read_to_string(&path) - .map_err(|e| format!("cannot read {TOKEN_FILE_ENV} ({}): {e}", path.display()))?, + read_private_file(&path) + .map_err(|e| format!("cannot use {TOKEN_FILE_ENV} ({}): {e}", path.display()))?, format!("{TOKEN_FILE_ENV} ({})", path.display()), ), None => { @@ -123,6 +128,31 @@ pub fn load_token(env_token: Option, file: Option) -> Result< Ok(token) } +/// Read a secret file, refusing one that anyone but its owner could read or +/// that this process does not own — as `ssh` does for key files. The token +/// is effectively root in the container; a world-readable copy of it would be +/// a way in for any process, not just root's. Checked on the opened file, so +/// the file judged is the file read. +fn read_private_file(path: &std::path::Path) -> Result { + use std::io::Read; + use std::os::unix::fs::MetadataExt; + let mut f = std::fs::File::open(path).map_err(|e| e.to_string())?; + let meta = f.metadata().map_err(|e| e.to_string())?; + let euid = unsafe { libc::geteuid() }; + if meta.uid() != euid { + return Err(format!("owned by uid {}, not this process's uid {euid}", meta.uid())); + } + if meta.mode() & 0o077 != 0 { + return Err(format!( + "mode {:o} lets others read it; it must be 0600 or stricter", + meta.mode() & 0o777 + )); + } + let mut s = String::new(); + f.read_to_string(&mut s).map_err(|e| e.to_string())?; + Ok(s) +} + /// Shared server state. pub(crate) struct AppState { pub config: Config, @@ -282,14 +312,31 @@ mod tests { assert!(!constant_time_eq(&[0u8; 256], b"")); } + #[test] + fn a_token_file_others_can_read_is_refused() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("token"); + std::fs::write(&path, "y".repeat(40)).unwrap(); + + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let e = load_token(None, Some(path.clone())).unwrap_err(); + assert!(e.contains("0600"), "{e}"); + + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(load_token(None, Some(path.clone())).unwrap(), "y".repeat(40)); + } + #[test] fn the_token_never_reaches_the_exec_base_env() { // `main` removes the var before capturing; this is the second guard, // for a caller that forgets. std::env::set_var(TOKEN_ENV, "x".repeat(40)); + std::env::set_var(TOKEN_FILE_ENV, "/run/triple-c/agent-token"); let cfg = Config::from_process("t".into()).unwrap(); std::env::remove_var(TOKEN_ENV); - assert!(cfg.base_env.iter().all(|(k, _)| k != TOKEN_ENV)); + std::env::remove_var(TOKEN_FILE_ENV); + assert!(cfg.base_env.iter().all(|(k, _)| !k.to_string_lossy().starts_with("TRIPLEC_AGENT_"))); assert!(cfg.base_env.iter().any(|(k, _)| k == "PATH")); } @@ -303,6 +350,10 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let f = dir.path().join("tok"); std::fs::write(&f, format!("{long}\n")).unwrap(); + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600)).unwrap(); + } assert_eq!(load_token(Some("".into()), Some(f.clone())).unwrap(), long); std::fs::write(&f, "\n").unwrap(); assert!(load_token(None, Some(f)).is_err()); diff --git a/agent/src/main.rs b/container/triple-c-agent/src/main.rs similarity index 100% rename from agent/src/main.rs rename to container/triple-c-agent/src/main.rs diff --git a/agent/src/pty.rs b/container/triple-c-agent/src/pty.rs similarity index 100% rename from agent/src/pty.rs rename to container/triple-c-agent/src/pty.rs diff --git a/agent/src/spawn.rs b/container/triple-c-agent/src/spawn.rs similarity index 96% rename from agent/src/spawn.rs rename to container/triple-c-agent/src/spawn.rs index 5a4ba1a..5f9c08d 100644 --- a/agent/src/spawn.rs +++ b/container/triple-c-agent/src/spawn.rs @@ -145,8 +145,11 @@ pub fn prepare(cfg: &Config, spec: &ExecSpec, tty: bool) -> Result Vec<(OsString, OsString)> { let mut env: Vec<(OsString, OsString)> = cfg.base_env.clone(); fn set(env: &mut Vec<(OsString, OsString)>, k: &OsStr, v: &OsStr) { @@ -174,10 +177,8 @@ fn merge_env(cfg: &Config, spec: &ExecSpec, user: &UserInfo, tty: bool) -> Vec<( } } } - for (k, v) in [("HOME", &user.home), ("USER", &user.name), ("LOGNAME", &user.name)] { - if !spec_set.contains(&k) { - set(&mut env, OsStr::new(k), OsStr::new(v)); - } + if !spec_set.contains(&"HOME") { + set(&mut env, OsStr::new("HOME"), OsStr::new(&user.home)); } env.retain(|(k, v)| { !k.is_empty() && !k.as_bytes().contains(&b'=') && !k.as_bytes().contains(&0) && !v.as_bytes().contains(&0) diff --git a/agent/src/tunnel.rs b/container/triple-c-agent/src/tunnel.rs similarity index 100% rename from agent/src/tunnel.rs rename to container/triple-c-agent/src/tunnel.rs diff --git a/agent/src/users.rs b/container/triple-c-agent/src/users.rs similarity index 100% rename from agent/src/users.rs rename to container/triple-c-agent/src/users.rs diff --git a/agent/tests/protocol.rs b/container/triple-c-agent/tests/protocol.rs similarity index 99% rename from agent/tests/protocol.rs rename to container/triple-c-agent/tests/protocol.rs index 7f981af..c2b3151 100644 --- a/agent/tests/protocol.rs +++ b/container/triple-c-agent/tests/protocol.rs @@ -352,14 +352,15 @@ async fn a_non_root_agent_refuses_other_users_with_403() { } #[tokio::test] -async fn env_merges_over_the_base_and_sets_home_user_logname_from_passwd() { +async fn env_merges_over_the_base_and_sets_only_home_from_passwd() { let a = start().await; - let script = r#"printf '%s|%s|%s|%s|%s|%s|%s' "$FOO" "$BAR" "$BASE_ONLY" "$HOME" "$USER" "$LOGNAME" "${GONE-unset}""#; + let script = r#"printf '%s|%s|%s|%s|%s|%s|%s' "$FOO" "$BAR" "$BASE_ONLY" "$HOME" "${USER-unset}" "${LOGNAME-unset}" "${GONE-unset}""#; let (_, v) = a .exec(json!({ "cmd": sh(script), "env": ["FOO=spec", "BAR=1", "BAR=2", "GONE"] })) .await; let home = passwd_home(&a.user); - assert_eq!(decode(&v).1, format!("spec|2|base|{home}|{u}|{u}|unset", u = a.user)); + // Like `docker exec`: HOME from passwd, and no USER/LOGNAME invented. + assert_eq!(decode(&v).1, format!("spec|2|base|{home}|unset|unset|unset")); // The spec's own HOME/USER/LOGNAME win over passwd. let (_, v) = a diff --git a/docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md b/docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md index f09a378..451aee8 100644 --- a/docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md +++ b/docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md @@ -40,8 +40,9 @@ has a quirk the app relies on, the agent reproduces it, and this document names - **Errors** are `4xx`/`5xx` with body `{"error": ""}`, Content-Type `application/json`. - **JSON** is UTF-8. Raw bytes inside JSON are standard base64 with padding. - **Users** are names resolved through `/etc/passwd` and `/etc/group` in the container. An exec - runs with the user's uid, primary gid and supplementary groups (`initgroups`). `HOME`, `USER` - and `LOGNAME` are set from passwd **unless the spec's env already sets them**. When the agent is + runs with the user's uid, primary gid and supplementary groups (`initgroups`). `HOME` is set + from passwd **unless the spec's env already sets it**; `USER` and `LOGNAME` are *not* added + (runc sets only `HOME` for an exec, verified by the app's parity test). When the agent is not root (tests), a spec naming a user other than the agent's own fails with `403`. - **ExecSpec** (JSON): ```json