claude-connector: add v3 multi-provider config, validation, readiness, and CLI verbs

Replace the v2 connector config and global ClaudeAuth switch with the
gamecult.model_connector.connector_config.v3 schema (ProviderEntry,
ProviderWire, ModelRow, EffortMap, ForcedToolChoice, OutputSchemaSupport).
Delete ClaudeAuth, MODEL_PREFIX, has_model_id_form, Flags::auth,
--auth, and --token-credential.

Add v3 validation (loopback-http or https base URLs, non-loopback
credentials, unique credentials and ids, <=1 ClaudeCodeCli, refuse
OpenAiChat until Cut 3, allowed_models subset of configured models),
per-entry readiness_of_in returning ConfigError::UnusableEntry without
leaking secrets, and config init/add-provider/add-model CLI verbs.
This commit is contained in:
Meta Vens 2026-12-03 23:22:03 +01:00
commit a7ac40d59a
5 changed files with 1530 additions and 514 deletions

View file

@ -1,5 +1,7 @@
use std::path::PathBuf;
use std::time::Duration;
use model_connector::ReasoningEffort;
use serde::{Deserialize, Serialize};
/// The provider tag the kit puts on every receipt and on the reasoning state
@ -7,19 +9,96 @@ use serde::{Deserialize, Serialize};
/// kit treats each backend's state as foreign to the other.
pub(crate) const PROVIDER: &str = "claude-code";
/// Which credential the connector authenticates with. One choice for the whole
/// connector, held in the systemd credential the config document's
/// `token_credential` names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClaudeAuth {
/// The subscription's OAuth token, given to the `claude` CLI child by
/// [`ClaudeCodeBackend`](crate::ClaudeCodeBackend). The plan's usage is
/// metered.
OAuthToken,
/// An Anthropic API key, used by [`MessagesBackend`](crate::MessagesBackend)
/// over HTTP; the CLI is never spawned. Nothing is metered: a key has no
/// subscription plan.
ApiKey,
/// One configured provider entry in the connector's v3 config document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderEntry {
/// Provider tag written on receipts and reasoning state items.
pub id: String,
/// Systemd credential name under `$CREDENTIALS_DIRECTORY`; `None` only for
/// a loopback HTTP `base_url`.
pub credential: Option<String>,
pub wire: ProviderWire,
}
/// Wire protocol and per-provider backend parameters for a [`ProviderEntry`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProviderWire {
AnthropicMessages {
base_url: String,
deadline_ms: u64,
max_response_bytes: usize,
},
OpenAiChat {
base_url: String,
strict_unsupported: Vec<String>,
deadline_ms: u64,
max_response_bytes: usize,
},
ClaudeCodeCli {
binary: PathBuf,
binary_sha256: [u8; 32],
work_dir: PathBuf,
config_dir: PathBuf,
prompt_dir: PathBuf,
handle_secret_credential: String,
instance: String,
deadline_ms: u64,
max_line_bytes: usize,
max_total_bytes: usize,
stderr_tail_bytes: usize,
meter_model: Option<String>,
},
}
/// One caller-facing model routed to a [`ProviderEntry`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelRow {
/// Caller-facing model id named in `ProviderRequest.model` and `allowed_models`.
pub id: String,
/// Id of the [`ProviderEntry`] that serves this model.
pub provider: String,
/// Provider-side model name sent on the wire.
pub upstream: String,
pub efforts: EffortMap,
pub unset_effort: Option<String>,
pub forced_tool_choice: ForcedToolChoice,
pub output_schema: OutputSchemaSupport,
pub strict_tools: bool,
}
/// Maps each contract [`ReasoningEffort`] to the provider's wire value.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffortMap {
pub low: Option<String>,
pub medium: Option<String>,
pub high: Option<String>,
pub max: Option<String>,
}
impl EffortMap {
pub fn get(&self, effort: ReasoningEffort) -> Option<&str> {
match effort {
ReasoningEffort::Low => self.low.as_deref(),
ReasoningEffort::Medium => self.medium.as_deref(),
ReasoningEffort::High => self.high.as_deref(),
ReasoningEffort::Max => self.max.as_deref(),
}
}
}
/// Whether the model accepts `ToolChoice::Required` (`tool_choice: any` / `required`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ForcedToolChoice {
Always,
WithoutThinking,
Never,
}
/// Whether the model natively enforces a request's output JSON schema.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum OutputSchemaSupport {
Native,
None,
}
/// What the connector's binary hands the backend. Every path is absolute.

File diff suppressed because it is too large Load diff

View file

@ -22,7 +22,10 @@ mod stream;
mod unit;
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
pub use config::{
ClaudeCodeConfig, ClaudeCodeLimits, EffortMap, ForcedToolChoice, ModelRow,
OutputSchemaSupport, ProviderEntry, ProviderWire,
};
pub use daemon::{
ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, check_ready, load_config, write_config,
};

View file

@ -2,6 +2,8 @@
//!
//! claude-connector serve --config PATH.cc
//! claude-connector config init PATH.cc --flag value ...
//! claude-connector config add-provider PATH.cc --provider ID --wire KIND ...
//! claude-connector config add-model PATH.cc --model ID --provider ID --upstream NAME ...
//! claude-connector config add-caller PATH.cc --caller-id ID --connection-key-file F ...
//! 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
@ -9,8 +11,8 @@
//! claude-connector lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...]
//!
//! `serve` takes its configuration from the typed document alone. The flags of
//! `config init` exist only to author that document. No message here echoes a
//! value that was typed or stored; refusals name a field or a flag.
//! `config init`, `add-provider`, and `add-model` exist only to author that document.
//! No message here echoes a value that was typed or stored; refusals name a field or a flag.
use std::collections::BTreeMap;
use std::path::PathBuf;
@ -18,8 +20,9 @@ use std::process::ExitCode;
use claude_connector::ask::{self, AskArgs, AskError};
use claude_connector::{
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, MIN_SECRET_BYTES,
check_ready, load_config, write_config,
ClaudeConnectorConfig, ConfigError, EffortMap, ForcedToolChoice, LeaseHolderConfig,
MIN_SECRET_BYTES, ModelRow, OutputSchemaSupport, ProviderEntry, ProviderWire, check_ready,
load_config, write_config,
};
use model_connector::{CallerConfig, LeaseScope, frame_bytes_for_payload};
@ -29,6 +32,12 @@ fn main() -> ExitCode {
let result = match args.as_slice() {
["serve", "--config", path] => serve(path).map(|()| ExitCode::SUCCESS),
["config", "init", path, flags @ ..] => init(path, flags).map(|()| ExitCode::SUCCESS),
["config", "add-provider", path, flags @ ..] => {
add_provider(path, flags).map(|()| ExitCode::SUCCESS)
}
["config", "add-model", path, flags @ ..] => {
add_model(path, flags).map(|()| ExitCode::SUCCESS)
}
["config", "add-caller", path, flags @ ..] => {
add_caller(path, flags).map(|()| ExitCode::SUCCESS)
}
@ -52,7 +61,7 @@ fn main() -> ExitCode {
#[derive(Debug, thiserror::Error)]
enum Failure {
#[error(
"usage: serve --config PATH | config init PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-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: serve --config PATH | config init PATH --flag value ... | config add-provider PATH --flag value ... | config add-model PATH --flag value ... | config add-caller PATH --flag value ... | config add-lease-holder PATH --flag value ... | config check PATH | ask --caller-id ID --connection-key-file FILE --model MODEL (--system TEXT | --system-file FILE) [--endpoint HOST:PORT] [--effort low|medium|high|max] [--max-output-tokens N] [--timeout-secs N] | lease run --socket PATH [--ttl-secs N] -- PROGRAM [ARGS...] (prompt on stdin, answer on stdout) (check reads the credentials from the environment it runs in: run it in the unit's environment)"
)]
Usage,
#[error(transparent)]
@ -61,6 +70,8 @@ enum Failure {
Missing(&'static str),
#[error("flag {0} is malformed")]
Malformed(&'static str),
#[error("flag {0} conflicts with --wire")]
Conflict(&'static str),
#[error("a flag is unknown, repeated or has no value")]
Flags,
#[error("{0}")]
@ -84,6 +95,8 @@ fn check(path: &str) -> Result<(), Failure> {
let config = load_config(path.as_ref())?;
check_ready(&config)?;
println!("claude connector configuration is valid and ready to serve");
println!("providers: {}", config.providers.len());
println!("models: {}", config.models.len());
println!("callers: {}", config.callers.len());
println!("lease_holders: {}", config.lease_holders.len());
Ok(())
@ -168,34 +181,61 @@ const CALLER: [&str; 5] = [
"--max-output-tokens",
];
const INIT: [&str; 23] = [
"--auth",
const INIT: [&str; 8] = [
"--listen",
"--replay-store",
"--max-payload-bytes",
"--socket-timeout-ms",
"--lease-socket",
"--lease-max-ms",
"--unit",
"--scope",
];
const PROVIDER: [&str; 18] = [
"--provider",
"--wire",
"--credential",
"--base-url",
"--deadline-ms",
"--max-response-bytes",
"--claude-binary",
"--claude-sha256",
"--work-dir",
"--config-dir",
"--prompt-dir",
"--instance",
"--token-credential",
"--handle-secret-credential",
"--handle-secret-file",
"--deadline-ms",
"--instance",
"--max-line-bytes",
"--max-total-bytes",
"--stderr-tail-bytes",
"--max-payload-bytes",
"--socket-timeout-ms",
"--lease-socket",
"--lease-max-ms",
"--meter-model",
];
const MODEL: [&str; 11] = [
"--model",
"--provider",
"--unit",
"--scope",
"--upstream",
"--effort-low",
"--effort-medium",
"--effort-high",
"--effort-max",
"--unset-effort",
"--forced-tool-choice",
"--output-schema",
"--strict-tools",
];
const LEASE_HOLDER: [&str; 4] = ["--caller-id", "--provider", "--unit", "--scope"];
#[derive(Clone, Copy)]
enum WireKind {
AnthropicMessages,
OpenAiChat,
ClaudeCodeCli,
}
impl Flags {
fn parse(
args: &[&str],
@ -237,6 +277,10 @@ impl Flags {
self.lists.get(name).map_or(&[], Vec::as_slice)
}
fn optional_text(&self, name: &'static str) -> Option<String> {
self.single.get(name).cloned()
}
fn text(&self, name: &'static str) -> Result<String, Failure> {
self.single.get(name).cloned().ok_or(Failure::Missing(name))
}
@ -251,13 +295,127 @@ 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")),
fn reject_any(&self, conflicting: &[&'static str]) -> Result<(), Failure> {
for &flag in conflicting {
if self.single.contains_key(flag) || self.lists.contains_key(flag) {
return Err(Failure::Conflict(flag));
}
}
Ok(())
}
fn wire(&self) -> Result<WireKind, Failure> {
match self.text("--wire")?.as_str() {
"anthropic-messages" => Ok(WireKind::AnthropicMessages),
"openai-chat" => Ok(WireKind::OpenAiChat),
"claude-code-cli" => Ok(WireKind::ClaudeCodeCli),
_ => Err(Failure::Malformed("--wire")),
}
}
fn forced_tool_choice(&self) -> Result<ForcedToolChoice, Failure> {
match self.text("--forced-tool-choice")?.as_str() {
"always" => Ok(ForcedToolChoice::Always),
"without-thinking" => Ok(ForcedToolChoice::WithoutThinking),
"never" => Ok(ForcedToolChoice::Never),
_ => Err(Failure::Malformed("--forced-tool-choice")),
}
}
fn output_schema(&self) -> Result<OutputSchemaSupport, Failure> {
match self.text("--output-schema")?.as_str() {
"native" => Ok(OutputSchemaSupport::Native),
"none" => Ok(OutputSchemaSupport::None),
_ => Err(Failure::Malformed("--output-schema")),
}
}
fn bool_flag(&self, name: &'static str) -> Result<bool, Failure> {
match self.text(name)?.as_str() {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(Failure::Malformed(name)),
}
}
fn provider_entry(&self, provider_id: &str) -> Result<ProviderEntry, Failure> {
const CLI_ONLY: &[&str] = &[
"--claude-binary",
"--claude-sha256",
"--work-dir",
"--config-dir",
"--prompt-dir",
"--handle-secret-credential",
"--handle-secret-file",
"--instance",
"--max-line-bytes",
"--max-total-bytes",
"--stderr-tail-bytes",
"--meter-model",
];
const HTTP_ONLY: &[&str] = &["--base-url", "--max-response-bytes", "--strict-unsupported"];
let wire = match self.wire()? {
WireKind::AnthropicMessages => {
self.reject_any(CLI_ONLY)?;
self.reject_any(&["--strict-unsupported"])?;
ProviderWire::AnthropicMessages {
base_url: self.text("--base-url")?,
deadline_ms: self.number_or("--deadline-ms", 600_000)?,
max_response_bytes: self.number_or("--max-response-bytes", 64 << 20)?,
}
}
WireKind::OpenAiChat => {
self.reject_any(CLI_ONLY)?;
ProviderWire::OpenAiChat {
base_url: self.text("--base-url")?,
strict_unsupported: self.list("--strict-unsupported").to_vec(),
deadline_ms: self.number_or("--deadline-ms", 600_000)?,
max_response_bytes: self.number_or("--max-response-bytes", 64 << 20)?,
}
}
WireKind::ClaudeCodeCli => {
self.reject_any(HTTP_ONLY)?;
ProviderWire::ClaudeCodeCli {
binary: self.path("--claude-binary")?,
binary_sha256: sha256(&self.text("--claude-sha256")?)
.ok_or(Failure::Malformed("--claude-sha256"))?,
work_dir: self.path("--work-dir")?,
config_dir: self.path("--config-dir")?,
prompt_dir: self.path("--prompt-dir")?,
handle_secret_credential: self.text("--handle-secret-credential")?,
instance: self.text("--instance")?,
deadline_ms: self.number_or("--deadline-ms", 600_000)?,
max_line_bytes: self.number_or("--max-line-bytes", 4 << 20)?,
max_total_bytes: self.number_or("--max-total-bytes", 64 << 20)?,
stderr_tail_bytes: self.number_or("--stderr-tail-bytes", 8192)?,
meter_model: self.optional_text("--meter-model"),
}
}
};
Ok(ProviderEntry {
id: provider_id.to_string(),
credential: self.optional_text("--credential"),
wire,
})
}
fn model_row(&self, provider_id: &str) -> Result<ModelRow, Failure> {
Ok(ModelRow {
id: self.text("--model")?,
provider: provider_id.to_string(),
upstream: self.text("--upstream")?,
efforts: EffortMap {
low: self.optional_text("--effort-low"),
medium: self.optional_text("--effort-medium"),
high: self.optional_text("--effort-high"),
max: self.optional_text("--effort-max"),
},
unset_effort: self.optional_text("--unset-effort"),
forced_tool_choice: self.forced_tool_choice()?,
output_schema: self.output_schema()?,
strict_tools: self.bool_flag("--strict-tools")?,
})
}
/// The exclusivity scope a leasing account holds: `per-caller` or `per-invocation`.
@ -370,9 +528,12 @@ fn ensure_secret_file(_: &std::path::Path) -> Result<(), Failure> {
fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(
args,
&[&INIT, &CALLER],
&["--allowed-model", "--lease-user"],
&[&INIT, &PROVIDER, &MODEL, &CALLER],
&["--allowed-model", "--lease-user", "--strict-unsupported"],
)?;
let provider_id = flags.text("--provider")?;
let provider = flags.provider_entry(&provider_id)?;
let model = flags.model_row(&provider_id)?;
let first = flags.caller()?;
let lease_holders = flags
.list("--lease-user")
@ -381,42 +542,63 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
Ok(LeaseHolderConfig {
unix_user: unix_user.clone(),
caller_id: first.caller_runtime_id.clone(),
provider: flags.text("--provider")?,
provider: provider_id.clone(),
unit: flags.text("--unit")?,
scope: flags.scope()?,
})
})
.collect::<Result<Vec<_>, Failure>>()?;
let secret_file = flags.path("--handle-secret-file")?;
let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. })
.then(|| flags.single.get("--handle-secret-file").map(PathBuf::from))
.flatten();
let config = ClaudeConnectorConfig {
listen: flags.text("--listen")?,
replay_store: flags.path("--replay-store")?,
claude_binary: flags.path("--claude-binary")?,
claude_binary_sha256: sha256(&flags.text("--claude-sha256")?)
.ok_or(Failure::Malformed("--claude-sha256"))?,
work_dir: flags.path("--work-dir")?,
config_dir: flags.path("--config-dir")?,
prompt_dir: flags.path("--prompt-dir")?,
instance: flags.text("--instance")?,
token_credential: flags.text("--token-credential")?,
deadline_ms: flags.number_or("--deadline-ms", 600_000)?,
max_line_bytes: flags.number_or("--max-line-bytes", 4 << 20)?,
max_total_bytes: flags.number_or("--max-total-bytes", 64 << 20)?,
stderr_tail_bytes: flags.number_or("--stderr-tail-bytes", 8192)?,
max_frame_bytes: frame_bytes_for_payload(first.max_payload_bytes),
max_connections: first.max_concurrent_requests.max(8),
socket_timeout_ms: flags.number_or("--socket-timeout-ms", 10_000)?,
max_expiry_skew_ms: 300_000,
providers: vec![provider],
models: vec![model],
callers: vec![first],
lease_socket: flags.single.get("--lease-socket").map(PathBuf::from),
lease_holders,
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
handle_secret_credential: flags.text("--handle-secret-credential")?,
auth: flags.auth()?,
};
// Validate before the secret file exists: a refused document leaves nothing.
config.validate()?;
ensure_secret_file(&secret_file)?;
if let Some(secret_file) = secret_file {
ensure_secret_file(&secret_file)?;
}
write_config(path.as_ref(), &config)?;
Ok(())
}
/// Appends one provider entry to an existing document.
fn add_provider(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(args, &[&PROVIDER], &["--strict-unsupported"])?;
let provider_id = flags.text("--provider")?;
let provider = flags.provider_entry(&provider_id)?;
let secret_file = matches!(provider.wire, ProviderWire::ClaudeCodeCli { .. })
.then(|| flags.single.get("--handle-secret-file").map(PathBuf::from))
.flatten();
let mut config = load_config(path.as_ref())?;
config.providers.push(provider);
config.validate()?;
if let Some(secret_file) = secret_file {
ensure_secret_file(&secret_file)?;
}
write_config(path.as_ref(), &config)?;
Ok(())
}
/// Appends one model row to an existing document.
fn add_model(path: &str, args: &[&str]) -> Result<(), Failure> {
let flags = Flags::parse(args, &[&MODEL], &[])?;
let provider_id = flags.text("--provider")?;
let model = flags.model_row(&provider_id)?;
let mut config = load_config(path.as_ref())?;
config.models.push(model);
write_config(path.as_ref(), &config)?;
Ok(())
}

View file

@ -1,6 +1,5 @@
//! The claude-connector's configuration document and binary: what the
//! document accepts, what it refuses, and that a document of the dollar era
//! fails closed.
//! document accepts, what it refuses, and that older documents fail closed.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@ -8,10 +7,11 @@ use std::process::{Command, Output};
use std::sync::atomic::{AtomicUsize, Ordering};
use claude_connector::{
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseHolderConfig, load_config, write_config,
ClaudeConnectorConfig, ConfigError, EffortMap, ForcedToolChoice, LeaseHolderConfig, ModelRow,
OutputSchemaSupport, ProviderEntry, ProviderWire, load_config, write_config,
};
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
use model_connector::{CallerConfig, LeaseScope};
use model_connector::{CallerConfig, LeaseScope, MAX_IDENTITY_BYTES};
const OPUS: &str = "claude-opus-5-1";
const HAIKU: &str = "claude-haiku-5-5";
@ -30,6 +30,7 @@ impl Scratch {
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn path(&self, name: &str) -> PathBuf {
self.0.join(name)
}
@ -41,27 +42,70 @@ impl Drop for Scratch {
}
}
fn cli_provider(id: &str) -> ProviderEntry {
ProviderEntry {
id: id.to_string(),
credential: Some("claude-token".to_string()),
wire: ProviderWire::ClaudeCodeCli {
binary: "/opt/claude/bin/claude".into(),
binary_sha256: [7; 32],
work_dir: "/var/lib/claude-connector/work".into(),
config_dir: "/var/lib/claude-connector/home".into(),
prompt_dir: "/var/lib/claude-connector/prompts".into(),
handle_secret_credential: "claude-handle-secret".to_string(),
instance: "persona-a".to_string(),
deadline_ms: 600_000,
max_line_bytes: 4 << 20,
max_total_bytes: 64 << 20,
stderr_tail_bytes: 8192,
meter_model: None,
},
}
}
fn http_provider(id: &str, base_url: &str, credential: Option<&str>) -> ProviderEntry {
ProviderEntry {
id: id.to_string(),
credential: credential.map(String::from),
wire: ProviderWire::AnthropicMessages {
base_url: base_url.to_string(),
deadline_ms: 600_000,
max_response_bytes: 64 << 20,
},
}
}
fn model_row(id: &str, provider: &str) -> ModelRow {
ModelRow {
id: id.to_string(),
provider: provider.to_string(),
upstream: id.to_string(),
efforts: EffortMap {
low: Some("low".to_string()),
medium: Some("medium".to_string()),
high: Some("high".to_string()),
max: Some("max".to_string()),
},
unset_effort: None,
forced_tool_choice: ForcedToolChoice::Never,
output_schema: OutputSchemaSupport::Native,
strict_tools: false,
}
}
fn valid() -> ClaudeConnectorConfig {
ClaudeConnectorConfig {
listen: "127.0.0.1:7443".to_string(),
replay_store: "/var/lib/claude-connector/replay.cc".into(),
claude_binary: "/opt/claude/bin/claude".into(),
claude_binary_sha256: [7; 32],
work_dir: "/var/lib/claude-connector/work".into(),
config_dir: "/var/lib/claude-connector/home".into(),
prompt_dir: "/var/lib/claude-connector/prompts".into(),
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,
stderr_tail_bytes: 8192,
max_frame_bytes: 2 << 20,
max_connections: 8,
socket_timeout_ms: 10_000,
max_expiry_skew_ms: 300_000,
providers: vec![cli_provider("claude-code")],
models: vec![
model_row(HAIKU, "claude-code"),
model_row(OPUS, "claude-code"),
],
callers: vec![CallerConfig {
caller_runtime_id: "persona-a-caller".to_string(),
connection_key_file: "/etc/claude-connector/caller.key".into(),
@ -137,26 +181,49 @@ fn a_dollar_era_config_is_refused_at_load() {
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
}
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")]
struct V2Config {
#[cultcache(key = 0)]
listen: String,
}
#[test]
fn the_known_models_are_the_allowed_models_by_form_alone() {
fn v2_config_is_refused_at_load() {
let scratch = Scratch::new();
let path = scratch.path("v2.cc");
{
let mut cache = CultCache::new();
cache.register_entry_type::<V2Config>().unwrap();
cache
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
.unwrap();
cache
.put(
"runtime".to_string(),
&V2Config {
listen: "127.0.0.1:7443".to_string(),
},
)
.unwrap();
}
assert!(matches!(load_config(&path), Err(ConfigError::Store)));
}
#[test]
fn allowed_models_must_be_subset_of_configured_models() {
for good in [
"deepseek-flash",
"gpt-5",
"custom/model-1",
"claude-opus-5-1",
"claude-haiku-5-5",
"claude-opus-5",
"claude-opus-5-1-20260101",
] {
let mut config = valid();
config.models.push(model_row(good, "claude-code"));
config.callers[0].allowed_models = vec![good.to_string()];
assert!(config.validate().is_ok(), "{good}");
}
for bad in [
"sonnet",
"claude-",
"claude-sonnet-latest",
"claude-Opus-5-1",
"claude-opus-5-1-2026",
"claude-opus-5-1-20260101-x",
] {
for bad in ["unconfigured-model", "deepseek-v4-pro", ""] {
let mut config = valid();
config.callers[0].allowed_models = vec![bad.to_string()];
assert_eq!(refused(&config), "allowed_models", "{bad}");
@ -164,11 +231,158 @@ fn the_known_models_are_the_allowed_models_by_form_alone() {
let mut twice = valid();
twice.callers[0].allowed_models = vec![OPUS.to_string(), OPUS.to_string()];
assert_eq!(refused(&twice), "allowed_models");
let mut none = valid();
none.callers[0].allowed_models.clear();
assert_eq!(refused(&none), "allowed_models");
}
#[test]
fn v3_validation_refuses_invalid_providers_models_and_urls() {
// Valid HTTPS and loopback HTTP URLs (with and without credential).
for (url, cred) in [
("https://api.example.com", Some("k1")),
("https://api.example.com/v1beta/openai", Some("k1")),
("http://127.0.0.1:8080", None),
("http://127.0.0.1:8080/v1", Some("k1")),
("http://[::1]:8080", None),
("http://[::1]:8080/v1", Some("k1")),
] {
let mut config = valid();
config.providers.push(http_provider("http-p", url, cred));
config.models.push(model_row("m-http", "http-p"));
assert!(config.validate().is_ok(), "{url} cred={cred:?}");
}
// Invalid base_urls.
for bad_url in [
"http://api.example.com",
"http://localhost:8080",
"http://192.168.1.10:8080",
"http://[fe80::1]:8080",
"ftp://api.example.com",
"https://user:pass@api.example.com",
"https://api.example.com?foo=bar",
"https://api.example.com#frag",
"https://api.example.com ",
" https://api.example.com",
"https://api.example.com/",
"https://api.example.com//v1",
"https://",
"",
] {
let mut config = valid();
config
.providers
.push(http_provider("http-p", bad_url, Some("k1")));
assert_eq!(refused(&config), "base_url", "{bad_url:?}");
}
// Keyless non-loopback refused.
let mut keyless_remote = valid();
keyless_remote
.providers
.push(http_provider("remote", "https://api.example.com", None));
assert_eq!(refused(&keyless_remote), "credential");
// Duplicate credential names across entries refused.
let mut dup_cred = valid();
dup_cred.providers.push(http_provider(
"remote",
"https://api.example.com",
Some("claude-token"),
));
assert_eq!(refused(&dup_cred), "credential");
// Provider credential colliding with CLI handle_secret_credential refused.
let mut collide_handle = valid();
collide_handle.providers.push(http_provider(
"remote",
"https://api.example.com",
Some("claude-handle-secret"),
));
assert_eq!(refused(&collide_handle), "credential");
// Model naming unknown provider refused.
let mut unknown_provider = valid();
unknown_provider
.models
.push(model_row("m-unknown", "nobody"));
assert_eq!(refused(&unknown_provider), "model_provider");
// Second ClaudeCodeCli entry refused.
let mut two_cli = valid();
two_cli.providers.push(ProviderEntry {
id: "cli-two".to_string(),
credential: Some("claude-token-two".to_string()),
wire: ProviderWire::ClaudeCodeCli {
binary: "/opt/claude/bin/claude".into(),
binary_sha256: [7; 32],
work_dir: "/var/lib/claude-connector/work2".into(),
config_dir: "/var/lib/claude-connector/home2".into(),
prompt_dir: "/var/lib/claude-connector/prompts2".into(),
handle_secret_credential: "claude-handle-secret-2".to_string(),
instance: "persona-b".to_string(),
deadline_ms: 600_000,
max_line_bytes: 4 << 20,
max_total_bytes: 64 << 20,
stderr_tail_bytes: 8192,
meter_model: None,
},
});
assert_eq!(refused(&two_cli), "providers");
// OpenAiChat entry refused until Cut 3.
let mut openai = valid();
openai.providers.push(ProviderEntry {
id: "deepseek".to_string(),
credential: Some("ds-key".to_string()),
wire: ProviderWire::OpenAiChat {
base_url: "https://api.deepseek.com".to_string(),
strict_unsupported: vec!["minLength".to_string()],
deadline_ms: 600_000,
max_response_bytes: 64 << 20,
},
});
assert_eq!(refused(&openai), "providers");
// Reserved stand-in provider id and oversized ids refused.
let mut stand_in = valid();
stand_in.providers = vec![http_provider(
"model-connector",
"https://api.example.com",
Some("k1"),
)];
assert_eq!(refused(&stand_in), "provider_id");
let mut oversized_provider = valid();
oversized_provider.providers.push(http_provider(
&"p".repeat(MAX_IDENTITY_BYTES + 1),
"https://api.example.com",
Some("k1"),
));
assert_eq!(refused(&oversized_provider), "provider_id");
let mut oversized_model = valid();
oversized_model
.models
.push(model_row(&"m".repeat(MAX_IDENTITY_BYTES + 1), "claude-code"));
assert_eq!(refused(&oversized_model), "model_id");
// Empty providers, empty models, duplicate ids, untrimmed upstream/efforts refused.
let mut empty_providers = valid();
empty_providers.providers.clear();
assert_eq!(refused(&empty_providers), "providers");
let mut empty_models = valid();
empty_models.models.clear();
assert_eq!(refused(&empty_models), "models");
let mut untrimmed_effort = valid();
untrimmed_effort.models[0].efforts.low = Some(" low".to_string());
assert_eq!(refused(&untrimmed_effort), "efforts");
}
#[test]
fn caller_bounds_are_required_nonzero() {
let edits: [fn(&mut ClaudeConnectorConfig); 3] = [
@ -212,6 +426,15 @@ fn a_lease_holder_names_a_configured_caller_and_valid_unit_and_provider() {
instanced_unit.lease_holders[0].scope = LeaseScope::PerInvocation;
assert!(instanced_unit.validate().is_ok());
// Custom CLI provider entry id binds lease_holders.provider.
let mut custom_cli = valid();
custom_cli.providers = vec![cli_provider("sub-cli")];
for model in &mut custom_cli.models {
model.provider = "sub-cli".to_string();
}
custom_cli.lease_holders[0].provider = "sub-cli".to_string();
assert!(custom_cli.validate().is_ok());
for bad_unit in [
"agent@.service",
"@a.service",
@ -230,23 +453,36 @@ fn a_lease_holder_names_a_configured_caller_and_valid_unit_and_provider() {
let mut bad_provider = valid();
bad_provider.lease_holders[0].provider = "deepseek".to_string();
assert_eq!(refused(&bad_provider), "lease_holders");
// Lease with CLI provider lacking both meter_model and any CLI ModelRow is refused.
let mut no_cli_model = valid();
no_cli_model
.providers
.push(http_provider("remote", "https://api.example.com", Some("k")));
no_cli_model.models = vec![model_row(HAIKU, "remote"), model_row(OPUS, "remote")];
assert_eq!(refused(&no_cli_model), "meter_model");
}
fn run(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_claude-connector"))
.args(args)
.env_clear()
.output()
.unwrap()
}
fn init_flags(scratch: &Scratch, extra: &[&str]) -> Vec<String> {
fn cli_init_flags(scratch: &Scratch, extra: &[&str]) -> Vec<String> {
let path = |name: &str| scratch.path(name).to_string_lossy().into_owned();
let mut flags: Vec<String> = [
"--listen",
"127.0.0.1:0",
"--replay-store",
&path("replay.cc"),
"--provider",
"claude-code",
"--wire",
"claude-code-cli",
"--credential",
"claude-token",
"--claude-binary",
&path("claude"),
"--claude-sha256",
@ -259,12 +495,62 @@ fn init_flags(scratch: &Scratch, extra: &[&str]) -> Vec<String> {
&path("prompts"),
"--instance",
"persona-a",
"--token-credential",
"claude-token",
"--handle-secret-credential",
"claude-handle-secret",
"--handle-secret-file",
&path("handle.secret"),
"--model",
HAIKU,
"--upstream",
HAIKU,
"--forced-tool-choice",
"never",
"--output-schema",
"native",
"--strict-tools",
"false",
"--caller-id",
"persona-a-caller",
"--connection-key-file",
&path("caller.key"),
"--connection-key-epoch",
"1",
"--allowed-model",
HAIKU,
]
.map(String::from)
.to_vec();
flags.extend(extra.iter().map(|flag| flag.to_string()));
flags
}
fn http_init_flags(scratch: &Scratch, extra: &[&str]) -> Vec<String> {
let path = |name: &str| scratch.path(name).to_string_lossy().into_owned();
let mut flags: Vec<String> = [
"--listen",
"127.0.0.1:0",
"--replay-store",
&path("replay.cc"),
"--provider",
"anthropic-a",
"--wire",
"anthropic-messages",
"--base-url",
"https://api.example.test",
"--credential",
"cred-one",
"--model",
HAIKU,
"--upstream",
"claude-haiku-upstream",
"--effort-low",
"low",
"--forced-tool-choice",
"always",
"--output-schema",
"native",
"--strict-tools",
"false",
"--caller-id",
"persona-a-caller",
"--connection-key-file",
@ -290,14 +576,273 @@ fn init(scratch: &Scratch, flags: &[String]) -> Output {
#[test]
fn config_init_writes_the_flags_into_the_document() {
let scratch = Scratch::new();
let made = init(&scratch, &init_flags(&scratch, &[]));
let made = init(&scratch, &cli_init_flags(&scratch, &[]));
assert!(made.status.success(), "{:?}", made);
let config = load_config(&scratch.path("connector.cc")).unwrap();
assert_eq!(config.providers.len(), 1);
assert_eq!(config.providers[0].id, "claude-code");
assert_eq!(config.models.len(), 1);
assert_eq!(config.models[0].id, HAIKU);
assert_eq!(config.callers[0].allowed_models, [HAIKU]);
assert_eq!(config.claude_binary_sha256, [0xab; 32]);
assert!(matches!(
config.providers[0].wire,
ProviderWire::ClaudeCodeCli {
binary_sha256,
..
} if binary_sha256 == [0xab; 32]
));
assert!(config.lease_holders.is_empty());
}
#[test]
fn config_init_without_provider_fails_naming_the_flag() {
let scratch = Scratch::new();
let config = scratch.path("connector.cc");
let p = config.to_str().unwrap();
// Bare `config init` without `--provider`.
let bare = run(&["config", "init", p]);
assert!(!bare.status.success(), "{bare:?}");
let bare_err = String::from_utf8_lossy(&bare.stderr);
assert!(bare_err.contains("--provider"), "{bare_err}");
assert!(!config.exists());
// Full flags except `--provider` omitted.
let all = http_init_flags(&scratch, &[]);
let mut without_provider = Vec::new();
let mut iter = all.iter();
while let Some(flag) = iter.next() {
if flag == "--provider" {
let _ = iter.next();
continue;
}
without_provider.push(flag.clone());
}
let out = init(&scratch, &without_provider);
assert!(!out.status.success(), "{out:?}");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("--provider"), "{stderr}");
assert!(!config.exists());
}
#[test]
fn config_init_rejects_v2_auth_and_conflicting_wire_flags() {
for bad in [
vec!["--auth", "oauth-token"],
vec!["--token-credential", "claude-token"],
] {
let scratch = Scratch::new();
let made = init(&scratch, &cli_init_flags(&scratch, &bad));
assert!(!made.status.success(), "{bad:?}");
assert!(!scratch.path("connector.cc").exists());
}
let scratch = Scratch::new();
let secret = scratch.path("handle.secret").to_string_lossy().into_owned();
let http_with_cli_flag = init(
&scratch,
&http_init_flags(&scratch, &["--handle-secret-file", &secret]),
);
assert!(!http_with_cli_flag.status.success());
assert!(
String::from_utf8_lossy(&http_with_cli_flag.stderr).contains("--handle-secret-file"),
"{}",
String::from_utf8_lossy(&http_with_cli_flag.stderr)
);
assert!(!scratch.path("connector.cc").exists());
let scratch = Scratch::new();
let cli_with_http_flag = init(
&scratch,
&cli_init_flags(&scratch, &["--base-url", "https://api.example.test"]),
);
assert!(!cli_with_http_flag.status.success());
assert!(
String::from_utf8_lossy(&cli_with_http_flag.stderr).contains("--base-url"),
"{}",
String::from_utf8_lossy(&cli_with_http_flag.stderr)
);
assert!(!scratch.path("connector.cc").exists());
}
#[test]
fn config_add_provider_and_add_model_append_and_validate() {
let scratch = Scratch::new();
let made = init(&scratch, &http_init_flags(&scratch, &[]));
assert!(made.status.success(), "{made:?}");
let config_path = scratch.path("connector.cc");
let p = config_path.to_str().unwrap();
let added_provider = run(&[
"config",
"add-provider",
p,
"--provider",
"local-stub",
"--wire",
"anthropic-messages",
"--base-url",
"http://127.0.0.1:8080",
]);
assert!(added_provider.status.success(), "{added_provider:?}");
let added_model = run(&[
"config",
"add-model",
p,
"--model",
"deepseek-flash",
"--provider",
"local-stub",
"--upstream",
"deepseek-chat",
"--effort-low",
"low",
"--effort-high",
"high",
"--unset-effort",
"none",
"--forced-tool-choice",
"without-thinking",
"--output-schema",
"none",
"--strict-tools",
"true",
]);
assert!(added_model.status.success(), "{added_model:?}");
let loaded = load_config(&config_path).unwrap();
assert_eq!(loaded.providers.len(), 2);
assert_eq!(loaded.providers[1].id, "local-stub");
assert_eq!(loaded.providers[1].credential, None);
assert_eq!(loaded.models.len(), 2);
assert_eq!(loaded.models[1].id, "deepseek-flash");
assert_eq!(loaded.models[1].provider, "local-stub");
assert_eq!(loaded.models[1].upstream, "deepseek-chat");
assert_eq!(loaded.models[1].unset_effort.as_deref(), Some("none"));
assert_eq!(
loaded.models[1].forced_tool_choice,
ForcedToolChoice::WithoutThinking
);
assert_eq!(loaded.models[1].output_schema, OutputSchemaSupport::None);
assert!(loaded.models[1].strict_tools);
let before_invalid = std::fs::read(&config_path).unwrap();
for bad_args in [
// OpenAiChat refused until Cut 3.
vec![
"config",
"add-provider",
p,
"--provider",
"ds",
"--wire",
"openai-chat",
"--base-url",
"https://api.deepseek.com",
"--credential",
"ds-cred",
],
// Duplicate credential refused.
vec![
"config",
"add-provider",
p,
"--provider",
"dup",
"--wire",
"anthropic-messages",
"--base-url",
"https://two.example.test",
"--credential",
"cred-one",
],
// Unknown provider on model refused.
vec![
"config",
"add-model",
p,
"--model",
"m-bad",
"--provider",
"nobody",
"--upstream",
"u",
"--forced-tool-choice",
"never",
"--output-schema",
"native",
"--strict-tools",
"false",
],
] {
let out = run(&bad_args);
assert!(!out.status.success(), "{bad_args:?} unexpectedly succeeded");
assert_eq!(
std::fs::read(&config_path).unwrap(),
before_invalid,
"{bad_args:?} modified config"
);
}
}
#[test]
fn readiness_names_failing_entry_id_and_never_leaks_secret() {
const SECRET_1: &str = "canary-secret-value-one-73a9";
const SECRET_2: &str = "canary-secret-value-two-88f1";
let scratch = Scratch::new();
std::fs::write(scratch.path("caller.key"), "k".repeat(48)).unwrap();
let creds = scratch.path("creds");
std::fs::create_dir_all(&creds).unwrap();
std::fs::write(creds.join("cred-one"), SECRET_1).unwrap();
std::fs::write(creds.join("cred-two"), SECRET_2).unwrap();
let made = init(&scratch, &http_init_flags(&scratch, &[]));
assert!(made.status.success(), "{made:?}");
let config_path = scratch.path("connector.cc");
let p = config_path.to_str().unwrap();
let added = run(&[
"config",
"add-provider",
p,
"--provider",
"anthropic-b",
"--wire",
"anthropic-messages",
"--base-url",
"https://b.example.test",
"--credential",
"cred-two",
]);
assert!(added.status.success(), "{added:?}");
let ok = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
.args(["config", "check", p])
.env("CREDENTIALS_DIRECTORY", &creds)
.output()
.unwrap();
assert!(ok.status.success(), "{ok:?}");
let stdout = String::from_utf8_lossy(&ok.stdout);
assert!(stdout.contains("providers: 2"), "{stdout}");
assert!(stdout.contains("models: 1"), "{stdout}");
// Remove the second entry's credential -> must fail naming `anthropic-b`, never the secret.
std::fs::remove_file(creds.join("cred-two")).unwrap();
let fail = Command::new(env!("CARGO_BIN_EXE_claude-connector"))
.args(["config", "check", p])
.env("CREDENTIALS_DIRECTORY", &creds)
.output()
.unwrap();
assert!(!fail.status.success(), "{fail:?}");
let stderr = String::from_utf8_lossy(&fail.stderr);
assert!(stderr.contains("anthropic-b"), "{stderr}");
for secret in [SECRET_1, SECRET_2, "cred-one", "cred-two"] {
assert!(!stderr.contains(secret), "leaked {secret}: {stderr}");
}
}
#[test]
fn the_dollar_flags_are_not_flags() {
let dollar_flags: [&[&str]; 4] = [
@ -308,7 +853,7 @@ fn the_dollar_flags_are_not_flags() {
];
for extra in dollar_flags {
let scratch = Scratch::new();
let made = init(&scratch, &init_flags(&scratch, extra));
let made = init(&scratch, &cli_init_flags(&scratch, extra));
assert!(!made.status.success(), "{extra:?} was accepted");
assert!(
!Path::new(&scratch.path("connector.cc")).exists(),
@ -326,198 +871,19 @@ fn serve_refuses_a_document_that_is_not_there() {
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_holders: 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_holders: Vec<LeaseHolderConfig>,
#[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_holders: now.lease_holders.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_holders: 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 callers_only = ClaudeConnectorConfig {
lease_socket: None,
lease_holders: vec![],
..keyed_with_a_lease()
};
assert!(callers_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",
"agent-a",
"--provider",
"claude-code",
"--unit",
"agent@a.service",
"--scope",
"per-caller",
];
let scratch = Scratch::new();
let leased = init(&scratch, &init_flags(&scratch, &[&["--auth", "api-key"], &lease[..]].concat()));
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 add_lease_holder_and_unit_validation() {
let scratch = Scratch::new();
let config_path = scratch.path("connector.cc");
let made = init(
&scratch,
&init_flags(
&cli_init_flags(
&scratch,
&[
"--lease-socket",
"/run/claude-connector/lease.sock",
"--lease-user",
"agent-a",
"--provider",
"claude-code",
"--unit",
"worker.service",
"--scope",
@ -618,9 +984,27 @@ fn add_lease_holder_and_unit_validation() {
}
#[test]
fn serve_and_check_refuse_a_key_document_that_carries_a_lease() {
fn serve_and_check_refuse_a_lease_without_cli_provider() {
let scratch = Scratch::new();
let path = scratch.path("handmade.cc");
let bad = ClaudeConnectorConfig {
providers: vec![http_provider(
"anthropic-messages",
"https://api.example.test",
Some("api-key"),
)],
models: vec![model_row(HAIKU, "anthropic-messages")],
callers: vec![CallerConfig {
allowed_models: vec![HAIKU.to_string()],
..valid().callers.into_iter().next().unwrap()
}],
lease_holders: vec![LeaseHolderConfig {
provider: "anthropic-messages".to_string(),
..valid().lease_holders.into_iter().next().unwrap()
}],
..valid()
};
assert!(write_config(&path, &bad).is_err());
{
// Written around write_config, which would refuse it.
let mut cache = CultCache::new();
@ -628,18 +1012,13 @@ fn serve_and_check_refuse_a_key_document_that_carries_a_lease() {
cache
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))
.unwrap();
cache
.put("runtime".to_string(), &keyed_with_a_lease())
.unwrap();
cache.put("runtime".to_string(), &bad).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)
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("lease_socket"), "{args:?}: {stderr}");
}
}