From 4baf80b9acd108c9e3b58a4a6de0741847c1fda7 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:10:58 +0200 Subject: [PATCH 1/6] Isolate daemon state and credentials from the sidecar worker In the Cloud Run sidecar the worker shares a volume with agenticd, and nothing set file modes on the state directory, so a worker could edit refs and the reverse-migration SQL that rollback runs against Postgres. The daemon now creates `.agentic` with mode 0700 and refuses to start unless it owns the repo and `.agentic`, the repo is not group- or world-writable, and `.agentic` is not a symlink. Credentials no longer have to travel through argv or the environment: `--postgres-url-file` and `AGENTIC_GCS_TOKEN_FILE` read them from secret volumes. Debug output for `GcsObjectStore` and `MemoryBackendSpec` omits the bearer token and database URL. The sidecar doc now describes the separate-uid layout that these checks assume. --- crates/agentic-core/src/gcs_store.rs | 18 +++- crates/agenticd/Cargo.toml | 3 + crates/agenticd/src/lib.rs | 2 + crates/agenticd/src/main.rs | 30 +++++- crates/agenticd/src/membackend.rs | 32 +++++- crates/agenticd/src/objstore.rs | 24 ++++- crates/agenticd/src/secrets.rs | 128 +++++++++++++++++++++++ crates/agenticd/src/state_dir.rs | 126 ++++++++++++++++++++++ crates/agenticd/tests/startup_refusal.rs | 102 ++++++++++++++++++ docs/integration/executor-sidecar.md | 55 ++++++++-- 10 files changed, 504 insertions(+), 16 deletions(-) create mode 100644 crates/agenticd/src/secrets.rs create mode 100644 crates/agenticd/src/state_dir.rs diff --git a/crates/agentic-core/src/gcs_store.rs b/crates/agentic-core/src/gcs_store.rs index b264513b..74db4f35 100644 --- a/crates/agentic-core/src/gcs_store.rs +++ b/crates/agentic-core/src/gcs_store.rs @@ -96,7 +96,7 @@ struct Downloaded { generation: Option, } -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct GcsObjectStore { bucket: String, /// Object-name prefix inside the bucket. Lets a single bucket host @@ -110,6 +110,22 @@ pub struct GcsObjectStore { allowlist: Arc, } +/// Manual `Debug`: never print the bearer token. +impl std::fmt::Debug for GcsObjectStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GcsObjectStore") + .field("bucket", &self.bucket) + .field("prefix", &self.prefix) + .field("cache_dir", &self.cache_dir) + .field("endpoint", &self.endpoint) + .field( + "bearer_token", + &self.bearer_token.as_ref().map(|_| ""), + ) + .finish_non_exhaustive() + } +} + impl GcsObjectStore { pub fn new( bucket: impl Into, diff --git a/crates/agenticd/Cargo.toml b/crates/agenticd/Cargo.toml index 5d3dae26..49f7e301 100644 --- a/crates/agenticd/Cargo.toml +++ b/crates/agenticd/Cargo.toml @@ -31,6 +31,9 @@ url.workspace = true chrono.workspace = true sqlx.workspace = true +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [dev-dependencies] tempfile = "3.10" sqlx.workspace = true diff --git a/crates/agenticd/src/lib.rs b/crates/agenticd/src/lib.rs index 683b3e25..094ba95d 100644 --- a/crates/agenticd/src/lib.rs +++ b/crates/agenticd/src/lib.rs @@ -17,6 +17,8 @@ pub mod migrate; pub mod objstore; pub mod peer_auth; pub mod rollback; +pub mod secrets; pub mod server; +pub mod state_dir; pub(crate) mod store_async; pub mod wire_error; diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index e50d7e8a..f8aba09f 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -74,6 +74,11 @@ struct Args { #[arg(long)] postgres: Option, + /// File holding the Postgres URL (trailing newline trimmed). Keeps + /// the password off argv. Alternative to `--postgres`. + #[arg(long, conflicts_with = "postgres")] + postgres_url_file: Option, + /// Comma-separated `table:pk` pairs to track. Required when /// `--postgres` is set. Example: `episodes:id,user_facts:id`. #[arg(long, value_delimiter = ',')] @@ -91,7 +96,8 @@ struct Args { /// pushes every object through to Google Cloud Storage with a /// write-through local cache (ADR-0004 Decision 5). For GCS, set /// `AGENTIC_GCS_ENDPOINT` to override the host (e.g. fake-gcs-server) - /// and `AGENTIC_GCS_TOKEN` for bearer auth. + /// and `AGENTIC_GCS_TOKEN` (or `AGENTIC_GCS_TOKEN_FILE`, a path to a + /// file holding the token) for bearer auth. #[arg(long, default_value = "fs")] object_store: String, @@ -316,6 +322,16 @@ async fn main() -> anyhow::Result<()> { "socket limits in force" ); + // Before anything reads or writes state: the daemon must own the repo + // and `.agentic` (see state_dir.rs). Runs before the object store opens + // so no state is created under a directory we then refuse. + agenticd::state_dir::secure_state_dir(&args.repo)?; + + let postgres_url = agenticd::secrets::resolve_postgres_url( + args.postgres.as_deref(), + args.postgres_url_file.as_deref(), + )?; + let agentic_dir = args.repo.join(".agentic"); let tables = parse_tracked_tables(&args.tables)?; @@ -392,7 +408,7 @@ async fn main() -> anyhow::Result<()> { args.repo.clone(), agentic_dir.clone(), store, - args.postgres.as_deref(), + postgres_url.as_deref(), tables, mcp_servers, Arc::clone(&peer_auth), @@ -406,6 +422,16 @@ async fn main() -> anyhow::Result<()> { let listener = UnixListener::bind(&socket_path) .with_context(|| format!("binding {}", socket_path.display()))?; + // Connecting to a Unix socket needs write permission on the file, and + // the worker runs as another uid. Access control is the SO_PEERCRED + // allowlist (ADR-0012), so open the file mode when one is enforced. + #[cfg(unix)] + if matches!(*peer_auth, PeerAuthPolicy::Allowlist(_)) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o666)) + .with_context(|| format!("setting mode on {}", socket_path.display()))?; + } + tracing::info!( socket = %socket_path.display(), repo = %args.repo.display(), diff --git a/crates/agenticd/src/membackend.rs b/crates/agenticd/src/membackend.rs index 2917f8d1..f7345de8 100644 --- a/crates/agenticd/src/membackend.rs +++ b/crates/agenticd/src/membackend.rs @@ -14,7 +14,6 @@ use agentic_memory::MemoryAdapter; use anyhow::Context; /// Which memory backend to attach. -#[derive(Debug)] pub enum MemoryBackendSpec { /// No memory backend; commits skip the memory-snapshot dimension. None, @@ -25,6 +24,20 @@ pub enum MemoryBackendSpec { }, } +/// Manual `Debug`: the URL carries the database password. +impl std::fmt::Debug for MemoryBackendSpec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::None => f.write_str("None"), + Self::Postgres { tables, .. } => f + .debug_struct("Postgres") + .field("url", &"") + .field("tables", tables) + .finish(), + } + } +} + impl MemoryBackendSpec { /// Derive the spec from the daemon's CLI configuration. Preserves /// the pre-factory behavior exactly: `--postgres` present requires @@ -89,6 +102,23 @@ mod tests { )); } + #[test] + fn debug_redacts_url() { + let spec = MemoryBackendSpec::from_flags( + Some("postgres://u:hunter2@h/db"), + vec![TrackedTable { + name: "t".into(), + pk: "id".into(), + }], + ) + .unwrap(); + let dbg = format!("{spec:?}"); + assert!( + !dbg.contains("hunter2") && !dbg.contains("postgres://"), + "{dbg}" + ); + } + #[test] fn from_flags_requires_tables_with_url() { let err = MemoryBackendSpec::from_flags(Some("postgres://x"), Vec::new()).unwrap_err(); diff --git a/crates/agenticd/src/objstore.rs b/crates/agenticd/src/objstore.rs index d4bd0275..36a3168b 100644 --- a/crates/agenticd/src/objstore.rs +++ b/crates/agenticd/src/objstore.rs @@ -11,8 +11,8 @@ //! (useful for shared-volume tests). //! - `gcs://bucket[/prefix]` — GCS-backed store (ADR-0004 Decision 5), //! with a write-through local cache. Endpoint and bearer token come -//! from `AGENTIC_GCS_ENDPOINT` and `AGENTIC_GCS_TOKEN` so the URL -//! itself stays free of credentials. +//! from `AGENTIC_GCS_ENDPOINT` and `AGENTIC_GCS_TOKEN` (or +//! `AGENTIC_GCS_TOKEN_FILE`) so the URL itself stays free of credentials. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -104,7 +104,10 @@ impl ObjectStoreSpec { cache_dir, } => { let endpoint = std::env::var(ENDPOINT_ENV).ok(); - let bearer = std::env::var(TOKEN_ENV).ok(); + let bearer = crate::secrets::resolve_gcs_token( + std::env::var(TOKEN_ENV).ok(), + std::env::var(crate::secrets::GCS_TOKEN_FILE_ENV).ok(), + )?; let store = GcsObjectStore::new(bucket.clone(), prefix, &cache_dir, endpoint, bearer) .with_context(|| format!("opening gcs object store {bucket}"))? @@ -123,6 +126,21 @@ mod tests { PathBuf::from("/tmp/repo/.agentic") } + #[test] + fn gcs_debug_redacts_token() { + let dir = tempfile::tempdir().unwrap(); + let store = GcsObjectStore::new( + "b", + "p", + dir.path(), + None, + Some("s3cret-bearer".to_string()), + ) + .unwrap(); + let dbg = format!("{store:?}"); + assert!(!dbg.contains("s3cret-bearer"), "{dbg}"); + } + #[test] fn fs_default() { let spec = ObjectStoreSpec::parse("fs", &agentic()).unwrap(); diff --git a/crates/agenticd/src/secrets.rs b/crates/agenticd/src/secrets.rs new file mode 100644 index 00000000..a0330c95 --- /dev/null +++ b/crates/agenticd/src/secrets.rs @@ -0,0 +1,128 @@ +//! Credential inputs: file-based alternatives to argv and env secrets. +//! +//! A Postgres URL on argv and a bearer token in the environment are both +//! readable by other processes sharing the container's process or volume +//! namespace. The `*_FILE` forms let a secret volume carry them instead. + +use std::path::Path; + +use anyhow::{anyhow, Context}; + +/// Env var naming a file that holds the GCS bearer token. +pub const GCS_TOKEN_FILE_ENV: &str = "AGENTIC_GCS_TOKEN_FILE"; + +/// Read a secret from `path`, trimming surrounding whitespace (secret +/// mounts and `echo` both leave a trailing newline). An empty result is +/// an error: silently running unauthenticated is worse than refusing. +pub fn read_secret_file(path: &Path, what: &str) -> anyhow::Result { + let raw = std::fs::read_to_string(path) + .with_context(|| format!("reading {what} file {}", path.display()))?; + let value = raw.trim(); + anyhow::ensure!(!value.is_empty(), "{what} file {} is empty", path.display()); + Ok(value.to_string()) +} + +/// Resolve the GCS bearer token from the plain env value and the file +/// env value. Setting both is ambiguous and refused. +pub fn resolve_gcs_token( + token: Option, + token_file: Option, +) -> anyhow::Result> { + match (token, token_file) { + (Some(_), Some(_)) => Err(anyhow!( + "AGENTIC_GCS_TOKEN and {GCS_TOKEN_FILE_ENV} are both set; set only one" + )), + (Some(t), None) => Ok(Some(t)), + (None, Some(f)) => read_secret_file(Path::new(&f), GCS_TOKEN_FILE_ENV).map(Some), + (None, None) => Ok(None), + } +} + +/// Resolve the Postgres URL from `--postgres` or `--postgres-url-file` +/// (clap already rejects both together). +pub fn resolve_postgres_url( + url: Option<&str>, + url_file: Option<&Path>, +) -> anyhow::Result> { + match (url, url_file) { + (Some(_), Some(_)) => Err(anyhow!( + "--postgres and --postgres-url-file are mutually exclusive" + )), + (Some(u), None) => Ok(Some(u.to_string())), + (None, Some(f)) => read_secret_file(f, "--postgres-url-file").map(Some), + (None, None) => Ok(None), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file_with(content: &str) -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("secret"); + std::fs::write(&p, content).unwrap(); + (dir, p) + } + + #[test] + fn trims_trailing_newline() { + let (_d, p) = file_with("postgres://u:p@h/db\n"); + assert_eq!(read_secret_file(&p, "x").unwrap(), "postgres://u:p@h/db"); + } + + #[test] + fn empty_file_is_an_error() { + let (_d, p) = file_with(" \n"); + let err = read_secret_file(&p, "x").unwrap_err().to_string(); + assert!(err.contains("is empty"), "{err}"); + } + + #[test] + fn missing_file_is_an_error() { + assert!(read_secret_file(Path::new("/nonexistent/secret"), "x").is_err()); + } + + #[test] + fn gcs_token_and_file_conflict() { + let err = resolve_gcs_token(Some("a".into()), Some("/f".into())) + .unwrap_err() + .to_string(); + assert!(err.contains("set only one"), "{err}"); + } + + #[test] + fn gcs_token_sources() { + assert_eq!(resolve_gcs_token(None, None).unwrap(), None); + assert_eq!( + resolve_gcs_token(Some("t".into()), None) + .unwrap() + .as_deref(), + Some("t") + ); + let (_d, p) = file_with("tok\n"); + assert_eq!( + resolve_gcs_token(None, Some(p.to_string_lossy().into())) + .unwrap() + .as_deref(), + Some("tok") + ); + } + + #[test] + fn postgres_url_sources() { + assert_eq!(resolve_postgres_url(None, None).unwrap(), None); + assert_eq!( + resolve_postgres_url(Some("postgres://x"), None) + .unwrap() + .as_deref(), + Some("postgres://x") + ); + let (_d, p) = file_with("postgres://u:p@h/db\n"); + assert_eq!( + resolve_postgres_url(None, Some(&p)).unwrap().as_deref(), + Some("postgres://u:p@h/db") + ); + assert!(resolve_postgres_url(Some("a"), Some(&p)).is_err()); + } +} diff --git a/crates/agenticd/src/state_dir.rs b/crates/agenticd/src/state_dir.rs new file mode 100644 index 00000000..728a0496 --- /dev/null +++ b/crates/agenticd/src/state_dir.rs @@ -0,0 +1,126 @@ +//! Ownership checks for the daemon's state directory. +//! +//! In the ADR-0004 sidecar the worker shares a volume with the daemon and +//! is adversarial. Refs, objects and `schema/*.down.sql` (which a plain +//! rollback executes against Postgres) live under `/.agentic`, so a +//! worker that can write there can steer the daemon. The daemon therefore +//! requires `` and `/.agentic` to be its own, `.agentic` to be +//! mode 0700, and `` not to be group- or world-writable. The worker +//! can still read `/prompts`, but must run as a different uid. + +use std::path::Path; + +/// Create or tighten `/.agentic` and verify ownership. Unix only; +/// elsewhere there is no uid model to check and this is a no-op. +#[cfg(unix)] +pub fn secure_state_dir(repo: &Path) -> anyhow::Result<()> { + use anyhow::{bail, Context}; + use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; + + // SAFETY: geteuid has no preconditions and cannot fail. + let euid = unsafe { libc::geteuid() }; + + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o755) + .create(repo) + .with_context(|| format!("creating repo directory {}", repo.display()))?; + let repo_meta = std::fs::metadata(repo).with_context(|| format!("stat {}", repo.display()))?; + if repo_meta.uid() != euid { + bail!( + "repo directory {} is owned by uid {}, not the daemon's uid {euid}; refusing to start", + repo.display(), + repo_meta.uid() + ); + } + if repo_meta.mode() & 0o022 != 0 { + bail!( + "repo directory {} is group- or world-writable (mode {:o}); refusing to start. \ + Run `chmod go-w` on it", + repo.display(), + repo_meta.mode() & 0o7777 + ); + } + + let dir = repo.join(".agentic"); + match std::fs::symlink_metadata(&dir) { + Ok(m) if m.file_type().is_symlink() => { + bail!("{} is a symlink; refusing to start", dir.display()) + } + Ok(m) if !m.is_dir() => bail!("{} is not a directory; refusing to start", dir.display()), + Ok(m) => { + if m.uid() != euid { + bail!( + "state directory {} is owned by uid {}, not the daemon's uid {euid}; refusing to start", + dir.display(), + m.uid() + ); + } + if m.mode() & 0o7777 != 0o700 { + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)) + .with_context(|| format!("setting mode 0700 on {}", dir.display()))?; + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + std::fs::DirBuilder::new() + .mode(0o700) + .create(&dir) + .with_context(|| format!("creating {}", dir.display()))?; + } + Err(e) => return Err(e).with_context(|| format!("stat {}", dir.display())), + } + Ok(()) +} + +#[cfg(not(unix))] +pub fn secure_state_dir(_repo: &Path) -> anyhow::Result<()> { + Ok(()) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + fn mode(p: &Path) -> u32 { + std::fs::metadata(p).unwrap().permissions().mode() & 0o7777 + } + + #[test] + fn creates_state_dir_0700() { + let t = tempfile::tempdir().unwrap(); + secure_state_dir(t.path()).unwrap(); + assert_eq!(mode(&t.path().join(".agentic")), 0o700); + } + + #[test] + fn tightens_existing_state_dir() { + let t = tempfile::tempdir().unwrap(); + let d = t.path().join(".agentic"); + std::fs::create_dir(&d).unwrap(); + std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o777)).unwrap(); + secure_state_dir(t.path()).unwrap(); + assert_eq!(mode(&d), 0o700); + } + + #[test] + fn refuses_group_writable_repo() { + let t = tempfile::tempdir().unwrap(); + std::fs::set_permissions(t.path(), std::fs::Permissions::from_mode(0o775)).unwrap(); + let err = secure_state_dir(t.path()).unwrap_err().to_string(); + assert!( + err.contains("writable") && err.contains(&*t.path().to_string_lossy()), + "{err}" + ); + assert!(!t.path().join(".agentic").exists()); + } + + #[test] + fn refuses_symlinked_state_dir() { + let t = tempfile::tempdir().unwrap(); + let target = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(target.path(), t.path().join(".agentic")).unwrap(); + let err = secure_state_dir(t.path()).unwrap_err().to_string(); + assert!(err.contains("symlink"), "{err}"); + } +} diff --git a/crates/agenticd/tests/startup_refusal.rs b/crates/agenticd/tests/startup_refusal.rs index 69d44b5b..9b15c8a9 100644 --- a/crates/agenticd/tests/startup_refusal.rs +++ b/crates/agenticd/tests/startup_refusal.rs @@ -61,3 +61,105 @@ fn startup_refuses_when_both_flags_set() { "stderr should mention mutual exclusivity; got: {stderr}" ); } + +#[cfg(unix)] +mod state_dir { + use super::agenticd_bin; + use std::os::unix::fs::PermissionsExt; + use std::process::Command; + + fn set_mode(p: &std::path::Path, mode: u32) { + std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap(); + } + + #[test] + fn refuses_group_writable_repo() { + let repo = tempfile::tempdir().unwrap(); + let sock = tempfile::tempdir().unwrap(); + set_mode(repo.path(), 0o777); + let out = Command::new(agenticd_bin()) + .arg("--repo") + .arg(repo.path()) + .arg("--socket") + .arg(sock.path().join("d.sock")) + .arg("--insecure-allow-any-uid") + .output() + .expect("run agenticd"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("writable") && stderr.contains(&*repo.path().to_string_lossy()), + "stderr should name the repo path; got: {stderr}" + ); + assert!( + !repo.path().join(".agentic").exists(), + "no state may be created under a refused repo" + ); + } + + #[test] + fn refuses_repo_owned_by_another_uid() { + // SAFETY: geteuid has no preconditions. + if unsafe { libc::geteuid() } == 0 { + return; // root owns everything; the check cannot fire + } + let sock = tempfile::tempdir().unwrap(); + let out = Command::new(agenticd_bin()) + .arg("--repo") + .arg("/usr") + .arg("--socket") + .arg(sock.path().join("d.sock")) + .arg("--insecure-allow-any-uid") + .output() + .expect("run agenticd"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("/usr") && stderr.contains("owned by uid"), + "got: {stderr}" + ); + } + + #[test] + fn startup_leaves_state_dir_0700() { + let repo = tempfile::tempdir().unwrap(); + let sock_dir = tempfile::tempdir().unwrap(); + let sock = sock_dir.path().join("d.sock"); + let state = repo.path().join(".agentic"); + std::fs::create_dir(&state).unwrap(); + set_mode(&state, 0o777); + let mut child = Command::new(agenticd_bin()) + .arg("--repo") + .arg(repo.path()) + .arg("--socket") + .arg(&sock) + .arg("--insecure-allow-any-uid") + .spawn() + .expect("run agenticd"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while !sock.exists() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let bound = sock.exists(); + let mode = std::fs::metadata(&state).unwrap().permissions().mode() & 0o7777; + let _ = child.kill(); + let _ = child.wait(); + assert!(bound, "daemon did not bind the socket"); + assert_eq!(mode, 0o700); + } +} + +#[test] +fn startup_refuses_postgres_url_and_file_together() { + let out = Command::new(agenticd_bin()) + .arg("--insecure-allow-any-uid") + .arg("--postgres") + .arg("postgres://x") + .arg("--postgres-url-file") + .arg("/nonexistent") + .output() + .expect("run agenticd"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("cannot be used with"), "got: {stderr}"); +} diff --git a/docs/integration/executor-sidecar.md b/docs/integration/executor-sidecar.md index 0136b40c..afcd5811 100644 --- a/docs/integration/executor-sidecar.md +++ b/docs/integration/executor-sidecar.md @@ -15,6 +15,18 @@ docker build -f crates/agenticd/Dockerfile.sidecar -t agenticd:sidecar . `debian:bookworm-slim` base, runs as non-root uid 65532, exposes no ports. Targeted size ~70 MB after `strip`. Build for `linux/amd64` (Cloud Run) and `linux/arm64` (Apple Silicon dev) via `docker buildx`. +## Trust boundary + +The worker runs model-driven code and is treated as adversarial. It shares a volume with the daemon, so the layout below keeps the daemon's state out of its reach: + +- The worker image sets a `USER` with a uid other than the sidecar's 65532 (Cloud Run runs each container as its image `USER`). The examples use 10001. +- The daemon starts with `--allowed-uid 10001` and refuses to start without an allowlist (ADR-0012). It admits only that uid on the socket and records it on each commit. +- The daemon creates and owns `--repo /shared/work`. At startup it creates `/shared/work/.agentic` with mode 0700, tightens an existing one to 0700, and refuses to start if the repo or `.agentic` is owned by another uid, if the repo is group- or world-writable, or if `.agentic` is a symlink. The error names the path. +- Refs, objects, the GCS cache and `schema/*.down.sql` live in `.agentic`, so the worker cannot edit them. It can still read the prompt files that rollback restores under `/shared/work/prompts`. +- Credentials arrive as files from Secret Manager volumes mounted into the `agenticd` container only. They never appear in argv or in the worker's environment. + +The daemon cannot make the shared volume's root directory private. A worker that can write to `/shared` can rename `/shared/work` while the daemon is stopped or running, so the ownership check is a startup guard and not a substitute for a volume the worker cannot write. Keep the socket as the only thing the worker needs there. + ## Cloud Run service definition (excerpt) ```yaml @@ -24,6 +36,7 @@ spec: containerConcurrency: 1 containers: - name: worker + # The image must set USER 10001 (any uid other than 65532). image: gcr.io//coding-worker: env: - { name: AGENTICD_SOCKET, value: /shared/agenticd.sock } @@ -36,29 +49,53 @@ spec: - /shared/work - --socket - /shared/agenticd.sock + - --allowed-uid + - "10001" - --object-store - gcs:/// + - --postgres-url-file + - /secrets/postgres/url + - --tables + - : env: - - name: AGENTIC_GCS_TOKEN - valueFrom: { secretKeyRef: { name: gcs-bearer, key: token } } + - { name: AGENTIC_GCS_TOKEN_FILE, value: /secrets/gcs/token } volumeMounts: - { name: shared, mountPath: /shared } + - { name: gcs-token, mountPath: /secrets/gcs, readOnly: true } + - { name: postgres-url, mountPath: /secrets/postgres, readOnly: true } volumes: - name: shared emptyDir: { medium: Memory } + - name: gcs-token + secret: + secretName: gcs-bearer + items: [{ key: latest, path: token }] + - name: postgres-url + secret: + secretName: postgres-url + items: [{ key: latest, path: url }] ``` -`/shared` is tmpfs; durability lives in GCS. +Drop the `--postgres-url-file` and `--tables` lines if the deployment has no memory backend. -## Env vars `agenticd` reads +`/shared` is tmpfs; durability lives in GCS. Because `/.agentic/schema` is empty on tmpfs at boot, reverse migrations need the sidecar image to provide the `.down.sql` files, for example copied into `/shared/work/.agentic/schema` by the sidecar's own entrypoint. The worker must never supply them: a plain rollback executes those files against Postgres. -| Variable | Meaning | Default | +When an allowlist is enforced, the daemon sets the socket file to mode 0666 after binding, because connecting to a Unix socket needs write permission on the file and the worker is a different uid. The `SO_PEERCRED` check is what gates access. + +## Flags and env vars `agenticd` reads + +| Input | Meaning | Default | |---|---|---| +| `--allowed-uid ` | Uid allowed on the socket; repeatable. Required unless `--insecure-allow-any-uid` is passed (ADR-0012). | _none_; startup fails | +| `--postgres-url-file ` | File holding the Postgres URL; one trailing newline is trimmed and an empty file is an error. Conflicts with `--postgres`. | _none_ | +| `AGENTIC_GCS_TOKEN_FILE` | Path to a file holding the GCS bearer token, trimmed the same way. Setting it together with `AGENTIC_GCS_TOKEN` is an error. | _none_ | | `AGENTIC_GCS_ENDPOINT` | Override GCS host (for `tests/fixtures/fake-gcs.yml`) | public GCS | -| `AGENTIC_GCS_TOKEN` | Bearer for the GCS JSON API | _none_; required for real GCS | +| `AGENTIC_GCS_TOKEN` | Bearer for the GCS JSON API, as a plain env value. Fine for the demo and tests; prefer the file form in the sidecar. | _none_; required for real GCS unless the file form is used | | `RUST_LOG` | tracing filter | `info` | -The sidecar does NOT call ADC or the GCE metadata server itself. In v1.0 the only supported wiring is to **inject the token via env at Cloud Run service startup** — the YAML excerpt above does that via a Secret Manager reference. ("Have the worker write it to `/shared`" is intentionally NOT supported: both containers start at the same time, `/shared` is empty on boot, and the sidecar would race the worker's first checkpoint. If token rotation past the Cloud Run instance lifetime becomes a requirement, file a follow-up — that needs a refresh thread inside `agenticd`.) +`--postgres ` still works for the demo and tests, but puts the password in argv. Use `--postgres-url-file` in the sidecar. + +The sidecar does NOT call ADC or the GCE metadata server itself. In v1.0 the only supported wiring is to **mount the token as a Secret Manager volume** into the `agenticd` container, as in the YAML excerpt above. ("Have the worker write it to `/shared`" is intentionally NOT supported: both containers start at the same time, `/shared` is empty on boot, and the sidecar would race the worker's first checkpoint. If token rotation past the Cloud Run instance lifetime becomes a requirement, file a follow-up, since that needs a refresh thread inside `agenticd`.) ## Worker code @@ -74,12 +111,12 @@ Per ADR-0004 Decision 4 there is no degraded mode. If the sidecar is unreachable ## Out of scope -- Wire auth — none in v1.0 (ADR-0004 Decision 2). +- Wire auth beyond the peer-uid allowlist. The socket admits only the uids named by `--allowed-uid` (ADR-0012); there is no token or mTLS exchange. - Multi-region failover — single-region in v1.0; document with design partners. - Concurrent writers — `containerConcurrency: 1` is a hard assumption. ## Verification 1. `docker build -f crates/agenticd/Dockerfile.sidecar -t agenticd:sidecar .` succeeds. -2. `docker run --rm -v "$PWD/.shared:/shared" agenticd:sidecar --repo /shared/work --socket /shared/agenticd.sock --object-store fs:///shared/objects` binds the socket and serves a `Ping`. +2. `docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/.shared:/shared" agenticd:sidecar --repo /shared/work --socket /shared/agenticd.sock --insecure-allow-any-uid --object-store fs:///shared/objects` (the container uid must own the mounted directory, and the insecure flag is for this local check only) binds the socket and serves a `Ping`. 3. Same as (2) but with `--object-store gcs://...` against `tests/fixtures/fake-gcs.yml` completes one commit-and-rollback cycle. Covered by the `gcs` CI job today. From 1ed38409e227b183095c662efacb3b82e6671b78 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:29:34 +0200 Subject: [PATCH 2/6] Check repo ancestors and stop widening the socket by path The ownership check covered only the repo and `.agentic`, but the daemon reopens those paths for its whole life, so a directory above the repo that another uid can write is enough to swap the state out. Startup now resolves the repo to its canonical path, uses it from then on, and refuses when the repo or any ancestor can be modified by another principal. An existing `.agentic` that is group- or world-writable is now refused instead of tightened. The socket is no longer chmodded after bind. It is created 0666, via a umask held only across the bind call, only when the allowlist names a uid other than the daemon's. The sidecar doc now keeps `--repo` on a volume only the daemon mounts and states what has not been verified on Cloud Run. --- crates/agenticd/src/main.rs | 48 ++++-- crates/agenticd/src/state_dir.rs | 185 +++++++++++++++++++---- crates/agenticd/tests/startup_refusal.rs | 137 ++++++++++++++--- docs/integration/executor-sidecar.md | 40 ++--- 4 files changed, 319 insertions(+), 91 deletions(-) diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index f8aba09f..97e8f975 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -258,6 +258,32 @@ fn load_approval_key( Ok(Some(key)) } +/// Bind the listener. Connecting to a Unix socket needs write permission +/// on the file, so when the allowlist names a uid other than the daemon's +/// (the sidecar worker) the socket is created 0666 by loosening the umask +/// for the bind call only; the SO_PEERCRED allowlist (ADR-0012) is what +/// gates access. Otherwise the default umask applies. +/// +/// The umask is process-wide, but this runs after state is opened and +/// before the accept loop, when no other thread creates files, and it is +/// restored immediately. +fn bind_socket(path: &std::path::Path, policy: &PeerAuthPolicy) -> std::io::Result { + #[cfg(unix)] + { + // SAFETY: geteuid cannot fail. + let euid = unsafe { libc::geteuid() }; + if matches!(policy, PeerAuthPolicy::Allowlist(uids) if uids.iter().any(|u| *u != euid)) { + // SAFETY: umask cannot fail; the previous value is restored below. + let old = unsafe { libc::umask(0o111) }; + let bound = UnixListener::bind(path); + unsafe { libc::umask(old) }; + return bound; + } + } + let _ = policy; + UnixListener::bind(path) +} + #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() @@ -325,14 +351,16 @@ async fn main() -> anyhow::Result<()> { // Before anything reads or writes state: the daemon must own the repo // and `.agentic` (see state_dir.rs). Runs before the object store opens // so no state is created under a directory we then refuse. - agenticd::state_dir::secure_state_dir(&args.repo)?; + // The canonical path is used from here on so the checked path cannot + // be redirected through a symlink afterwards. + let repo = agenticd::state_dir::secure_state_dir(&args.repo)?; let postgres_url = agenticd::secrets::resolve_postgres_url( args.postgres.as_deref(), args.postgres_url_file.as_deref(), )?; - let agentic_dir = args.repo.join(".agentic"); + let agentic_dir = repo.join(".agentic"); let tables = parse_tracked_tables(&args.tables)?; let mcp_servers = parse_mcp_spec(&args.mcp)?; @@ -405,7 +433,7 @@ async fn main() -> anyhow::Result<()> { let peer_auth = Arc::new(peer_auth); let state = Arc::new( DaemonState::open( - args.repo.clone(), + repo.clone(), agentic_dir.clone(), store, postgres_url.as_deref(), @@ -419,22 +447,12 @@ async fn main() -> anyhow::Result<()> { .with_exempt_entropy_prefixes(args.scanner_exempt_entropy_prefixes.clone()), ); - let listener = UnixListener::bind(&socket_path) + let listener = bind_socket(&socket_path, &peer_auth) .with_context(|| format!("binding {}", socket_path.display()))?; - // Connecting to a Unix socket needs write permission on the file, and - // the worker runs as another uid. Access control is the SO_PEERCRED - // allowlist (ADR-0012), so open the file mode when one is enforced. - #[cfg(unix)] - if matches!(*peer_auth, PeerAuthPolicy::Allowlist(_)) { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o666)) - .with_context(|| format!("setting mode on {}", socket_path.display()))?; - } - tracing::info!( socket = %socket_path.display(), - repo = %args.repo.display(), + repo = %repo.display(), "agenticd listening" ); diff --git a/crates/agenticd/src/state_dir.rs b/crates/agenticd/src/state_dir.rs index 728a0496..2538c684 100644 --- a/crates/agenticd/src/state_dir.rs +++ b/crates/agenticd/src/state_dir.rs @@ -2,30 +2,45 @@ //! //! In the ADR-0004 sidecar the worker shares a volume with the daemon and //! is adversarial. Refs, objects and `schema/*.down.sql` (which a plain -//! rollback executes against Postgres) live under `/.agentic`, so a -//! worker that can write there can steer the daemon. The daemon therefore -//! requires `` and `/.agentic` to be its own, `.agentic` to be -//! mode 0700, and `` not to be group- or world-writable. The worker -//! can still read `/prompts`, but must run as a different uid. +//! rollback executes against Postgres) live under `/.agentic`, and +//! the daemon reopens those paths for the life of the process. A worker +//! that can write there, or that can write to any directory above it and +//! so rename the repo out of the way, can steer the daemon. The daemon +//! therefore refuses to start unless: +//! +//! - `` is owned by its euid; +//! - neither `` nor any ancestor up to `/` can be modified by +//! another principal (see [`writable_by_others`]); +//! - `/.agentic` is a real directory owned by it, with no group or +//! other write bit; it is then tightened to 0700. +//! +//! The worker may read `/prompts`, but must run as a different uid. -use std::path::Path; +use std::path::{Path, PathBuf}; -/// Create or tighten `/.agentic` and verify ownership. Unix only; -/// elsewhere there is no uid model to check and this is a no-op. +/// Create or tighten `/.agentic` and verify ownership, returning the +/// canonical repo path. The caller must use the returned path from here on, +/// so a symlink in the original path cannot be repointed after the check. +/// Unix only; elsewhere there is no uid model and this returns `repo`. #[cfg(unix)] -pub fn secure_state_dir(repo: &Path) -> anyhow::Result<()> { +pub fn secure_state_dir(repo: &Path) -> anyhow::Result { use anyhow::{bail, Context}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; - // SAFETY: geteuid has no preconditions and cannot fail. - let euid = unsafe { libc::geteuid() }; + // SAFETY: geteuid and getegid have no preconditions and cannot fail. + let (euid, egid) = unsafe { (libc::geteuid(), libc::getegid()) }; std::fs::DirBuilder::new() .recursive(true) .mode(0o755) .create(repo) .with_context(|| format!("creating repo directory {}", repo.display()))?; - let repo_meta = std::fs::metadata(repo).with_context(|| format!("stat {}", repo.display()))?; + // Resolve symlinks first so every directory that can rename a path + // component is on the chain checked below (macOS `/var` is a symlink). + let repo = std::fs::canonicalize(repo) + .with_context(|| format!("resolving repo directory {}", repo.display()))?; + + let repo_meta = std::fs::metadata(&repo).with_context(|| format!("stat {}", repo.display()))?; if repo_meta.uid() != euid { bail!( "repo directory {} is owned by uid {}, not the daemon's uid {euid}; refusing to start", @@ -33,13 +48,14 @@ pub fn secure_state_dir(repo: &Path) -> anyhow::Result<()> { repo_meta.uid() ); } - if repo_meta.mode() & 0o022 != 0 { - bail!( - "repo directory {} is group- or world-writable (mode {:o}); refusing to start. \ - Run `chmod go-w` on it", - repo.display(), - repo_meta.mode() & 0o7777 - ); + for dir in repo.ancestors() { + let m = std::fs::metadata(dir).with_context(|| format!("stat {}", dir.display()))?; + if let Some(why) = writable_by_others(&m, euid, egid) { + bail!( + "{} {why}; another uid could replace the daemon's state, refusing to start", + dir.display() + ); + } } let dir = repo.join(".agentic"); @@ -56,6 +72,16 @@ pub fn secure_state_dir(repo: &Path) -> anyhow::Result<()> { m.uid() ); } + // Already group/other writable means someone else may have + // planted content; tightening the mode would not undo that. + if m.mode() & 0o022 != 0 { + bail!( + "state directory {} is group- or world-writable (mode {:o}); \ + its contents cannot be trusted, refusing to start", + dir.display(), + m.mode() & 0o7777 + ); + } if m.mode() & 0o7777 != 0o700 { std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)) .with_context(|| format!("setting mode 0700 on {}", dir.display()))?; @@ -69,12 +95,37 @@ pub fn secure_state_dir(repo: &Path) -> anyhow::Result<()> { } Err(e) => return Err(e).with_context(|| format!("stat {}", dir.display())), } - Ok(()) + Ok(repo) +} + +/// Whether a principal other than the daemon (and root) could add, remove +/// or rename entries in this directory, with a reason if so. +/// +/// - Owned by neither the daemon nor root: the owner can chmod and write. +/// - Other-writable without the sticky bit (a sticky `/tmp` only lets +/// owners rename their own entries, so it is fine). +/// - Group-writable when the directory's gid is not the daemon's egid. +/// Group-write with the process's own gid is allowed so a umask-002 +/// checkout on a user-private-group system keeps working; the worker +/// must then not share that group. +#[cfg(unix)] +fn writable_by_others(m: &std::fs::Metadata, euid: u32, egid: u32) -> Option<&'static str> { + use std::os::unix::fs::MetadataExt; + let mode = m.mode(); + if m.uid() != euid && m.uid() != 0 { + Some("is owned by another uid") + } else if mode & 0o002 != 0 && mode & 0o1000 == 0 { + Some("is world-writable without the sticky bit") + } else if mode & 0o020 != 0 && m.gid() != egid { + Some("is writable by a group other than the daemon's") + } else { + None + } } #[cfg(not(unix))] -pub fn secure_state_dir(_repo: &Path) -> anyhow::Result<()> { - Ok(()) +pub fn secure_state_dir(repo: &Path) -> anyhow::Result { + Ok(repo.to_path_buf()) } #[cfg(all(test, unix))] @@ -82,39 +133,107 @@ mod tests { use super::*; use std::os::unix::fs::PermissionsExt; + fn set_mode(p: &Path, mode: u32) { + std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap(); + } + fn mode(p: &Path) -> u32 { std::fs::metadata(p).unwrap().permissions().mode() & 0o7777 } + /// `/outer/repo`, with `outer` set to `outer_mode` first. + fn nested(outer_mode: u32) -> (tempfile::TempDir, PathBuf, PathBuf) { + let t = tempfile::tempdir().unwrap(); + let outer = t.path().join("outer"); + std::fs::create_dir(&outer).unwrap(); + set_mode(&outer, outer_mode); + let repo = outer.join("repo"); + (t, outer, repo) + } + #[test] - fn creates_state_dir_0700() { + fn creates_state_dir_0700_and_returns_canonical_path() { let t = tempfile::tempdir().unwrap(); - secure_state_dir(t.path()).unwrap(); - assert_eq!(mode(&t.path().join(".agentic")), 0o700); + let repo = secure_state_dir(t.path()).unwrap(); + assert_eq!(repo, std::fs::canonicalize(t.path()).unwrap()); + assert_eq!(mode(&repo.join(".agentic")), 0o700); } #[test] - fn tightens_existing_state_dir() { + fn tightens_existing_0755_state_dir() { let t = tempfile::tempdir().unwrap(); let d = t.path().join(".agentic"); std::fs::create_dir(&d).unwrap(); - std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o777)).unwrap(); + set_mode(&d, 0o755); secure_state_dir(t.path()).unwrap(); assert_eq!(mode(&d), 0o700); } #[test] - fn refuses_group_writable_repo() { + fn refuses_group_or_world_writable_state_dir() { + for m in [0o775, 0o777] { + let t = tempfile::tempdir().unwrap(); + let d = t.path().join(".agentic"); + std::fs::create_dir(&d).unwrap(); + set_mode(&d, m); + let err = secure_state_dir(t.path()).unwrap_err().to_string(); + assert!( + err.contains("writable") && err.contains("agentic"), + "{m:o}: {err}" + ); + assert_eq!(mode(&d), m, "a refused dir must not be modified"); + } + } + + #[test] + fn refuses_world_writable_repo() { let t = tempfile::tempdir().unwrap(); - std::fs::set_permissions(t.path(), std::fs::Permissions::from_mode(0o775)).unwrap(); + set_mode(t.path(), 0o777); let err = secure_state_dir(t.path()).unwrap_err().to_string(); - assert!( - err.contains("writable") && err.contains(&*t.path().to_string_lossy()), - "{err}" - ); + assert!(err.contains("world-writable"), "{err}"); assert!(!t.path().join(".agentic").exists()); } + #[test] + fn refuses_world_writable_ancestor_without_sticky() { + let (_t, outer, repo) = nested(0o777); + let err = secure_state_dir(&repo).unwrap_err().to_string(); + let outer = std::fs::canonicalize(&outer).unwrap(); + assert!(err.contains(&*outer.to_string_lossy()), "{err}"); + } + + #[test] + fn allows_world_writable_ancestor_with_sticky() { + let (_t, _outer, repo) = nested(0o1777); + secure_state_dir(&repo).unwrap(); + } + + #[test] + fn allows_group_writable_ancestor_with_own_gid() { + let (_t, outer, repo) = nested(0o775); + // SAFETY: getegid cannot fail. + let egid = unsafe { libc::getegid() }; + std::os::unix::fs::chown(&outer, None, Some(egid)).unwrap(); + secure_state_dir(&repo).unwrap(); + } + + #[test] + fn refuses_group_writable_ancestor_with_foreign_gid() { + // SAFETY: getegid/getgroups with a sized buffer are sound. + let egid = unsafe { libc::getegid() }; + let mut groups = [0 as libc::gid_t; 256]; + let n = unsafe { libc::getgroups(256, groups.as_mut_ptr()) }; + let Some(other) = groups[..n.max(0) as usize].iter().find(|g| **g != egid) else { + return; // no supplementary group to borrow on this machine + }; + let (_t, outer, repo) = nested(0o775); + if std::os::unix::fs::chown(&outer, None, Some(*other)).is_err() { + return; + } + let err = secure_state_dir(&repo).unwrap_err().to_string(); + assert!(err.contains("group other than"), "{err}"); + } + #[test] fn refuses_symlinked_state_dir() { let t = tempfile::tempdir().unwrap(); diff --git a/crates/agenticd/tests/startup_refusal.rs b/crates/agenticd/tests/startup_refusal.rs index 9b15c8a9..b780f03f 100644 --- a/crates/agenticd/tests/startup_refusal.rs +++ b/crates/agenticd/tests/startup_refusal.rs @@ -72,23 +72,50 @@ mod state_dir { std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap(); } - #[test] - fn refuses_group_writable_repo() { - let repo = tempfile::tempdir().unwrap(); + /// Run the daemon expecting it to refuse to start; returns stderr. A + /// daemon that starts instead is killed and fails the test, so a + /// regression is a failure and not a hang. + fn expect_refusal(repo: &std::path::Path) -> String { + use std::process::Stdio; let sock = tempfile::tempdir().unwrap(); - set_mode(repo.path(), 0o777); - let out = Command::new(agenticd_bin()) + let mut child = Command::new(agenticd_bin()) .arg("--repo") - .arg(repo.path()) + .arg(repo) .arg("--socket") .arg(sock.path().join("d.sock")) .arg("--insecure-allow-any-uid") - .output() + .stderr(Stdio::piped()) + .spawn() .expect("run agenticd"); - assert!(!out.status.success()); - let stderr = String::from_utf8_lossy(&out.stderr); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15); + let status = loop { + if let Some(st) = child.try_wait().unwrap() { + break Some(st); + } + if std::time::Instant::now() > deadline { + break None; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + }; + if status.is_none() { + let _ = child.kill(); + } + let out = child.wait_with_output().unwrap(); assert!( - stderr.contains("writable") && stderr.contains(&*repo.path().to_string_lossy()), + status.is_some_and(|st| !st.success()), + "daemon should have refused to start" + ); + String::from_utf8_lossy(&out.stderr).into_owned() + } + + #[test] + fn refuses_group_writable_repo() { + let repo = tempfile::tempdir().unwrap(); + set_mode(repo.path(), 0o777); + let stderr = expect_refusal(repo.path()); + let canonical = std::fs::canonicalize(repo.path()).unwrap(); + assert!( + stderr.contains("writable") && stderr.contains(&*canonical.to_string_lossy()), "stderr should name the repo path; got: {stderr}" ); assert!( @@ -120,32 +147,92 @@ mod state_dir { ); } - #[test] - fn startup_leaves_state_dir_0700() { - let repo = tempfile::tempdir().unwrap(); + /// Spawn the daemon (umask pinned to 022), wait for the socket, return + /// the socket and state-dir modes, then kill it. + fn run_and_stat(repo: &std::path::Path, extra: &[&str]) -> (u32, u32) { + use std::os::unix::process::CommandExt; let sock_dir = tempfile::tempdir().unwrap(); let sock = sock_dir.path().join("d.sock"); - let state = repo.path().join(".agentic"); - std::fs::create_dir(&state).unwrap(); - set_mode(&state, 0o777); - let mut child = Command::new(agenticd_bin()) - .arg("--repo") - .arg(repo.path()) + let mut cmd = Command::new(agenticd_bin()); + cmd.arg("--repo") + .arg(repo) .arg("--socket") .arg(&sock) - .arg("--insecure-allow-any-uid") - .spawn() - .expect("run agenticd"); + .args(extra); + // SAFETY: umask is async-signal-safe and runs in the child only. + unsafe { + cmd.pre_exec(|| { + libc::umask(0o022); + Ok(()) + }); + } + let mut child = cmd.spawn().expect("run agenticd"); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); while !sock.exists() && std::time::Instant::now() < deadline { std::thread::sleep(std::time::Duration::from_millis(50)); } let bound = sock.exists(); - let mode = std::fs::metadata(&state).unwrap().permissions().mode() & 0o7777; + let sock_mode = + bound.then(|| std::fs::metadata(&sock).unwrap().permissions().mode() & 0o7777); + let state_mode = std::fs::metadata(repo.join(".agentic")) + .unwrap() + .permissions() + .mode() + & 0o7777; let _ = child.kill(); let _ = child.wait(); - assert!(bound, "daemon did not bind the socket"); - assert_eq!(mode, 0o700); + ( + sock_mode.expect("daemon did not bind the socket"), + state_mode, + ) + } + + #[test] + fn startup_tightens_0755_state_dir_to_0700() { + let repo = tempfile::tempdir().unwrap(); + let state = repo.path().join(".agentic"); + std::fs::create_dir(&state).unwrap(); + set_mode(&state, 0o755); + let (_, state_mode) = run_and_stat(repo.path(), &["--insecure-allow-any-uid"]); + assert_eq!(state_mode, 0o700); + } + + #[test] + fn refuses_existing_writable_state_dir() { + for m in [0o775, 0o777] { + let repo = tempfile::tempdir().unwrap(); + let state = repo.path().join(".agentic"); + std::fs::create_dir(&state).unwrap(); + set_mode(&state, m); + let stderr = expect_refusal(repo.path()); + assert!( + stderr.contains(".agentic") && stderr.contains("writable"), + "{m:o}: {stderr}" + ); + } + } + + #[test] + fn socket_is_0666_only_when_allowlist_names_another_uid() { + // SAFETY: geteuid cannot fail. + let euid = unsafe { libc::geteuid() }; + let other = (euid + 1).to_string(); + let own = euid.to_string(); + + let repo = tempfile::tempdir().unwrap(); + let (sock_mode, _) = run_and_stat(repo.path(), &["--allowed-uid", &other]); + assert_eq!( + sock_mode, 0o666, + "worker uid listed: socket must be connectable" + ); + + let repo = tempfile::tempdir().unwrap(); + let (sock_mode, _) = run_and_stat(repo.path(), &["--allowed-uid", &own]); + assert_eq!(sock_mode, 0o755, "own uid only: default umask applies"); + + let repo = tempfile::tempdir().unwrap(); + let (sock_mode, _) = run_and_stat(repo.path(), &["--insecure-allow-any-uid"]); + assert_eq!(sock_mode, 0o755); } } diff --git a/docs/integration/executor-sidecar.md b/docs/integration/executor-sidecar.md index afcd5811..fe33a3c9 100644 --- a/docs/integration/executor-sidecar.md +++ b/docs/integration/executor-sidecar.md @@ -17,15 +17,16 @@ docker build -f crates/agenticd/Dockerfile.sidecar -t agenticd:sidecar . ## Trust boundary -The worker runs model-driven code and is treated as adversarial. It shares a volume with the daemon, so the layout below keeps the daemon's state out of its reach: +The worker runs model-driven code and is treated as adversarial. The layout below keeps the daemon's state out of its reach: - The worker image sets a `USER` with a uid other than the sidecar's 65532 (Cloud Run runs each container as its image `USER`). The examples use 10001. -- The daemon starts with `--allowed-uid 10001` and refuses to start without an allowlist (ADR-0012). It admits only that uid on the socket and records it on each commit. -- The daemon creates and owns `--repo /shared/work`. At startup it creates `/shared/work/.agentic` with mode 0700, tightens an existing one to 0700, and refuses to start if the repo or `.agentic` is owned by another uid, if the repo is group- or world-writable, or if `.agentic` is a symlink. The error names the path. -- Refs, objects, the GCS cache and `schema/*.down.sql` live in `.agentic`, so the worker cannot edit them. It can still read the prompt files that rollback restores under `/shared/work/prompts`. -- Credentials arrive as files from Secret Manager volumes mounted into the `agenticd` container only. They never appear in argv or in the worker's environment. +- The daemon starts with `--allowed-uid 10001` and refuses to start without an allowlist (ADR-0012). It admits only that uid on the socket and records it on each commit. When the allowlist names a uid other than the daemon's own, the daemon creates the socket mode 0666, since connecting needs write permission on the file. The `SO_PEERCRED` check is what gates access. +- `--repo` lives on its own emptyDir (`state`) that only the `agenticd` container mounts. The shared volume (`ipc`) carries the socket and nothing else. A worker that can write to a directory above the repo can rename the repo and plant its own `.agentic`, so the state volume must not be writable by the worker. +- At startup the daemon resolves `--repo` to its canonical path and refuses to start, naming the path, if the repo or any ancestor up to `/` can be modified by another principal. That means owned by neither the daemon nor root, world-writable without the sticky bit, or group-writable with a group other than the daemon's. It also refuses if the repo is owned by another uid, or if `.agentic` is a symlink, owned by another uid, or already group- or world-writable. Otherwise it creates `.agentic` at mode 0700 or tightens an existing one to 0700. +- Refs, objects, the GCS cache and `schema/*.down.sql` live in `.agentic`, so the worker cannot edit them. If the worker must read the prompts that rollback restores, mount the `state` volume into the worker read-only. Do not mount it writable. +- Credentials arrive as files from Secret Manager volumes mounted into the `agenticd` container only. This removes the argv and environment exposure. It does not isolate the secrets from the worker: all containers in one Cloud Run instance share the service identity, so the worker can fetch the same secrets or call the bucket directly. Real isolation needs a separate identity for the sidecar (ADR-0015, Proposed). -The daemon cannot make the shared volume's root directory private. A worker that can write to `/shared` can rename `/shared/work` while the daemon is stopped or running, so the ownership check is a startup guard and not a substitute for a volume the worker cannot write. Keep the socket as the only thing the worker needs there. +**Not verified on Cloud Run.** We have not confirmed the owner and mode of an emptyDir volume root, or whether it can be mounted read-only into one container. If the volume root is world-writable, the daemon refuses to start by design, and the layout needs a volume whose root is owned by the daemon or root and is not writable by other uids. Test the exact deployment before relying on it. ## Cloud Run service definition (excerpt) @@ -39,16 +40,18 @@ spec: # The image must set USER 10001 (any uid other than 65532). image: gcr.io//coding-worker: env: - - { name: AGENTICD_SOCKET, value: /shared/agenticd.sock } + - { name: AGENTICD_SOCKET, value: /ipc/agenticd.sock } volumeMounts: - - { name: shared, mountPath: /shared } + - { name: ipc, mountPath: /ipc } + # Only if the worker must read restored prompts, and only read-only: + # - { name: state, mountPath: /state, readOnly: true } - name: agenticd image: gcr.io//agenticd-sidecar: args: - --repo - - /shared/work + - /state/work - --socket - - /shared/agenticd.sock + - /ipc/agenticd.sock - --allowed-uid - "10001" - --object-store @@ -60,11 +63,14 @@ spec: env: - { name: AGENTIC_GCS_TOKEN_FILE, value: /secrets/gcs/token } volumeMounts: - - { name: shared, mountPath: /shared } + - { name: ipc, mountPath: /ipc } + - { name: state, mountPath: /state } - { name: gcs-token, mountPath: /secrets/gcs, readOnly: true } - { name: postgres-url, mountPath: /secrets/postgres, readOnly: true } volumes: - - name: shared + - name: ipc + emptyDir: { medium: Memory } + - name: state emptyDir: { medium: Memory } - name: gcs-token secret: @@ -78,16 +84,14 @@ spec: Drop the `--postgres-url-file` and `--tables` lines if the deployment has no memory backend. -`/shared` is tmpfs; durability lives in GCS. Because `/.agentic/schema` is empty on tmpfs at boot, reverse migrations need the sidecar image to provide the `.down.sql` files, for example copied into `/shared/work/.agentic/schema` by the sidecar's own entrypoint. The worker must never supply them: a plain rollback executes those files against Postgres. - -When an allowlist is enforced, the daemon sets the socket file to mode 0666 after binding, because connecting to a Unix socket needs write permission on the file and the worker is a different uid. The `SO_PEERCRED` check is what gates access. +Both emptyDirs are tmpfs; durability lives in GCS. Because `/.agentic/schema` is empty on tmpfs at boot, reverse migrations need the sidecar image to provide the `.down.sql` files, for example copied into `/state/work/.agentic/schema` by the sidecar's own entrypoint. The worker must never supply them: a plain rollback executes those files against Postgres. ## Flags and env vars `agenticd` reads | Input | Meaning | Default | |---|---|---| | `--allowed-uid ` | Uid allowed on the socket; repeatable. Required unless `--insecure-allow-any-uid` is passed (ADR-0012). | _none_; startup fails | -| `--postgres-url-file ` | File holding the Postgres URL; one trailing newline is trimmed and an empty file is an error. Conflicts with `--postgres`. | _none_ | +| `--postgres-url-file ` | File holding the Postgres URL; surrounding whitespace is trimmed and an empty file is an error. Conflicts with `--postgres`. | _none_ | | `AGENTIC_GCS_TOKEN_FILE` | Path to a file holding the GCS bearer token, trimmed the same way. Setting it together with `AGENTIC_GCS_TOKEN` is an error. | _none_ | | `AGENTIC_GCS_ENDPOINT` | Override GCS host (for `tests/fixtures/fake-gcs.yml`) | public GCS | | `AGENTIC_GCS_TOKEN` | Bearer for the GCS JSON API, as a plain env value. Fine for the demo and tests; prefer the file form in the sidecar. | _none_; required for real GCS unless the file form is used | @@ -95,7 +99,7 @@ When an allowlist is enforced, the daemon sets the socket file to mode 0666 afte `--postgres ` still works for the demo and tests, but puts the password in argv. Use `--postgres-url-file` in the sidecar. -The sidecar does NOT call ADC or the GCE metadata server itself. In v1.0 the only supported wiring is to **mount the token as a Secret Manager volume** into the `agenticd` container, as in the YAML excerpt above. ("Have the worker write it to `/shared`" is intentionally NOT supported: both containers start at the same time, `/shared` is empty on boot, and the sidecar would race the worker's first checkpoint. If token rotation past the Cloud Run instance lifetime becomes a requirement, file a follow-up, since that needs a refresh thread inside `agenticd`.) +The sidecar does NOT call ADC or the GCE metadata server itself. In v1.0 the only supported wiring is to **mount the token as a Secret Manager volume** into the `agenticd` container, as in the YAML excerpt above. ("Have the worker write it to `/ipc`" is intentionally NOT supported: both containers start at the same time, `/ipc` is empty on boot, and the sidecar would race the worker's first checkpoint. If token rotation past the Cloud Run instance lifetime becomes a requirement, file a follow-up, since that needs a refresh thread inside `agenticd`.) ## Worker code @@ -118,5 +122,5 @@ Per ADR-0004 Decision 4 there is no degraded mode. If the sidecar is unreachable ## Verification 1. `docker build -f crates/agenticd/Dockerfile.sidecar -t agenticd:sidecar .` succeeds. -2. `docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/.shared:/shared" agenticd:sidecar --repo /shared/work --socket /shared/agenticd.sock --insecure-allow-any-uid --object-store fs:///shared/objects` (the container uid must own the mounted directory, and the insecure flag is for this local check only) binds the socket and serves a `Ping`. +2. `docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/.state:/state" -v "$PWD/.ipc:/ipc" agenticd:sidecar --repo /state/work --socket /ipc/agenticd.sock --insecure-allow-any-uid` (the default `fs` object store lives under `/state/work/.agentic`; the container uid must own both mounted directories, and the insecure flag is for this local check only) binds the socket and serves a `Ping`. 3. Same as (2) but with `--object-store gcs://...` against `tests/fixtures/fake-gcs.yml` completes one commit-and-rollback cycle. Covered by the `gcs` CI job today. From 86259740cda99dbe20766a15f51bd7f32dcfd05d Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:44:40 +0200 Subject: [PATCH 3/6] Make the repo check strict and let sticky and trusted ancestors through The repo directory now refuses any group or other write bit, sticky bit or not, since it is where `.agentic` gets planted. The ancestor exemptions apply only to strict ancestors. A sticky ancestor such as a root-owned `/tmp` passes when its child on the path is owned by the daemon or root, which the previous check wrongly refused. `--trusted-volume-root` lets an operator exempt one ancestor they assert only agenticd mounts, for volume roots that are world-writable. The default socket path is built from the repo as given again, and a dangling symlink at the socket path is removed before binding. The demo script drops group write on its repo directory and `.agentic` so umask-002 checkouts still run. --- crates/agenticd/src/main.rs | 19 ++- crates/agenticd/src/state_dir.rs | 154 ++++++++++++++---- crates/agenticd/tests/startup_refusal.rs | 34 ++++ docs/integration/executor-sidecar.md | 15 +- .../langgraph-rollback/scripts/run-demo.sh | 3 + 5 files changed, 187 insertions(+), 38 deletions(-) diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index 97e8f975..a6d360ec 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -91,6 +91,14 @@ struct Args { #[arg(long, value_delimiter = ',')] mcp: Vec, + /// Canonical directory the operator asserts only agenticd can write + /// (for example a state volume root that only the daemon mounts). It is + /// exempt from the ancestor write check; the repo itself never is. + /// Without it, a world-writable volume root makes the daemon refuse + /// to start. + #[arg(long)] + trusted_volume_root: Option, + /// Object-store backend. `fs` (default) uses `/.agentic/objects`; /// `fs:///abs/path` uses an explicit on-disk root; `gcs://bucket[/prefix]` /// pushes every object through to Google Cloud Storage with a @@ -353,7 +361,8 @@ async fn main() -> anyhow::Result<()> { // so no state is created under a directory we then refuse. // The canonical path is used from here on so the checked path cannot // be redirected through a symlink afterwards. - let repo = agenticd::state_dir::secure_state_dir(&args.repo)?; + let repo = + agenticd::state_dir::secure_state_dir(&args.repo, args.trusted_volume_root.as_deref())?; let postgres_url = agenticd::secrets::resolve_postgres_url( args.postgres.as_deref(), @@ -406,12 +415,16 @@ async fn main() -> anyhow::Result<()> { let socket_path = args .socket .clone() - .unwrap_or_else(|| agentic_dir.join("agenticd.sock")); + // Built from the repo as given, not the canonical path, so a deep + // checkout is not pushed past the Unix socket path limit. + .unwrap_or_else(|| args.repo.join(".agentic").join("agenticd.sock")); if let Some(parent) = socket_path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("creating socket parent directory {}", parent.display()))?; } - if socket_path.exists() { + // symlink_metadata so a dangling symlink is removed too; remove_file + // unlinks the link, never its target. + if std::fs::symlink_metadata(&socket_path).is_ok() { std::fs::remove_file(&socket_path) .with_context(|| format!("removing stale socket {}", socket_path.display()))?; } diff --git a/crates/agenticd/src/state_dir.rs b/crates/agenticd/src/state_dir.rs index 2538c684..363470ac 100644 --- a/crates/agenticd/src/state_dir.rs +++ b/crates/agenticd/src/state_dir.rs @@ -8,9 +8,9 @@ //! so rename the repo out of the way, can steer the daemon. The daemon //! therefore refuses to start unless: //! -//! - `` is owned by its euid; -//! - neither `` nor any ancestor up to `/` can be modified by -//! another principal (see [`writable_by_others`]); +//! - `` is owned by its euid and has no group or other write bit; +//! - no ancestor up to `/` can be modified by another principal (see +//! [`ancestor_writable_by_others`]); //! - `/.agentic` is a real directory owned by it, with no group or //! other write bit; it is then tightened to 0700. //! @@ -21,9 +21,12 @@ use std::path::{Path, PathBuf}; /// Create or tighten `/.agentic` and verify ownership, returning the /// canonical repo path. The caller must use the returned path from here on, /// so a symlink in the original path cannot be repointed after the check. -/// Unix only; elsewhere there is no uid model and this returns `repo`. +/// `trusted_root` (`--trusted-volume-root`) names an ancestor the operator +/// asserts only the daemon can write, exempting it (never the repo itself) +/// from the ancestor check. Unix only; elsewhere there is no uid model and +/// this returns `repo`. #[cfg(unix)] -pub fn secure_state_dir(repo: &Path) -> anyhow::Result { +pub fn secure_state_dir(repo: &Path, trusted_root: Option<&Path>) -> anyhow::Result { use anyhow::{bail, Context}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; @@ -40,6 +43,13 @@ pub fn secure_state_dir(repo: &Path) -> anyhow::Result { let repo = std::fs::canonicalize(repo) .with_context(|| format!("resolving repo directory {}", repo.display()))?; + let trusted_root = trusted_root + .map(|t| { + std::fs::canonicalize(t) + .with_context(|| format!("resolving --trusted-volume-root {}", t.display())) + }) + .transpose()?; + let repo_meta = std::fs::metadata(&repo).with_context(|| format!("stat {}", repo.display()))?; if repo_meta.uid() != euid { bail!( @@ -48,11 +58,29 @@ pub fn secure_state_dir(repo: &Path) -> anyhow::Result { repo_meta.uid() ); } - for dir in repo.ancestors() { + // The repo itself is strict: any group or other write bit lets another + // principal plant or replace `.agentic`, sticky bit or not. + if repo_meta.mode() & 0o022 != 0 { + bail!( + "repo directory {} is group- or world-writable (mode {:o}); refusing to start. \ + Run `chmod go-w` on it", + repo.display(), + repo_meta.mode() & 0o7777 + ); + } + let chain: Vec<&Path> = repo.ancestors().collect(); + for pair in chain.windows(2) { + let (child, dir) = (pair[0], pair[1]); + if trusted_root.as_deref() == Some(dir) { + continue; + } let m = std::fs::metadata(dir).with_context(|| format!("stat {}", dir.display()))?; - if let Some(why) = writable_by_others(&m, euid, egid) { + let child_m = + std::fs::metadata(child).with_context(|| format!("stat {}", child.display()))?; + if let Some(why) = ancestor_writable_by_others(&m, &child_m, euid, egid) { bail!( - "{} {why}; another uid could replace the daemon's state, refusing to start", + "{} {why}; another uid could replace the daemon's state, refusing to start \ + (if only agenticd mounts this directory, pass --trusted-volume-root)", dir.display() ); } @@ -99,22 +127,33 @@ pub fn secure_state_dir(repo: &Path) -> anyhow::Result { } /// Whether a principal other than the daemon (and root) could add, remove -/// or rename entries in this directory, with a reason if so. +/// or rename `child` through this strict ancestor, with a reason if so. /// /// - Owned by neither the daemon nor root: the owner can chmod and write. -/// - Other-writable without the sticky bit (a sticky `/tmp` only lets -/// owners rename their own entries, so it is fine). -/// - Group-writable when the directory's gid is not the daemon's egid. -/// Group-write with the process's own gid is allowed so a umask-002 -/// checkout on a user-private-group system keeps working; the worker -/// must then not share that group. +/// - Sticky: exempt from the group and other write checks, because a +/// sticky directory (a root-owned `/tmp`) only lets an entry's owner +/// rename or remove it. That holds only if `child` is owned by the daemon +/// or root, so no other uid created it. +/// - Otherwise other-writable is refused, and so is group-writable when the +/// directory's gid is not the daemon's egid. Group-write with the +/// process's own gid is allowed so a umask-002 checkout on a +/// user-private-group system keeps working; the worker must then not +/// share the daemon's primary group. #[cfg(unix)] -fn writable_by_others(m: &std::fs::Metadata, euid: u32, egid: u32) -> Option<&'static str> { +fn ancestor_writable_by_others( + m: &std::fs::Metadata, + child: &std::fs::Metadata, + euid: u32, + egid: u32, +) -> Option<&'static str> { use std::os::unix::fs::MetadataExt; let mode = m.mode(); if m.uid() != euid && m.uid() != 0 { Some("is owned by another uid") - } else if mode & 0o002 != 0 && mode & 0o1000 == 0 { + } else if mode & 0o1000 != 0 { + (child.uid() != euid && child.uid() != 0) + .then_some("is sticky but its child on the path to the repo is owned by another uid") + } else if mode & 0o002 != 0 { Some("is world-writable without the sticky bit") } else if mode & 0o020 != 0 && m.gid() != egid { Some("is writable by a group other than the daemon's") @@ -124,7 +163,7 @@ fn writable_by_others(m: &std::fs::Metadata, euid: u32, egid: u32) -> Option<&'s } #[cfg(not(unix))] -pub fn secure_state_dir(repo: &Path) -> anyhow::Result { +pub fn secure_state_dir(repo: &Path, _trusted_root: Option<&Path>) -> anyhow::Result { Ok(repo.to_path_buf()) } @@ -141,6 +180,18 @@ mod tests { std::fs::metadata(p).unwrap().permissions().mode() & 0o7777 } + /// A supplementary group of this process other than its egid, if any. + fn foreign_gid() -> Option { + // SAFETY: getegid/getgroups with a sized buffer are sound. + let egid = unsafe { libc::getegid() }; + let mut groups = [0 as libc::gid_t; 256]; + let n = unsafe { libc::getgroups(256, groups.as_mut_ptr()) }; + groups[..n.max(0) as usize] + .iter() + .copied() + .find(|g| *g != egid) + } + /// `/outer/repo`, with `outer` set to `outer_mode` first. fn nested(outer_mode: u32) -> (tempfile::TempDir, PathBuf, PathBuf) { let t = tempfile::tempdir().unwrap(); @@ -154,7 +205,7 @@ mod tests { #[test] fn creates_state_dir_0700_and_returns_canonical_path() { let t = tempfile::tempdir().unwrap(); - let repo = secure_state_dir(t.path()).unwrap(); + let repo = secure_state_dir(t.path(), None).unwrap(); assert_eq!(repo, std::fs::canonicalize(t.path()).unwrap()); assert_eq!(mode(&repo.join(".agentic")), 0o700); } @@ -165,7 +216,7 @@ mod tests { let d = t.path().join(".agentic"); std::fs::create_dir(&d).unwrap(); set_mode(&d, 0o755); - secure_state_dir(t.path()).unwrap(); + secure_state_dir(t.path(), None).unwrap(); assert_eq!(mode(&d), 0o700); } @@ -176,7 +227,7 @@ mod tests { let d = t.path().join(".agentic"); std::fs::create_dir(&d).unwrap(); set_mode(&d, m); - let err = secure_state_dir(t.path()).unwrap_err().to_string(); + let err = secure_state_dir(t.path(), None).unwrap_err().to_string(); assert!( err.contains("writable") && err.contains("agentic"), "{m:o}: {err}" @@ -189,15 +240,56 @@ mod tests { fn refuses_world_writable_repo() { let t = tempfile::tempdir().unwrap(); set_mode(t.path(), 0o777); - let err = secure_state_dir(t.path()).unwrap_err().to_string(); + let err = secure_state_dir(t.path(), None).unwrap_err().to_string(); assert!(err.contains("world-writable"), "{err}"); assert!(!t.path().join(".agentic").exists()); } + #[test] + fn refuses_sticky_world_writable_repo() { + let t = tempfile::tempdir().unwrap(); + set_mode(t.path(), 0o1777); + let err = secure_state_dir(t.path(), None).unwrap_err().to_string(); + assert!(err.contains("writable"), "{err}"); + } + + #[test] + fn refuses_group_writable_repo_with_own_gid() { + let t = tempfile::tempdir().unwrap(); + set_mode(t.path(), 0o775); + // SAFETY: getegid cannot fail. + std::os::unix::fs::chown(t.path(), None, Some(unsafe { libc::getegid() })).unwrap(); + let err = secure_state_dir(t.path(), None).unwrap_err().to_string(); + assert!(err.contains("writable"), "{err}"); + } + + #[test] + fn allows_sticky_ancestor_with_foreign_gid() { + // A root-owned 1777 /tmp has gid 0, not the daemon's egid. + let (_t, outer, repo) = nested(0o1777); + if let Some(other) = foreign_gid() { + let _ = std::os::unix::fs::chown(&outer, None, Some(other)); + } + secure_state_dir(&repo, None).unwrap(); + } + + #[test] + fn trusted_root_exempts_only_that_ancestor() { + let (_t, outer, repo) = nested(0o777); + assert!(secure_state_dir(&repo, None).is_err()); + secure_state_dir(&repo, Some(&outer)).unwrap(); + // Never exempts the repo itself. + set_mode(&repo, 0o777); + let err = secure_state_dir(&repo, Some(&repo)) + .unwrap_err() + .to_string(); + assert!(err.contains("repo directory"), "{err}"); + } + #[test] fn refuses_world_writable_ancestor_without_sticky() { let (_t, outer, repo) = nested(0o777); - let err = secure_state_dir(&repo).unwrap_err().to_string(); + let err = secure_state_dir(&repo, None).unwrap_err().to_string(); let outer = std::fs::canonicalize(&outer).unwrap(); assert!(err.contains(&*outer.to_string_lossy()), "{err}"); } @@ -205,7 +297,7 @@ mod tests { #[test] fn allows_world_writable_ancestor_with_sticky() { let (_t, _outer, repo) = nested(0o1777); - secure_state_dir(&repo).unwrap(); + secure_state_dir(&repo, None).unwrap(); } #[test] @@ -214,23 +306,19 @@ mod tests { // SAFETY: getegid cannot fail. let egid = unsafe { libc::getegid() }; std::os::unix::fs::chown(&outer, None, Some(egid)).unwrap(); - secure_state_dir(&repo).unwrap(); + secure_state_dir(&repo, None).unwrap(); } #[test] fn refuses_group_writable_ancestor_with_foreign_gid() { - // SAFETY: getegid/getgroups with a sized buffer are sound. - let egid = unsafe { libc::getegid() }; - let mut groups = [0 as libc::gid_t; 256]; - let n = unsafe { libc::getgroups(256, groups.as_mut_ptr()) }; - let Some(other) = groups[..n.max(0) as usize].iter().find(|g| **g != egid) else { + let Some(other) = foreign_gid() else { return; // no supplementary group to borrow on this machine }; let (_t, outer, repo) = nested(0o775); - if std::os::unix::fs::chown(&outer, None, Some(*other)).is_err() { + if std::os::unix::fs::chown(&outer, None, Some(other)).is_err() { return; } - let err = secure_state_dir(&repo).unwrap_err().to_string(); + let err = secure_state_dir(&repo, None).unwrap_err().to_string(); assert!(err.contains("group other than"), "{err}"); } @@ -239,7 +327,7 @@ mod tests { let t = tempfile::tempdir().unwrap(); let target = tempfile::tempdir().unwrap(); std::os::unix::fs::symlink(target.path(), t.path().join(".agentic")).unwrap(); - let err = secure_state_dir(t.path()).unwrap_err().to_string(); + let err = secure_state_dir(t.path(), None).unwrap_err().to_string(); assert!(err.contains("symlink"), "{err}"); } } diff --git a/crates/agenticd/tests/startup_refusal.rs b/crates/agenticd/tests/startup_refusal.rs index b780f03f..b777143c 100644 --- a/crates/agenticd/tests/startup_refusal.rs +++ b/crates/agenticd/tests/startup_refusal.rs @@ -212,6 +212,40 @@ mod state_dir { } } + #[test] + fn startup_removes_dangling_symlink_at_socket_path() { + let repo = tempfile::tempdir().unwrap(); + let sock_dir = tempfile::tempdir().unwrap(); + let sock = sock_dir.path().join("d.sock"); + let target = sock_dir.path().join("does-not-exist"); + std::os::unix::fs::symlink(&target, &sock).unwrap(); + let mut child = Command::new(agenticd_bin()) + .arg("--repo") + .arg(repo.path()) + .arg("--socket") + .arg(&sock) + .arg("--insecure-allow-any-uid") + .spawn() + .expect("run agenticd"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + let is_socket = |p: &std::path::Path| { + use std::os::unix::fs::FileTypeExt; + std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_socket()) + }; + while !is_socket(&sock) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let bound = is_socket(&sock); + let target_created = target.exists(); + let _ = child.kill(); + let _ = child.wait(); + assert!( + bound, + "daemon should replace the dangling symlink with its socket" + ); + assert!(!target_created, "the link target must never be created"); + } + #[test] fn socket_is_0666_only_when_allowlist_names_another_uid() { // SAFETY: geteuid cannot fail. diff --git a/docs/integration/executor-sidecar.md b/docs/integration/executor-sidecar.md index fe33a3c9..8c3c73b7 100644 --- a/docs/integration/executor-sidecar.md +++ b/docs/integration/executor-sidecar.md @@ -22,11 +22,19 @@ The worker runs model-driven code and is treated as adversarial. The layout belo - The worker image sets a `USER` with a uid other than the sidecar's 65532 (Cloud Run runs each container as its image `USER`). The examples use 10001. - The daemon starts with `--allowed-uid 10001` and refuses to start without an allowlist (ADR-0012). It admits only that uid on the socket and records it on each commit. When the allowlist names a uid other than the daemon's own, the daemon creates the socket mode 0666, since connecting needs write permission on the file. The `SO_PEERCRED` check is what gates access. - `--repo` lives on its own emptyDir (`state`) that only the `agenticd` container mounts. The shared volume (`ipc`) carries the socket and nothing else. A worker that can write to a directory above the repo can rename the repo and plant its own `.agentic`, so the state volume must not be writable by the worker. -- At startup the daemon resolves `--repo` to its canonical path and refuses to start, naming the path, if the repo or any ancestor up to `/` can be modified by another principal. That means owned by neither the daemon nor root, world-writable without the sticky bit, or group-writable with a group other than the daemon's. It also refuses if the repo is owned by another uid, or if `.agentic` is a symlink, owned by another uid, or already group- or world-writable. Otherwise it creates `.agentic` at mode 0700 or tightens an existing one to 0700. +- At startup the daemon resolves `--repo` to its canonical path and refuses to start, naming the path, if: + - the repo is owned by another uid, or has any group or other write bit (the sticky bit and gid do not matter for the repo itself); + - any ancestor up to `/` is owned by neither the daemon nor root, or is world-writable without the sticky bit, or is group-writable with a group other than the daemon's. A sticky ancestor such as a root-owned `/tmp` passes when its child on the path is owned by the daemon or root; + - `.agentic` is a symlink, is owned by another uid, or is already group- or world-writable. + + Otherwise it creates `.agentic` at mode 0700 or tightens an existing one to 0700. +- Group-write with the daemon's own gid is allowed on ancestors, so user-private-group checkouts under umask 002 keep working. The residual is that the worker must not share the daemon's primary group (the sidecar image uses gid 65532). +- `--trusted-volume-root ` exempts one ancestor, matched by canonical path, from the ancestor check. Use it when only agenticd mounts that directory. Kubernetes-style emptyDir roots are often world-writable, and without the flag the daemon refuses to start. It never exempts the repo itself. +- The socket path lives on the shared volume, so the worker can replace or remove the socket file. Nothing other than the worker's own client should trust that path. - Refs, objects, the GCS cache and `schema/*.down.sql` live in `.agentic`, so the worker cannot edit them. If the worker must read the prompts that rollback restores, mount the `state` volume into the worker read-only. Do not mount it writable. - Credentials arrive as files from Secret Manager volumes mounted into the `agenticd` container only. This removes the argv and environment exposure. It does not isolate the secrets from the worker: all containers in one Cloud Run instance share the service identity, so the worker can fetch the same secrets or call the bucket directly. Real isolation needs a separate identity for the sidecar (ADR-0015, Proposed). -**Not verified on Cloud Run.** We have not confirmed the owner and mode of an emptyDir volume root, or whether it can be mounted read-only into one container. If the volume root is world-writable, the daemon refuses to start by design, and the layout needs a volume whose root is owned by the daemon or root and is not writable by other uids. Test the exact deployment before relying on it. +**Not verified on Cloud Run.** We have not confirmed the owner and mode of an emptyDir volume root, or whether it can be mounted read-only into one container. If the root is world-writable, the daemon refuses to start unless you pass `--trusted-volume-root /state`. Pass it only because the `state` volume is mounted into the `agenticd` container alone. Test the exact deployment before relying on it. ## Cloud Run service definition (excerpt) @@ -50,6 +58,8 @@ spec: args: - --repo - /state/work + - --trusted-volume-root + - /state - --socket - /ipc/agenticd.sock - --allowed-uid @@ -91,6 +101,7 @@ Both emptyDirs are tmpfs; durability lives in GCS. Because `/.agentic/sche | Input | Meaning | Default | |---|---|---| | `--allowed-uid ` | Uid allowed on the socket; repeatable. Required unless `--insecure-allow-any-uid` is passed (ADR-0012). | _none_; startup fails | +| `--trusted-volume-root ` | Ancestor of `--repo` that the operator asserts only agenticd can write; exempt from the ancestor write check. Never exempts the repo. | _none_ | | `--postgres-url-file ` | File holding the Postgres URL; surrounding whitespace is trimmed and an empty file is an error. Conflicts with `--postgres`. | _none_ | | `AGENTIC_GCS_TOKEN_FILE` | Path to a file holding the GCS bearer token, trimmed the same way. Setting it together with `AGENTIC_GCS_TOKEN` is an error. | _none_ | | `AGENTIC_GCS_ENDPOINT` | Override GCS host (for `tests/fixtures/fake-gcs.yml`) | public GCS | diff --git a/examples/langgraph-rollback/scripts/run-demo.sh b/examples/langgraph-rollback/scripts/run-demo.sh index 3c8cb7b2..1e042761 100755 --- a/examples/langgraph-rollback/scripts/run-demo.sh +++ b/examples/langgraph-rollback/scripts/run-demo.sh @@ -105,6 +105,9 @@ step "3. building + starting agenticd" ( cd "${REPO_ROOT}" && cargo build --release -p agenticd -p agentic-cli >/dev/null ) rm -rf "${DEMO_DIR}/.agentic" "${AGENTIC_BIN}" --repo "${DEMO_DIR}" init >/dev/null +# agenticd refuses a repo or .agentic that is group- or world-writable. +# A checkout or `init` under umask 002 creates them 0775. +chmod go-w "${DEMO_DIR}" "${DEMO_DIR}/.agentic" "${AGENTICD_BIN}" --repo "${DEMO_DIR}" --postgres "${DATABASE_URL}" --tables episodes:id \ --socket "${AGENTIC_SOCKET}" \ --insecure-allow-any-uid \ From 778e2e5879c1d8ff3ad684ef543414f939b55751 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:57:22 +0200 Subject: [PATCH 4/6] Stat the repo chain without following symlinks and fail long socket paths early The ancestor checks read metadata through symlinks, so a component swapped for a link after canonicalization would have been judged by its target. Every entry in the resolved chain, and the child used for the sticky check, is now read with symlink_metadata and refused if it is a symlink. The default socket path is built from the canonical repo again, and a path over the sun_path limit fails at startup with a message that says to pass `--socket`. A trusted volume root now skips only the write-bit checks and must still be owned by the daemon or root. --- crates/agenticd/src/main.rs | 21 +++-- crates/agenticd/src/state_dir.rs | 105 +++++++++++++++++++++-- crates/agenticd/tests/startup_refusal.rs | 15 ++++ docs/integration/executor-sidecar.md | 4 +- 4 files changed, 126 insertions(+), 19 deletions(-) diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index a6d360ec..303f273b 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -359,8 +359,9 @@ async fn main() -> anyhow::Result<()> { // Before anything reads or writes state: the daemon must own the repo // and `.agentic` (see state_dir.rs). Runs before the object store opens // so no state is created under a directory we then refuse. - // The canonical path is used from here on so the checked path cannot - // be redirected through a symlink afterwards. + // `repo` is the canonical path and is used for all state and the default + // socket from here on, so the checked path cannot be redirected through + // a symlink afterwards. `args.repo` is only the operator's spelling. let repo = agenticd::state_dir::secure_state_dir(&args.repo, args.trusted_volume_root.as_deref())?; @@ -412,12 +413,16 @@ async fn main() -> anyhow::Result<()> { // failure, etc.) would leave a stale socket lying around and clients // / health checks would see ECONNREFUSED on connect instead of the // honest ENOENT. (Copilot review on PR #50, third pass.) - let socket_path = args - .socket - .clone() - // Built from the repo as given, not the canonical path, so a deep - // checkout is not pushed past the Unix socket path limit. - .unwrap_or_else(|| args.repo.join(".agentic").join("agenticd.sock")); + let socket_path = match args.socket.clone() { + Some(p) => p, + None => { + let p = agentic_dir.join("agenticd.sock"); + // A deep canonical path can exceed sun_path; say how to fix it + // instead of failing later in bind. + agenticd::state_dir::check_default_socket_len(&p)?; + p + } + }; if let Some(parent) = socket_path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("creating socket parent directory {}", parent.display()))?; diff --git a/crates/agenticd/src/state_dir.rs b/crates/agenticd/src/state_dir.rs index 363470ac..59ac2609 100644 --- a/crates/agenticd/src/state_dir.rs +++ b/crates/agenticd/src/state_dir.rs @@ -50,7 +50,7 @@ pub fn secure_state_dir(repo: &Path, trusted_root: Option<&Path>) -> anyhow::Res }) .transpose()?; - let repo_meta = std::fs::metadata(&repo).with_context(|| format!("stat {}", repo.display()))?; + let repo_meta = lstat_no_symlink(&repo)?; if repo_meta.uid() != euid { bail!( "repo directory {} is owned by uid {}, not the daemon's uid {euid}; refusing to start", @@ -71,13 +71,10 @@ pub fn secure_state_dir(repo: &Path, trusted_root: Option<&Path>) -> anyhow::Res let chain: Vec<&Path> = repo.ancestors().collect(); for pair in chain.windows(2) { let (child, dir) = (pair[0], pair[1]); - if trusted_root.as_deref() == Some(dir) { - continue; - } - let m = std::fs::metadata(dir).with_context(|| format!("stat {}", dir.display()))?; - let child_m = - std::fs::metadata(child).with_context(|| format!("stat {}", child.display()))?; - if let Some(why) = ancestor_writable_by_others(&m, &child_m, euid, egid) { + let m = lstat_no_symlink(dir)?; + let child_m = lstat_no_symlink(child)?; + let trusted = trusted_root.as_deref() == Some(dir); + if let Some(why) = ancestor_writable_by_others(&m, &child_m, euid, egid, trusted) { bail!( "{} {why}; another uid could replace the daemon's state, refusing to start \ (if only agenticd mounts this directory, pass --trusted-volume-root)", @@ -126,10 +123,28 @@ pub fn secure_state_dir(repo: &Path, trusted_root: Option<&Path>) -> anyhow::Res Ok(repo) } +/// `symlink_metadata` that refuses a symlink. After canonicalize no +/// component of the repo path can be one, so a symlink means it was swapped +/// since, and following it would check the wrong directory. The entry's own +/// uid and mode are what matter, never its target's. +#[cfg(unix)] +fn lstat_no_symlink(p: &Path) -> anyhow::Result { + use anyhow::Context; + let m = std::fs::symlink_metadata(p).with_context(|| format!("stat {}", p.display()))?; + anyhow::ensure!( + !m.file_type().is_symlink(), + "{} is a symlink in the resolved repo path; refusing to start", + p.display() + ); + Ok(m) +} + /// Whether a principal other than the daemon (and root) could add, remove /// or rename `child` through this strict ancestor, with a reason if so. /// /// - Owned by neither the daemon nor root: the owner can chmod and write. +/// This applies even to a `trusted` ancestor (`--trusted-volume-root`), +/// which skips only the checks below. /// - Sticky: exempt from the group and other write checks, because a /// sticky directory (a root-owned `/tmp`) only lets an entry's owner /// rename or remove it. That holds only if `child` is owned by the daemon @@ -145,11 +160,14 @@ fn ancestor_writable_by_others( child: &std::fs::Metadata, euid: u32, egid: u32, + trusted: bool, ) -> Option<&'static str> { use std::os::unix::fs::MetadataExt; let mode = m.mode(); if m.uid() != euid && m.uid() != 0 { Some("is owned by another uid") + } else if trusted { + None } else if mode & 0o1000 != 0 { (child.uid() != euid && child.uid() != 0) .then_some("is sticky but its child on the path to the repo is owned by another uid") @@ -162,6 +180,31 @@ fn ancestor_writable_by_others( } } +/// Refuse a default socket path that `bind` would reject for length +/// (`sun_path` is 104 bytes on macOS, 108 on Linux, and must leave room for +/// the NUL), with an error that says what to do about it. +#[cfg(unix)] +pub fn check_default_socket_len(path: &Path) -> anyhow::Result<()> { + use std::os::unix::ffi::OsStrExt; + // SAFETY: sockaddr_un is plain data; all-zero is a valid value. + let limit = unsafe { std::mem::zeroed::() } + .sun_path + .len(); + let len = path.as_os_str().as_bytes().len(); + anyhow::ensure!( + len < limit, + "default socket path {} is {len} bytes, over the {} byte limit; pass --socket ", + path.display(), + limit - 1 + ); + Ok(()) +} + +#[cfg(not(unix))] +pub fn check_default_socket_len(_path: &Path) -> anyhow::Result<()> { + Ok(()) +} + #[cfg(not(unix))] pub fn secure_state_dir(repo: &Path, _trusted_root: Option<&Path>) -> anyhow::Result { Ok(repo.to_path_buf()) @@ -170,7 +213,7 @@ pub fn secure_state_dir(repo: &Path, _trusted_root: Option<&Path>) -> anyhow::Re #[cfg(all(test, unix))] mod tests { use super::*; - use std::os::unix::fs::PermissionsExt; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; fn set_mode(p: &Path, mode: u32) { std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)).unwrap(); @@ -273,6 +316,50 @@ mod tests { secure_state_dir(&repo, None).unwrap(); } + #[test] + fn long_default_socket_path_gets_actionable_error() { + let t = tempfile::tempdir().unwrap(); + let repo = secure_state_dir(&t.path().join("a".repeat(120)), None).unwrap(); + let sock = repo.join(".agentic").join("agenticd.sock"); + let err = check_default_socket_len(&sock).unwrap_err().to_string(); + assert!(err.contains("--socket "), "{err}"); + assert!(check_default_socket_len(Path::new("/tmp/x.sock")).is_ok()); + } + + #[test] + fn chain_entries_that_are_symlinks_are_refused() { + let t = tempfile::tempdir().unwrap(); + let real = t.path().join("real"); + std::fs::create_dir(&real).unwrap(); + let link = t.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let err = lstat_no_symlink(&link).unwrap_err().to_string(); + assert!(err.contains("is a symlink"), "{err}"); + assert!(lstat_no_symlink(&real).is_ok()); + // A symlinked repo path is fine: it is resolved before the checks. + let repo = secure_state_dir(&link.join("repo"), None).unwrap(); + assert!(repo.starts_with(std::fs::canonicalize(&real).unwrap())); + } + + #[test] + fn trusted_flag_skips_write_bits_but_not_ownership() { + let (_t, outer, repo) = nested(0o777); + let m = std::fs::symlink_metadata(&outer).unwrap(); + let child = std::fs::symlink_metadata(repo.parent().unwrap()).unwrap(); + // SAFETY: getegid cannot fail. + let (uid, egid) = (m.uid(), unsafe { libc::getegid() }); + assert!(ancestor_writable_by_others(&m, &child, uid, egid, false).is_some()); + assert!(ancestor_writable_by_others(&m, &child, uid, egid, true).is_none()); + if uid != 0 { + // A daemon whose euid is neither the owner nor root. + let other = uid + 1; + assert_eq!( + ancestor_writable_by_others(&m, &child, other, egid, true), + Some("is owned by another uid") + ); + } + } + #[test] fn trusted_root_exempts_only_that_ancestor() { let (_t, outer, repo) = nested(0o777); diff --git a/crates/agenticd/tests/startup_refusal.rs b/crates/agenticd/tests/startup_refusal.rs index b777143c..e771c4f4 100644 --- a/crates/agenticd/tests/startup_refusal.rs +++ b/crates/agenticd/tests/startup_refusal.rs @@ -212,6 +212,21 @@ mod state_dir { } } + #[test] + fn long_canonical_repo_path_gets_socket_flag_hint() { + let t = tempfile::tempdir().unwrap(); + let repo = t.path().join("a".repeat(120)); + let out = Command::new(agenticd_bin()) + .arg("--repo") + .arg(&repo) + .arg("--insecure-allow-any-uid") + .output() + .expect("run agenticd"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("--socket "), "{stderr}"); + } + #[test] fn startup_removes_dangling_symlink_at_socket_path() { let repo = tempfile::tempdir().unwrap(); diff --git a/docs/integration/executor-sidecar.md b/docs/integration/executor-sidecar.md index 8c3c73b7..e3b7246f 100644 --- a/docs/integration/executor-sidecar.md +++ b/docs/integration/executor-sidecar.md @@ -29,12 +29,12 @@ The worker runs model-driven code and is treated as adversarial. The layout belo Otherwise it creates `.agentic` at mode 0700 or tightens an existing one to 0700. - Group-write with the daemon's own gid is allowed on ancestors, so user-private-group checkouts under umask 002 keep working. The residual is that the worker must not share the daemon's primary group (the sidecar image uses gid 65532). -- `--trusted-volume-root ` exempts one ancestor, matched by canonical path, from the ancestor check. Use it when only agenticd mounts that directory. Kubernetes-style emptyDir roots are often world-writable, and without the flag the daemon refuses to start. It never exempts the repo itself. +- `--trusted-volume-root ` exempts one ancestor, matched by canonical path, from the ancestor check. Use it when only agenticd mounts that directory. Kubernetes-style emptyDir roots are often world-writable, and without the flag the daemon refuses to start. It skips only the write-bit checks, so the directory must still be owned by the daemon or root, and it never exempts the repo itself. Drop the flag whenever the worker mounts the state volume, even read-only. - The socket path lives on the shared volume, so the worker can replace or remove the socket file. Nothing other than the worker's own client should trust that path. - Refs, objects, the GCS cache and `schema/*.down.sql` live in `.agentic`, so the worker cannot edit them. If the worker must read the prompts that rollback restores, mount the `state` volume into the worker read-only. Do not mount it writable. - Credentials arrive as files from Secret Manager volumes mounted into the `agenticd` container only. This removes the argv and environment exposure. It does not isolate the secrets from the worker: all containers in one Cloud Run instance share the service identity, so the worker can fetch the same secrets or call the bucket directly. Real isolation needs a separate identity for the sidecar (ADR-0015, Proposed). -**Not verified on Cloud Run.** We have not confirmed the owner and mode of an emptyDir volume root, or whether it can be mounted read-only into one container. If the root is world-writable, the daemon refuses to start unless you pass `--trusted-volume-root /state`. Pass it only because the `state` volume is mounted into the `agenticd` container alone. Test the exact deployment before relying on it. +**Not verified on Cloud Run.** We have not confirmed the owner and mode of an emptyDir volume root, or whether it can be mounted read-only into one container. If the root is world-writable, the daemon refuses to start unless you pass `--trusted-volume-root /state`. Pass it only because the `state` volume is mounted into the `agenticd` container alone; drop it if you give the worker the read-only prompt mount. Test the exact deployment before relying on it. ## Cloud Run service definition (excerpt) From 323eea85e4504cddf46b71a714c031998b2611cb Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 09:59:59 +0200 Subject: [PATCH 5/6] Hint the trusted volume flag only where it helps An ownership refusal cannot be fixed with --trusted-volume-root, so do not suggest it there. --- crates/agenticd/src/state_dir.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/agenticd/src/state_dir.rs b/crates/agenticd/src/state_dir.rs index 59ac2609..70427ac0 100644 --- a/crates/agenticd/src/state_dir.rs +++ b/crates/agenticd/src/state_dir.rs @@ -75,9 +75,14 @@ pub fn secure_state_dir(repo: &Path, trusted_root: Option<&Path>) -> anyhow::Res let child_m = lstat_no_symlink(child)?; let trusted = trusted_root.as_deref() == Some(dir); if let Some(why) = ancestor_writable_by_others(&m, &child_m, euid, egid, trusted) { + // The flag cannot fix an ownership refusal, so only hint it otherwise. + let hint = if m.uid() != euid && m.uid() != 0 { + "" + } else { + " (if only agenticd mounts this directory, pass --trusted-volume-root)" + }; bail!( - "{} {why}; another uid could replace the daemon's state, refusing to start \ - (if only agenticd mounts this directory, pass --trusted-volume-root)", + "{} {why}; another uid could replace the daemon's state, refusing to start{hint}", dir.display() ); } From 047ff8bcbe87f698261bb831f605b5fcb3b6b0dd Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Fri, 20 Nov 2026 10:08:30 +0200 Subject: [PATCH 6/6] Require --socket when the allowlist names another uid The default socket lives in the 0700 state directory, which another uid cannot traverse, so an allowed worker could never connect. Refuse at startup with an actionable error instead. --- crates/agenticd/src/main.rs | 17 +++++++++++++++++ crates/agenticd/tests/startup_refusal.rs | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/crates/agenticd/src/main.rs b/crates/agenticd/src/main.rs index 303f273b..867f207b 100644 --- a/crates/agenticd/src/main.rs +++ b/crates/agenticd/src/main.rs @@ -416,6 +416,23 @@ async fn main() -> anyhow::Result<()> { let socket_path = match args.socket.clone() { Some(p) => p, None => { + // The default socket sits inside the 0700 state directory, which + // another uid cannot traverse; an allowlist naming one needs an + // explicit socket outside it. + #[cfg(unix)] + { + // SAFETY: geteuid cannot fail. + let euid = unsafe { libc::geteuid() }; + if matches!(&peer_auth, PeerAuthPolicy::Allowlist(uids) if uids.iter().any(|u| *u != euid)) + { + anyhow::bail!( + "--allowed-uid names a uid other than the daemon's, but the default socket \ + lives in the private {} directory that uid cannot reach; pass --socket \ + ", + agentic_dir.display() + ); + } + } let p = agentic_dir.join("agenticd.sock"); // A deep canonical path can exceed sun_path; say how to fix it // instead of failing later in bind. diff --git a/crates/agenticd/tests/startup_refusal.rs b/crates/agenticd/tests/startup_refusal.rs index e771c4f4..66c64a36 100644 --- a/crates/agenticd/tests/startup_refusal.rs +++ b/crates/agenticd/tests/startup_refusal.rs @@ -285,6 +285,24 @@ mod state_dir { } } +#[cfg(unix)] +#[test] +fn startup_requires_socket_flag_when_allowlist_names_another_uid() { + // SAFETY: geteuid cannot fail. + let other = (unsafe { libc::geteuid() } + 1).to_string(); + let repo = tempfile::tempdir().unwrap(); + let out = Command::new(agenticd_bin()) + .arg("--repo") + .arg(repo.path()) + .arg("--allowed-uid") + .arg(&other) + .output() + .expect("run agenticd"); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("pass --socket"), "got: {stderr}"); +} + #[test] fn startup_refuses_postgres_url_and_file_together() { let out = Command::new(agenticd_bin())