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.
This commit is contained in:
Meta Vens 2026-12-03 21:07:38 +01:00
commit 38f66dd29c
16 changed files with 1126 additions and 265 deletions

View file

@ -11,7 +11,7 @@ use std::time::Duration;
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{ 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, ServeLimits, ServiceError, TransportService, load_admissions, serve_service,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -19,7 +19,7 @@ use thiserror::Error;
use crate::backend::readiness; use crate::backend::readiness;
#[cfg(target_os = "linux")] #[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")] #[cfg(target_os = "linux")]
use crate::unit::SystemdUnits; use crate::unit::SystemdUnits;
#[cfg(unix)] #[cfg(unix)]
@ -32,18 +32,18 @@ use crate::{
const CONFIG_KEY: &str = "runtime"; const CONFIG_KEY: &str = "runtime";
const MODEL_PREFIX: &str = "claude-"; const MODEL_PREFIX: &str = "claude-";
/// A unix account that may lease the subscription token for a Self run or a /// A unix account that may lease the subscription token, the provider and full
/// Persona turn, the unit its process must run in (`mind-self@<unit_instance>` /// systemd unit its process must run in, its exclusivity scope, and the
/// or `mind-persona@<unit_instance>`, by `turn`), and the configured caller /// configured caller whose name its leases carry.
/// whose name its leases carry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeaseCallerConfig { pub struct LeaseHolderConfig {
pub unix_user: String, pub unix_user: String,
pub caller_id: String, pub caller_id: String,
/// The kind of turn this account leases for: it fixes the unit, `mind-self@` pub provider: String,
/// or `mind-persona@`, its process must run in. pub unit: String,
pub turn: LeaseTurn, /// Exclusivity scope of this holder's leases: one per caller or one per
pub unit_instance: String, /// unit invocation.
pub scope: LeaseScope,
} }
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[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. /// Ids are unique. Handles are bound to the caller that was given them.
#[cultcache(key = 17)] #[cultcache(key = 17)]
pub callers: Vec<CallerConfig>, pub callers: Vec<CallerConfig>,
/// 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. /// or none when this connector lends no token.
#[cultcache(key = 19)] #[cultcache(key = 19)]
pub lease_socket: Option<PathBuf>, pub lease_socket: Option<PathBuf>,
/// The accounts allowed to lease, each bound to a configured caller. /// The accounts allowed to lease, each bound to a configured caller.
/// Empty exactly when `lease_socket` is none. /// Empty exactly when `lease_socket` is none.
#[cultcache(key = 20)] #[cultcache(key = 20)]
pub lease_callers: Vec<LeaseCallerConfig>, pub lease_holders: Vec<LeaseHolderConfig>,
/// The furthest a lease's expiry may lie from now. /// The furthest a lease's expiry may lie from now.
#[cultcache(key = 21)] #[cultcache(key = 21)]
pub lease_max_ms: u64, pub lease_max_ms: u64,
@ -249,17 +249,17 @@ impl ClaudeConnectorConfig {
fn validate_leases(&self) -> Result<(), ConfigError> { fn validate_leases(&self) -> Result<(), ConfigError> {
// A key has no plan and is never lent: no lease socket, no lease row, whatever else the // 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 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")); return Err(ConfigError::Invalid("auth"));
} }
let Some(socket) = &self.lease_socket else { let Some(socket) = &self.lease_socket else {
return if self.lease_callers.is_empty() { return if self.lease_holders.is_empty() {
Ok(()) Ok(())
} else { } else {
Err(ConfigError::Invalid("lease_callers")) Err(ConfigError::Invalid("lease_holders"))
}; };
}; };
if !socket.is_absolute() { if !socket.is_absolute() {
@ -269,18 +269,19 @@ impl ClaudeConnectorConfig {
return Err(ConfigError::Invalid("lease_max_ms")); return Err(ConfigError::Invalid("lease_max_ms"));
} }
let mut users = BTreeSet::new(); let mut users = BTreeSet::new();
if self.lease_callers.is_empty() if self.lease_holders.is_empty()
|| !self.lease_callers.iter().all(|lease| { || !self.lease_holders.iter().all(|lease| {
is_trimmed_nonempty(&lease.unix_user) is_trimmed_nonempty(&lease.unix_user)
&& self && self
.callers .callers
.iter() .iter()
.any(|caller| caller.caller_runtime_id == lease.caller_id) .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()) && users.insert(lease.unix_user.as_str())
}) })
{ {
return Err(ConfigError::Invalid("lease_callers")); return Err(ConfigError::Invalid("lease_holders"));
} }
Ok(()) Ok(())
} }
@ -322,12 +323,29 @@ impl ClaudeConnectorConfig {
} }
} }
/// The `<instance>` of a unit name, as plain as a systemd instance can be. /// A systemd service unit name: `name.service` or `name@instance.service`.
fn is_unit_instance(text: &str) -> bool { fn is_systemd_unit_name(text: &str) -> bool {
!text.is_empty() if text.len() > 256 {
&& text return false;
.bytes() }
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) 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 { fn is_trimmed_nonempty(text: &str) -> bool {
@ -479,7 +497,7 @@ fn readiness_of(config: &ClaudeConnectorConfig) -> Result<Vec<CallerAdmission>,
} }
} }
if config.lease_socket.is_some() { if config.lease_socket.is_some() {
lease_callers_of(config)?; lease_holders_of(config)?;
} }
Ok(admissions) Ok(admissions)
} }
@ -487,26 +505,27 @@ fn readiness_of(config: &ClaudeConnectorConfig) -> Result<Vec<CallerAdmission>,
/// The accounts allowed to lease, resolved to the uids the kernel will report /// 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. /// for their connections. An account the system does not have is not ready.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn lease_callers_of(config: &ClaudeConnectorConfig) -> Result<Vec<LeaseCaller>, ConfigError> { fn lease_holders_of(config: &ClaudeConnectorConfig) -> Result<Vec<LeaseHolder>, ConfigError> {
config config
.lease_callers .lease_holders
.iter() .iter()
.map(|lease| { .map(|lease| {
user_uid(&lease.unix_user) user_uid(&lease.unix_user)
.map(|uid| LeaseCaller { .map(|uid| LeaseHolder {
uid, uid,
caller_id: lease.caller_id.clone(), caller_id: lease.caller_id.clone(),
turn: lease.turn, provider: lease.provider.clone(),
unit_instance: lease.unit_instance.clone(), unit: lease.unit.clone(),
scope: lease.scope,
}) })
.ok_or(ConfigError::Unusable("lease_callers")) .ok_or(ConfigError::Unusable("lease_holders"))
}) })
.collect() .collect()
} }
/// Peer credentials identify a lease caller only on Linux. /// Peer credentials identify a lease holder only on Linux.
#[cfg(not(target_os = "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")) Err(ConfigError::Unusable("lease_socket"))
} }
@ -524,7 +543,7 @@ fn start_leases(
use std::os::unix::fs::{FileTypeExt, PermissionsExt}; use std::os::unix::fs::{FileTypeExt, PermissionsExt};
use std::os::unix::net::UnixListener; 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. // 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()) { if std::fs::symlink_metadata(socket).is_ok_and(|found| found.file_type().is_socket()) {
let _ = std::fs::remove_file(socket); let _ = std::fs::remove_file(socket);
@ -545,7 +564,7 @@ fn start_leases(
.spawn(move || { .spawn(move || {
let _ = serve_leases( let _ = serve_leases(
&listener, &listener,
callers, holders,
limits, limits,
service, service,
quota, 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: /// [`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)] #[cfg(unix)]
fn serve_config_with( fn serve_config_with(
path: &Path, path: &Path,
@ -701,7 +720,7 @@ mod tests {
max_output_tokens: 32_768, max_output_tokens: 32_768,
}], }],
lease_socket: None, lease_socket: None,
lease_callers: Vec::new(), lease_holders: Vec::new(),
lease_max_ms: 3_600_000, lease_max_ms: 3_600_000,
}; };
write_config(&at("connector.cc"), &config).unwrap(); write_config(&at("connector.cc"), &config).unwrap();
@ -711,10 +730,10 @@ mod tests {
let path = at("connector.cc"); let path = at("connector.cc");
let lease = std::sync::Arc::new(std::sync::Mutex::new(None)); 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 || { let served = std::thread::spawn(move || {
serve_config_with(&path, |cell| { 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(20));
}; };
std::thread::sleep(Duration::from_millis(500)); 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(); let _lease = cell.asking();
while !at("spawned").exists() { while !at("spawned").exists() {
@ -799,6 +818,34 @@ mod tests {
assert!(!written.contains("canary")); 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)] #[cfg(unix)]
mod prompt_dir { mod prompt_dir {
use std::os::unix::fs::{PermissionsExt, chown, symlink}; use std::os::unix::fs::{PermissionsExt, chown, symlink};

View file

@ -19,7 +19,7 @@ use crate::handle::Plan;
/// environment names that descriptor. /// environment names that descriptor.
pub(crate) const TOKEN_FD: i32 = 3; pub(crate) const TOKEN_FD: i32 = 3;
/// The variable that tells the CLI which descriptor holds the subscription token. /// 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"; const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
/// The environment of the child: exactly these names and nothing inherited. /// The environment of the child: exactly these names and nothing inherited.

View file

@ -1,23 +1,22 @@
//! The Self-run credential lease. The connector is the only holder of the //! The credential lease. The connector is the only holder of the
//! subscription token and the one owner of Self-run admission (rulings //! subscription token and the one owner of lease admission. A holder asks
//! self-runs-through-connector and self-run-credential-lease). A Self run asks
//! over a unix socket for a lease. The connector decides who may ask (the //! 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 //! 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 //! 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 //! 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 //! 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 //! 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. //! 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 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 //! (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 //! 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 //! 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` //! a reply frame. The connector spawns nothing here: the holder's `claude`
//! stays in the Self run's own unit. //! stays in the holder's own unit.
use std::ffi::CString; use std::ffi::CString;
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};
@ -31,7 +30,7 @@ use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use model_connector::{ use model_connector::{
LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn, PlanQuota, TransportService, UsageReadout, LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope, PlanQuota, TransportService, UsageReadout,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -173,28 +172,16 @@ fn read_message(stream: &mut impl Bounded, deadline: Instant) -> io::Result<Leas
/// The most a pipe takes in one atomic write. /// The most a pipe takes in one atomic write.
const PIPE_BUF: usize = 4096; const PIPE_BUF: usize = 4096;
/// A unix account allowed to lease, the unit its process must run in (the /// A unix account allowed to lease, the configured systemd unit its process
/// Self or the Persona unit of its instance, by `turn`), and the /// must run in, the provider it leases for, its exclusivity scope, and the
/// caller whose name its leases carry. /// configured caller whose name its leases carry.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct LeaseCaller { pub struct LeaseHolder {
pub uid: u32, pub uid: u32,
pub caller_id: String, pub caller_id: String,
/// Which kind of turn this account leases for; it picks the unit. pub provider: String,
pub turn: LeaseTurn, pub unit: String,
/// The `<instance>` of `mind-self@<instance>.service` or pub scope: LeaseScope,
/// `mind-persona@<instance>.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),
}
}
} }
/// The systemd unit invocation a process runs in. /// The systemd unit invocation a process runs in.
@ -389,7 +376,7 @@ impl Drop for Permit {
} }
struct Lender { struct Lender {
callers: Vec<LeaseCaller>, holders: Vec<LeaseHolder>,
limits: LeaseLimits, limits: LeaseLimits,
service: Arc<Mutex<TransportService>>, service: Arc<Mutex<TransportService>>,
quota: Arc<QuotaCell>, quota: Arc<QuotaCell>,
@ -410,14 +397,13 @@ const READOUT_CONNECTIONS: usize = 4;
/// one usage readout. A lease: request, then grant or refusal, then (after a /// 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 /// 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 /// is the socket's group, and it reads the plan's windows without waking the
/// meter. A caller is /// meter. A holder is the account whose uid the kernel reports for the
/// the account whose uid the kernel reports for the connection, and only a /// connection, and only a process in that holder's configured unit may lease,
/// process in that caller's unit may lease, once per unit invocation for a Self /// once per caller for `PerCaller` and once per unit invocation for
/// run and once per turn for a Persona; no /// `PerInvocation`; no field of any message names either.
/// field of any message names either.
pub fn serve_leases( pub fn serve_leases(
listener: &UnixListener, listener: &UnixListener,
callers: Vec<LeaseCaller>, holders: Vec<LeaseHolder>,
limits: LeaseLimits, limits: LeaseLimits,
service: Arc<Mutex<TransportService>>, service: Arc<Mutex<TransportService>>,
quota: Arc<QuotaCell>, quota: Arc<QuotaCell>,
@ -425,7 +411,7 @@ pub fn serve_leases(
units: Arc<dyn PeerUnits>, units: Arc<dyn PeerUnits>,
) -> io::Result<()> { ) -> io::Result<()> {
let lender = Arc::new(Lender { let lender = Arc::new(Lender {
callers, holders,
limits, limits,
service, service,
quota, quota,
@ -487,7 +473,7 @@ impl Lender {
peer: PeerCredentials, peer: PeerCredentials,
request: LeaseRequest, request: LeaseRequest,
) -> io::Result<()> { ) -> 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( return refuse(
&mut stream, &mut stream,
LeaseRefusalKind::UnknownCaller, LeaseRefusalKind::UnknownCaller,
@ -499,13 +485,13 @@ impl Lender {
let Some(invocation) = peer let Some(invocation) = peer
.process .process
.as_ref() .as_ref()
.and_then(|process| self.units.invocation_in(process.as_fd(), &caller.unit())) .and_then(|process| self.units.invocation_in(process.as_fd(), &holder.unit))
.filter(|found| found.unit == caller.unit()) .filter(|found| found.unit == holder.unit)
else { else {
return refuse( return refuse(
&mut stream, &mut stream,
LeaseRefusalKind::UnknownCaller, LeaseRefusalKind::UnknownCaller,
"this process is not in the Self unit", "this process is not in the configured unit",
); );
}; };
let now = unix_ms(); let now = unix_ms();
@ -522,7 +508,7 @@ impl Lender {
// plan the refusal reads is the one this process last observed, but a // 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 // cell with no weekly reading (a restart empties it) gets the meter's
// first read, bounded, before the lease is lent "unobserved" for its // 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. // ends: the meter reads while one is held or lately asked for.
let _asking = self.quota.asking(); let _asking = self.quota.asking();
let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT); let plan = self.quota.snapshot_with_week(FIRST_READ_WAIT);
@ -532,8 +518,8 @@ impl Lender {
.lock() .lock()
.map_err(|_| io::Error::other("service lock"))? .map_err(|_| io::Error::other("service lock"))?
.begin_lease( .begin_lease(
&caller.caller_id, &holder.caller_id,
caller.turn, holder.scope,
&invocation.invocation_id, &invocation.invocation_id,
request.expires_at_unix_ms, request.expires_at_unix_ms,
now, now,
@ -562,7 +548,7 @@ impl Lender {
}; };
self.hold( self.hold(
stream, stream,
caller, holder,
&grant, &grant,
&invocation, &invocation,
peer.process, peer.process,
@ -579,7 +565,7 @@ impl Lender {
fn hold( fn hold(
&self, &self,
mut stream: UnixStream, mut stream: UnixStream,
caller: &LeaseCaller, holder: &LeaseHolder,
grant: &LeaseGrant, grant: &LeaseGrant,
invocation: &PeerUnit, invocation: &PeerUnit,
process: Option<OwnedFd>, process: Option<OwnedFd>,
@ -588,7 +574,7 @@ impl Lender {
) -> io::Result<()> { ) -> io::Result<()> {
let held = self.keep( let held = self.keep(
&mut stream, &mut stream,
caller, holder,
grant, grant,
invocation, invocation,
process.as_ref(), process.as_ref(),
@ -598,7 +584,7 @@ impl Lender {
self.service self.service
.lock() .lock()
.map_err(|_| io::Error::other("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 held
} }
@ -607,7 +593,7 @@ impl Lender {
fn keep( fn keep(
&self, &self,
stream: &mut UnixStream, stream: &mut UnixStream,
caller: &LeaseCaller, holder: &LeaseHolder,
grant: &LeaseGrant, grant: &LeaseGrant,
invocation: &PeerUnit, invocation: &PeerUnit,
process: Option<&OwnedFd>, process: Option<&OwnedFd>,
@ -651,7 +637,7 @@ impl Lender {
Err(_) => return Ok(()), Err(_) => return Ok(()),
} }
let still = process 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); .is_some_and(|found| found == *invocation);
if !still { if !still {
return Ok(()); return Ok(());
@ -723,7 +709,7 @@ mod tests {
.unwrap(), .unwrap(),
)); ));
let lender = Lender { let lender = Lender {
callers: Vec::new(), holders: Vec::new(),
limits: LeaseLimits { limits: LeaseLimits {
socket_timeout: Duration::from_secs(2), socket_timeout: Duration::from_secs(2),
max_lease_ms: 3_600_000, max_lease_ms: 3_600_000,
@ -747,7 +733,7 @@ mod tests {
thread::spawn(move || { thread::spawn(move || {
let _ = serve_leases( let _ = serve_leases(
&listener, &listener,
lender.callers, lender.holders,
lender.limits, lender.limits,
service, service,
quota, quota,

View file

@ -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<String>,
}
/// 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<ExitStatus, LeaseRunError> {
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<ExitStatus, LeaseRunError> {
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<u8>, Vec<OwnedFd>), LeaseRunError> {
let mut frame = Vec::new();
let mut fds = Vec::new();
let mut expected_total: Option<usize> = 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<OwnedFd>), 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::<RawFd>()) as u32) } as usize;
let mut control = vec![0_u64; space.div_ceil(size_of::<u64>())];
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::<u64>()) 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::<RawFd>();
for index in 0..(cmsg_len - base) / size_of::<RawFd>() {
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<u8>, Vec<OwnedFd>), 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);
}
}

View file

@ -11,6 +11,8 @@ mod handle;
mod launch; mod launch;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
mod lease; mod lease;
#[cfg(target_os = "linux")]
pub mod lease_run;
mod messages; mod messages;
mod meter; mod meter;
mod process; mod process;
@ -22,7 +24,7 @@ mod unit;
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource}; pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits}; pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
pub use daemon::{ pub use daemon::{
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config, ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, check_ready, load_config, write_config,
}; };
#[cfg(unix)] #[cfg(unix)]
pub use daemon::{check_prompt_dir, serve_config}; pub use daemon::{check_prompt_dir, serve_config};
@ -31,7 +33,7 @@ pub use handle::{FsSessionStore, MIN_SECRET_BYTES, SessionStore};
pub use launch::ChildEnv; pub use launch::ChildEnv;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub use lease::{ pub use lease::{
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit, LeaseRequest, LeaseUsageReadoutRequest, MAX_LEASE_FRAME_BYTES, PeerCredentials, PeerUnit,
PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid, PeerUnits, decode_frame, encode_frame, peer_credentials, serve_leases, user_uid,
}; };

View file

@ -3,9 +3,10 @@
//! claude-connector serve --config PATH.cc //! claude-connector serve --config PATH.cc
//! claude-connector config init PATH.cc --flag value ... //! 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-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 config check PATH.cc
//! claude-connector ask --caller-id ID --connection-key-file F --model M (--system TEXT | --system-file F) < prompt //! 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 //! `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 //! `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::ask::{self, AskArgs, AskError};
use claude_connector::{ use claude_connector::{
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready, ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, MIN_SECRET_BYTES,
load_config, write_config, 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 { fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect(); let args: Vec<String> = std::env::args().skip(1).collect();
let args: Vec<&str> = args.iter().map(String::as_str).collect(); let args: Vec<&str> = args.iter().map(String::as_str).collect();
let result = match args.as_slice() { let result = match args.as_slice() {
["serve", "--config", path] => serve(path), ["serve", "--config", path] => serve(path).map(|()| ExitCode::SUCCESS),
["config", "init", path, flags @ ..] => init(path, flags), ["config", "init", path, flags @ ..] => init(path, flags).map(|()| ExitCode::SUCCESS),
["config", "add-caller", path, flags @ ..] => add_caller(path, flags), ["config", "add-caller", path, flags @ ..] => {
["config", "add-lease-caller", path, flags @ ..] => add_lease_caller(path, flags), add_caller(path, flags).map(|()| ExitCode::SUCCESS)
["config", "check", path] => check(path), }
["ask", flags @ ..] => run_ask(flags), ["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), _ => Err(Failure::Usage),
}; };
match result { match result {
Ok(()) => ExitCode::SUCCESS, Ok(code) => code,
Err(failure) => { Err(failure) => {
eprintln!("claude-connector: {failure}"); eprintln!("claude-connector: {failure}");
ExitCode::FAILURE ExitCode::FAILURE
@ -46,7 +52,7 @@ fn main() -> ExitCode {
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
enum Failure { enum Failure {
#[error( #[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, Usage,
#[error(transparent)] #[error(transparent)]
@ -59,6 +65,9 @@ enum Failure {
Flags, Flags,
#[error("{0}")] #[error("{0}")]
Ask(#[from] AskError), Ask(#[from] AskError),
#[cfg(target_os = "linux")]
#[error("{0}")]
LeaseRun(#[from] claude_connector::lease_run::LeaseRunError),
} }
#[cfg(unix)] #[cfg(unix)]
@ -76,7 +85,7 @@ fn check(path: &str) -> Result<(), Failure> {
check_ready(&config)?; check_ready(&config)?;
println!("claude connector configuration is valid and ready to serve"); println!("claude connector configuration is valid and ready to serve");
println!("callers: {}", config.callers.len()); println!("callers: {}", config.callers.len());
println!("lease_callers: {}", config.lease_callers.len()); println!("lease_holders: {}", config.lease_holders.len());
Ok(()) Ok(())
} }
@ -159,7 +168,7 @@ const CALLER: [&str; 5] = [
"--max-output-tokens", "--max-output-tokens",
]; ];
const INIT: [&str; 22] = [ const INIT: [&str; 23] = [
"--auth", "--auth",
"--listen", "--listen",
"--replay-store", "--replay-store",
@ -180,11 +189,12 @@ const INIT: [&str; 22] = [
"--socket-timeout-ms", "--socket-timeout-ms",
"--lease-socket", "--lease-socket",
"--lease-max-ms", "--lease-max-ms",
"--turn", "--provider",
"--lease-unit-instance", "--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 { impl Flags {
fn parse( fn parse(
@ -250,12 +260,12 @@ impl Flags {
} }
} }
/// The kind of turn a leasing account serves: `self` or `persona`. /// The exclusivity scope a leasing account holds: `per-caller` or `per-invocation`.
fn turn(&self) -> Result<LeaseTurn, Failure> { fn scope(&self) -> Result<LeaseScope, Failure> {
match self.text("--turn")?.as_str() { match self.text("--scope")?.as_str() {
"self" => Ok(LeaseTurn::SelfRun), "per-caller" => Ok(LeaseScope::PerCaller),
"persona" => Ok(LeaseTurn::PersonaTurn), "per-invocation" => Ok(LeaseScope::PerInvocation),
_ => Err(Failure::Malformed("--turn")), _ => Err(Failure::Malformed("--scope")),
} }
} }
@ -364,15 +374,16 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
&["--allowed-model", "--lease-user"], &["--allowed-model", "--lease-user"],
)?; )?;
let first = flags.caller()?; let first = flags.caller()?;
let lease_callers = flags let lease_holders = flags
.list("--lease-user") .list("--lease-user")
.iter() .iter()
.map(|unix_user| { .map(|unix_user| {
Ok(LeaseCallerConfig { Ok(LeaseHolderConfig {
unix_user: unix_user.clone(), unix_user: unix_user.clone(),
caller_id: first.caller_runtime_id.clone(), caller_id: first.caller_runtime_id.clone(),
turn: flags.turn()?, provider: flags.text("--provider")?,
unit_instance: flags.text("--lease-unit-instance")?, unit: flags.text("--unit")?,
scope: flags.scope()?,
}) })
}) })
.collect::<Result<Vec<_>, Failure>>()?; .collect::<Result<Vec<_>, Failure>>()?;
@ -398,7 +409,7 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
max_expiry_skew_ms: 300_000, max_expiry_skew_ms: 300_000,
callers: vec![first], callers: vec![first],
lease_socket: flags.single.get("--lease-socket").map(PathBuf::from), 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)?, lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
handle_secret_credential: flags.text("--handle-secret-credential")?, handle_secret_credential: flags.text("--handle-secret-credential")?,
auth: flags.auth()?, auth: flags.auth()?,
@ -434,20 +445,62 @@ fn add_caller(path: &str, args: &[&str]) -> Result<(), Failure> {
Ok(()) Ok(())
} }
/// Appends one leasing account to an existing document that lends a token. /// Appends one lease holder to an existing document that lends a token.
fn add_lease_caller(path: &str, args: &[&str]) -> Result<(), Failure> { fn add_lease_holder(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(args, &[&LEASE_CALLER, &["--lease-user"]], &[])?; let flags = Flags::parse(args, &[&LEASE_HOLDER, &["--lease-user"]], &[])?;
let mut config = load_config(path.as_ref())?; let mut config = load_config(path.as_ref())?;
config.lease_callers.push(LeaseCallerConfig { config.lease_holders.push(LeaseHolderConfig {
unix_user: flags.text("--lease-user")?, unix_user: flags.text("--lease-user")?,
caller_id: flags.text("--caller-id")?, caller_id: flags.text("--caller-id")?,
turn: flags.turn()?, provider: flags.text("--provider")?,
unit_instance: flags.text("--lease-unit-instance")?, unit: flags.text("--unit")?,
scope: flags.scope()?,
}); });
write_config(path.as_ref(), &config)?; write_config(path.as_ref(), &config)?;
Ok(()) Ok(())
} }
#[cfg(target_os = "linux")]
fn run_lease(args: &[&str]) -> Result<ExitCode, Failure> {
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<ExitCode, Failure> {
Err(Failure::Usage)
}
#[cfg(all(test, unix))] #[cfg(all(test, unix))]
mod tests { mod tests {
use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::os::unix::fs::{MetadataExt, PermissionsExt};

View file

@ -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 //! 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 //! `rate_limit_event`, on a call the CLI makes, and lease holders make theirs
//! leases that report nothing back. So when the `seven_day` reading in the //! under leases that report nothing back. So when the `seven_day` reading in
//! [`QuotaCell`] is `STALE` old, the meter makes the smallest real call //! 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 //! 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 //! 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 //! call. The meter holds no credential, speaks no protocol and writes nothing
//! itself. //! itself.
//! //!
//! The meter is driven by the connector's own lease state. It reads only //! 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 //! while a lease is held or one was asked for less than `STALE` ago: an idle
//! swarm brake stops the units, they ask for nothing, and a braked or quiet //! deployment asks for nothing, and idle lease holders spend nothing. A call
//! swarm spends nothing. A call that fails, or completes without refreshing //! that fails, or completes without refreshing the reading, is not retried at
//! the reading, is not retried at the staleness period: the wait doubles per //! the staleness period: the wait doubles per consecutive miss, up to `CEILING`.
//! consecutive miss, up to `CEILING`.
use std::sync::Arc; use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
@ -289,7 +288,7 @@ mod tests {
made: Arc<AtomicUsize>, made: Arc<AtomicUsize>,
script: Arc<Mutex<Script>>, script: Arc<Mutex<Script>>,
log: Arc<Mutex<Vec<String>>>, log: Arc<Mutex<Vec<String>>>,
/// The lease the swarm holds until a test lets go of it. /// The lease held until a test lets go of it.
lease: Option<Asking>, lease: Option<Asking>,
} }
@ -382,7 +381,7 @@ mod tests {
} }
#[test] #[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(); let mut rig = rig();
drop(rig.lease.take()); drop(rig.lease.take());
for step in 0..10 { for step in 0..10 {

View file

@ -46,6 +46,8 @@ pub trait RunningChild: Send {
#[cfg(unix)] #[cfg(unix)]
pub use unix::StdProcessPort; pub use unix::StdProcessPort;
#[cfg(unix)]
pub(crate) use unix::place_fd;
#[cfg(unix)] #[cfg(unix)]
mod unix { mod unix {
@ -77,7 +79,7 @@ mod unix {
/// Makes `source` also descriptor `target`, open across exec. Runs between /// Makes `source` also descriptor `target`, open across exec. Runs between
/// fork and exec in the child, so it calls nothing but `dup2` and `fcntl`. /// 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. // SAFETY: dup2 and fcntl take integers only and are async-signal-safe.
unsafe { unsafe {
if source == target { if source == target {

View file

@ -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 /// own observation: an event that names one window says nothing about the
/// others. /// others.
/// ///
/// It also keeps who is asking: a lease request is the swarm's only sign of /// It also keeps who is asking: a lease request is the connector's sign that a
/// life the connector sees, and the meter reads the plan only while someone /// holder is active, and the meter reads the plan only while someone asks.
/// asks.
#[derive(Default)] #[derive(Default)]
pub struct QuotaCell { pub struct QuotaCell {
windows: Mutex<BTreeMap<String, PlanQuota>>, windows: Mutex<BTreeMap<String, PlanQuota>>,

View file

@ -141,17 +141,16 @@ mod tests {
#[test] #[test]
fn a_service_unit_is_the_last_cgroup_component() { 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!( assert_eq!(
unit_of_cgroup(service).as_deref(), unit_of_cgroup(service).as_deref(),
Some("mind-self@huginn.service") Some("agent@alice.service")
); );
// Several hierarchies listed: the unified one decides. // Several hierarchies listed: the unified one decides.
let hybrid = "12:cpu:/foo\n0::/system.slice/mind-self@a.service\n"; let hybrid = "12:cpu:/foo\n0::/system.slice/agent@a.service\n";
assert_eq!( assert_eq!(unit_of_cgroup(hybrid).as_deref(), Some("agent@a.service"));
unit_of_cgroup(hybrid).as_deref(), let plain = "0::/system.slice/other.service\n";
Some("mind-self@a.service") assert_eq!(unit_of_cgroup(plain).as_deref(), Some("other.service"));
);
} }
#[test] #[test]
@ -160,7 +159,7 @@ mod tests {
"0::/\n", "0::/\n",
"0::/user.slice/user-1000.slice/session-3.scope\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::/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", "0::/system.slice/.service\n",
"1:name=systemd:/system.slice/a.service\n", "1:name=systemd:/system.slice/a.service\n",
"", "",
@ -188,7 +187,7 @@ mod tests {
} }
const ID: &str = "0123456789abcdef0123456789abcdef"; 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` /// A fake `/proc` with one process in `cgroup`, and a fake `systemctl`
/// that records its arguments, runs `side_effect`, and exits `status` /// that records its arguments, runs `side_effect`, and exits `status`

View file

@ -8,10 +8,10 @@ use std::process::{Command, Output};
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use claude_connector::{ 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 cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{CallerConfig, LeaseTurn}; use model_connector::{CallerConfig, LeaseScope};
const OPUS: &str = "claude-opus-5-1"; const OPUS: &str = "claude-opus-5-1";
const HAIKU: &str = "claude-haiku-5-5"; const HAIKU: &str = "claude-haiku-5-5";
@ -72,11 +72,12 @@ fn valid() -> ClaudeConnectorConfig {
max_output_tokens: 32_768, max_output_tokens: 32_768,
}], }],
lease_socket: Some("/run/claude-connector/lease.sock".into()), lease_socket: Some("/run/claude-connector/lease.sock".into()),
lease_callers: vec![LeaseCallerConfig { lease_holders: vec![LeaseHolderConfig {
unix_user: "mind-eureka-self".to_string(), unix_user: "agent-alice".to_string(),
caller_id: "persona-a-caller".to_string(), caller_id: "persona-a-caller".to_string(),
turn: LeaseTurn::SelfRun, provider: "claude-code".to_string(),
unit_instance: "eureka".to_string(), unit: "agent@alice.service".to_string(),
scope: LeaseScope::PerCaller,
}], }],
lease_max_ms: 3_600_000, lease_max_ms: 3_600_000,
} }
@ -183,24 +184,52 @@ fn caller_bounds_are_required_nonzero() {
} }
#[test] #[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(); let mut stranger = valid();
stranger.lease_callers[0].caller_id = "nobody".to_string(); stranger.lease_holders[0].caller_id = "nobody".to_string();
assert_eq!(refused(&stranger), "lease_callers"); assert_eq!(refused(&stranger), "lease_holders");
let mut no_callers = valid(); let mut no_holders = valid();
no_callers.lease_callers.clear(); no_holders.lease_holders.clear();
assert_eq!(refused(&no_callers), "lease_callers"); assert_eq!(refused(&no_holders), "lease_holders");
let mut no_socket = valid(); let mut no_socket = valid();
no_socket.lease_socket = None; no_socket.lease_socket = None;
assert_eq!(refused(&no_socket), "lease_callers"); assert_eq!(refused(&no_socket), "lease_holders");
no_socket.lease_callers.clear(); no_socket.lease_holders.clear();
assert!(no_socket.validate().is_ok()); assert!(no_socket.validate().is_ok());
let mut twice = valid(); let mut twice = valid();
twice.lease_callers.push(twice.lease_callers[0].clone()); twice.lease_holders.push(twice.lease_holders[0].clone());
assert_eq!(refused(&twice), "lease_callers"); 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 { 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(); let config = load_config(&scratch.path("connector.cc")).unwrap();
assert_eq!(config.callers[0].allowed_models, [HAIKU]); assert_eq!(config.callers[0].allowed_models, [HAIKU]);
assert_eq!(config.claude_binary_sha256, [0xab; 32]); assert_eq!(config.claude_binary_sha256, [0xab; 32]);
assert!(config.lease_callers.is_empty()); assert!(config.lease_holders.is_empty());
} }
#[test] #[test]
@ -304,7 +333,7 @@ fn the_auth_choice_round_trips() {
let keyed = ClaudeConnectorConfig { let keyed = ClaudeConnectorConfig {
auth: ClaudeAuth::ApiKey, auth: ClaudeAuth::ApiKey,
lease_socket: None, lease_socket: None,
lease_callers: vec![], lease_holders: vec![],
..valid() ..valid()
}; };
write_config(&path, &keyed).unwrap(); write_config(&path, &keyed).unwrap();
@ -354,7 +383,7 @@ struct BeforeAuth {
#[cultcache(key = 19)] #[cultcache(key = 19)]
lease_socket: Option<PathBuf>, lease_socket: Option<PathBuf>,
#[cultcache(key = 20)] #[cultcache(key = 20)]
lease_callers: Vec<LeaseCallerConfig>, lease_holders: Vec<LeaseHolderConfig>,
#[cultcache(key = 21)] #[cultcache(key = 21)]
lease_max_ms: u64, lease_max_ms: u64,
#[cultcache(key = 22)] #[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, max_expiry_skew_ms: now.max_expiry_skew_ms,
callers: now.callers.clone(), callers: now.callers.clone(),
lease_socket: now.lease_socket.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, lease_max_ms: now.lease_max_ms,
handle_secret_credential: now.handle_secret_credential.clone(), 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() { fn a_key_is_never_lent_so_no_lease_socket_or_row_may_accompany_it() {
assert_eq!(refused(&keyed_with_a_lease()), "auth"); assert_eq!(refused(&keyed_with_a_lease()), "auth");
let socket_only = ClaudeConnectorConfig { let socket_only = ClaudeConnectorConfig {
lease_callers: vec![], lease_holders: vec![],
..keyed_with_a_lease() ..keyed_with_a_lease()
}; };
assert_eq!(refused(&socket_only), "auth"); 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() ..keyed_with_a_lease()
}; };
assert_eq!(refused(&rows_only), "auth"); assert_eq!(refused(&rows_only), "auth");
let personas_only = ClaudeConnectorConfig { let callers_only = ClaudeConnectorConfig {
lease_socket: None, lease_socket: None,
lease_callers: vec![], lease_holders: vec![],
..keyed_with_a_lease() ..keyed_with_a_lease()
}; };
assert!(personas_only.validate().is_ok()); assert!(callers_only.validate().is_ok());
let scratch = Scratch::new(); let scratch = Scratch::new();
assert!(write_config(&scratch.path("keyed.cc"), &keyed_with_a_lease()).is_err()); 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", "--lease-socket",
"/run/claude-connector/lease.sock", "/run/claude-connector/lease.sock",
"--lease-user", "--lease-user",
"mind-a-self", "agent-a",
"--turn", "--provider",
"self", "claude-code",
"--lease-unit-instance", "--unit",
"a", "agent@a.service",
"--scope",
"per-caller",
]; ];
let scratch = Scratch::new(); let scratch = Scratch::new();
let leased = init(&scratch, &init_flags(&scratch, &[&["--auth", "api-key"], &lease[..]].concat())); 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:?}"); 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] #[test]
fn serve_and_check_refuse_a_key_document_that_carries_a_lease() { fn serve_and_check_refuse_a_key_document_that_carries_a_lease() {
let scratch = Scratch::new(); let scratch = Scratch::new();

View file

@ -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 //! 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 //! 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. //! 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 std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use claude_connector::{ use claude_connector::{
LeaseCaller, LeaseGranted, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused, LeaseGranted, LeaseHolder, LeaseLimits, LeaseMessage, LeaseRefusalKind, LeaseRefused,
LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource, LeaseRequest, LeaseUsageReadoutRequest, PeerUnit, PeerUnits, QuotaCell, TokenSource,
decode_frame, encode_frame, serve_leases, 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; use zeroize::Zeroizing;
const CALLER: &str = "eureka"; const CALLER: &str = "eureka";
const MODEL: &str = "claude-opus-5-1"; const MODEL: &str = "claude-opus-5-1";
const TOKEN: &str = "sk-canary-lease-4c1f9a"; const TOKEN: &str = "sk-canary-lease-4c1f9a";
const INSTANCE: &str = "eureka"; const UNIT: &str = "agent@alice.service";
const UNIT: &str = "mind-self@eureka.service";
static SEQUENCE: AtomicUsize = AtomicUsize::new(0); static SEQUENCE: AtomicUsize = AtomicUsize::new(0);
@ -102,7 +101,7 @@ struct Harness {
} }
impl 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) { fn enter(&self, n: u64) {
self.run_in(UNIT, n); self.run_in(UNIT, n);
} }
@ -224,7 +223,8 @@ fn contains(haystack: &[u8], needle: &str) -> bool {
/// What a harness is built from. /// What a harness is built from.
struct Setup { struct Setup {
uid: u32, uid: u32,
turn: LeaseTurn, scope: LeaseScope,
unit: &'static str,
token: Option<&'static str>, token: Option<&'static str>,
max_connections: usize, max_connections: usize,
} }
@ -232,14 +232,15 @@ struct Setup {
fn setup() -> Setup { fn setup() -> Setup {
Setup { Setup {
uid: own_uid(), uid: own_uid(),
turn: LeaseTurn::SelfRun, scope: LeaseScope::PerCaller,
unit: UNIT,
token: Some(TOKEN), token: Some(TOKEN),
max_connections: 8, max_connections: 8,
} }
} }
/// A listener serving `uid` as the caller `eureka`. Peers start in invocation /// 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 { fn start(setup: Setup) -> Harness {
let units = Arc::new(FakeUnits { let units = Arc::new(FakeUnits {
peer: Mutex::new(None), peer: Mutex::new(None),
@ -283,16 +284,17 @@ fn start(setup: Setup) -> Harness {
tokens.clone(), tokens.clone(),
units.clone(), units.clone(),
); );
let caller = LeaseCaller { let holder = LeaseHolder {
uid: setup.uid, uid: setup.uid,
caller_id: CALLER.to_string(), caller_id: CALLER.to_string(),
turn: setup.turn, provider: "claude-code".to_string(),
unit_instance: INSTANCE.to_string(), unit: setup.unit.to_string(),
scope: setup.scope,
}; };
std::thread::spawn(move || { std::thread::spawn(move || {
let _ = serve_leases( let _ = serve_leases(
&listener, &listener,
vec![caller], vec![holder],
LeaseLimits { LeaseLimits {
socket_timeout: Duration::from_secs(2), socket_timeout: Duration::from_secs(2),
max_lease_ms: 3_600_000, max_lease_ms: 3_600_000,
@ -449,7 +451,7 @@ fn high_utilization_refuses_nothing() {
} }
#[test] #[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 { let harness = start(Setup {
uid: own_uid().wrapping_add(1), uid: own_uid().wrapping_add(1),
..setup() ..setup()
@ -460,9 +462,9 @@ fn a_peer_uid_outside_the_lease_callers_is_refused_and_nothing_is_read() {
} }
#[test] #[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()); let harness = start(setup());
harness.run_in("mind-persona@eureka.service", 1); harness.run_in("other.service", 1);
let answer = ask(&harness, 60_000); let answer = ask(&harness, 60_000);
assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller)); assert_eq!(refusal_of(&answer), Some(LeaseRefusalKind::UnknownCaller));
assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0); assert_eq!(harness.tokens.reads.load(Ordering::SeqCst), 0);
@ -699,7 +701,7 @@ fn a_readout_answers_the_cells_windows_and_lends_nothing() {
} }
#[test] #[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 { let harness = start(Setup {
uid: own_uid().wrapping_add(1), uid: own_uid().wrapping_add(1),
..setup() ..setup()
@ -726,3 +728,61 @@ fn a_readout_beside_a_held_lease_leaves_it_held() {
assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy)); assert_eq!(refusal_of(&second), Some(LeaseRefusalKind::Busy));
assert!(granted_ok(&held)); 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))
);
}

View file

@ -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::<RawFd>() 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::<u64>())];
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::<u8>(),
libc::CMSG_DATA(header),
size_of::<RawFd>(),
);
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}");
}
}

View file

@ -172,7 +172,7 @@ pub fn serve(
} }
/// `serve` over a service the caller opened and keeps a handle to, so another /// `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 /// replay store and plan. The limits must already have been validated against the
/// service's admissions. /// service's admissions.
pub fn serve_service( pub fn serve_service(

View file

@ -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) .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)] #[derive(Debug, Clone, Copy)]
struct LiveLease { struct LiveLease {
turn: LeaseTurn, scope: LeaseScope,
expires_at_unix_ms: u64, expires_at_unix_ms: u64,
} }
@ -779,7 +779,7 @@ fn replay_store_error(error: impl std::fmt::Display) -> ServiceError {
} }
mod lease; mod lease;
pub use lease::{LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseTurn}; pub use lease::{LeaseAdmission, LeaseGrant, LeaseRefusal, LeaseScope};
fn contract_refusal(error: &ContractError) -> Refusal { fn contract_refusal(error: &ContractError) -> Refusal {
match error { match error {

View file

@ -1,27 +1,29 @@
//! A credential lease: a Self run's or a Persona turn's hold on the token the //! A credential lease: a holder's hold on the token the connector lends.
//! connector lends. The lease is memory bound to its holder's open connection, //! The lease is memory bound to its holder's open connection, not a record and
//! not a record and not a charge: it decides `Busy` while it is held and //! not a charge: it decides `Busy` while it is held and nothing else. It ends
//! nothing else. It ends when its holder lets go (`end_lease`), when the unit //! when its holder lets go (`end_lease`), when the unit invocation it served
//! invocation it served ends, or when its expiry passes. Nothing is billed and //! ends, or when its expiry passes. Nothing is billed and nothing is reserved.
//! nothing is reserved. The only usage-derived refusal is the provider's own //! The only usage-derived refusal is the provider's own (`ProviderRejected`),
//! (`ProviderRejected`), repeated with the provider's own expiry. //! repeated with the provider's own expiry.
use super::*; use super::*;
/// The request-id namespace of leases. /// The request-id namespace of leases.
const LEASE_PREFIX: &str = "lease:"; const LEASE_PREFIX: &str = "lease:";
/// What a Persona turn's lease id adds to its invocation id, so a Persona /// What a per-invocation lease id adds to its invocation id, so a
/// lease and a Self lease of one caller and one invocation never share an id. /// per-invocation lease and a per-caller lease of one caller and one
const PERSONA_SUFFIX: &str = ":persona"; /// 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 /// Exclusivity scope of a lease. It is a property of the lease holder's
/// configured row, never of a request. A caller holds one Self lease at a /// configured row, never of a request. A `PerCaller` holder keeps one lease open
/// time; a Persona turn holds one lease per live invocation, one at a time. /// 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)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LeaseTurn { pub enum LeaseScope {
SelfRun, PerCaller,
PersonaTurn, PerInvocation,
} }
/// What an admitted lease holds. /// What an admitted lease holds.
@ -34,8 +36,8 @@ pub struct LeaseGrant {
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeaseRefusal { pub enum LeaseRefusal {
UnknownCaller, UnknownCaller,
/// A Self run: the caller holds a Self lease now. A Persona turn: this /// `PerCaller`: the caller holds a per-caller lease now. `PerInvocation`:
/// invocation holds a lease now. /// this invocation holds a lease now.
Busy, Busy,
/// The provider is refusing right now and has said until when. /// The provider is refusing right now and has said until when.
ProviderRejected, ProviderRejected,
@ -49,16 +51,16 @@ pub enum LeaseAdmission {
impl TransportService { impl TransportService {
/// Grants `caller_runtime_id` a lease for the unit invocation /// Grants `caller_runtime_id` a lease for the unit invocation
/// `invocation_id` until `expires_at_unix_ms`. A Self run's lease is /// `invocation_id` until `expires_at_unix_ms`. A `PerCaller` lease is
/// `lease:<invocation>` and one is open per caller; a Persona turn's is /// `lease:<invocation>` and one is open per caller; a `PerInvocation` lease
/// `lease:<invocation>:persona`, one open per invocation; neither blocks /// is `lease:<invocation>:invocation`, one open per invocation; neither
/// the other. A lease takes no request slot. `plan` is the backend's plan /// blocks the other. A lease takes no request slot. `plan` is the backend's
/// quota as it stands: a provider that is refusing right now refuses the /// plan quota as it stands: a provider that is refusing right now refuses
/// lease. A lease past its expiry no longer holds anything. /// the lease. A lease past its expiry no longer holds anything.
pub fn begin_lease( pub fn begin_lease(
&mut self, &mut self,
caller_runtime_id: &str, caller_runtime_id: &str,
turn: LeaseTurn, scope: LeaseScope,
invocation_id: &str, invocation_id: &str,
expires_at_unix_ms: u64, expires_at_unix_ms: u64,
now_unix_ms: u64, now_unix_ms: u64,
@ -68,9 +70,9 @@ impl TransportService {
return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller)); return Ok(LeaseAdmission::Refused(LeaseRefusal::UnknownCaller));
} }
require_id(invocation_id, "invocation_id")?; require_id(invocation_id, "invocation_id")?;
let suffix = match turn { let suffix = match scope {
LeaseTurn::SelfRun => "", LeaseScope::PerCaller => "",
LeaseTurn::PersonaTurn => PERSONA_SUFFIX, LeaseScope::PerInvocation => INVOCATION_SUFFIX,
}; };
let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}"); let lease_id = format!("{LEASE_PREFIX}{invocation_id}{suffix}");
if lease_id.len() > MAX_IDENTITY_BYTES { if lease_id.len() > MAX_IDENTITY_BYTES {
@ -82,11 +84,11 @@ impl TransportService {
caller_runtime_id: caller_runtime_id.to_string(), caller_runtime_id: caller_runtime_id.to_string(),
request_id: lease_id.clone(), request_id: lease_id.clone(),
}; };
let busy = match turn { let busy = match scope {
LeaseTurn::SelfRun => self.leases.iter().any(|(held, lease)| { LeaseScope::PerCaller => self.leases.iter().any(|(held, lease)| {
lease.turn == LeaseTurn::SelfRun && held.caller_runtime_id == caller_runtime_id 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 { if busy {
return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy)); return Ok(LeaseAdmission::Refused(LeaseRefusal::Busy));
@ -97,7 +99,7 @@ impl TransportService {
self.leases.insert( self.leases.insert(
identity, identity,
LiveLease { LiveLease {
turn, scope,
expires_at_unix_ms, expires_at_unix_ms,
}, },
); );
@ -155,17 +157,17 @@ mod tests {
fn lease_in( fn lease_in(
service: &mut TransportService, service: &mut TransportService,
turn: LeaseTurn, scope: LeaseScope,
run: &str, run: &str,
plan: &PlanQuotaSnapshot, plan: &PlanQuotaSnapshot,
) -> LeaseAdmission { ) -> LeaseAdmission {
service service
.begin_lease(CALLER, turn, run, NOW + 60_000, NOW, plan) .begin_lease(CALLER, scope, run, NOW + 60_000, NOW, plan)
.unwrap() .unwrap()
} }
fn lease(service: &mut TransportService, run: &str) -> LeaseAdmission { 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 { fn granted(admission: LeaseAdmission) -> LeaseGrant {
@ -186,7 +188,7 @@ mod tests {
} }
#[test] #[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 store = TestStore::new();
let mut service = open(&store); let mut service = open(&store);
granted(lease(&mut service, "run-1")); granted(lease(&mut service, "run-1"));
@ -223,14 +225,14 @@ mod tests {
let mut service = open(&store); let mut service = open(&store);
granted( granted(
service service
.begin_lease(CALLER, LeaseTurn::SelfRun, "run-1", NOW + 10, NOW, &none()) .begin_lease(CALLER, LeaseScope::PerCaller, "run-1", NOW + 10, NOW, &none())
.unwrap(), .unwrap(),
); );
assert_eq!( assert_eq!(
service service
.begin_lease( .begin_lease(
CALLER, CALLER,
LeaseTurn::SelfRun, LeaseScope::PerCaller,
"run-2", "run-2",
NOW + 99, NOW + 99,
NOW + 9, NOW + 9,
@ -244,7 +246,7 @@ mod tests {
service service
.begin_lease( .begin_lease(
CALLER, CALLER,
LeaseTurn::SelfRun, LeaseScope::PerCaller,
"run-2", "run-2",
NOW + 99, NOW + 99,
NOW + 10, NOW + 10,
@ -262,7 +264,7 @@ mod tests {
service service
.begin_lease( .begin_lease(
"stranger", "stranger",
LeaseTurn::SelfRun, LeaseScope::PerCaller,
"run-1", "run-1",
NOW + 1, NOW + 1,
NOW, NOW,
@ -274,22 +276,22 @@ mod tests {
} }
#[test] #[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 store = TestStore::new();
let mut service = open(&store); let mut service = open(&store);
let persona = |service: &mut TransportService, run: &str| { let per_invocation = |service: &mut TransportService, run: &str| {
lease_in(service, LeaseTurn::PersonaTurn, run, &none()) lease_in(service, LeaseScope::PerInvocation, run, &none())
}; };
let first = granted(persona(&mut service, "turn-1")); let first = granted(per_invocation(&mut service, "turn-1"));
assert_eq!(first.lease_id, "lease:turn-1:persona"); assert_eq!(first.lease_id, "lease:turn-1:invocation");
assert_eq!( assert_eq!(
persona(&mut service, "turn-1"), per_invocation(&mut service, "turn-1"),
LeaseAdmission::Refused(LeaseRefusal::Busy) LeaseAdmission::Refused(LeaseRefusal::Busy)
); );
granted(persona(&mut service, "turn-2")); granted(per_invocation(&mut service, "turn-2"));
granted(lease(&mut service, "turn-1")); granted(lease(&mut service, "turn-1"));
service.end_lease(CALLER, &first.lease_id); service.end_lease(CALLER, &first.lease_id);
granted(persona(&mut service, "turn-1")); granted(per_invocation(&mut service, "turn-1"));
} }
#[test] #[test]
@ -298,7 +300,7 @@ mod tests {
let mut service = open(&store); let mut service = open(&store);
let rejected = window(1_000, "rejected", NOW + 5_000); let rejected = window(1_000, "rejected", NOW + 5_000);
assert_eq!( assert_eq!(
lease_in(&mut service, LeaseTurn::SelfRun, "run-1", &rejected), lease_in(&mut service, LeaseScope::PerCaller, "run-1", &rejected),
LeaseAdmission::Refused(LeaseRefusal::ProviderRejected) LeaseAdmission::Refused(LeaseRefusal::ProviderRejected)
); );
let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| { let call = |service: &mut TransportService, now: u64, plan: &PlanQuotaSnapshot| {
@ -338,7 +340,7 @@ mod tests {
service service
.begin_lease( .begin_lease(
CALLER, CALLER,
LeaseTurn::SelfRun, LeaseScope::PerCaller,
"run-1", "run-1",
NOW + 9_000, NOW + 9_000,
NOW + 5_000, NOW + 5_000,
@ -354,11 +356,11 @@ mod tests {
let store = TestStore::new(); let store = TestStore::new();
let mut service = open(&store); let mut service = open(&store);
let full = window(999, "allowed", NOW + 5_000); 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); let warned = window(1_000, "allowed_warning", NOW + 5_000);
granted(lease_in( granted(lease_in(
&mut service, &mut service,
LeaseTurn::PersonaTurn, LeaseScope::PerInvocation,
"turn-1", "turn-1",
&warned, &warned,
)); ));
@ -371,30 +373,37 @@ mod tests {
let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len()); let longest = "r".repeat(MAX_IDENTITY_BYTES - LEASE_PREFIX.len());
let grant = granted(lease(&mut service, &longest)); let grant = granted(lease(&mut service, &longest));
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES); 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] #[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 store = TestStore::new();
let mut service = open(&store); 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( let grant = granted(lease_in(
&mut service, &mut service,
LeaseTurn::PersonaTurn, LeaseScope::PerInvocation,
&longest, &longest,
&none(), &none(),
)); ));
assert_eq!(grant.lease_id.len(), MAX_IDENTITY_BYTES); 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( fn lease_try(
service: &mut TransportService, service: &mut TransportService,
turn: LeaseTurn, scope: LeaseScope,
run: &str, run: &str,
) -> Result<LeaseAdmission, ServiceError> { ) -> Result<LeaseAdmission, ServiceError> {
service.begin_lease(CALLER, turn, run, NOW + 60_000, NOW, &none()) service.begin_lease(CALLER, scope, run, NOW + 60_000, NOW, &none())
} }
#[test] #[test]
@ -421,7 +430,7 @@ mod tests {
// And a call in flight does not make the caller busy for a lease. // And a call in flight does not make the caller busy for a lease.
granted(lease_in( granted(lease_in(
&mut service, &mut service,
LeaseTurn::PersonaTurn, LeaseScope::PerInvocation,
"turn-1", "turn-1",
&none(), &none(),
)); ));