Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion crates/agentic-core/src/gcs_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ struct Downloaded {
generation: Option<String>,
}

#[derive(Debug, Clone)]
#[derive(Clone)]
pub struct GcsObjectStore {
bucket: String,
/// Object-name prefix inside the bucket. Lets a single bucket host
Expand All @@ -110,6 +110,22 @@ pub struct GcsObjectStore {
allowlist: Arc<Allowlist>,
}

/// 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(|_| "<redacted>"),
)
.finish_non_exhaustive()
}
}

impl GcsObjectStore {
pub fn new(
bucket: impl Into<String>,
Expand Down
3 changes: 3 additions & 0 deletions crates/agenticd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions crates/agenticd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
101 changes: 90 additions & 11 deletions crates/agenticd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ struct Args {
#[arg(long)]
postgres: Option<String>,

/// 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<PathBuf>,

/// Comma-separated `table:pk` pairs to track. Required when
/// `--postgres` is set. Example: `episodes:id,user_facts:id`.
#[arg(long, value_delimiter = ',')]
Expand All @@ -86,12 +91,21 @@ struct Args {
#[arg(long, value_delimiter = ',')]
mcp: Vec<String>,

/// 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<PathBuf>,

/// Object-store backend. `fs` (default) uses `<repo>/.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,

Expand Down Expand Up @@ -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<UnixListener> {
#[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()
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -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 \
<path outside .agentic>",
agentic_dir.display()
);
}
}
let p = agentic_dir.join("agenticd.sock");
Comment thread
tonibergholm-codento marked this conversation as resolved.
Resolved
// 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()))?;
}
Expand All @@ -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),
Expand All @@ -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"
);

Expand Down
32 changes: 31 additions & 1 deletion crates/agenticd/src/membackend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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", &"<redacted>")
.field("tables", tables)
.finish(),
}
}
}

impl MemoryBackendSpec {
/// Derive the spec from the daemon's CLI configuration. Preserves
/// the pre-factory behavior exactly: `--postgres` present requires
Expand Down Expand Up @@ -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();
Expand Down
24 changes: 21 additions & 3 deletions crates/agenticd/src/objstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}"))?
Expand All @@ -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();
Expand Down
Loading
Loading