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
16 changes: 12 additions & 4 deletions crates/agenticd/src/state_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,14 @@ mod tests {
.find(|g| *g != egid)
}

/// A repo dir pinned to 0700: `tempfile::tempdir()` follows the umask
/// (0775 under umask 002), which `secure_state_dir` refuses.
fn private_tmp() -> tempfile::TempDir {
let t = tempfile::tempdir().unwrap();
set_mode(t.path(), 0o700);
t
}

/// `<tmp>/outer/repo`, with `outer` set to `outer_mode` first.
fn nested(outer_mode: u32) -> (tempfile::TempDir, PathBuf, PathBuf) {
let t = tempfile::tempdir().unwrap();
Expand All @@ -252,15 +260,15 @@ mod tests {

#[test]
fn creates_state_dir_0700_and_returns_canonical_path() {
let t = tempfile::tempdir().unwrap();
let t = private_tmp();
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 t = private_tmp();
let d = t.path().join(".agentic");
std::fs::create_dir(&d).unwrap();
set_mode(&d, 0o755);
Expand All @@ -271,7 +279,7 @@ mod tests {
#[test]
fn refuses_group_or_world_writable_state_dir() {
for m in [0o775, 0o777] {
let t = tempfile::tempdir().unwrap();
let t = private_tmp();
let d = t.path().join(".agentic");
std::fs::create_dir(&d).unwrap();
set_mode(&d, m);
Expand Down Expand Up @@ -416,7 +424,7 @@ mod tests {

#[test]
fn refuses_symlinked_state_dir() {
let t = tempfile::tempdir().unwrap();
let t = private_tmp();
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();
Expand Down
30 changes: 28 additions & 2 deletions crates/agenticd/tests/approval_key_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,32 @@ fn spawn_daemon_with(
.expect("spawn agenticd")
}

async fn send(sock: &std::path::Path, request: Request) -> Response {
let conn = UnixStream::connect(sock).await.unwrap();
/// The socket file appears at bind(), before listen(), so it existing does not
/// mean connect() succeeds yet. Retry a refused connect for a bounded time.
async fn connect_when_ready(sock: &std::path::Path) -> UnixStream {
let deadline = Instant::now() + Duration::from_secs(20);
loop {
match UnixStream::connect(sock).await {
Ok(conn) => return conn,
Err(e)
if e.kind() == std::io::ErrorKind::ConnectionRefused
&& Instant::now() < deadline =>
{
tokio::time::sleep(Duration::from_millis(25)).await;
}
Err(e) => panic!("daemon never accepted a connection: {e}"),
}
}
}

/// `first`: only the first request of a test waits for the daemon to start
/// accepting; later ones must connect on the first attempt.
async fn send(sock: &std::path::Path, request: Request, first: bool) -> Response {
let conn = if first {
connect_when_ready(sock).await
} else {
UnixStream::connect(sock).await.expect("connect")
};
let (r, w) = conn.into_split();
let mut r = tokio::io::BufReader::new(r);
let mut w = tokio::io::BufWriter::new(w);
Expand Down Expand Up @@ -112,6 +136,7 @@ async fn rollback_error_code_with(repo: &std::path::Path, extra: &[&std::ffi::Os
model: None,
no_memory: true,
}),
true,
)
.await
else {
Expand All @@ -125,6 +150,7 @@ async fn rollback_error_code_with(repo: &std::path::Path, extra: &[&std::ffi::Os
accept_data_loss: true,
approval_token: None,
},
false,
)
.await;
let _ = child.kill();
Expand Down
54 changes: 45 additions & 9 deletions crates/agenticd/tests/socket_limits_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ fn agenticd_bin() -> std::path::PathBuf {
env!("CARGO_BIN_EXE_agenticd").into()
}

/// Temp dir pinned to 0700: the daemon refuses a group-writable repo, and
/// `TempDir::new` follows the umask (0775 under umask 002).
fn private_dir() -> TempDir {
use std::os::unix::fs::PermissionsExt;
let dir = TempDir::new().unwrap();
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
dir
}

/// Reaps the spawned daemon on drop so a failing assertion can't leak
/// an orphaned agenticd process holding the test socket.
struct DaemonProc(Child);
Expand All @@ -40,7 +49,8 @@ async fn spawn_daemon(dir: &TempDir, extra_args: &[&str]) -> (DaemonProc, std::p
cmd.arg(a);
}
let child = DaemonProc(cmd.spawn().expect("spawn agenticd"));
for _ in 0..50 {
// Generous: startup on a loaded machine can take seconds.
for _ in 0..400 {
if sock.exists() {
break;
}
Expand All @@ -50,9 +60,35 @@ async fn spawn_daemon(dir: &TempDir, extra_args: &[&str]) -> (DaemonProc, std::p
(child, sock)
}

/// Connect, retrying while the daemon is not yet accepting. The socket file
/// appears at bind(), before listen(), so its existence does not mean
/// connect() succeeds. A refused connect is never admitted, so retrying it
/// cannot count against the connection caps under test.
async fn connect_when_ready(sock: &std::path::Path) -> UnixStream {
let deadline = tokio::time::Instant::now() + Duration::from_secs(20);
loop {
match UnixStream::connect(sock).await {
Ok(conn) => return conn,
Err(e)
if e.kind() == std::io::ErrorKind::ConnectionRefused
&& tokio::time::Instant::now() < deadline =>
{
tokio::time::sleep(Duration::from_millis(25)).await;
}
Err(e) => panic!("daemon never accepted a connection: {e}"),
}
}
}

/// Open a connection and prove it is live with a Ping/Pong round trip.
async fn connect_and_ping(sock: &std::path::Path, tag: &str) -> UnixStream {
let mut conn = UnixStream::connect(sock).await.expect("connect");
/// `first`: only the first connection of a test waits for the daemon to start
/// accepting; later ones must connect on the first attempt.
async fn connect_and_ping(sock: &std::path::Path, tag: &str, first: bool) -> UnixStream {
let mut conn = if first {
connect_when_ready(sock).await
} else {
UnixStream::connect(sock).await.expect("connect")
};
write_frame(&mut conn, &Envelope::new(tag.to_string(), Request::Ping))
.await
.expect("write ping");
Expand Down Expand Up @@ -92,11 +128,11 @@ async fn assert_dropped(sock: &std::path::Path) {

#[tokio::test]
async fn global_connection_cap_drops_excess_and_spares_existing() {
let dir = TempDir::new().unwrap();
let dir = private_dir();
let (_daemon, sock) = spawn_daemon(&dir, &["--max-connections", "2"]).await;

let mut c1 = connect_and_ping(&sock, "c1").await;
let _c2 = connect_and_ping(&sock, "c2").await;
let mut c1 = connect_and_ping(&sock, "c1", true).await;
let _c2 = connect_and_ping(&sock, "c2", false).await;

// Third connection is over the global cap: dropped at accept.
assert_dropped(&sock).await;
Expand All @@ -114,7 +150,7 @@ async fn global_connection_cap_drops_excess_and_spares_existing() {

#[tokio::test]
async fn per_uid_connection_cap_drops_excess() {
let dir = TempDir::new().unwrap();
let dir = private_dir();
// Global cap far above the per-UID cap so the per-UID path is the
// one that trips: every connection here shares the test's UID.
let (_daemon, sock) = spawn_daemon(
Expand All @@ -123,13 +159,13 @@ async fn per_uid_connection_cap_drops_excess() {
)
.await;

let _c1 = connect_and_ping(&sock, "c1").await;
let _c1 = connect_and_ping(&sock, "c1", true).await;
assert_dropped(&sock).await;
}

#[tokio::test]
async fn zero_limit_refuses_startup() {
let dir = TempDir::new().unwrap();
let dir = private_dir();
let sock = dir.path().join("agenticd.sock");
let mut child = Command::new(agenticd_bin())
.arg("--repo")
Expand Down
28 changes: 19 additions & 9 deletions crates/agenticd/tests/startup_refusal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,19 @@ fn startup_refuses_when_both_flags_set() {
);
}

/// A repo dir with mode pinned to 0700. `tempfile::tempdir()` follows the
/// umask (0775 under umask 002), which the daemon refuses as group-writable.
#[cfg(unix)]
fn private_repo() -> tempfile::TempDir {
use std::os::unix::fs::PermissionsExt;
let repo = tempfile::tempdir().unwrap();
std::fs::set_permissions(repo.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
repo
}

#[cfg(unix)]
mod state_dir {
use super::agenticd_bin;
use super::{agenticd_bin, private_repo};
use std::os::unix::fs::PermissionsExt;
use std::process::Command;

Expand Down Expand Up @@ -189,7 +199,7 @@ mod state_dir {

#[test]
fn startup_tightens_0755_state_dir_to_0700() {
let repo = tempfile::tempdir().unwrap();
let repo = private_repo();
let state = repo.path().join(".agentic");
std::fs::create_dir(&state).unwrap();
set_mode(&state, 0o755);
Expand All @@ -200,7 +210,7 @@ mod state_dir {
#[test]
fn refuses_existing_writable_state_dir() {
for m in [0o775, 0o777] {
let repo = tempfile::tempdir().unwrap();
let repo = private_repo();
let state = repo.path().join(".agentic");
std::fs::create_dir(&state).unwrap();
set_mode(&state, m);
Expand Down Expand Up @@ -229,8 +239,8 @@ mod state_dir {

#[test]
fn startup_removes_dangling_symlink_at_socket_path() {
let repo = tempfile::tempdir().unwrap();
let sock_dir = tempfile::tempdir().unwrap();
let repo = private_repo();
let sock_dir = private_repo();
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();
Expand Down Expand Up @@ -268,18 +278,18 @@ mod state_dir {
let other = (euid + 1).to_string();
let own = euid.to_string();

let repo = tempfile::tempdir().unwrap();
let repo = private_repo();
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 repo = private_repo();
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 repo = private_repo();
let (sock_mode, _) = run_and_stat(repo.path(), &["--insecure-allow-any-uid"]);
assert_eq!(sock_mode, 0o755);
}
Expand All @@ -290,7 +300,7 @@ mod state_dir {
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 repo = private_repo();
let out = Command::new(agenticd_bin())
.arg("--repo")
.arg(repo.path())
Expand Down
Loading