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..867f207b 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 = ',')] @@ -86,12 +91,21 @@ 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 /// 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, @@ -252,6 +266,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() @@ -316,7 +356,21 @@ async fn main() -> anyhow::Result<()> { "socket limits in force" ); - let agentic_dir = args.repo.join(".agentic"); + // 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. + // `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())?; + + let postgres_url = agenticd::secrets::resolve_postgres_url( + args.postgres.as_deref(), + args.postgres_url_file.as_deref(), + )?; + + let agentic_dir = repo.join(".agentic"); let tables = parse_tracked_tables(&args.tables)?; let mcp_servers = parse_mcp_spec(&args.mcp)?; @@ -359,15 +413,40 @@ 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() - .unwrap_or_else(|| agentic_dir.join("agenticd.sock")); + 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. + 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()))?; } - 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()))?; } @@ -389,10 +468,10 @@ 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, - args.postgres.as_deref(), + postgres_url.as_deref(), tables, mcp_servers, Arc::clone(&peer_auth), @@ -403,12 +482,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()))?; tracing::info!( socket = %socket_path.display(), - repo = %args.repo.display(), + repo = %repo.display(), "agenticd listening" ); 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..70427ac0 --- /dev/null +++ b/crates/agenticd/src/state_dir.rs @@ -0,0 +1,425 @@ +//! 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`, 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 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. +//! +//! The worker may read `/prompts`, but must run as a different uid. + +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. +/// `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, trusted_root: Option<&Path>) -> anyhow::Result { + use anyhow::{bail, Context}; + use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; + + // 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()))?; + // 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 trusted_root = trusted_root + .map(|t| { + std::fs::canonicalize(t) + .with_context(|| format!("resolving --trusted-volume-root {}", t.display())) + }) + .transpose()?; + + 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", + repo.display(), + repo_meta.uid() + ); + } + // 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]); + 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) { + // 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{hint}", + dir.display() + ); + } + } + + 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() + ); + } + // 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()))?; + } + } + 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(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 +/// 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 ancestor_writable_by_others( + m: &std::fs::Metadata, + 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") + } 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") + } else { + None + } +} + +/// 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()) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + 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(); + } + + fn mode(p: &Path) -> u32 { + 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(); + 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_and_returns_canonical_path() { + let t = tempfile::tempdir().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); + } + + #[test] + fn tightens_existing_0755_state_dir() { + let t = tempfile::tempdir().unwrap(); + let d = t.path().join(".agentic"); + std::fs::create_dir(&d).unwrap(); + set_mode(&d, 0o755); + secure_state_dir(t.path(), None).unwrap(); + assert_eq!(mode(&d), 0o700); + } + + #[test] + 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(), None).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(); + set_mode(t.path(), 0o777); + 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 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); + 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, None).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, None).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, None).unwrap(); + } + + #[test] + fn refuses_group_writable_ancestor_with_foreign_gid() { + 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() { + return; + } + let err = secure_state_dir(&repo, None).unwrap_err().to_string(); + assert!(err.contains("group other than"), "{err}"); + } + + #[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(), 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 69d44b5b..66c64a36 100644 --- a/crates/agenticd/tests/startup_refusal.rs +++ b/crates/agenticd/tests/startup_refusal.rs @@ -61,3 +61,259 @@ 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(); + } + + /// 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(); + let mut child = Command::new(agenticd_bin()) + .arg("--repo") + .arg(repo) + .arg("--socket") + .arg(sock.path().join("d.sock")) + .arg("--insecure-allow-any-uid") + .stderr(Stdio::piped()) + .spawn() + .expect("run agenticd"); + 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!( + 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!( + !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}" + ); + } + + /// 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 mut cmd = Command::new(agenticd_bin()); + cmd.arg("--repo") + .arg(repo) + .arg("--socket") + .arg(&sock) + .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 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(); + ( + 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 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(); + 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. + 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); + } +} + +#[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()) + .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..e3b7246f 100644 --- a/docs/integration/executor-sidecar.md +++ b/docs/integration/executor-sidecar.md @@ -15,6 +15,27 @@ 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. 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. 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 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 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; 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) ```yaml @@ -24,41 +45,72 @@ 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 } + - { 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 + - --trusted-volume-root + - /state - --socket - - /shared/agenticd.sock + - /ipc/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: 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: + 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 +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. -| Variable | Meaning | Default | +## 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 | +| `--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 | -| `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 `/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 @@ -74,12 +126,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/.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. 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 \