diff --git a/packages/paperclip-runner/runner/Cargo.lock b/packages/paperclip-runner/runner/Cargo.lock index 9d4d7de39e1..c37f8a370b4 100644 --- a/packages/paperclip-runner/runner/Cargo.lock +++ b/packages/paperclip-runner/runner/Cargo.lock @@ -1855,6 +1855,7 @@ dependencies = [ "serde_json", "sha1 0.10.7", "sha2 0.10.9", + "time", "tokio", "toml_edit", "tungstenite", diff --git a/packages/paperclip-runner/runner/Cargo.toml b/packages/paperclip-runner/runner/Cargo.toml index 05e26ff4236..efe441d2d5e 100644 --- a/packages/paperclip-runner/runner/Cargo.toml +++ b/packages/paperclip-runner/runner/Cargo.toml @@ -37,5 +37,6 @@ rustix = { version = "1.1", features = ["fs", "net", "process"] } sha1 = "0.10" tungstenite = { version = "0.28", default-features = false, features = ["handshake", "rustls-tls-native-roots"] } toml_edit = "0.22" +time = { version = "0.3.55", default-features = false, features = ["parsing"] } tokio = { version = "1.50", features = ["rt-multi-thread", "sync", "time"] } uuid = { version = "1.22", features = ["v4"] } diff --git a/packages/paperclip-runner/runner/crates/runner-core/Cargo.toml b/packages/paperclip-runner/runner/crates/runner-core/Cargo.toml index 6a8771d229a..fe2828ee169 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/Cargo.toml +++ b/packages/paperclip-runner/runner/crates/runner-core/Cargo.toml @@ -32,6 +32,7 @@ rustix.workspace = true sha1.workspace = true tungstenite.workspace = true toml_edit.workspace = true +time.workspace = true tokio.workspace = true uuid.workspace = true diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs b/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs new file mode 100644 index 00000000000..f8e99618116 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/src/credential_write_back.rs @@ -0,0 +1,350 @@ +use std::fs::{self, File}; +use std::io::{self, Read}; +use std::path::Path; + +use serde_json::Value; + +pub(crate) const ACPX_AUTH_JSON_FILE_ENV: &str = "PAPERCLIP_ACPX_AUTH_JSON_FILE"; + +const MAX_BYTES: u64 = 256 * 1024; +const MAX_FUTURE_LAST_REFRESH_SKEW_MS: f64 = 5.0 * 60.0 * 1000.0; +const MAX_PLAUSIBLE_EXPIRY_MS: f64 = 400.0 * 24.0 * 60.0 * 60.0 * 1000.0; +const EPOCH_SECONDS_MAX: f64 = 1e12; + +#[derive(Debug, PartialEq)] +enum Expiry { + Absent, + Unreadable, + At(f64), +} + +#[derive(Debug, PartialEq)] +enum Freshness { + Unusable, + ApiKey, + Codex { + account: String, + last_refresh: Option, + }, + Grok { + identity: String, + expires: Expiry, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct HostStamp { + dev: u64, + ino: u64, + len: u64, + mtime: (i64, i64), + ctime: (i64, i64), +} + +#[cfg(unix)] +impl HostStamp { + fn of(metadata: &fs::Metadata) -> Self { + use std::os::unix::fs::MetadataExt; + Self { + dev: metadata.dev(), + ino: metadata.ino(), + len: metadata.len(), + mtime: (metadata.mtime(), metadata.mtime_nsec()), + ctime: (metadata.ctime(), metadata.ctime_nsec()), + } + } +} + +#[cfg(unix)] +pub(crate) fn host_stamp(path: &Path) -> Option { + fs::symlink_metadata(path) + .ok() + .map(|metadata| HostStamp::of(&metadata)) +} + +#[cfg(not(unix))] +pub(crate) fn host_stamp(_path: &Path) -> Option { + None +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum WriteBack { + Written, + Kept(Option), + Raced, +} + +fn nonempty(value: &Value) -> Option<&str> { + value + .as_str() + .map(str::trim) + .filter(|value| !value.is_empty()) +} + +fn freshness(provider: &str, bytes: &[u8]) -> Freshness { + if bytes.len() as u64 > MAX_BYTES { + return Freshness::Unusable; + } + let Ok(value) = serde_json::from_slice::(bytes) else { + return Freshness::Unusable; + }; + let Some(object) = value.as_object() else { + return Freshness::Unusable; + }; + match provider { + "codex" => { + if nonempty(&value["OPENAI_API_KEY"]).is_some() { + return Freshness::ApiKey; + } + let tokens = &value["tokens"]; + if !tokens.is_object() { + return Freshness::Unusable; + } + let Some(account) = nonempty(&tokens["account_id"]) else { + return Freshness::Unusable; + }; + if ["id_token", "access_token", "refresh_token"] + .iter() + .all(|key| nonempty(&tokens[*key]).is_none()) + { + return Freshness::Unusable; + } + Freshness::Codex { + account: account.to_owned(), + last_refresh: value["last_refresh"].as_str().and_then(parse_rfc3339_ms), + } + } + "grok" => { + if object.len() != 1 { + return Freshness::Unusable; + } + let (identity, auth) = object.iter().next().expect("one entry"); + if !is_grok_identity(identity) + || !auth.is_object() + || nonempty(&auth["key"]).is_none() + || nonempty(&auth["refresh_token"]).is_none() + { + return Freshness::Unusable; + } + let expires = match &auth["expires_at"] { + Value::Null => Expiry::Absent, + Value::String(raw) => parse_rfc3339_ms(raw).map_or(Expiry::Unreadable, Expiry::At), + Value::Number(raw) => match raw.as_f64() { + Some(raw) if raw.is_finite() => Expiry::At(if raw < EPOCH_SECONDS_MAX { + raw * 1000.0 + } else { + raw + }), + _ => Expiry::Unreadable, + }, + _ => Expiry::Unreadable, + }; + Freshness::Grok { + identity: identity.clone(), + expires, + } + } + _ => Freshness::Unusable, + } +} + +fn is_grok_identity(key: &str) -> bool { + let bytes = key.as_bytes(); + if bytes.len() < 39 { + return false; + } + let (prefix, suffix) = bytes.split_at(bytes.len() - 38); + let uuid = &suffix[2..]; + let uuid_valid = uuid.iter().enumerate().all(|(index, byte)| { + if matches!(index, 8 | 13 | 18 | 23) { + *byte == b'-' + } else { + byte.is_ascii_hexdigit() + } + }); + let Ok(prefix) = std::str::from_utf8(prefix) else { + return false; + }; + &suffix[..2] == b"::" && uuid_valid && !prefix.contains(['\n', '\r', '\u{2028}', '\u{2029}']) +} + +fn prefer_source(source: &Freshness, destination: &Freshness, now_ms: f64) -> bool { + match (source, destination) { + ( + Freshness::Codex { + account: source_account, + last_refresh: source_refresh, + }, + Freshness::Codex { + account: destination_account, + last_refresh: destination_refresh, + }, + ) if source_account == destination_account => match (source_refresh, destination_refresh) { + (Some(source), Some(destination)) => { + source - now_ms <= MAX_FUTURE_LAST_REFRESH_SKEW_MS && source > destination + } + _ => false, + }, + ( + Freshness::Grok { + identity: source_identity, + expires: source_expiry, + }, + Freshness::Grok { + identity: destination_identity, + expires: destination_expiry, + }, + ) if source_identity == destination_identity => match (source_expiry, destination_expiry) { + (Expiry::At(source), Expiry::At(destination)) => { + source - now_ms <= MAX_PLAUSIBLE_EXPIRY_MS && source > destination + } + _ => false, + }, + _ => false, + } +} + +fn parse_rfc3339_ms(value: &str) -> Option { + let instant = + time::OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339).ok()?; + Some(instant.unix_timestamp_nanos().div_euclid(1_000_000) as f64) +} + +fn invalid(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message.to_owned()) +} + +#[cfg(unix)] +pub(crate) fn read_host_credential(path: &Path) -> io::Result<(Vec, fs::Metadata)> { + use rustix::fs::{open, Mode, OFlags}; + use std::os::unix::fs::MetadataExt; + if !path.is_absolute() { + return Err(invalid("credential file path is not absolute")); + } + let fd = open( + path, + OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, + Mode::empty(), + )?; + let mut file = File::from(fd); + let before = file.metadata()?; + if !before.is_file() + || before.len() == 0 + || before.len() > MAX_BYTES + || before.mode() & 0o077 != 0 + || before.uid() != rustix::process::getuid().as_raw() + { + return Err(invalid( + "credential file is not a private, bounded regular file", + )); + } + let mut bytes = Vec::new(); + let read = (&mut file).take(MAX_BYTES + 1).read_to_end(&mut bytes); + let after = file.metadata()?; + if read.is_err() + || after.len() != bytes.len() as u64 + || before.len() != after.len() + || before.mtime() != after.mtime() + || before.mtime_nsec() != after.mtime_nsec() + { + bytes.fill(0); + return Err(invalid("credential file changed while read")); + } + Ok((bytes, before)) +} + +#[cfg(not(unix))] +pub(crate) fn read_host_credential(_path: &Path) -> io::Result<(Vec, fs::Metadata)> { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "credential files require Unix", + )) +} + +#[cfg(unix)] +pub(crate) fn write_back( + provider: &str, + source: &[u8], + destination: &Path, + now_ms: f64, +) -> io::Result { + let source_freshness = freshness(provider, source); + if matches!(source_freshness, Freshness::Unusable | Freshness::ApiKey) { + return Ok(WriteBack::Kept(None)); + } + let (mut current, metadata) = read_host_credential(destination)?; + let replace = prefer_source(&source_freshness, &freshness(provider, ¤t), now_ms); + current.fill(0); + if !replace { + return Ok(WriteBack::Kept(Some(HostStamp::of(&metadata)))); + } + replace_if_unchanged(source, destination, &metadata) +} + +#[cfg(unix)] +fn replace_if_unchanged( + source: &[u8], + destination: &Path, + metadata: &fs::Metadata, +) -> io::Result { + use std::io::Write; + use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; + + let parent = destination + .parent() + .ok_or_else(|| invalid("credential file has no parent directory"))?; + let name = destination + .file_name() + .ok_or_else(|| invalid("credential file has no name"))? + .to_string_lossy(); + let temporary = parent.join(format!( + ".{name}.{}.{}.paperclip-refresh", + std::process::id(), + uuid::Uuid::new_v4().simple() + )); + let result = (|| -> io::Result { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(rustix::fs::OFlags::NOFOLLOW.bits() as i32) + .open(&temporary)?; + file.set_permissions(fs::Permissions::from_mode(metadata.mode() & 0o7777))?; + file.write_all(source)?; + file.sync_all()?; + drop(file); + if HostStamp::of(&fs::symlink_metadata(destination)?) != HostStamp::of(metadata) { + return Ok(WriteBack::Raced); + } + fs::rename(&temporary, destination)?; + File::open(parent)?.sync_all()?; + Ok(WriteBack::Written) + })(); + if !matches!(result, Ok(WriteBack::Written)) { + let _ = fs::remove_file(&temporary); + } + result +} + +#[cfg(not(unix))] +pub(crate) fn write_back( + _provider: &str, + _source: &[u8], + _destination: &Path, + _now_ms: f64, +) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "credential files require Unix", + )) +} + +pub(crate) fn now_ms() -> f64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0.0, |elapsed| elapsed.as_millis() as f64) +} + +#[cfg(all(test, unix))] +#[path = "tests/credential_write_back.rs"] +mod tests; diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs index 7e903c75105..a7f5a126414 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs @@ -19,6 +19,8 @@ mod codex_startup_trust; mod codex_usage; mod configured_environment; mod credential_observer; +#[allow(dead_code)] +mod credential_write_back; mod cursor_cloud_proxy; pub mod dot_provider_backend; pub mod durable; diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_write_back.rs b/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_write_back.rs new file mode 100644 index 00000000000..094cdf15685 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/src/tests/credential_write_back.rs @@ -0,0 +1,195 @@ +use super::*; +use serde_json::json; +use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt}; +use std::path::PathBuf; + +const NOW: f64 = 1_800_000_000_000.0; +const IDENTITY: &str = "https://issuer.example::12345678-1234-4234-8234-123456789abc"; +const OTHER: &str = "https://issuer.example::87654321-4321-4321-4321-cba987654321"; + +struct Directory(PathBuf); +impl Directory { + fn new() -> Self { + let root = + std::env::temp_dir().join(format!("credential-write-back-{}", uuid::Uuid::new_v4())); + fs::create_dir(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + Self(fs::canonicalize(root).unwrap()) + } + fn write(&self, name: &str, value: &Value, mode: u32) -> PathBuf { + let path = self.0.join(name); + fs::write(&path, bytes(value)).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap(); + path + } + fn entries(&self) -> usize { + fs::read_dir(&self.0).unwrap().count() + } +} +impl Drop for Directory { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn codex(account: &str, last_refresh: &str) -> Value { + json!({"tokens":{"account_id":account, "access_token":"access", "refresh_token":"refresh"}, + "last_refresh": last_refresh}) +} + +fn grok(identity: &str, expires_at: Value) -> Value { + json!({ identity: {"key":"access", "refresh_token":"refresh", "expires_at": expires_at}}) +} + +fn bytes(value: &Value) -> Vec { + serde_json::to_vec(value).unwrap() +} + +#[test] +fn replacement_follows_the_adapter_freshness_rules() { + let codex_host = codex("account-1", "2027-01-15T07:59:00Z"); + let grok_host = grok(IDENTITY, json!(1_800_003_600)); + let api_key = json!({"OPENAI_API_KEY":"key"}); + #[rustfmt::skip] + let cases = [ + ("codex newer", "codex", codex("account-1", "2027-01-15T07:59:59Z"), &codex_host, true), + ("codex newer offset", "codex", codex("account-1", "2027-01-15T09:59:30+02:00"), &codex_host, true), + ("codex within skew", "codex", codex("account-1", "2027-01-15T08:04:00Z"), &codex_host, true), + ("codex implausible", "codex", codex("account-1", "2027-01-15T08:06:00Z"), &codex_host, false), + ("codex older", "codex", codex("account-1", "2027-01-15T07:58:00Z"), &codex_host, false), + ("codex equal", "codex", codex("account-1", "2027-01-15T07:59:00.000999Z"), &codex_host, false), + ("codex other account", "codex", codex("account-2", "2027-01-15T07:59:59Z"), &codex_host, false), + ("codex unparseable", "codex", codex("account-1", "recently"), &codex_host, false), + ("codex api-key source", "codex", api_key.clone(), &codex_host, false), + ("codex api-key host", "codex", codex("account-1", "2027-01-15T07:59:59Z"), &api_key, false), + ("grok newer seconds", "grok", grok(IDENTITY, json!(1_800_003_660)), &grok_host, true), + ("grok newer milliseconds", "grok", grok(IDENTITY, json!(1_800_003_660_000_u64)), &grok_host, true), + ("grok newer ISO", "grok", grok(IDENTITY, json!("2027-01-15T09:01:00Z")), &grok_host, true), + ("grok older", "grok", grok(IDENTITY, json!(1_800_003_540)), &grok_host, false), + ("grok equal", "grok", grok(IDENTITY, json!(1_800_003_600_000_u64)), &grok_host, false), + ("grok other identity", "grok", grok(OTHER, json!(1_800_003_660)), &grok_host, false), + ("grok invalid identity", "grok", grok("issuer:12345678-1234-4234-8234-123456789abc", json!(1_800_003_660)), &grok_host, false), + ("grok missing expiry", "grok", grok(IDENTITY, Value::Null), &grok_host, false), + ("grok unreadable expiry", "grok", grok(IDENTITY, json!("tomorrow")), &grok_host, false), + ("grok implausible", "grok", grok(IDENTITY, json!(1_800_000_000 + 401 * 86_400)), &grok_host, false), + ("grok host expiry missing", "grok", grok(IDENTITY, json!(1_800_003_660)), &grok(IDENTITY, Value::Null), false), + ]; + for (name, provider, source, destination, expected) in cases { + let decision = prefer_source( + &freshness(provider, &bytes(&source)), + &freshness(provider, &bytes(destination)), + NOW, + ); + assert_eq!(decision, expected, "{name}"); + } +} + +#[test] +fn replacement_is_atomic_and_keeps_the_file_mode() { + let directory = Directory::new(); + let host = directory.write( + "auth.json", + &codex("account-1", "2027-01-15T07:59:00Z"), + 0o400, + ); + let before = fs::metadata(&host).unwrap(); + let refreshed = bytes(&codex("account-1", "2027-01-15T07:59:59Z")); + assert_eq!( + write_back("codex", &refreshed, &host, NOW).unwrap(), + WriteBack::Written + ); + let after = fs::metadata(&host).unwrap(); + assert_ne!(after.ino(), before.ino()); + assert_eq!(after.mode() & 0o7777, 0o400); + assert_eq!(after.uid(), before.uid()); + assert_eq!(fs::read(&host).unwrap(), refreshed); + assert_eq!(directory.entries(), 1, "no temporary file remains"); + assert_eq!( + write_back("codex", &refreshed, &host, NOW).unwrap(), + WriteBack::Kept(host_stamp(&host)) + ); +} + +#[test] +fn never_creates_follows_or_writes_an_unsafe_host_file() { + let refreshed = bytes(&codex("account-1", "2027-01-15T07:59:59Z")); + let directory = Directory::new(); + let missing = directory.0.join("auth.json"); + assert!(write_back("codex", &refreshed, &missing, NOW).is_err()); + assert!(!missing.exists()); + + let target = directory.write( + "target.json", + &codex("account-1", "2027-01-15T07:59:00Z"), + 0o600, + ); + let link = directory.0.join("link.json"); + symlink(&target, &link).unwrap(); + let open = directory.write( + "open.json", + &codex("account-1", "2027-01-15T07:59:00Z"), + 0o644, + ); + for path in [link, open] { + let before = fs::read(&path).unwrap(); + assert!(write_back("codex", &refreshed, &path, NOW).is_err()); + assert_eq!(fs::read(&path).unwrap(), before); + } + assert!(fs::symlink_metadata(directory.0.join("link.json")) + .unwrap() + .file_type() + .is_symlink()); +} + +#[test] +fn abandons_the_replacement_when_the_host_file_changes() { + let directory = Directory::new(); + let host = directory.write( + "auth.json", + &codex("account-1", "2027-01-15T07:59:00Z"), + 0o600, + ); + let (_, decided) = read_host_credential(&host).unwrap(); + let rewritten = directory.write( + "next.json", + &codex("account-1", "2027-01-15T07:59:30Z"), + 0o600, + ); + fs::rename(&rewritten, &host).unwrap(); + let refreshed = bytes(&codex("account-1", "2027-01-15T07:59:59Z")); + assert_eq!( + replace_if_unchanged(&refreshed, &host, &decided).unwrap(), + WriteBack::Raced + ); + assert_eq!( + fs::read(&host).unwrap(), + bytes(&codex("account-1", "2027-01-15T07:59:30Z")) + ); + assert_eq!( + directory.entries(), + 1, + "the abandoned replacement is removed" + ); +} + +#[test] +fn an_oversized_refresh_never_replaces_the_host_file() { + let directory = Directory::new(); + let original = codex("account-1", "2027-01-15T07:59:00Z"); + let host = directory.write("auth.json", &original, 0o600); + let mut padded = bytes(&codex("account-1", "2027-01-15T07:59:59Z")); + padded.extend(std::iter::repeat_n( + b' ', + MAX_BYTES as usize + 1 - padded.len(), + )); + assert_eq!( + write_back("codex", &padded, &host, NOW).unwrap(), + WriteBack::Kept(None) + ); + assert_eq!(fs::read(&host).unwrap(), bytes(&original)); + padded.pop(); + assert_eq!( + write_back("codex", &padded, &host, NOW).unwrap(), + WriteBack::Written + ); +}