claude-connector: authenticate the Claude child with an API key (config auth field) #3

Merged
eureka merged 11 commits from hands/connector-api-key into main 2026-11-29 17:36:26 +00:00
13 changed files with 422 additions and 30 deletions

View file

@ -53,8 +53,12 @@ Crate `crates/claude-connector` (library and the `claude-connector` binary that
- `ProcessPort` is the one OS seam (`StdProcessPort`, unix, kills the child's whole process
group); `SessionStore` and `StderrSink` are the other ports. `ClaudeCodeConfig` is what the
binary hands in; the credential is read from a systemd credential and reaches the child on a
pipe (`CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR`), never in an environment. `QuotaCell` keeps the
plan windows the CLI's `rate_limit_event`s report, for the usage readout and the lease grant.
pipe, never in an environment: `CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR` by default, or
`CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR` when the config document says `auth` is an API key
(`config init --auth api-key`; one choice for the whole connector, held in the credential
`--token-credential` names). `QuotaCell` keeps the plan windows the CLI's `rate_limit_event`s
report, for the usage readout and the lease grant; on an API key there is no plan, no meter
runs and the cell stays empty.
## Asking for one no-tools completion

View file

@ -278,7 +278,7 @@ pub fn ask(args: &AskArgs) -> Result<String, AskError> {
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{ClaudeCodeConfig, ClaudeCodeLimits};
use crate::config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
use crate::handle::{SessionStore, plan};
use model_connector::ToolDefinition;
@ -315,6 +315,7 @@ mod tests {
prompt_dir: "/p".into(),
token_credential: "t".into(),
handle_secret_credential: "h".into(),
auth: ClaudeAuth::OAuthToken,
instance: "i".into(),
limits: ClaudeCodeLimits {
deadline: Duration::from_secs(1),

View file

@ -261,7 +261,7 @@ impl ClaudeCodeBackend {
deadline,
&request.model,
request.output_schema_json.as_deref(),
&self.quota,
self.config.auth.is_metered().then_some(&*self.quota),
);
child.kill();
child.wait();
@ -367,7 +367,7 @@ fn read_stream(
deadline: Instant,
model: &str,
schema: Option<&str>,
quota: &QuotaCell,
quota: Option<&QuotaCell>,
) -> Result<Finished, Failure> {
let mut state = StreamState::new(model, schema, quota);
let finished = loop {

View file

@ -11,7 +11,7 @@ use model_connector::{
};
use super::*;
use crate::config::ClaudeCodeLimits;
use crate::config::{ClaudeAuth, ClaudeCodeLimits};
use crate::handle::{FsSessionStore, SessionStore};
use crate::launch::ChildEnv;
@ -19,6 +19,8 @@ const CANARY_TOKEN: &str = "canary-oauth-token-value";
/// The variable the connector's own environment must never hand on.
const TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";
const TOKEN_FD_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
const KEY_FD_ENV: &str = "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR";
const CANARY_KEY: &str = "canary-api-key-value";
const MODEL: &str = "claude-haiku-5-5";
const INSTANCE: &str = "persona-a";
const SESSION: &str = "11111111-2222-3333-4444-555555555555";
@ -333,6 +335,7 @@ fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeCon
config_dir: PathBuf::from("/cfg"),
prompt_dir: dir.join("prompts"),
token_credential: "claude-token".to_string(),
auth: ClaudeAuth::OAuthToken,
handle_secret_credential: "claude-handle-secret".to_string(),
instance: instance.to_string(),
limits,
@ -674,6 +677,92 @@ fn child_env_is_cleared_and_names_the_token_descriptor_never_the_token() {
assert!(!format!("{result:?}").contains(CANARY_TOKEN));
}
// ---- API key authentication ----
/// A rig whose child authenticates with an API key.
fn api_rig(scripts: Vec<Script>) -> Rig {
let mut rig = rig(scripts);
rig.backend.config.auth = ClaudeAuth::ApiKey;
rig.backend.tokens = Box::new(FixedToken(Some(CANARY_KEY)));
rig
}
#[test]
fn api_key_mode_names_the_key_descriptor_and_never_the_key_or_the_oauth_variable() {
let rig = api_rig(vec![structured_script()]);
let result = rig.run(schema_request());
let seen = rig.seen();
let mut names: Vec<&str> = seen.env.iter().map(|(name, _)| name.as_str()).collect();
names.sort();
assert_eq!(
names,
[
KEY_FD_ENV,
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
"CLAUDE_CONFIG_DIR",
"HOME",
"PATH"
]
);
assert!(seen.env.contains(&(KEY_FD_ENV.to_string(), "3".to_string())));
// The key travels beside the environment, to the port, alone.
assert_eq!(seen.token, CANARY_KEY);
let everything = format!(
"{:?} {:?} {:?} {result:?}",
seen.env, seen.argv, rig.backend.config
);
assert!(!everything.contains(CANARY_KEY));
let sunk = String::from_utf8(rig.sink.0.lock().unwrap().clone()).unwrap();
assert!(!sunk.contains(CANARY_KEY));
}
#[test]
fn api_key_mode_reads_no_plan_and_the_cell_stays_empty() {
let rig = api_rig(vec![structured_script()]);
rig.run(schema_request());
assert!(quota_of(&rig).windows.is_empty());
}
#[test]
fn oauth_mode_still_feeds_the_cell_and_names_the_oauth_descriptor() {
let rig = rig(vec![structured_script()]);
rig.run(schema_request());
assert!(!quota_of(&rig).windows.is_empty());
let seen = rig.seen();
assert!(seen.env.iter().any(|(name, _)| name == TOKEN_FD_ENV));
assert!(seen.env.iter().all(|(name, _)| name != KEY_FD_ENV));
}
#[test]
fn a_missing_api_key_fails_before_spawn() {
let mut rig = api_rig(vec![ok_script(SESSION, "x")]);
rig.backend.tokens = Box::new(FixedToken(None));
let (kind, _, usage) = failure_of(&rig.run(request(vec![user("hi")])));
assert_eq!(kind, FailureKind::Authentication);
assert_eq!(usage, Some(usage_zero()));
assert_eq!(rig.spawns(), 0);
}
#[test]
fn a_missing_api_key_is_not_ready() {
let dir = sandbox();
let (work, cfg) = (dir.path().join("work"), dir.path().join("cfg"));
std::fs::create_dir_all(&work).unwrap();
std::fs::create_dir_all(&cfg).unwrap();
let mut config = config(dir.path(), INSTANCE, limits());
config.work_dir = work;
config.config_dir = cfg;
config.auth = ClaudeAuth::ApiKey;
assert_eq!(
readiness(&config, &FixedToken(None), &FixedSecret(Some(SECRET))),
Err("token_credential")
);
assert_eq!(
readiness(&config, &FixedToken(Some(CANARY_KEY)), &FixedSecret(Some(SECRET))),
Ok(())
);
}
#[test]
fn the_token_never_reaches_a_message_an_event_or_a_debug_form() {
// A failing run, so a message is built, and the env's own Debug.
@ -2113,7 +2202,16 @@ fn quota_of(rig: &Rig) -> model_connector::PlanQuotaSnapshot {
/// The windows with their observation stamps zeroed, for comparing readings.
fn readings(rig: &Rig) -> Vec<model_connector::PlanQuota> {
let mut windows = quota_of(rig).windows;
readings_at(rig, None)
}
/// The held windows as of `now` (unix ms), or as of the wall clock when none.
fn readings_at(rig: &Rig, now: Option<u64>) -> Vec<model_connector::PlanQuota> {
let cell = rig.backend.quota();
let mut windows = match now {
Some(now) => cell.snapshot_at(now).windows,
None => cell.snapshot().windows,
};
for window in &mut windows {
window.observed_at_unix_ms = 0;
}
@ -2469,6 +2567,31 @@ mod real {
assert!(held.contains(&3));
}
#[test]
fn api_key_reaches_the_child_on_its_pipe_and_nowhere_else() {
let probe = TempDir::new();
let body = format!(
"fd=\"${KEY_FD_ENV}\"\neval \"cat <&$fd\" > '{d}/key'\nenv > '{d}/env'\nprintf '%s\n' \"$@\" > '{d}/argv'\nprintf '%s' \"${TOKEN_FD_ENV}\" > '{d}/oauth'\n{lines}",
d = probe.path().display(),
lines = printf_lines(&good_lines())
);
let mut fake = fake(&body, limits());
fake.backend.config.auth = ClaudeAuth::ApiKey;
fake.backend.tokens = Box::new(FixedToken(Some(CANARY_KEY)));
let result = fake.run(request(vec![user("hello")]));
assert!(matches!(
outcome(&result),
TransportOutcome::Completed { .. }
));
let read = |name: &str| std::fs::read_to_string(probe.path().join(name)).unwrap();
assert_eq!(read("key"), CANARY_KEY, "the pipe holds the key");
assert_eq!(read("oauth"), "", "the OAuth variable is not set");
assert!(!read("env").contains(CANARY_KEY) && !read("argv").contains(CANARY_KEY));
assert!(read("env").contains(&format!("{KEY_FD_ENV}=3")));
let sunk = String::from_utf8(fake.sink.0.lock().unwrap().clone()).unwrap();
assert!(!sunk.contains(CANARY_KEY) && !format!("{result:?}").contains(CANARY_KEY));
}
#[test]
fn a_token_too_large_for_a_pipe_is_refused_at_its_bound_not_hung() {
let fake = fake("exit 0", limits());
@ -2764,9 +2887,10 @@ fn the_meter_call_reads_the_week_from_a_real_captured_event() {
.read_meter()
.expect("the captured call completes");
assert_eq!((usage.input_tokens, usage.output_tokens), (384, 4));
// 0.06 of the week used; it resets at 1794261600 (unix s).
// 0.06 of the week used; it resets at 1794261600 (unix s). Read as of an instant before
// that reset, so the captured event stays a live reading whatever the wall clock says.
assert_eq!(
readings(&rig),
readings_at(&rig, Some(1_794_261_600_000 - 1)),
vec![window("seven_day", 60, 1_794_261_600_000)]
);
let argv = rig.seen().argv;

View file

@ -1,11 +1,39 @@
use std::path::PathBuf;
use std::time::Duration;
use serde::{Deserialize, Serialize};
/// The provider tag the kit puts on every receipt and on the reasoning state
/// of this backend. It is distinct from any Messages-API backend's tag, so the
/// kit treats each backend's state as foreign to the other.
pub(crate) const PROVIDER: &str = "claude-code";
/// Which credential the child authenticates with. One choice for the whole
/// connector; the credential itself is the systemd credential
/// [`ClaudeCodeConfig::token_credential`] names, and it reaches the child on a
/// pipe whichever this is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClaudeAuth {
/// The subscription's OAuth token. The plan's usage is metered.
OAuthToken,
/// An Anthropic API key. Nothing is metered: a key has no subscription plan.
ApiKey,
}
impl ClaudeAuth {
/// The variable that tells the CLI which descriptor holds the credential.
pub(crate) fn fd_var(self) -> &'static str {
match self {
Self::OAuthToken => "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
Self::ApiKey => "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
}
}
/// Whether the credential has a subscription plan to meter.
pub(crate) fn is_metered(self) -> bool {
self == Self::OAuthToken
}
}
/// What the connector's binary hands the backend. Every path is absolute.
#[derive(Debug, Clone)]
pub struct ClaudeCodeConfig {
@ -22,9 +50,11 @@ pub struct ClaudeCodeConfig {
/// A directory the connector owns (mode 0700), where each call's system
/// prompt is staged for the child.
pub prompt_dir: PathBuf,
/// The name of the systemd credential that holds the child's token, under
/// The name of the systemd credential that holds the child's credential, under
/// `$CREDENTIALS_DIRECTORY`.
pub token_credential: String,
/// Which credential that is: the subscription token or an API key.
pub auth: ClaudeAuth,
/// The name of the systemd credential that holds the handle secret: the
/// key every handle is authenticated with.
pub handle_secret_credential: String,

View file

@ -25,7 +25,8 @@ use crate::unit::SystemdUnits;
#[cfg(unix)]
use crate::meter;
use crate::{
ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, StderrSink,
ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource,
StderrSink,
};
const CONFIG_KEY: &str = "runtime";
@ -106,6 +107,11 @@ pub struct ClaudeConnectorConfig {
/// least 32 bytes), the key every handle is authenticated with.
#[cultcache(key = 22)]
pub handle_secret_credential: String,
/// Which credential `token_credential` holds: the subscription token, or an
/// Anthropic API key. A document written before this field existed is refused at
/// load (the canonical-form check): the installer authors the document again.
#[cultcache(key = 23)]
pub auth: ClaudeAuth,
}
/// A refusal. It names the field or stage that failed and nothing the
@ -242,6 +248,13 @@ impl ClaudeConnectorConfig {
}
fn validate_leases(&self) -> Result<(), ConfigError> {
// A key has no plan and is never lent: no lease socket, no lease row, whatever else the
// document says. Personas call with their own connection keys and need neither.
if self.auth == ClaudeAuth::ApiKey
&& (self.lease_socket.is_some() || !self.lease_callers.is_empty())
{
return Err(ConfigError::Invalid("auth"));
}
let Some(socket) = &self.lease_socket else {
return if self.lease_callers.is_empty() {
Ok(())
@ -280,6 +293,7 @@ impl ClaudeConnectorConfig {
config_dir: self.config_dir.clone(),
prompt_dir: self.prompt_dir.clone(),
token_credential: self.token_credential.clone(),
auth: self.auth,
handle_secret_credential: self.handle_secret_credential.clone(),
instance: self.instance.clone(),
limits: ClaudeCodeLimits {
@ -565,10 +579,13 @@ fn serve_config_with(
.map_err(|error| ConfigError::from(ServeError::Service(error)))?,
));
// The meter is running before the first lease can ask, so that lease can
// wait for its first read.
// wait for its first read. An API key has no subscription plan to read:
// no meter runs, the cell stays empty, and no lease waits for it.
let quota = backend.quota();
meter::start(quota.clone(), Box::new(backend.clone()))
.map_err(|_| ConfigError::Serving("meter"))?;
if config.auth.is_metered() {
meter::start(quota.clone(), Box::new(backend.clone()))
.map_err(|_| ConfigError::Serving("meter"))?;
}
started(&quota);
#[cfg(target_os = "linux")]
if let Some(socket) = &config.lease_socket {
@ -640,6 +657,7 @@ mod tests {
instance: "persona-a".to_string(),
token_credential: "claude-token".to_string(),
handle_secret_credential: "claude-handle-secret".to_string(),
auth: ClaudeAuth::OAuthToken,
deadline_ms: 600_000,
max_line_bytes: 4 << 20,
max_total_bytes: 64 << 20,

View file

@ -13,12 +13,10 @@ use model_connector::{ProviderRequest, ReasoningEffort};
use crate::config::ClaudeCodeConfig;
use crate::handle::Plan;
/// The variable that tells the CLI which file descriptor holds its credential.
/// The token itself never enters the environment: the process port writes it
/// into a pipe and hands the child the read end at [`TOKEN_FD`].
pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
/// The descriptor number the child finds the token pipe at: the first one
/// after stdin, stdout and stderr.
/// The credential never enters the environment, whichever `ClaudeAuth` it is:
/// the process port writes it into a pipe and hands the child the read end at
/// [`TOKEN_FD`], the first descriptor after stdin, stdout and stderr, and the
/// environment names that descriptor.
pub(crate) const TOKEN_FD: i32 = 3;
const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
@ -50,7 +48,7 @@ pub(crate) fn child_env(config: &ClaudeCodeConfig, request: &ProviderRequest) ->
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
request.max_output_tokens.to_string(),
),
(TOKEN_FD_VAR, TOKEN_FD.to_string()),
(config.auth.fd_var(), TOKEN_FD.to_string()),
])
}

View file

@ -19,7 +19,7 @@ mod stream;
mod unit;
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
pub use config::{ClaudeCodeConfig, ClaudeCodeLimits};
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
pub use daemon::{
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
};

View file

@ -17,7 +17,7 @@ use std::process::ExitCode;
use claude_connector::ask::{self, AskArgs, AskError};
use claude_connector::{
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
load_config, write_config,
};
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
@ -159,7 +159,8 @@ const CALLER: [&str; 5] = [
"--max-output-tokens",
];
const INIT: [&str; 21] = [
const INIT: [&str; 22] = [
"--auth",
"--listen",
"--replay-store",
"--claude-binary",
@ -240,6 +241,15 @@ impl Flags {
.map_err(|_| Failure::Malformed(name))
}
/// Which credential `--token-credential` names: `oauth-token` (the default) or `api-key`.
fn auth(&self) -> Result<ClaudeAuth, Failure> {
match self.single.get("--auth").map(String::as_str) {
None | Some("oauth-token") => Ok(ClaudeAuth::OAuthToken),
Some("api-key") => Ok(ClaudeAuth::ApiKey),
Some(_) => Err(Failure::Malformed("--auth")),
}
}
/// The kind of turn a leasing account serves: `self` or `persona`.
fn turn(&self) -> Result<LeaseTurn, Failure> {
match self.text("--turn")?.as_str() {
@ -391,6 +401,7 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
lease_callers,
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
handle_secret_credential: flags.text("--handle-secret-credential")?,
auth: flags.auth()?,
};
// Validate before the secret file exists: a refused document leaves nothing.
config.validate()?;

View file

@ -155,7 +155,7 @@ impl QuotaCell {
/// The windows as of `now`. One whose reset time has passed is reported
/// `expired` with no utilization: the reading described a window that no
/// longer exists.
fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
pub(crate) fn snapshot_at(&self, now: u64) -> PlanQuotaSnapshot {
let held = self.windows.lock().unwrap_or_else(|e| e.into_inner());
PlanQuotaSnapshot {
windows: held

View file

@ -121,7 +121,7 @@ pub(crate) struct StreamState<'a> {
/// Whether that schema's top type admits an object (absent counts): the
/// structured output must be an object, never a bare scalar or array.
schema_top_is_object: bool,
quota: &'a QuotaCell,
quota: Option<&'a QuotaCell>,
session_id: Option<String>,
texts: Vec<String>,
message_id: Option<String>,
@ -130,7 +130,7 @@ pub(crate) struct StreamState<'a> {
impl<'a> StreamState<'a> {
/// `schema` is the request's output schema text, when it carried one.
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: &'a QuotaCell) -> Self {
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: Option<&'a QuotaCell>) -> Self {
let top = schema
.and_then(|text| serde_json::from_str::<Value>(text).ok())
.and_then(|schema| schema.get("type").cloned());
@ -176,7 +176,9 @@ impl<'a> StreamState<'a> {
if let Some(info) = &line.rate_limit_info {
self.plan_rejected |=
info.get("status").and_then(Value::as_str) == Some("rejected");
self.quota.observe(plan_windows(info));
if let Some(quota) = self.quota {
quota.observe(plan_windows(info));
}
}
Step::More
}

View file

@ -528,7 +528,7 @@ fn stdin_and_stdout_failures_have_their_own_wording() {
#[test]
fn a_forced_tools_request_reaches_the_planner_is_refused_and_no_child_starts() {
use claude_connector::{
ChildEnv, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
ChildEnv, ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
SessionStore, StderrSink, TokenSource,
};
use sha2::{Digest, Sha256};
@ -582,6 +582,7 @@ fn a_forced_tools_request_reaches_the_planner_is_refused_and_no_child_starts() {
prompt_dir: dir.join("prompt"),
token_credential: "t".into(),
handle_secret_credential: "h".into(),
auth: ClaudeAuth::OAuthToken,
instance: "i".into(),
limits: ClaudeCodeLimits {
deadline: Duration::from_secs(5),

View file

@ -8,7 +8,7 @@ use std::process::{Command, Output};
use std::sync::atomic::{AtomicUsize, Ordering};
use claude_connector::{
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{CallerConfig, LeaseTurn};
@ -53,6 +53,7 @@ fn valid() -> ClaudeConnectorConfig {
instance: "persona-a".to_string(),
token_credential: "claude-token".to_string(),
handle_secret_credential: "claude-handle-secret".to_string(),
auth: ClaudeAuth::OAuthToken,
deadline_ms: 600_000,
max_line_bytes: 4 << 20,
max_total_bytes: 64 << 20,
@ -295,3 +296,205 @@ fn serve_refuses_a_document_that_is_not_there() {
assert!(!served.status.success(), "{served:?}");
assert!(!String::from_utf8_lossy(&served.stderr).is_empty());
}
#[test]
fn the_auth_choice_round_trips() {
let scratch = Scratch::new();
let path = scratch.path("connector.cc");
let keyed = ClaudeConnectorConfig {
auth: ClaudeAuth::ApiKey,
lease_socket: None,
lease_callers: vec![],
..valid()
};
write_config(&path, &keyed).unwrap();
assert_eq!(load_config(&path).unwrap().auth, ClaudeAuth::ApiKey);
}
/// A document written before the auth field existed: the same type id, keys 0 to 22.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")]
struct BeforeAuth {
#[cultcache(key = 0)]
listen: String,
#[cultcache(key = 1)]
replay_store: PathBuf,
#[cultcache(key = 2)]
claude_binary: PathBuf,
#[cultcache(key = 3)]
claude_binary_sha256: [u8; 32],
#[cultcache(key = 4)]
work_dir: PathBuf,
#[cultcache(key = 5)]
config_dir: PathBuf,
#[cultcache(key = 6)]
prompt_dir: PathBuf,
#[cultcache(key = 7)]
instance: String,
#[cultcache(key = 8)]
token_credential: String,
#[cultcache(key = 9)]
deadline_ms: u64,
#[cultcache(key = 10)]
max_line_bytes: usize,
#[cultcache(key = 11)]
max_total_bytes: usize,
#[cultcache(key = 12)]
stderr_tail_bytes: usize,
#[cultcache(key = 13)]
max_frame_bytes: usize,
#[cultcache(key = 14)]
max_connections: usize,
#[cultcache(key = 15)]
socket_timeout_ms: u64,
#[cultcache(key = 16)]
max_expiry_skew_ms: u64,
#[cultcache(key = 17)]
callers: Vec<CallerConfig>,
#[cultcache(key = 19)]
lease_socket: Option<PathBuf>,
#[cultcache(key = 20)]
lease_callers: Vec<LeaseCallerConfig>,
#[cultcache(key = 21)]
lease_max_ms: u64,
#[cultcache(key = 22)]
handle_secret_credential: String,
}
#[test]
fn a_document_from_before_the_auth_field_is_refused_until_it_is_authored_again() {
let scratch = Scratch::new();
let path = scratch.path("before.cc");
let now = valid();
{
let mut cache = CultCache::new();
cache.register_entry_type::<BeforeAuth>().unwrap();
cache
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
.unwrap();
cache
.put(
"runtime".to_string(),
&BeforeAuth {
listen: now.listen.clone(),
replay_store: now.replay_store.clone(),
claude_binary: now.claude_binary.clone(),
claude_binary_sha256: now.claude_binary_sha256,
work_dir: now.work_dir.clone(),
config_dir: now.config_dir.clone(),
prompt_dir: now.prompt_dir.clone(),
instance: now.instance.clone(),
token_credential: now.token_credential.clone(),
deadline_ms: now.deadline_ms,
max_line_bytes: now.max_line_bytes,
max_total_bytes: now.max_total_bytes,
stderr_tail_bytes: now.stderr_tail_bytes,
max_frame_bytes: now.max_frame_bytes,
max_connections: now.max_connections,
socket_timeout_ms: now.socket_timeout_ms,
max_expiry_skew_ms: now.max_expiry_skew_ms,
callers: now.callers.clone(),
lease_socket: now.lease_socket.clone(),
lease_callers: now.lease_callers.clone(),
lease_max_ms: now.lease_max_ms,
handle_secret_credential: now.handle_secret_credential.clone(),
},
)
.unwrap();
}
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
}
#[test]
fn config_init_takes_the_auth_flag_and_refuses_an_unknown_one() {
let auth_of = |extra: &[&str]| {
let scratch = Scratch::new();
let made = init(&scratch, &init_flags(&scratch, extra));
made.status
.success()
.then(|| load_config(&scratch.path("connector.cc")).unwrap().auth)
};
assert_eq!(auth_of(&[]), Some(ClaudeAuth::OAuthToken));
assert_eq!(auth_of(&["--auth", "oauth-token"]), Some(ClaudeAuth::OAuthToken));
assert_eq!(auth_of(&["--auth", "api-key"]), Some(ClaudeAuth::ApiKey));
assert_eq!(auth_of(&["--auth", "key"]), None);
}
/// The document an operator could author by hand around `write_config`'s refusal: a key and a lease.
fn keyed_with_a_lease() -> ClaudeConnectorConfig {
ClaudeConnectorConfig {
auth: ClaudeAuth::ApiKey,
..valid()
}
}
#[test]
fn a_key_is_never_lent_so_no_lease_socket_or_row_may_accompany_it() {
assert_eq!(refused(&keyed_with_a_lease()), "auth");
let socket_only = ClaudeConnectorConfig {
lease_callers: vec![],
..keyed_with_a_lease()
};
assert_eq!(refused(&socket_only), "auth");
let rows_only = ClaudeConnectorConfig {
lease_socket: None,
..keyed_with_a_lease()
};
assert_eq!(refused(&rows_only), "auth");
let personas_only = ClaudeConnectorConfig {
lease_socket: None,
lease_callers: vec![],
..keyed_with_a_lease()
};
assert!(personas_only.validate().is_ok());
let scratch = Scratch::new();
assert!(write_config(&scratch.path("keyed.cc"), &keyed_with_a_lease()).is_err());
}
#[test]
fn config_init_refuses_a_key_with_a_lease_and_accepts_it_without() {
let lease = [
"--lease-socket",
"/run/claude-connector/lease.sock",
"--lease-user",
"mind-a-self",
"--turn",
"self",
"--lease-unit-instance",
"a",
];
let scratch = Scratch::new();
let leased = init(&scratch, &init_flags(&scratch, &[&["--auth", "api-key"], &lease[..]].concat()));
assert!(!leased.status.success(), "{leased:?}");
assert!(!scratch.path("connector.cc").exists());
let scratch = Scratch::new();
let bare = init(&scratch, &init_flags(&scratch, &["--auth", "api-key"]));
assert!(bare.status.success(), "{bare:?}");
}
#[test]
fn serve_and_check_refuse_a_key_document_that_carries_a_lease() {
let scratch = Scratch::new();
let path = scratch.path("handmade.cc");
{
// Written around write_config, which would refuse it.
let mut cache = CultCache::new();
cache.register_entry_type::<ClaudeConnectorConfig>().unwrap();
cache
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
.unwrap();
cache
.put("runtime".to_string(), &keyed_with_a_lease())
.unwrap();
}
let p = path.to_str().unwrap();
for args in [vec!["serve", "--config", p], vec!["config", "check", p]] {
let out = run(&args);
assert!(!out.status.success(), "{args:?}: {out:?}");
assert!(
String::from_utf8_lossy(&out.stderr).contains("auth"),
"{args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
}
}