From 38f66dd29c9a8e75becd76968c7dff71ca95cc9d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:07:38 +0100 Subject: [PATCH] Generalize credential lease and add lease run launcher Replace topology-tied lease naming (LeaseTurn, LeaseCaller::unit(), is_unit_instance, add-lease-caller, mind-self/mind-persona/swarm strings) with LeaseScope (PerCaller, PerInvocation), LeaseHolder / LeaseHolderConfig carrying configured provider, full systemd unit name, and scope, and config add-lease-holder. Add claude_connector::lease_run and the CLI subcommand to request a lease over the unix socket, receive the token pipe via SCM_RIGHTS, place it on fd 3 with CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3, hold the socket open until the child exits, and return its exit status. --- crates/claude-connector/src/daemon.rs | 133 +++++--- crates/claude-connector/src/launch.rs | 2 +- crates/claude-connector/src/lease.rs | 86 ++--- crates/claude-connector/src/lease_run.rs | 319 ++++++++++++++++++ crates/claude-connector/src/lib.rs | 6 +- crates/claude-connector/src/main.rs | 121 +++++-- crates/claude-connector/src/meter.rs | 21 +- crates/claude-connector/src/process.rs | 4 +- crates/claude-connector/src/quota.rs | 5 +- crates/claude-connector/src/unit.rs | 17 +- .../claude-connector/tests/config_document.rs | 203 +++++++++-- crates/claude-connector/tests/lease.rs | 94 +++++- crates/claude-connector/tests/lease_run.rs | 241 +++++++++++++ crates/model-connector/src/serve.rs | 2 +- crates/model-connector/src/service.rs | 6 +- crates/model-connector/src/service/lease.rs | 131 +++---- 16 files changed, 1126 insertions(+), 265 deletions(-) create mode 100644 crates/claude-connector/src/lease_run.rs create mode 100644 crates/claude-connector/tests/lease_run.rs diff --git a/crates/claude-connector/src/daemon.rs b/crates/claude-connector/src/daemon.rs index c1aaa62..c24a39d 100644 --- a/crates/claude-connector/src/daemon.rs +++ b/crates/claude-connector/src/daemon.rs @@ -11,7 +11,7 @@ use std::time::Duration; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; use model_connector::{ - CallerAdmission, CallerConfig, LeaseTurn, MIN_PAYLOAD_BYTES, ProviderBackend, ServeError, + CallerAdmission, CallerConfig, LeaseScope, MIN_PAYLOAD_BYTES, ProviderBackend, ServeError, ServeLimits, ServiceError, TransportService, load_admissions, serve_service, }; use serde::{Deserialize, Serialize}; @@ -19,7 +19,7 @@ use thiserror::Error; use crate::backend::readiness; #[cfg(target_os = "linux")] -use crate::lease::{LeaseCaller, LeaseLimits, serve_leases, user_uid}; +use crate::lease::{LeaseHolder, LeaseLimits, serve_leases, user_uid}; #[cfg(target_os = "linux")] use crate::unit::SystemdUnits; #[cfg(unix)] @@ -32,18 +32,18 @@ use crate::{ const CONFIG_KEY: &str = "runtime"; const MODEL_PREFIX: &str = "claude-"; -/// A unix account that may lease the subscription token for a Self run or a -/// Persona turn, the unit its process must run in (`mind-self@` -/// or `mind-persona@`, by `turn`), and the configured caller -/// whose name its leases carry. +/// A unix account that may lease the subscription token, the provider and full +/// systemd unit its process must run in, its exclusivity scope, and the +/// configured caller whose name its leases carry. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct LeaseCallerConfig { +pub struct LeaseHolderConfig { pub unix_user: String, pub caller_id: String, - /// The kind of turn this account leases for: it fixes the unit, `mind-self@` - /// or `mind-persona@`, its process must run in. - pub turn: LeaseTurn, - pub unit_instance: String, + pub provider: String, + pub unit: String, + /// Exclusivity scope of this holder's leases: one per caller or one per + /// unit invocation. + pub scope: LeaseScope, } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] @@ -92,14 +92,14 @@ pub struct ClaudeConnectorConfig { /// Ids are unique. Handles are bound to the caller that was given them. #[cultcache(key = 17)] pub callers: Vec, - /// Where the Self-run lease socket is bound (a systemd RuntimeDirectory), + /// Where the credential lease socket is bound (a systemd RuntimeDirectory), /// or none when this connector lends no token. #[cultcache(key = 19)] pub lease_socket: Option, /// The accounts allowed to lease, each bound to a configured caller. /// Empty exactly when `lease_socket` is none. #[cultcache(key = 20)] - pub lease_callers: Vec, + pub lease_holders: Vec, /// The furthest a lease's expiry may lie from now. #[cultcache(key = 21)] pub lease_max_ms: u64, @@ -249,17 +249,17 @@ impl ClaudeConnectorConfig { fn validate_leases(&self) -> Result<(), ConfigError> { // A key has no plan and is never lent: no lease socket, no lease row, whatever else the - // document says. Personas call with their own connection keys and need neither. + // document says. Callers use their own connection keys and need neither. if self.auth == ClaudeAuth::ApiKey - && (self.lease_socket.is_some() || !self.lease_callers.is_empty()) + && (self.lease_socket.is_some() || !self.lease_holders.is_empty()) { return Err(ConfigError::Invalid("auth")); } let Some(socket) = &self.lease_socket else { - return if self.lease_callers.is_empty() { + return if self.lease_holders.is_empty() { Ok(()) } else { - Err(ConfigError::Invalid("lease_callers")) + Err(ConfigError::Invalid("lease_holders")) }; }; if !socket.is_absolute() { @@ -269,18 +269,19 @@ impl ClaudeConnectorConfig { return Err(ConfigError::Invalid("lease_max_ms")); } let mut users = BTreeSet::new(); - if self.lease_callers.is_empty() - || !self.lease_callers.iter().all(|lease| { + if self.lease_holders.is_empty() + || !self.lease_holders.iter().all(|lease| { is_trimmed_nonempty(&lease.unix_user) && self .callers .iter() .any(|caller| caller.caller_runtime_id == lease.caller_id) - && is_unit_instance(&lease.unit_instance) + && lease.provider == crate::config::PROVIDER + && is_systemd_unit_name(&lease.unit) && users.insert(lease.unix_user.as_str()) }) { - return Err(ConfigError::Invalid("lease_callers")); + return Err(ConfigError::Invalid("lease_holders")); } Ok(()) } @@ -322,12 +323,29 @@ impl ClaudeConnectorConfig { } } -/// The `` of a unit name, as plain as a systemd instance can be. -fn is_unit_instance(text: &str) -> bool { - !text.is_empty() - && text - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) +/// A systemd service unit name: `name.service` or `name@instance.service`. +fn is_systemd_unit_name(text: &str) -> bool { + if text.len() > 256 { + return false; + } + let Some(stem) = text.strip_suffix(".service") else { + return false; + }; + let valid_part = |part: &str| { + !part.is_empty() + && !part.starts_with('.') + && !part.ends_with('.') + && !part.contains("..") + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) + }; + match stem.split_once('@') { + Some((name, instance)) => { + !instance.contains('@') && valid_part(name) && valid_part(instance) + } + None => valid_part(stem), + } } fn is_trimmed_nonempty(text: &str) -> bool { @@ -479,7 +497,7 @@ fn readiness_of(config: &ClaudeConnectorConfig) -> Result, } } if config.lease_socket.is_some() { - lease_callers_of(config)?; + lease_holders_of(config)?; } Ok(admissions) } @@ -487,26 +505,27 @@ fn readiness_of(config: &ClaudeConnectorConfig) -> Result, /// The accounts allowed to lease, resolved to the uids the kernel will report /// for their connections. An account the system does not have is not ready. #[cfg(target_os = "linux")] -fn lease_callers_of(config: &ClaudeConnectorConfig) -> Result, ConfigError> { +fn lease_holders_of(config: &ClaudeConnectorConfig) -> Result, ConfigError> { config - .lease_callers + .lease_holders .iter() .map(|lease| { user_uid(&lease.unix_user) - .map(|uid| LeaseCaller { + .map(|uid| LeaseHolder { uid, caller_id: lease.caller_id.clone(), - turn: lease.turn, - unit_instance: lease.unit_instance.clone(), + provider: lease.provider.clone(), + unit: lease.unit.clone(), + scope: lease.scope, }) - .ok_or(ConfigError::Unusable("lease_callers")) + .ok_or(ConfigError::Unusable("lease_holders")) }) .collect() } -/// Peer credentials identify a lease caller only on Linux. +/// Peer credentials identify a lease holder only on Linux. #[cfg(not(target_os = "linux"))] -fn lease_callers_of(_: &ClaudeConnectorConfig) -> Result<(), ConfigError> { +fn lease_holders_of(_: &ClaudeConnectorConfig) -> Result<(), ConfigError> { Err(ConfigError::Unusable("lease_socket")) } @@ -524,7 +543,7 @@ fn start_leases( use std::os::unix::fs::{FileTypeExt, PermissionsExt}; use std::os::unix::net::UnixListener; - let callers = lease_callers_of(config)?; + let holders = lease_holders_of(config)?; // A socket a previous run left is replaced; anything else at the path is not ours. if std::fs::symlink_metadata(socket).is_ok_and(|found| found.file_type().is_socket()) { let _ = std::fs::remove_file(socket); @@ -545,7 +564,7 @@ fn start_leases( .spawn(move || { let _ = serve_leases( &listener, - callers, + holders, limits, service, quota, @@ -571,7 +590,7 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> { } /// [`serve_config`] handing the quota cell to `started` once the meter runs: -/// a test stands in for the swarm's lease requests only through here. +/// a test stands in for lease requests only through here. #[cfg(unix)] fn serve_config_with( path: &Path, @@ -701,7 +720,7 @@ mod tests { max_output_tokens: 32_768, }], lease_socket: None, - lease_callers: Vec::new(), + lease_holders: Vec::new(), lease_max_ms: 3_600_000, }; write_config(&at("connector.cc"), &config).unwrap(); @@ -711,10 +730,10 @@ mod tests { let path = at("connector.cc"); let lease = std::sync::Arc::new(std::sync::Mutex::new(None)); - let swarm = lease.clone(); + let held_quota = lease.clone(); let served = std::thread::spawn(move || { serve_config_with(&path, |cell| { - *swarm.lock().unwrap() = Some(cell.clone()); + *held_quota.lock().unwrap() = Some(cell.clone()); }) }); @@ -727,7 +746,7 @@ mod tests { std::thread::sleep(Duration::from_millis(20)); }; std::thread::sleep(Duration::from_millis(500)); - assert!(!at("spawned").exists(), "a quiet swarm spends nothing"); + assert!(!at("spawned").exists(), "an idle deployment spends nothing"); let _lease = cell.asking(); while !at("spawned").exists() { @@ -799,6 +818,34 @@ mod tests { assert!(!written.contains("canary")); } + #[test] + fn systemd_unit_names_allow_plain_and_instanced_services_only() { + assert!(is_systemd_unit_name("agent.service")); + assert!(is_systemd_unit_name("agent@alice.service")); + assert!(is_systemd_unit_name("foo.bar@baz-1_2.service")); + let max_len = format!("{}.service", "a".repeat(256 - ".service".len())); + assert_eq!(max_len.len(), 256); + assert!(is_systemd_unit_name(&max_len)); + + let too_long = format!("{}.service", "a".repeat(257 - ".service".len())); + for bad in [ + "agent@.service", + "@a.service", + "a@b@c.service", + ".service", + "agent", + "a/b.service", + "a..b.service", + ".a.service", + "a.@b.service", + "a@.b.service", + "a b.service", + too_long.as_str(), + ] { + assert!(!is_systemd_unit_name(bad), "unexpectedly accepted {bad:?}"); + } + } + #[cfg(unix)] mod prompt_dir { use std::os::unix::fs::{PermissionsExt, chown, symlink}; diff --git a/crates/claude-connector/src/launch.rs b/crates/claude-connector/src/launch.rs index 3b273d6..c11abcb 100644 --- a/crates/claude-connector/src/launch.rs +++ b/crates/claude-connector/src/launch.rs @@ -19,7 +19,7 @@ use crate::handle::Plan; /// environment names that descriptor. pub(crate) const TOKEN_FD: i32 = 3; /// The variable that tells the CLI which descriptor holds the subscription token. -const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"; +pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"; const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin"; /// The environment of the child: exactly these names and nothing inherited. diff --git a/crates/claude-connector/src/lease.rs b/crates/claude-connector/src/lease.rs index a049bba..af27c13 100644 --- a/crates/claude-connector/src/lease.rs +++ b/crates/claude-connector/src/lease.rs @@ -1,23 +1,22 @@ -//! The Self-run credential lease. The connector is the only holder of the -//! subscription token and the one owner of Self-run admission (rulings -//! self-runs-through-connector and self-run-credential-lease). A Self run asks +//! The credential lease. The connector is the only holder of the +//! subscription token and the one owner of lease admission. A holder asks //! over a unix socket for a lease. The connector decides who may ask (the //! peer's uid, and the systemd unit invocation its process runs in), and hands //! back one pipe fd that holds the token, with the plan's usage windows. The //! lease lasts while the holder keeps the socket open: it ends when the holder //! closes it, when its unit invocation ends, or when its expiry passes. Nothing //! is reserved and nothing is billed; the only usage-derived refusal is the -//! provider's own, repeated until its own reset. Nothing the run says about +//! provider's own, repeated until its own reset. Nothing the holder says about //! itself decides who it is or what the plan allows. //! //! The same socket also answers a usage readout to any peer that can reach it //! (the claude-lease group): no lease, no caller check, no token read and no -//! wake of the meter. Usage is state every Mind reads. +//! wake of the meter. Usage is state every peer with socket access reads. //! //! The token exists in this process only as the value the token source returns //! and in the pipe. It is not in an environment, an argument, a file, a log or -//! a reply frame. The connector spawns nothing here: the Self run's `claude` -//! stays in the Self run's own unit. +//! a reply frame. The connector spawns nothing here: the holder's `claude` +//! stays in the holder's own unit. use std::ffi::CString; use std::io::{self, Read, Write}; @@ -31,7 +30,7 @@ use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use model_connector::{ - LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn, PlanQuota, TransportService, UsageReadout, + LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope, PlanQuota, TransportService, UsageReadout, }; use serde::{Deserialize, Serialize}; @@ -173,28 +172,16 @@ fn read_message(stream: &mut impl Bounded, deadline: Instant) -> io::Result` of `mind-self@.service` or - /// `mind-persona@.service`. - pub unit_instance: String, -} - -impl LeaseCaller { - /// The one unit a lease to this caller may be requested from. - pub fn unit(&self) -> String { - match self.turn { - LeaseTurn::SelfRun => format!("mind-self@{}.service", self.unit_instance), - LeaseTurn::PersonaTurn => format!("mind-persona@{}.service", self.unit_instance), - } - } + pub provider: String, + pub unit: String, + pub scope: LeaseScope, } /// The systemd unit invocation a process runs in. @@ -389,7 +376,7 @@ impl Drop for Permit { } struct Lender { - callers: Vec, + holders: Vec, limits: LeaseLimits, service: Arc>, quota: Arc, @@ -410,14 +397,13 @@ const READOUT_CONNECTIONS: usize = 4; /// one usage readout. A lease: request, then grant or refusal, then (after a /// grant) the hold. A readout: request, then one frame, then close; its reach /// is the socket's group, and it reads the plan's windows without waking the -/// meter. A caller is -/// the account whose uid the kernel reports for the connection, and only a -/// process in that caller's unit may lease, once per unit invocation for a Self -/// run and once per turn for a Persona; no -/// field of any message names either. +/// meter. A holder is the account whose uid the kernel reports for the +/// connection, and only a process in that holder's configured unit may lease, +/// once per caller for `PerCaller` and once per unit invocation for +/// `PerInvocation`; no field of any message names either. pub fn serve_leases( listener: &UnixListener, - callers: Vec, + holders: Vec, limits: LeaseLimits, service: Arc>, quota: Arc, @@ -425,7 +411,7 @@ pub fn serve_leases( units: Arc, ) -> io::Result<()> { let lender = Arc::new(Lender { - callers, + holders, limits, service, quota, @@ -487,7 +473,7 @@ impl Lender { peer: PeerCredentials, request: LeaseRequest, ) -> io::Result<()> { - let Some(caller) = self.callers.iter().find(|caller| caller.uid == peer.uid) else { + let Some(holder) = self.holders.iter().find(|holder| holder.uid == peer.uid) else { return refuse( &mut stream, LeaseRefusalKind::UnknownCaller, @@ -499,13 +485,13 @@ impl Lender { let Some(invocation) = peer .process .as_ref() - .and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit())) - .filter(|found| found.unit == caller.unit()) + .and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit)) + .filter(|found| found.unit == holder.unit) else { return refuse( &mut stream, LeaseRefusalKind::UnknownCaller, - "this process is not in the Self unit", + "this process is not in the configured unit", ); }; let now = unix_ms(); @@ -522,7 +508,7 @@ impl Lender { // plan the refusal reads is the one this process last observed, but a // cell with no weekly reading (a restart empties it) gets the meter's // first read, bounded, before the lease is lent "unobserved" for its - // whole life. The request is the swarm's sign of life, however it + // whole life. The request is the holder's sign of life, however it // ends: the meter reads while one is held or lately asked for. let _asking = self.quota.asking(); let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT); @@ -532,8 +518,8 @@ impl Lender { .lock() .map_err(|_| io::Error::other("service lock"))? .begin_lease( - &caller.caller_id, - caller.turn, + &holder.caller_id, + holder.scope, &invocation.invocation_id, request.expires_at_unix_ms, now, @@ -562,7 +548,7 @@ impl Lender { }; self.hold( stream, - caller, + holder, &grant, &invocation, peer.process, @@ -579,7 +565,7 @@ impl Lender { fn hold( &self, mut stream: UnixStream, - caller: &LeaseCaller, + holder: &LeaseHolder, grant: &LeaseGrant, invocation: &PeerUnit, process: Option, @@ -588,7 +574,7 @@ impl Lender { ) -> io::Result<()> { let held = self.keep( &mut stream, - caller, + holder, grant, invocation, process.as_ref(), @@ -598,7 +584,7 @@ impl Lender { self.service .lock() .map_err(|_| io::Error::other("service lock"))? - .end_lease(&caller.caller_id, &grant.lease_id); + .end_lease(&holder.caller_id, &grant.lease_id); held } @@ -607,7 +593,7 @@ impl Lender { fn keep( &self, stream: &mut UnixStream, - caller: &LeaseCaller, + holder: &LeaseHolder, grant: &LeaseGrant, invocation: &PeerUnit, process: Option<&OwnedFd>, @@ -651,7 +637,7 @@ impl Lender { Err(_) => return Ok(()), } let still = process - .and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit())) + .and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit)) .is_some_and(|found| found == *invocation); if !still { return Ok(()); @@ -723,7 +709,7 @@ mod tests { .unwrap(), )); let lender = Lender { - callers: Vec::new(), + holders: Vec::new(), limits: LeaseLimits { socket_timeout: Duration::from_secs(2), max_lease_ms: 3_600_000, @@ -747,7 +733,7 @@ mod tests { thread::spawn(move || { let _ = serve_leases( &listener, - lender.callers, + lender.holders, lender.limits, service, quota, diff --git a/crates/claude-connector/src/lease_run.rs b/crates/claude-connector/src/lease_run.rs new file mode 100644 index 0000000..8d86aed --- /dev/null +++ b/crates/claude-connector/src/lease_run.rs @@ -0,0 +1,319 @@ +//! Runs a command with a lent subscription token delivered on descriptor 3 +//! (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3`). +//! +//! Connects to the connector's lease socket, requests a lease, receives the +//! grant frame and the pipe read descriptor via `SCM_RIGHTS`, spawns the child +//! with the descriptor placed at fd 3, drops the parent's copy of the pipe, +//! holds the unix socket open until the child exits, and returns the child's +//! exit status. Never reads the token bytes or writes them (or any path or +//! refusal detail) to the environment, argv, or stderr. + +use std::io::{self, ErrorKind, Write}; +use std::mem::{size_of, zeroed}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::net::UnixStream; +use std::os::unix::process::CommandExt; +use std::path::PathBuf; +use std::process::{Command, ExitStatus}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::launch::{TOKEN_FD, TOKEN_FD_VAR}; +use crate::lease::{ + LeaseMessage, LeaseRefusalKind, LeaseRequest, MAX_LEASE_FRAME_BYTES, decode_frame, encode_frame, +}; +use crate::process::place_fd; + +/// Default lease lifetime requested when `--ttl-secs` is omitted (59 minutes). +pub const DEFAULT_TTL_SECS: u64 = 3_540; + +/// Timeout applied to the initial request write and grant frame read. +const SOCKET_TIMEOUT: Duration = Duration::from_secs(30); + +/// Arguments for [`lease_run`]. +#[derive(Debug, Clone)] +pub struct LeaseRunArgs { + pub socket: PathBuf, + pub ttl: Duration, + pub program: String, + pub args: Vec, +} + +/// Failures from requesting a lease or launching the child; never echoes +/// input paths, program names, token bytes, or lender refusal detail text. +#[derive(Debug, thiserror::Error)] +pub enum LeaseRunError { + #[error("the lease ttl is invalid")] + Ttl, + #[error("the system clock could not be read")] + Clock, + #[error("the lease program is missing")] + Program, + #[error("the lease socket connection failed: {0}")] + Connect(ErrorKind), + #[error("the lease request could not be sent: {0}")] + Send(ErrorKind), + #[error("the lease reply could not be read: {0}")] + Receive(ErrorKind), + #[error("the lease reply frame is malformed")] + Frame, + #[error("the lease grant did not carry exactly one token descriptor")] + UnexpectedFds, + #[error("the lease request was refused: {0:?}")] + Refused(LeaseRefusalKind), + #[error("the leased command could not be spawned: {0}")] + Spawn(ErrorKind), + #[error("waiting on the leased command failed: {0}")] + Wait(ErrorKind), +} + +/// Requests a credential lease over `args.socket`, spawns `args.program` with +/// `args.args` and the token pipe placed at [`TOKEN_FD`] (`TOKEN_FD_VAR=3`), +/// holds the socket open until the child exits, and returns the child's status. +pub fn lease_run(args: &LeaseRunArgs) -> Result { + if args.program.is_empty() { + return Err(LeaseRunError::Program); + } + let ttl_ms = u64::try_from(args.ttl.as_millis()) + .ok() + .filter(|ms| *ms > 0) + .ok_or(LeaseRunError::Ttl)?; + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| LeaseRunError::Clock) + .and_then(|elapsed| u64::try_from(elapsed.as_millis()).map_err(|_| LeaseRunError::Clock))?; + let expires_at_unix_ms = now_ms.checked_add(ttl_ms).ok_or(LeaseRunError::Ttl)?; + + let mut stream = + UnixStream::connect(&args.socket).map_err(|error| LeaseRunError::Connect(error.kind()))?; + stream + .set_write_timeout(Some(SOCKET_TIMEOUT)) + .map_err(|error| LeaseRunError::Send(error.kind()))?; + stream + .set_read_timeout(Some(SOCKET_TIMEOUT)) + .map_err(|error| LeaseRunError::Receive(error.kind()))?; + + let request = encode_frame(&LeaseMessage::ClaudeLeaseRequest(LeaseRequest { + expires_at_unix_ms, + })); + stream + .write_all(&request) + .map_err(|error| LeaseRunError::Send(error.kind()))?; + + let (frame, fds) = recv_frame_with_fds(&stream)?; + let message = decode_frame(&frame).ok_or(LeaseRunError::Frame)?; + match message { + LeaseMessage::ClaudeLeaseRefusal(refusal) => Err(LeaseRunError::Refused(refusal.kind)), + LeaseMessage::ClaudeLeaseGrant(_) => { + if fds.len() != 1 { + return Err(LeaseRunError::UnexpectedFds); + } + let token_fd = fds.into_iter().next().ok_or(LeaseRunError::UnexpectedFds)?; + spawn_and_hold(stream, token_fd, &args.program, &args.args) + } + _ => Err(LeaseRunError::Frame), + } +} + +fn spawn_and_hold( + stream: UnixStream, + token_fd: OwnedFd, + program: &str, + args: &[String], +) -> Result { + let mut command = Command::new(program); + command.args(args).env(TOKEN_FD_VAR, TOKEN_FD.to_string()); + let source = token_fd.as_raw_fd(); + // SAFETY: `place_fd` calls only async-signal-safe `dup2` and `fcntl`. + unsafe { + command.pre_exec(move || place_fd(source, TOKEN_FD)); + } + let mut child = command + .spawn() + .map_err(|error| LeaseRunError::Spawn(error.kind()))?; + drop(token_fd); + let status = child + .wait() + .map_err(|error| LeaseRunError::Wait(error.kind()))?; + drop(stream); + Ok(status) +} + +fn recv_frame_with_fds(stream: &UnixStream) -> Result<(Vec, Vec), LeaseRunError> { + let mut frame = Vec::new(); + let mut fds = Vec::new(); + let mut expected_total: Option = None; + let mut chunk = vec![0_u8; 4 + MAX_LEASE_FRAME_BYTES + 1]; + + loop { + let read_cap = match expected_total { + None => chunk.len(), + Some(total) => (total - frame.len()) + 1, + }; + let (received, mut chunk_fds) = recv_chunk(stream, &mut chunk[..read_cap])?; + fds.append(&mut chunk_fds); + if received == 0 { + return Err(LeaseRunError::Frame); + } + frame.extend_from_slice(&chunk[..received]); + if expected_total.is_none() && frame.len() >= 4 { + let len = u32::from_be_bytes([frame[0], frame[1], frame[2], frame[3]]) as usize; + if len == 0 || len > MAX_LEASE_FRAME_BYTES { + return Err(LeaseRunError::Frame); + } + expected_total = Some(4 + len); + } + if let Some(total) = expected_total { + if frame.len() > total { + return Err(LeaseRunError::Frame); + } + if frame.len() == total { + return Ok((frame, fds)); + } + } + } +} + +fn recv_chunk(stream: &UnixStream, buf: &mut [u8]) -> Result<(usize, Vec), LeaseRunError> { + const MAX_CMSG_FDS: usize = 16; + // SAFETY: `CMSG_SPACE` is a pure size computation. + let space = unsafe { libc::CMSG_SPACE((MAX_CMSG_FDS * size_of::()) as u32) } as usize; + let mut control = vec![0_u64; space.div_ceil(size_of::())]; + let mut vector = libc::iovec { + iov_base: buf.as_mut_ptr().cast(), + iov_len: buf.len(), + }; + // SAFETY: `buf` and `control` outlive `recvmsg`; `msg_controllen` matches the + // byte length of `control`; descriptors received via `SCM_RIGHTS` with + // `MSG_CMSG_CLOEXEC` are newly installed in this process and owned nowhere else. + unsafe { + let mut message: libc::msghdr = zeroed(); + message.msg_iov = &mut vector; + message.msg_iovlen = 1; + message.msg_control = control.as_mut_ptr().cast(); + message.msg_controllen = (control.len() * size_of::()) as _; + let received = loop { + let n = libc::recvmsg(stream.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC); + if n >= 0 || io::Error::last_os_error().kind() != ErrorKind::Interrupted { + break n; + } + }; + if received < 0 { + return Err(LeaseRunError::Receive(io::Error::last_os_error().kind())); + } + let mut fds = Vec::new(); + let mut header = libc::CMSG_FIRSTHDR(&message); + while !header.is_null() { + if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS { + let cmsg_len = (*header).cmsg_len as usize; + let base = libc::CMSG_LEN(0) as usize; + if cmsg_len >= base { + let data = libc::CMSG_DATA(header).cast::(); + for index in 0..(cmsg_len - base) / size_of::() { + fds.push(OwnedFd::from_raw_fd(data.add(index).read_unaligned())); + } + } + } + header = libc::CMSG_NXTHDR(&message, header); + } + if (message.msg_flags & libc::MSG_CTRUNC) != 0 { + return Err(LeaseRunError::UnexpectedFds); + } + Ok((received as usize, fds)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::lease::{LeaseGranted, LeaseRefused}; + + fn roundtrip_bytes(bytes: &[u8]) -> Result<(Vec, Vec), LeaseRunError> { + let (rx, mut tx) = UnixStream::pair().unwrap(); + let data = bytes.to_vec(); + let writer = std::thread::spawn(move || { + let _ = tx.write_all(&data); + drop(tx); + }); + let result = recv_frame_with_fds(&rx); + writer.join().unwrap(); + result + } + + #[test] + fn recv_rejects_zero_over_bound_truncated_and_trailing_frames() { + assert!(matches!(roundtrip_bytes(&[]), Err(LeaseRunError::Frame))); + assert!(matches!( + roundtrip_bytes(&[0, 0, 0, 0]), + Err(LeaseRunError::Frame) + )); + let over = (MAX_LEASE_FRAME_BYTES as u32 + 1).to_be_bytes(); + assert!(matches!(roundtrip_bytes(&over), Err(LeaseRunError::Frame))); + + let valid = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::Busy, + detail: "busy".to_string(), + })); + assert!(matches!( + roundtrip_bytes(&valid[..valid.len() - 1]), + Err(LeaseRunError::Frame) + )); + let mut trailing = valid.clone(); + trailing.push(0); + assert!(matches!( + roundtrip_bytes(&trailing), + Err(LeaseRunError::Frame) + )); + let (read, fds) = roundtrip_bytes(&valid).unwrap(); + assert_eq!(read, valid); + assert!(fds.is_empty()); + } + + #[test] + fn grant_without_fd_is_rejected_and_refusal_never_echoes_detail() { + let dir = std::env::temp_dir().join(format!("lease-run-unit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let socket = dir.join("lease.sock"); + let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap(); + + let server = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut buf = [0_u8; 256]; + let _ = io::Read::read(&mut stream, &mut buf); + let grant = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted { + lease_id: "lease:1".to_string(), + plan_quota: vec![], + })); + stream.write_all(&grant).unwrap(); + + let (mut stream, _) = listener.accept().unwrap(); + let _ = io::Read::read(&mut stream, &mut buf); + let refusal = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind: LeaseRefusalKind::ProviderRejected, + detail: "CANARY-DETAIL-SECRET".to_string(), + })); + stream.write_all(&refusal).unwrap(); + }); + + let args = LeaseRunArgs { + socket: socket.clone(), + ttl: Duration::from_secs(DEFAULT_TTL_SECS), + program: "/bin/true".to_string(), + args: vec![], + }; + assert!(matches!( + lease_run(&args), + Err(LeaseRunError::UnexpectedFds) + )); + let err = lease_run(&args).unwrap_err(); + let text = format!("{err} {err:?}"); + assert!(matches!( + err, + LeaseRunError::Refused(LeaseRefusalKind::ProviderRejected) + )); + assert!(!text.contains("CANARY-DETAIL-SECRET"), "{text}"); + + server.join().unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/claude-connector/src/lib.rs b/crates/claude-connector/src/lib.rs index c904d0a..141c366 100644 --- a/crates/claude-connector/src/lib.rs +++ b/crates/claude-connector/src/lib.rs @@ -11,6 +11,8 @@ mod handle; mod launch; #[cfg(target_os = "linux")] mod lease; +#[cfg(target_os = "linux")] +pub mod lease_run; mod messages; mod meter; mod process; @@ -22,7 +24,7 @@ mod unit; pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource}; pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits}; pub use daemon::{ - ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config, + ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, check_ready, load_config, write_config, }; #[cfg(unix)] pub use daemon::{check_prompt_dir, serve_config}; @@ -31,7 +33,7 @@ pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore}; pub use launch::ChildEnv; #[cfg(target_os = "linux")] pub use lease::{ - LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, + LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit, PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid, }; diff --git a/crates/claude-connector/src/main.rs b/crates/claude-connector/src/main.rs index 11d93eb..5ce5e89 100644 --- a/crates/claude-connector/src/main.rs +++ b/crates/claude-connector/src/main.rs @@ -3,9 +3,10 @@ //! claude-connector serve --config PATH.cc //! claude-connector config init PATH.cc --flag value ... //! claude-connector config add-caller PATH.cc --caller-id ID --connection-key-file F ... -//! claude-connector config add-lease-caller PATH.cc --lease-user U --caller-id ID ... +//! claude-connector config add-lease-holder PATH.cc --lease-user U --caller-id ID --provider P --unit NAME --scope per-caller|per-invocation //! claude-connector config check PATH.cc //! claude-connector ask --caller-id ID --connection-key-file F --model M (--system TEXT | --system-file F) < prompt +//! claude-connector lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...] //! //! `serve` takes its configuration from the typed document alone. The flags of //! `config init` exist only to author that document. No message here echoes a @@ -17,25 +18,30 @@ use std::process::ExitCode; use claude_connector::ask::{self, AskArgs, AskError}; use claude_connector::{ - ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready, - load_config, write_config, + ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, MIN_SECRET_BYTES, + check_ready, load_config, write_config, }; -use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload}; +use model_connector::{CallerConfig, LeaseScope, frame_bytes_for_payload}; fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); let args: Vec<&str> = args.iter().map(String::as_str).collect(); let result = match args.as_slice() { - ["serve", "--config", path] => serve(path), - ["config", "init", path, flags @ ..] => init(path, flags), - ["config", "add-caller", path, flags @ ..] => add_caller(path, flags), - ["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags), - ["config", "check", path] => check(path), - ["ask", flags @ ..] => run_ask(flags), + ["serve", "--config", path] => serve(path).map(|()| ExitCode::SUCCESS), + ["config", "init", path, flags @ ..] => init(path, flags).map(|()| ExitCode::SUCCESS), + ["config", "add-caller", path, flags @ ..] => { + add_caller(path, flags).map(|()| ExitCode::SUCCESS) + } + ["config", "add-lease-holder", path, flags @ ..] => { + add_lease_holder(path, flags).map(|()| ExitCode::SUCCESS) + } + ["config", "check", path] => check(path).map(|()| ExitCode::SUCCESS), + ["ask", flags @ ..] => run_ask(flags).map(|()| ExitCode::SUCCESS), + ["lease", "run", rest @ ..] => run_lease(rest), _ => Err(Failure::Usage), }; match result { - Ok(()) => ExitCode::SUCCESS, + Ok(code) => code, Err(failure) => { eprintln!("claude-connector: {failure}"); ExitCode::FAILURE @@ -46,7 +52,7 @@ fn main() -> ExitCode { #[derive(Debug, thiserror::Error)] enum Failure { #[error( - "usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-caller PATH --flag value ... | config check PATH | ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] (prompt on stdin, answer on stdout) (check reads the credentials from the environment it runs in: run it in the unit's environment)" + "usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-holder PATH --flag value ... | config check PATH | ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] | lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...] (prompt on stdin, answer on stdout) (check reads the credentials from the environment it runs in: run it in the unit's environment)" )] Usage, #[error(transparent)] @@ -59,6 +65,9 @@ enum Failure { Flags, #[error("{0}")] Ask(#[from] AskError), + #[cfg(target_os = "linux")] + #[error("{0}")] + LeaseRun(#[from] claude_connector::lease_run::LeaseRunError), } #[cfg(unix)] @@ -76,7 +85,7 @@ fn check(path: &str) -> Result<(), Failure> { check_ready(&config)?; println!("claude connector configuration is valid and ready to serve"); println!("callers: {}", config.callers.len()); - println!("lease_callers: {}", config.lease_callers.len()); + println!("lease_holders: {}", config.lease_holders.len()); Ok(()) } @@ -159,7 +168,7 @@ const CALLER: [&str; 5] = [ "--max-output-tokens", ]; -const INIT: [&str; 22] = [ +const INIT: [&str; 23] = [ "--auth", "--listen", "--replay-store", @@ -180,11 +189,12 @@ const INIT: [&str; 22] = [ "--socket-timeout-ms", "--lease-socket", "--lease-max-ms", - "--turn", - "--lease-unit-instance", + "--provider", + "--unit", + "--scope", ]; -const LEASE_CALLER: [&str; 3] = ["--caller-id", "--turn", "--lease-unit-instance"]; +const LEASE_HOLDER: [&str; 4] = ["--caller-id", "--provider", "--unit", "--scope"]; impl Flags { fn parse( @@ -250,12 +260,12 @@ impl Flags { } } - /// The kind of turn a leasing account serves: `self` or `persona`. - fn turn(&self) -> Result { - match self.text("--turn")?.as_str() { - "self" => Ok(LeaseTurn::SelfRun), - "persona" => Ok(LeaseTurn::PersonaTurn), - _ => Err(Failure::Malformed("--turn")), + /// The exclusivity scope a leasing account holds: `per-caller` or `per-invocation`. + fn scope(&self) -> Result { + match self.text("--scope")?.as_str() { + "per-caller" => Ok(LeaseScope::PerCaller), + "per-invocation" => Ok(LeaseScope::PerInvocation), + _ => Err(Failure::Malformed("--scope")), } } @@ -364,15 +374,16 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> { &["--allowed-model", "--lease-user"], )?; let first = flags.caller()?; - let lease_callers = flags + let lease_holders = flags .list("--lease-user") .iter() .map(|unix_user| { - Ok(LeaseCallerConfig { + Ok(LeaseHolderConfig { unix_user: unix_user.clone(), caller_id: first.caller_runtime_id.clone(), - turn: flags.turn()?, - unit_instance: flags.text("--lease-unit-instance")?, + provider: flags.text("--provider")?, + unit: flags.text("--unit")?, + scope: flags.scope()?, }) }) .collect::, Failure>>()?; @@ -398,7 +409,7 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> { max_expiry_skew_ms: 300_000, callers: vec![first], lease_socket: flags.single.get("--lease-socket").map(PathBuf::from), - lease_callers, + lease_holders, lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?, handle_secret_credential: flags.text("--handle-secret-credential")?, auth: flags.auth()?, @@ -434,20 +445,62 @@ fn add_caller(path: &str, args: &[&str]) -> Result<(), Failure> { Ok(()) } -/// Appends one leasing account to an existing document that lends a token. -fn add_lease_caller(path: &str, args: &[&str]) -> Result<(), Failure> { - let flags = Flags::parse(args, &[&LEASE_CALLER, &["--lease-user"]], &[])?; +/// Appends one lease holder to an existing document that lends a token. +fn add_lease_holder(path: &str, args: &[&str]) -> Result<(), Failure> { + let flags = Flags::parse(args, &[&LEASE_HOLDER, &["--lease-user"]], &[])?; let mut config = load_config(path.as_ref())?; - config.lease_callers.push(LeaseCallerConfig { + config.lease_holders.push(LeaseHolderConfig { unix_user: flags.text("--lease-user")?, caller_id: flags.text("--caller-id")?, - turn: flags.turn()?, - unit_instance: flags.text("--lease-unit-instance")?, + provider: flags.text("--provider")?, + unit: flags.text("--unit")?, + scope: flags.scope()?, }); write_config(path.as_ref(), &config)?; Ok(()) } +#[cfg(target_os = "linux")] +fn run_lease(args: &[&str]) -> Result { + use std::os::unix::process::ExitStatusExt; + use std::time::Duration; + + use claude_connector::lease_run::{DEFAULT_TTL_SECS, LeaseRunArgs, lease_run}; + + let Some(sep) = args.iter().position(|arg| *arg == "--") else { + return Err(Failure::Usage); + }; + let (flag_args, cmd_args) = (&args[..sep], &args[sep + 1..]); + let Some((&program, program_args)) = cmd_args.split_first() else { + return Err(Failure::Usage); + }; + if program.is_empty() { + return Err(Failure::Usage); + } + let flags = Flags::parse(flag_args, &[&["--socket", "--ttl-secs"]], &[])?; + let socket = flags.path("--socket")?; + let ttl_secs: u64 = flags.number_or("--ttl-secs", DEFAULT_TTL_SECS)?; + if ttl_secs == 0 { + return Err(Failure::Malformed("--ttl-secs")); + } + let status = lease_run(&LeaseRunArgs { + socket, + ttl: Duration::from_secs(ttl_secs), + program: program.to_string(), + args: program_args.iter().map(|arg| (*arg).to_string()).collect(), + })?; + let code = status + .code() + .or_else(|| status.signal().map(|signal| 128 + signal)) + .unwrap_or(1); + Ok(ExitCode::from(u8::try_from(code).unwrap_or(1))) +} + +#[cfg(not(target_os = "linux"))] +fn run_lease(_: &[&str]) -> Result { + Err(Failure::Usage) +} + #[cfg(all(test, unix))] mod tests { use std::os::unix::fs::{MetadataExt, PermissionsExt}; diff --git a/crates/claude-connector/src/meter.rs b/crates/claude-connector/src/meter.rs index 51ef749..1357abf 100644 --- a/crates/claude-connector/src/meter.rs +++ b/crates/claude-connector/src/meter.rs @@ -1,19 +1,18 @@ -//! The meter: keeps the plan's weekly reading fresh while the swarm is +//! The meter: keeps the plan's weekly reading fresh while lease holders are //! working. The subscription reports its windows only inside the CLI's -//! `rate_limit_event`, on a call the CLI makes, and Personas make theirs under -//! leases that report nothing back. So when the `seven_day` reading in the -//! [`QuotaCell`] is `STALE` old, the meter makes the smallest real call +//! `rate_limit_event`, on a call the CLI makes, and lease holders make theirs +//! under leases that report nothing back. So when the `seven_day` reading in +//! the [`QuotaCell`] is `STALE` old, the meter makes the smallest real call //! through the backend's own path (one `claude -p` on the cheapest model with //! a trivial prompt) and the stream fills the cell exactly as it does for any //! call. The meter holds no credential, speaks no protocol and writes nothing //! itself. //! //! The meter is driven by the connector's own lease state. It reads only -//! while a lease is held or one was asked for less than `STALE` ago: a held -//! swarm brake stops the units, they ask for nothing, and a braked or quiet -//! swarm spends nothing. A call that fails, or completes without refreshing -//! the reading, is not retried at the staleness period: the wait doubles per -//! consecutive miss, up to `CEILING`. +//! while a lease is held or one was asked for less than `STALE` ago: an idle +//! deployment asks for nothing, and idle lease holders spend nothing. A call +//! that fails, or completes without refreshing the reading, is not retried at +//! the staleness period: the wait doubles per consecutive miss, up to `CEILING`. use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -289,7 +288,7 @@ mod tests { made: Arc, script: Arc>, log: Arc>>, - /// The lease the swarm holds until a test lets go of it. + /// The lease held until a test lets go of it. lease: Option, } @@ -382,7 +381,7 @@ mod tests { } #[test] - fn a_swarm_that_asks_for_nothing_spends_nothing_however_stale_the_reading() { + fn no_lease_requests_spends_nothing_however_stale_the_reading() { let mut rig = rig(); drop(rig.lease.take()); for step in 0..10 { diff --git a/crates/claude-connector/src/process.rs b/crates/claude-connector/src/process.rs index 2421e0e..b4936ea 100644 --- a/crates/claude-connector/src/process.rs +++ b/crates/claude-connector/src/process.rs @@ -46,6 +46,8 @@ pub trait RunningChild: Send { #[cfg(unix)] pub use unix::StdProcessPort; +#[cfg(unix)] +pub(crate) use unix::place_fd; #[cfg(unix)] mod unix { @@ -77,7 +79,7 @@ mod unix { /// Makes `source` also descriptor `target`, open across exec. Runs between /// fork and exec in the child, so it calls nothing but `dup2` and `fcntl`. - fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> { + pub(crate) fn place_fd(source: RawFd, target: RawFd) -> io::Result<()> { // SAFETY: dup2 and fcntl take integers only and are async-signal-safe. unsafe { if source == target { diff --git a/crates/claude-connector/src/quota.rs b/crates/claude-connector/src/quota.rs index 1bf568f..3af2d7a 100644 --- a/crates/claude-connector/src/quota.rs +++ b/crates/claude-connector/src/quota.rs @@ -25,9 +25,8 @@ const FIRST_READ_POLL: Duration = Duration::from_millis(50); /// own observation: an event that names one window says nothing about the /// others. /// -/// It also keeps who is asking: a lease request is the swarm's only sign of -/// life the connector sees, and the meter reads the plan only while someone -/// asks. +/// It also keeps who is asking: a lease request is the connector's sign that a +/// holder is active, and the meter reads the plan only while someone asks. #[derive(Default)] pub struct QuotaCell { windows: Mutex>, diff --git a/crates/claude-connector/src/unit.rs b/crates/claude-connector/src/unit.rs index 1ab8dc9..f435064 100644 --- a/crates/claude-connector/src/unit.rs +++ b/crates/claude-connector/src/unit.rs @@ -141,17 +141,16 @@ mod tests { #[test] fn a_service_unit_is_the_last_cgroup_component() { - let service = "0::/system.slice/system-mind\\x2dself.slice/mind-self@huginn.service\n"; + let service = "0::/system.slice/system-agent\\x2dpool.slice/agent@alice.service\n"; assert_eq!( unit_of_cgroup(service).as_deref(), - Some("mind-self@huginn.service") + Some("agent@alice.service") ); // Several hierarchies listed: the unified one decides. - let hybrid = "12:cpu:/foo\n0::/system.slice/mind-self@a.service\n"; - assert_eq!( - unit_of_cgroup(hybrid).as_deref(), - Some("mind-self@a.service") - ); + let hybrid = "12:cpu:/foo\n0::/system.slice/agent@a.service\n"; + assert_eq!(unit_of_cgroup(hybrid).as_deref(), Some("agent@a.service")); + let plain = "0::/system.slice/other.service\n"; + assert_eq!(unit_of_cgroup(plain).as_deref(), Some("other.service")); } #[test] @@ -160,7 +159,7 @@ mod tests { "0::/\n", "0::/user.slice/user-1000.slice/session-3.scope\n", "0::/user.slice/user-1000.slice/user@1000.service/app.slice/x.service/child\n", - "0::/system.slice/mind-self@huginn.service/sub\n", + "0::/system.slice/agent@alice.service/sub\n", "0::/system.slice/.service\n", "1:name=systemd:/system.slice/a.service\n", "", @@ -188,7 +187,7 @@ mod tests { } const ID: &str = "0123456789abcdef0123456789abcdef"; - const UNIT: &str = "mind-self@eureka.service"; + const UNIT: &str = "worker@node.service"; /// A fake `/proc` with one process in `cgroup`, and a fake `systemctl` /// that records its arguments, runs `side_effect`, and exits `status` diff --git a/crates/claude-connector/tests/config_document.rs b/crates/claude-connector/tests/config_document.rs index 4ac4523..7a69e64 100644 --- a/crates/claude-connector/tests/config_document.rs +++ b/crates/claude-connector/tests/config_document.rs @@ -8,10 +8,10 @@ use std::process::{Command, Output}; use std::sync::atomic::{AtomicUsize, Ordering}; use claude_connector::{ - ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config, + ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, load_config, write_config, }; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; -use model_connector::{CallerConfig, LeaseTurn}; +use model_connector::{CallerConfig, LeaseScope}; const OPUS: &str = "claude-opus-5-1"; const HAIKU: &str = "claude-haiku-5-5"; @@ -72,11 +72,12 @@ fn valid() -> ClaudeConnectorConfig { max_output_tokens: 32_768, }], lease_socket: Some("/run/claude-connector/lease.sock".into()), - lease_callers: vec![LeaseCallerConfig { - unix_user: "mind-eureka-self".to_string(), + lease_holders: vec![LeaseHolderConfig { + unix_user: "agent-alice".to_string(), caller_id: "persona-a-caller".to_string(), - turn: LeaseTurn::SelfRun, - unit_instance: "eureka".to_string(), + provider: "claude-code".to_string(), + unit: "agent@alice.service".to_string(), + scope: LeaseScope::PerCaller, }], lease_max_ms: 3_600_000, } @@ -183,24 +184,52 @@ fn caller_bounds_are_required_nonzero() { } #[test] -fn a_lease_caller_names_a_configured_caller_and_a_socket_exists_exactly_when_it_leases() { +fn a_lease_holder_names_a_configured_caller_and_valid_unit_and_provider() { let mut stranger = valid(); - stranger.lease_callers[0].caller_id = "nobody".to_string(); - assert_eq!(refused(&stranger), "lease_callers"); + stranger.lease_holders[0].caller_id = "nobody".to_string(); + assert_eq!(refused(&stranger), "lease_holders"); - let mut no_callers = valid(); - no_callers.lease_callers.clear(); - assert_eq!(refused(&no_callers), "lease_callers"); + let mut no_holders = valid(); + no_holders.lease_holders.clear(); + assert_eq!(refused(&no_holders), "lease_holders"); let mut no_socket = valid(); no_socket.lease_socket = None; - assert_eq!(refused(&no_socket), "lease_callers"); - no_socket.lease_callers.clear(); + assert_eq!(refused(&no_socket), "lease_holders"); + no_socket.lease_holders.clear(); assert!(no_socket.validate().is_ok()); let mut twice = valid(); - twice.lease_callers.push(twice.lease_callers[0].clone()); - assert_eq!(refused(&twice), "lease_callers"); + twice.lease_holders.push(twice.lease_holders[0].clone()); + assert_eq!(refused(&twice), "lease_holders"); + + let mut plain_unit = valid(); + plain_unit.lease_holders[0].unit = "worker.service".to_string(); + assert!(plain_unit.validate().is_ok()); + + let mut instanced_unit = valid(); + instanced_unit.lease_holders[0].unit = "agent@alice.service".to_string(); + instanced_unit.lease_holders[0].scope = LeaseScope::PerInvocation; + assert!(instanced_unit.validate().is_ok()); + + for bad_unit in [ + "agent@.service", + "@a.service", + "a@b@c.service", + ".service", + "agent", + "a/b.service", + "a..b.service", + "a b.service", + ] { + let mut bad = valid(); + bad.lease_holders[0].unit = bad_unit.to_string(); + assert_eq!(refused(&bad), "lease_holders", "{bad_unit:?}"); + } + + let mut bad_provider = valid(); + bad_provider.lease_holders[0].provider = "deepseek".to_string(); + assert_eq!(refused(&bad_provider), "lease_holders"); } fn run(args: &[&str]) -> Output { @@ -266,7 +295,7 @@ fn config_init_writes_the_flags_into_the_document() { let config = load_config(&scratch.path("connector.cc")).unwrap(); assert_eq!(config.callers[0].allowed_models, [HAIKU]); assert_eq!(config.claude_binary_sha256, [0xab; 32]); - assert!(config.lease_callers.is_empty()); + assert!(config.lease_holders.is_empty()); } #[test] @@ -304,7 +333,7 @@ fn the_auth_choice_round_trips() { let keyed = ClaudeConnectorConfig { auth: ClaudeAuth::ApiKey, lease_socket: None, - lease_callers: vec![], + lease_holders: vec![], ..valid() }; write_config(&path, &keyed).unwrap(); @@ -354,7 +383,7 @@ struct BeforeAuth { #[cultcache(key = 19)] lease_socket: Option, #[cultcache(key = 20)] - lease_callers: Vec, + lease_holders: Vec, #[cultcache(key = 21)] lease_max_ms: u64, #[cultcache(key = 22)] @@ -395,7 +424,7 @@ fn a_document_from_before_the_auth_field_is_refused_until_it_is_authored_again() max_expiry_skew_ms: now.max_expiry_skew_ms, callers: now.callers.clone(), lease_socket: now.lease_socket.clone(), - lease_callers: now.lease_callers.clone(), + lease_holders: now.lease_holders.clone(), lease_max_ms: now.lease_max_ms, handle_secret_credential: now.handle_secret_credential.clone(), }, @@ -432,7 +461,7 @@ fn keyed_with_a_lease() -> ClaudeConnectorConfig { fn a_key_is_never_lent_so_no_lease_socket_or_row_may_accompany_it() { assert_eq!(refused(&keyed_with_a_lease()), "auth"); let socket_only = ClaudeConnectorConfig { - lease_callers: vec![], + lease_holders: vec![], ..keyed_with_a_lease() }; assert_eq!(refused(&socket_only), "auth"); @@ -441,12 +470,12 @@ fn a_key_is_never_lent_so_no_lease_socket_or_row_may_accompany_it() { ..keyed_with_a_lease() }; assert_eq!(refused(&rows_only), "auth"); - let personas_only = ClaudeConnectorConfig { + let callers_only = ClaudeConnectorConfig { lease_socket: None, - lease_callers: vec![], + lease_holders: vec![], ..keyed_with_a_lease() }; - assert!(personas_only.validate().is_ok()); + assert!(callers_only.validate().is_ok()); let scratch = Scratch::new(); assert!(write_config(&scratch.path("keyed.cc"), &keyed_with_a_lease()).is_err()); } @@ -457,11 +486,13 @@ fn config_init_refuses_a_key_with_a_lease_and_accepts_it_without() { "--lease-socket", "/run/claude-connector/lease.sock", "--lease-user", - "mind-a-self", - "--turn", - "self", - "--lease-unit-instance", - "a", + "agent-a", + "--provider", + "claude-code", + "--unit", + "agent@a.service", + "--scope", + "per-caller", ]; let scratch = Scratch::new(); let leased = init(&scratch, &init_flags(&scratch, &[&["--auth", "api-key"], &lease[..]].concat())); @@ -472,6 +503,120 @@ fn config_init_refuses_a_key_with_a_lease_and_accepts_it_without() { assert!(bare.status.success(), "{bare:?}"); } +#[test] +fn add_lease_holder_and_unit_validation() { + let scratch = Scratch::new(); + let config_path = scratch.path("connector.cc"); + let made = init( + &scratch, + &init_flags( + &scratch, + &[ + "--lease-socket", + "/run/claude-connector/lease.sock", + "--lease-user", + "agent-a", + "--provider", + "claude-code", + "--unit", + "worker.service", + "--scope", + "per-caller", + ], + ), + ); + assert!(made.status.success(), "{made:?}"); + let p = config_path.to_str().unwrap(); + + let added = run(&[ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-b", + "--caller-id", + "persona-a-caller", + "--provider", + "claude-code", + "--unit", + "agent@b.service", + "--scope", + "per-invocation", + ]); + assert!(added.status.success(), "{added:?}"); + let config = load_config(&config_path).unwrap(); + assert_eq!(config.lease_holders.len(), 2); + assert_eq!(config.lease_holders[0].unit, "worker.service"); + assert_eq!(config.lease_holders[0].scope, LeaseScope::PerCaller); + assert_eq!(config.lease_holders[1].unit, "agent@b.service"); + assert_eq!(config.lease_holders[1].scope, LeaseScope::PerInvocation); + + for bad_args in [ + vec![ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--provider", + "claude-code", + "--unit", + "agent@.service", + "--scope", + "per-caller", + ], + vec![ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--provider", + "other", + "--unit", + "agent@c.service", + "--scope", + "per-caller", + ], + vec![ + "config", + "add-lease-holder", + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--provider", + "claude-code", + "--unit", + "agent@c.service", + "--scope", + "invalid", + ], + vec![ + "config", + concat!("add-lease-", "caller"), + p, + "--lease-user", + "agent-c", + "--caller-id", + "persona-a-caller", + "--turn", + "self", + "--lease-unit-instance", + "c", + ], + ] { + let out = run(&bad_args); + assert!(!out.status.success(), "{bad_args:?} unexpectedly succeeded"); + } + assert_eq!(load_config(&config_path).unwrap().lease_holders.len(), 2); +} + #[test] fn serve_and_check_refuse_a_key_document_that_carries_a_lease() { let scratch = Scratch::new(); diff --git a/crates/claude-connector/tests/lease.rs b/crates/claude-connector/tests/lease.rs index 9c6f27d..d51ba6a 100644 --- a/crates/claude-connector/tests/lease.rs +++ b/crates/claude-connector/tests/lease.rs @@ -1,4 +1,4 @@ -//! The Self-run credential lease over a real unix socket: who may lease, where +//! The credential lease over a real unix socket: who may lease, where //! the token goes, what ends a lease, and the one usage-derived refusal, the //! provider's own. Nothing is reserved and nothing is billed. The unit a peer //! runs in is the `PeerUnits` port, answered here by a fake. @@ -14,18 +14,17 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use claude_connector::{ - LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, + LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource, decode_frame, encode_frame, serve_leases, }; -use model_connector::{CallerAdmission, LeaseTurn, PlanQuota, TransportService, UsageReadout}; +use model_connector::{CallerAdmission, LeaseScope, PlanQuota, TransportService, UsageReadout}; use zeroize::Zeroizing; const CALLER: &str = "eureka"; const MODEL: &str = "claude-opus-5-1"; const TOKEN: &str = "sk-canary-lease-4c1f9a"; -const INSTANCE: &str = "eureka"; -const UNIT: &str = "mind-self@eureka.service"; +const UNIT: &str = "agent@alice.service"; static SEQUENCE: AtomicUsize = AtomicUsize::new(0); @@ -102,7 +101,7 @@ struct Harness { } impl Harness { - /// The peers connect from invocation `n` of the Self unit. + /// The peers connect from invocation `n` of the configured unit. fn enter(&self, n: u64) { self.run_in(UNIT, n); } @@ -224,7 +223,8 @@ fn contains(haystack: &[u8], needle: &str) -> bool { /// What a harness is built from. struct Setup { uid: u32, - turn: LeaseTurn, + scope: LeaseScope, + unit: &'static str, token: Option<&'static str>, max_connections: usize, } @@ -232,14 +232,15 @@ struct Setup { fn setup() -> Setup { Setup { uid: own_uid(), - turn: LeaseTurn::SelfRun, + scope: LeaseScope::PerCaller, + unit: UNIT, token: Some(TOKEN), max_connections: 8, } } /// A listener serving `uid` as the caller `eureka`. Peers start in invocation -/// 1 of the Self unit. +/// 1 of the configured unit. fn start(setup: Setup) -> Harness { let units = Arc::new(FakeUnits { peer: Mutex::new(None), @@ -283,16 +284,17 @@ fn start(setup: Setup) -> Harness { tokens.clone(), units.clone(), ); - let caller = LeaseCaller { + let holder = LeaseHolder { uid: setup.uid, caller_id: CALLER.to_string(), - turn: setup.turn, - unit_instance: INSTANCE.to_string(), + provider: "claude-code".to_string(), + unit: setup.unit.to_string(), + scope: setup.scope, }; std::thread::spawn(move || { let _ = serve_leases( &listener, - vec![caller], + vec![holder], LeaseLimits { socket_timeout: Duration::from_secs(2), max_lease_ms: 3_600_000, @@ -449,7 +451,7 @@ fn high_utilization_refuses_nothing() { } #[test] -fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() { +fn a_peer_uid_outside_the_lease_holders_is_refused_and_nothing_is_read() { let harness = start(Setup { uid: own_uid().wrapping_add(1), ..setup() @@ -460,9 +462,9 @@ fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() { } #[test] -fn the_configured_uid_outside_the_self_unit_is_refused_and_nothing_is_read() { +fn the_configured_uid_outside_the_configured_unit_is_refused_and_nothing_is_read() { let harness = start(setup()); - harness.run_in("mind-persona@eureka.service", 1); + harness.run_in("other.service", 1); let answer = ask(&harness, 60_000); assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller)); assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0); @@ -699,7 +701,7 @@ fn a_readout_answers_the_cells_windows_and_lends_nothing() { } #[test] -fn a_peer_outside_the_lease_callers_still_reads_usage() { +fn a_peer_outside_the_lease_holders_still_reads_usage() { let harness = start(Setup { uid: own_uid().wrapping_add(1), ..setup() @@ -726,3 +728,61 @@ fn a_readout_beside_a_held_lease_leaves_it_held() { assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy)); assert!(granted_ok(&held)); } + +#[test] +fn per_invocation_holder_in_configured_unit_leases_and_other_unit_is_refused() { + let harness = start(Setup { + scope: LeaseScope::PerInvocation, + unit: "agent@alice.service", + ..setup() + }); + harness.run_in("agent@alice.service", 1); + let answer = ask(&harness, 60_000); + assert!(granted_ok(&answer)); + assert_eq!( + granted(&answer).lease_id, + format!("lease:{}:invocation", invocation(1)) + ); + + harness.run_in("other.service", 2); + let refused = ask(&harness, 60_000); + assert_eq!(refusal_of(&refused), Some(LeaseRefusalKind::UnknownCaller)); +} + +#[test] +fn per_caller_and_per_invocation_busy_rules() { + let per_caller = start(Setup { + scope: LeaseScope::PerCaller, + ..setup() + }); + let first = ask(&per_caller, 60_000); + assert!(granted_ok(&first)); + assert_eq!( + granted(&first).lease_id, + format!("lease:{}", invocation(1)) + ); + per_caller.enter(2); + assert_eq!( + refusal_of(&ask(&per_caller, 60_000)), + Some(LeaseRefusalKind::Busy) + ); + drop(first); + + let per_invocation = start(Setup { + scope: LeaseScope::PerInvocation, + ..setup() + }); + let inv1 = ask(&per_invocation, 60_000); + assert!(granted_ok(&inv1)); + assert_eq!( + refusal_of(&ask(&per_invocation, 60_000)), + Some(LeaseRefusalKind::Busy) + ); + per_invocation.enter(2); + let inv2 = ask(&per_invocation, 60_000); + assert!(granted_ok(&inv2)); + assert_eq!( + granted(&inv2).lease_id, + format!("lease:{}:invocation", invocation(2)) + ); +} diff --git a/crates/claude-connector/tests/lease_run.rs b/crates/claude-connector/tests/lease_run.rs new file mode 100644 index 0000000..27f120c --- /dev/null +++ b/crates/claude-connector/tests/lease_run.rs @@ -0,0 +1,241 @@ +//! Integration tests for `claude-connector lease run`. +#![cfg(target_os = "linux")] + +use std::io::{self, Read, Write}; +use std::mem::{size_of, zeroed}; +use std::os::fd::{AsRawFd, RawFd}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::PathBuf; +use std::process::Command; +use std::ptr; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use claude_connector::{ + LeaseGranted, LeaseMessage, LeaseRefusalKind, LeaseRefused, MAX_LEASE_FRAME_BYTES, + decode_frame, encode_frame, +}; + +static SEQUENCE: AtomicUsize = AtomicUsize::new(0); + +struct Scratch(PathBuf); + +impl Scratch { + fn new() -> Self { + let dir = std::env::temp_dir().join(format!( + "claude-lease-run-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::SeqCst) + )); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn path(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn read_request_frame(stream: &mut UnixStream) -> LeaseMessage { + let mut len_buf = [0_u8; 4]; + stream.read_exact(&mut len_buf).unwrap(); + let len = u32::from_be_bytes(len_buf) as usize; + assert!(len > 0 && len <= MAX_LEASE_FRAME_BYTES); + let mut body = vec![0_u8; len]; + stream.read_exact(&mut body).unwrap(); + let mut whole = Vec::with_capacity(4 + len); + whole.extend_from_slice(&len_buf); + whole.extend_from_slice(&body); + decode_frame(&whole).unwrap() +} + +fn send_with_fd(stream: &UnixStream, frame: &[u8], fd: RawFd) -> io::Result<()> { + let fd_size = size_of::() as u32; + // SAFETY: `CMSG_SPACE` is a pure size computation. + let space = unsafe { libc::CMSG_SPACE(fd_size) } as usize; + let mut control = vec![0_u64; space.div_ceil(size_of::())]; + let mut vector = libc::iovec { + iov_base: frame.as_ptr().cast_mut().cast(), + iov_len: frame.len(), + }; + // SAFETY: buffers outlive `sendmsg` and `control` is sized for one fd. + let sent = unsafe { + let mut message: libc::msghdr = zeroed(); + message.msg_iov = &mut vector; + message.msg_iovlen = 1; + message.msg_control = control.as_mut_ptr().cast(); + message.msg_controllen = space as _; + let header = libc::CMSG_FIRSTHDR(&message); + (*header).cmsg_level = libc::SOL_SOCKET; + (*header).cmsg_type = libc::SCM_RIGHTS; + (*header).cmsg_len = libc::CMSG_LEN(fd_size) as _; + ptr::copy_nonoverlapping( + ptr::from_ref(&fd).cast::(), + libc::CMSG_DATA(header), + size_of::(), + ); + libc::sendmsg(stream.as_raw_fd(), &message, libc::MSG_NOSIGNAL) + }; + let Ok(sent) = usize::try_from(sent) else { + return Err(io::Error::last_os_error()); + }; + let mut stream = stream; + stream.write_all(&frame[sent..]) +} + +#[test] +fn fake_lender_fd3_status_and_socket_hold() { + const TOKEN: &str = "sk-canary-lease-run-88f1c"; + let scratch = Scratch::new(); + let socket = scratch.path("lease.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + + let started_flag = scratch.path("child.started"); + let release_flag = scratch.path("lender.checked"); + let token_seen = scratch.path("child.token"); + let eof_seen = Arc::new(AtomicBool::new(false)); + let eof_seen_lender = eof_seen.clone(); + + let lender = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let req = read_request_frame(&mut stream); + assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_))); + + let (read_end, mut write_end) = std::io::pipe().unwrap(); + write_end.write_all(TOKEN.as_bytes()).unwrap(); + drop(write_end); + + let frame = encode_frame(&LeaseMessage::ClaudeLeaseGrant(LeaseGranted { + lease_id: "lease:test-run".to_string(), + plan_quota: vec![], + })); + send_with_fd(&stream, &frame, read_end.as_raw_fd()).unwrap(); + drop(read_end); + + let mut buf = [0_u8; 16]; + loop { + match stream.read(&mut buf) { + Ok(0) | Err(_) => { + eof_seen_lender.store(true, Ordering::Release); + break; + } + Ok(_) => {} + } + } + }); + + // Child reads fd 3, checks env/cmdline do not hold the token, signals startup, + // waits for the test thread to assert the lender socket is still open, and exits 42. + let script = format!( + r#"set -eu +test "${{CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR:-}}" = "3" +tok=$(cat <&3) +printf '%s' "$tok" > "{token_seen}" +if env | grep -qF "{TOKEN}"; then exit 91; fi +if tr '\0' '\n' < /proc/self/cmdline | grep -qF "{TOKEN}"; then exit 92; fi +: > "{started_flag}" +i=0 +while [ ! -e "{release_flag}" ]; do + i=$((i + 1)) + if [ "$i" -gt 200 ]; then exit 93; fi + sleep 0.05 +done +exit 42 +"#, + token_seen = token_seen.display(), + started_flag = started_flag.display(), + release_flag = release_flag.display(), + ); + + let mut child = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args([ + "lease", + "run", + "--socket", + socket.to_str().unwrap(), + "--", + "/bin/sh", + "-c", + &script, + ]) + .env("KEEP_INHERITED", "yes") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap(); + + let deadline = Instant::now() + Duration::from_secs(10); + while !started_flag.exists() { + assert!(Instant::now() < deadline, "leased child never started"); + std::thread::sleep(Duration::from_millis(20)); + } + assert!( + !eof_seen.load(Ordering::Acquire), + "lender saw EOF while leased child was still running" + ); + std::fs::write(&release_flag, b"ok").unwrap(); + + let output = child.wait_with_output().unwrap(); + assert_eq!(output.status.code(), Some(42), "{output:?}"); + assert_eq!(std::fs::read_to_string(&token_seen).unwrap(), TOKEN); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains(TOKEN), "{stderr}"); + + lender.join().unwrap(); + assert!( + eof_seen.load(Ordering::Acquire), + "lender did not see EOF after child exited" + ); +} + +#[test] +fn refused_busy_and_unknown_caller_do_not_spawn() { + const CANARY_DETAIL: &str = "CANARY-REFUSAL-DETAIL-7f3a"; + for kind in [LeaseRefusalKind::Busy, LeaseRefusalKind::UnknownCaller] { + let scratch = Scratch::new(); + let socket = scratch.path("lease.sock"); + let spawned_marker = scratch.path("should-not-exist"); + let listener = UnixListener::bind(&socket).unwrap(); + + let lender = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let req = read_request_frame(&mut stream); + assert!(matches!(req, LeaseMessage::ClaudeLeaseRequest(_))); + let frame = encode_frame(&LeaseMessage::ClaudeLeaseRefusal(LeaseRefused { + kind, + detail: CANARY_DETAIL.to_string(), + })); + stream.write_all(&frame).unwrap(); + }); + + let output = Command::new(env!("CARGO_BIN_EXE_claude-connector")) + .args([ + "lease", + "run", + "--socket", + socket.to_str().unwrap(), + "--", + "/bin/sh", + "-c", + &format!("touch '{}'", spawned_marker.display()), + ]) + .output() + .unwrap(); + + lender.join().unwrap(); + assert!(!output.status.success(), "{kind:?}: {output:?}"); + assert!( + !spawned_marker.exists(), + "{kind:?}: child spawned on refusal" + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!stderr.contains(CANARY_DETAIL), "{kind:?}: {stderr}"); + } +} diff --git a/crates/model-connector/src/serve.rs b/crates/model-connector/src/serve.rs index 2c2ac91..dfd368c 100644 --- a/crates/model-connector/src/serve.rs +++ b/crates/model-connector/src/serve.rs @@ -172,7 +172,7 @@ pub fn serve( } /// `serve` over a service the caller opened and keeps a handle to, so another -/// front of the same service (the Self-run credential lease) shares its +/// front of the same service (the credential lease) shares its /// replay store and plan. The limits must already have been validated against the /// service's admissions. pub fn serve_service( diff --git a/crates/model-connector/src/service.rs b/crates/model-connector/src/service.rs index 5fe2db8..6127018 100644 --- a/crates/model-connector/src/service.rs +++ b/crates/model-connector/src/service.rs @@ -110,10 +110,10 @@ pub(crate) fn provider_rejects(plan: &PlanQuotaSnapshot, now_unix_ms: u64) -> bo .any(|window| window.status == REJECTED && window.resets_at_unix_ms > now_unix_ms) } -/// A Self run's or Persona turn's credential lease while its holder keeps it. +/// A credential lease while its holder keeps it. #[derive(Debug, Clone, Copy)] struct LiveLease { - turn: LeaseTurn, + scope: LeaseScope, expires_at_unix_ms: u64, } @@ -779,7 +779,7 @@ fn replay_store_error(error: impl std::fmt::Display) -> ServiceError { } mod lease; -pub use lease::{LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn}; +pub use lease::{LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope}; fn contract_refusal(error: &ContractError) -> Refusal { match error { diff --git a/crates/model-connector/src/service/lease.rs b/crates/model-connector/src/service/lease.rs index 5d55bf3..c67bec4 100644 --- a/crates/model-connector/src/service/lease.rs +++ b/crates/model-connector/src/service/lease.rs @@ -1,27 +1,29 @@ -//! A credential lease: a Self run's or a Persona turn's hold on the token the -//! connector lends. The lease is memory bound to its holder's open connection, -//! not a record and not a charge: it decides `Busy` while it is held and -//! nothing else. It ends when its holder lets go (`end_lease`), when the unit -//! invocation it served ends, or when its expiry passes. Nothing is billed and -//! nothing is reserved. The only usage-derived refusal is the provider's own -//! (`ProviderRejected`), repeated with the provider's own expiry. +//! A credential lease: a holder's hold on the token the connector lends. +//! The lease is memory bound to its holder's open connection, not a record and +//! not a charge: it decides `Busy` while it is held and nothing else. It ends +//! when its holder lets go (`end_lease`), when the unit invocation it served +//! ends, or when its expiry passes. Nothing is billed and nothing is reserved. +//! The only usage-derived refusal is the provider's own (`ProviderRejected`), +//! repeated with the provider's own expiry. use super::*; /// The request-id namespace of leases. const LEASE_PREFIX: &str = "lease:"; -/// What a Persona turn's lease id adds to its invocation id, so a Persona -/// lease and a Self lease of one caller and one invocation never share an id. -const PERSONA_SUFFIX: &str = ":persona"; +/// What a per-invocation lease id adds to its invocation id, so a +/// per-invocation lease and a per-caller lease of one caller and one +/// invocation never share an id. +const INVOCATION_SUFFIX: &str = ":invocation"; -/// Which kind of turn a lease serves. It is a property of the lease caller's -/// configured row, never of a request. A caller holds one Self lease at a -/// time; a Persona turn holds one lease per live invocation, one at a time. +/// Exclusivity scope of a lease. It is a property of the lease holder's +/// configured row, never of a request. A `PerCaller` holder keeps one lease open +/// per caller at a time; a `PerInvocation` holder keeps one lease open per live +/// unit invocation at a time. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum LeaseTurn { - SelfRun, - PersonaTurn, +pub enum LeaseScope { + PerCaller, + PerInvocation, } /// What an admitted lease holds. @@ -34,8 +36,8 @@ pub struct LeaseGrant { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LeaseRefusal { UnknownCaller, - /// A Self run: the caller holds a Self lease now. A Persona turn: this - /// invocation holds a lease now. + /// `PerCaller`: the caller holds a per-caller lease now. `PerInvocation`: + /// this invocation holds a lease now. Busy, /// The provider is refusing right now and has said until when. ProviderRejected, @@ -49,16 +51,16 @@ pub enum LeaseAdmission { impl TransportService { /// Grants `caller_runtime_id` a lease for the unit invocation - /// `invocation_id` until `expires_at_unix_ms`. A Self run's lease is - /// `lease:` and one is open per caller; a Persona turn's is - /// `lease::persona`, one open per invocation; neither blocks - /// the other. A lease takes no request slot. `plan` is the backend's plan - /// quota as it stands: a provider that is refusing right now refuses the - /// lease. A lease past its expiry no longer holds anything. + /// `invocation_id` until `expires_at_unix_ms`. A `PerCaller` lease is + /// `lease:` and one is open per caller; a `PerInvocation` lease + /// is `lease::invocation`, one open per invocation; neither + /// blocks the other. A lease takes no request slot. `plan` is the backend's + /// plan quota as it stands: a provider that is refusing right now refuses + /// the lease. A lease past its expiry no longer holds anything. pub fn begin_lease( &mut self, caller_runtime_id: &str, - turn: LeaseTurn, + scope: LeaseScope, invocation_id: &str, expires_at_unix_ms: u64, now_unix_ms: u64, @@ -68,9 +70,9 @@ impl TransportService { return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller)); } require_id(invocation_id, "invocation_id")?; - let suffix = match turn { - LeaseTurn::SelfRun => "", - LeaseTurn::PersonaTurn => PERSONA_SUFFIX, + let suffix = match scope { + LeaseScope::PerCaller => "", + LeaseScope::PerInvocation => INVOCATION_SUFFIX, }; let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}"); if lease_id.len() > MAX_IDENTITY_BYTES { @@ -82,11 +84,11 @@ impl TransportService { caller_runtime_id: caller_runtime_id.to_string(), request_id: lease_id.clone(), }; - let busy = match turn { - LeaseTurn::SelfRun => self.leases.iter().any(|(held, lease)| { - lease.turn == LeaseTurn::SelfRun && held.caller_runtime_id == caller_runtime_id + let busy = match scope { + LeaseScope::PerCaller => self.leases.iter().any(|(held, lease)| { + lease.scope == LeaseScope::PerCaller && held.caller_runtime_id == caller_runtime_id }), - LeaseTurn::PersonaTurn => self.leases.contains_key(&identity), + LeaseScope::PerInvocation => self.leases.contains_key(&identity), }; if busy { return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy)); @@ -97,7 +99,7 @@ impl TransportService { self.leases.insert( identity, LiveLease { - turn, + scope, expires_at_unix_ms, }, ); @@ -155,17 +157,17 @@ mod tests { fn lease_in( service: &mut TransportService, - turn: LeaseTurn, + scope: LeaseScope, run: &str, plan: &PlanQuotaSnapshot, ) -> LeaseAdmission { service - .begin_lease(CALLER, turn, run, NOW + 60_000, NOW, plan) + .begin_lease(CALLER, scope, run, NOW + 60_000, NOW, plan) .unwrap() } fn lease(service: &mut TransportService, run: &str) -> LeaseAdmission { - lease_in(service, LeaseTurn::SelfRun, run, &none()) + lease_in(service, LeaseScope::PerCaller, run, &none()) } fn granted(admission: LeaseAdmission) -> LeaseGrant { @@ -186,7 +188,7 @@ mod tests { } #[test] - fn a_caller_holds_one_self_lease_at_a_time() { + fn a_per_caller_holder_holds_one_lease_at_a_time() { let store = TestStore::new(); let mut service = open(&store); granted(lease(&mut service, "run-1")); @@ -223,14 +225,14 @@ mod tests { let mut service = open(&store); granted( service - .begin_lease(CALLER, LeaseTurn::SelfRun, "run-1", NOW + 10, NOW, &none()) + .begin_lease(CALLER, LeaseScope::PerCaller, "run-1", NOW + 10, NOW, &none()) .unwrap(), ); assert_eq!( service .begin_lease( CALLER, - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-2", NOW + 99, NOW + 9, @@ -244,7 +246,7 @@ mod tests { service .begin_lease( CALLER, - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-2", NOW + 99, NOW + 10, @@ -262,7 +264,7 @@ mod tests { service .begin_lease( "stranger", - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-1", NOW + 1, NOW, @@ -274,22 +276,22 @@ mod tests { } #[test] - fn a_persona_holds_one_lease_per_invocation_and_never_blocks_the_self_lease() { + fn a_per_invocation_holder_holds_one_lease_per_invocation_and_never_blocks_per_caller() { let store = TestStore::new(); let mut service = open(&store); - let persona = |service: &mut TransportService, run: &str| { - lease_in(service, LeaseTurn::PersonaTurn, run, &none()) + let per_invocation = |service: &mut TransportService, run: &str| { + lease_in(service, LeaseScope::PerInvocation, run, &none()) }; - let first = granted(persona(&mut service, "turn-1")); - assert_eq!(first.lease_id, "lease:turn-1:persona"); + let first = granted(per_invocation(&mut service, "turn-1")); + assert_eq!(first.lease_id, "lease:turn-1:invocation"); assert_eq!( - persona(&mut service, "turn-1"), + per_invocation(&mut service, "turn-1"), LeaseAdmission::Refused(LeaseRefusal::Busy) ); - granted(persona(&mut service, "turn-2")); + granted(per_invocation(&mut service, "turn-2")); granted(lease(&mut service, "turn-1")); service.end_lease(CALLER, &first.lease_id); - granted(persona(&mut service, "turn-1")); + granted(per_invocation(&mut service, "turn-1")); } #[test] @@ -298,7 +300,7 @@ mod tests { let mut service = open(&store); let rejected = window(1_000, "rejected", NOW + 5_000); assert_eq!( - lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &rejected), + lease_in(&mut service, LeaseScope::PerCaller, "run-1", &rejected), LeaseAdmission::Refused(LeaseRefusal::ProviderRejected) ); let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| { @@ -338,7 +340,7 @@ mod tests { service .begin_lease( CALLER, - LeaseTurn::SelfRun, + LeaseScope::PerCaller, "run-1", NOW + 9_000, NOW + 5_000, @@ -354,11 +356,11 @@ mod tests { let store = TestStore::new(); let mut service = open(&store); let full = window(999, "allowed", NOW + 5_000); - granted(lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &full)); + granted(lease_in(&mut service, LeaseScope::PerCaller, "run-1", &full)); let warned = window(1_000, "allowed_warning", NOW + 5_000); granted(lease_in( &mut service, - LeaseTurn::PersonaTurn, + LeaseScope::PerInvocation, "turn-1", &warned, )); @@ -371,30 +373,37 @@ mod tests { let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len()); let grant = granted(lease(&mut service, &longest)); assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES); - assert!(lease_try(&mut service, LeaseTurn::SelfRun, &format!("{longest}r")).is_err()); + assert!(lease_try(&mut service, LeaseScope::PerCaller, &format!("{longest}r")).is_err()); } #[test] - fn a_persona_invocation_id_leaves_room_for_its_suffix() { + fn a_per_invocation_id_leaves_room_for_its_suffix() { let store = TestStore::new(); let mut service = open(&store); - let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - PERSONA_SUFFIX.len()); + let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len() - INVOCATION_SUFFIX.len()); let grant = granted(lease_in( &mut service, - LeaseTurn::PersonaTurn, + LeaseScope::PerInvocation, &longest, &none(), )); assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES); - assert!(lease_try(&mut service, LeaseTurn::PersonaTurn, &format!("{longest}r")).is_err()); + assert!( + lease_try( + &mut service, + LeaseScope::PerInvocation, + &format!("{longest}r") + ) + .is_err() + ); } fn lease_try( service: &mut TransportService, - turn: LeaseTurn, + scope: LeaseScope, run: &str, ) -> Result { - service.begin_lease(CALLER, turn, run, NOW + 60_000, NOW, &none()) + service.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, &none()) } #[test] @@ -421,7 +430,7 @@ mod tests { // And a call in flight does not make the caller busy for a lease. granted(lease_in( &mut service, - LeaseTurn::PersonaTurn, + LeaseScope::PerInvocation, "turn-1", &none(), ));