diff --git a/crates/claude-connector/src/config.rs b/crates/claude-connector/src/config.rs index d34fa8d..a29cadb 100644 --- a/crates/claude-connector/src/config.rs +++ b/crates/claude-connector/src/config.rs @@ -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, + 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, + 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, + }, +} + +/// 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, + 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, + pub medium: Option, + pub high: Option, + pub max: Option, +} + +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. diff --git a/crates/claude-connector/src/daemon.rs b/crates/claude-connector/src/daemon.rs index fb098a3..2d640c2 100644 --- a/crates/claude-connector/src/daemon.rs +++ b/crates/claude-connector/src/daemon.rs @@ -4,33 +4,38 @@ //! them. Validation errors name a field and never echo a value. use std::collections::BTreeSet; -use std::net::{SocketAddr, TcpListener}; +use std::net::{IpAddr, SocketAddr, TcpListener}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; +#[cfg(unix)] +use model_connector::ProviderBackend; use model_connector::{ - CallerAdmission, CallerConfig, LeaseScope, MIN_PAYLOAD_BYTES, ProviderBackend, ProviderRoutes, - ServeError, ServeLimits, ServiceError, TransportService, load_admissions, serve_service, + CallerAdmission, CallerConfig, LeaseScope, MAX_IDENTITY_BYTES, MIN_PAYLOAD_BYTES, + ProviderRoutes, ServeError, ServeLimits, ServiceError, TransportService, load_admissions, + serve_service, }; use serde::{Deserialize, Serialize}; use thiserror::Error; +use zeroize::Zeroizing; use crate::backend::readiness; #[cfg(target_os = "linux")] use crate::lease::{LeaseHolder, LeaseLimits, serve_leases, user_uid}; +#[cfg(unix)] +use crate::meter; #[cfg(target_os = "linux")] use crate::unit::SystemdUnits; #[cfg(unix)] -use crate::meter; +use crate::{MessagesBackend, MessagesConfig}; use crate::{ - ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, - MessagesBackend, MessagesConfig, StderrSink, + ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, ModelRow, + ProviderEntry, ProviderWire, StderrSink, TokenSource, }; const CONFIG_KEY: &str = "runtime"; -const MODEL_PREFIX: &str = "claude-"; /// A unix account that may lease the subscription token, the provider and full /// systemd unit its process must run in, its exclusivity scope, and the @@ -47,7 +52,7 @@ pub struct LeaseHolderConfig { } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "gamecult.model_connector.claude_connector_config.v2")] +#[cultcache(type = "gamecult.model_connector.connector_config.v3")] pub struct ClaudeConnectorConfig { /// A loopback socket address. #[cultcache(key = 0)] @@ -55,63 +60,35 @@ pub struct ClaudeConnectorConfig { #[cultcache(key = 1)] pub replay_store: PathBuf, #[cultcache(key = 2)] - pub claude_binary: PathBuf, - #[cultcache(key = 3)] - pub claude_binary_sha256: [u8; 32], - #[cultcache(key = 4)] - pub work_dir: PathBuf, - #[cultcache(key = 5)] - pub config_dir: PathBuf, - /// Where each call's system prompt is staged: a directory the connector - /// owns, mode 0700. - #[cultcache(key = 6)] - pub prompt_dir: PathBuf, - #[cultcache(key = 7)] - pub instance: String, - /// The name of the systemd credential that holds the child's token. - #[cultcache(key = 8)] - pub token_credential: String, - #[cultcache(key = 9)] - pub deadline_ms: u64, - #[cultcache(key = 10)] - pub max_line_bytes: usize, - #[cultcache(key = 11)] - pub max_total_bytes: usize, - #[cultcache(key = 12)] - pub stderr_tail_bytes: usize, - #[cultcache(key = 13)] pub max_frame_bytes: usize, - #[cultcache(key = 14)] + #[cultcache(key = 3)] pub max_connections: usize, - #[cultcache(key = 15)] + #[cultcache(key = 4)] pub socket_timeout_ms: u64, - #[cultcache(key = 16)] + #[cultcache(key = 5)] pub max_expiry_skew_ms: u64, + /// Configured upstream providers; each carries its own credential and wire parameters. + #[cultcache(key = 6)] + pub providers: Vec, + /// Caller-facing models, each routed to a configured provider. + #[cultcache(key = 7)] + pub models: Vec, /// Every caller of this connector: its own connection key and epoch, models, /// concurrency, payload and output bounds. /// Ids are unique. Handles are bound to the caller that was given them. - #[cultcache(key = 17)] + #[cultcache(key = 8)] pub callers: Vec, /// Where the credential lease socket is bound (a systemd RuntimeDirectory), /// or none when this connector lends no token. - #[cultcache(key = 19)] + #[cultcache(key = 9)] pub lease_socket: Option, /// The accounts allowed to lease, each bound to a configured caller. /// Empty exactly when `lease_socket` is none. - #[cultcache(key = 20)] + #[cultcache(key = 10)] pub lease_holders: Vec, /// The furthest a lease's expiry may lie from now. - #[cultcache(key = 21)] + #[cultcache(key = 11)] pub lease_max_ms: u64, - /// The name of the systemd credential that holds the handle secret (at - /// 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 @@ -129,6 +106,9 @@ pub enum ConfigError { /// Something the document names exists but cannot be used now. #[error("the configured {0} cannot be used")] Unusable(&'static str), + /// A configured provider entry exists but cannot be used now. + #[error("configured provider {id} field {field} cannot be used")] + UnusableEntry { id: String, field: &'static str }, /// The serve loop failed after it started. #[error("the serve loop failed at {0}")] Serving(&'static str), @@ -161,8 +141,8 @@ impl From for ConfigError { } impl ClaudeConnectorConfig { - /// The one validation: `config init`, `config check` and `serve` all pass - /// through it. Returns the listen address. + /// The one validation: `config init`, `config add-provider`, `config add-model`, + /// `config check`, and `serve` all pass through it. Returns the listen address. pub fn validate(&self) -> Result { let listen = self .listen @@ -170,38 +150,8 @@ impl ClaudeConnectorConfig { .ok() .filter(|address| address.ip().is_loopback()) .ok_or(ConfigError::Invalid("listen"))?; - let paths = [ - ("replay_store", &self.replay_store), - ("claude_binary", &self.claude_binary), - ("work_dir", &self.work_dir), - ("config_dir", &self.config_dir), - ("prompt_dir", &self.prompt_dir), - ]; - for (field, path) in paths { - if !path.is_absolute() { - return Err(ConfigError::Invalid(field)); - } - } - if self.claude_binary_sha256 == [0; 32] { - return Err(ConfigError::Invalid("claude_binary_sha256")); - } - if !is_trimmed_nonempty(&self.instance) { - return Err(ConfigError::Invalid("instance")); - } - if !is_credential_name(&self.token_credential) { - return Err(ConfigError::Invalid("token_credential")); - } - if !is_credential_name(&self.handle_secret_credential) - || self.handle_secret_credential == self.token_credential - { - return Err(ConfigError::Invalid("handle_secret_credential")); - } - if self.deadline_ms == 0 - || self.max_line_bytes == 0 - || self.max_total_bytes < self.max_line_bytes - || self.stderr_tail_bytes == 0 - { - return Err(ConfigError::Invalid("child limits")); + if !self.replay_store.is_absolute() { + return Err(ConfigError::Invalid("replay_store")); } if self.max_frame_bytes == 0 || self.max_connections == 0 @@ -210,6 +160,139 @@ impl ClaudeConnectorConfig { { return Err(ConfigError::Invalid("serve limits")); } + + if self.providers.is_empty() { + return Err(ConfigError::Invalid("providers")); + } + let mut provider_ids = BTreeSet::new(); + let mut credential_names = BTreeSet::new(); + let mut cli_provider: Option<&str> = None; + for entry in &self.providers { + if !is_valid_identity(&entry.id) || entry.id == "model-connector" { + return Err(ConfigError::Invalid("provider_id")); + } + if !provider_ids.insert(entry.id.as_str()) { + return Err(ConfigError::Invalid("providers")); + } + if let Some(credential) = &entry.credential { + if !is_credential_name(credential) { + return Err(ConfigError::Invalid("credential")); + } + if !credential_names.insert(credential.as_str()) { + return Err(ConfigError::Invalid("credential")); + } + } + match &entry.wire { + ProviderWire::AnthropicMessages { + base_url, + deadline_ms, + max_response_bytes, + } => { + let is_loopback = validate_base_url(base_url)?; + if !is_loopback && entry.credential.is_none() { + return Err(ConfigError::Invalid("credential")); + } + if *deadline_ms == 0 || *max_response_bytes == 0 { + return Err(ConfigError::Invalid("http limits")); + } + } + ProviderWire::OpenAiChat { .. } => { + return Err(ConfigError::Invalid("providers")); + } + ProviderWire::ClaudeCodeCli { + binary, + binary_sha256, + work_dir, + config_dir, + prompt_dir, + handle_secret_credential, + instance, + deadline_ms, + max_line_bytes, + max_total_bytes, + stderr_tail_bytes, + meter_model, + } => { + if cli_provider.is_some() { + return Err(ConfigError::Invalid("providers")); + } + cli_provider = Some(entry.id.as_str()); + if entry.credential.is_none() { + return Err(ConfigError::Invalid("credential")); + } + for (field, path) in [ + ("claude_binary", binary), + ("work_dir", work_dir), + ("config_dir", config_dir), + ("prompt_dir", prompt_dir), + ] { + if !path.is_absolute() { + return Err(ConfigError::Invalid(field)); + } + } + if *binary_sha256 == [0; 32] { + return Err(ConfigError::Invalid("claude_binary_sha256")); + } + if !is_trimmed_nonempty(instance) { + return Err(ConfigError::Invalid("instance")); + } + if !is_credential_name(handle_secret_credential) + || !credential_names.insert(handle_secret_credential.as_str()) + { + return Err(ConfigError::Invalid("handle_secret_credential")); + } + if *deadline_ms == 0 + || *max_line_bytes == 0 + || *max_total_bytes < *max_line_bytes + || *stderr_tail_bytes == 0 + { + return Err(ConfigError::Invalid("child limits")); + } + if let Some(model) = meter_model + && !is_valid_identity(model) + { + return Err(ConfigError::Invalid("meter_model")); + } + } + } + } + + if self.models.is_empty() { + return Err(ConfigError::Invalid("models")); + } + let mut model_ids = BTreeSet::new(); + for model in &self.models { + if !is_valid_identity(&model.id) { + return Err(ConfigError::Invalid("model_id")); + } + if !model_ids.insert(model.id.as_str()) { + return Err(ConfigError::Invalid("models")); + } + if !provider_ids.contains(model.provider.as_str()) { + return Err(ConfigError::Invalid("model_provider")); + } + if !is_trimmed_nonempty(&model.upstream) { + return Err(ConfigError::Invalid("upstream")); + } + for effort in [ + &model.efforts.low, + &model.efforts.medium, + &model.efforts.high, + &model.efforts.max, + ] { + if let Some(value) = effort + && !is_trimmed_nonempty(value) + { + return Err(ConfigError::Invalid("efforts")); + } + } + if let Some(value) = &model.unset_effort + && !is_trimmed_nonempty(value) + { + return Err(ConfigError::Invalid("unset_effort")); + } + } + if self.callers.is_empty() { return Err(ConfigError::Invalid("callers")); } @@ -238,23 +321,22 @@ impl ClaudeConnectorConfig { } let mut seen = BTreeSet::new(); for model in &caller.allowed_models { - if !has_model_id_form(model) || !seen.insert(model.as_str()) { + if !model_ids.contains(model.as_str()) || !seen.insert(model.as_str()) { return Err(ConfigError::Invalid("allowed_models")); } } } - self.validate_leases()?; + self.validate_leases(cli_provider)?; Ok(listen) } - 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. Callers use their own connection keys and need neither. - if self.auth == ClaudeAuth::ApiKey - && (self.lease_socket.is_some() || !self.lease_holders.is_empty()) - { - return Err(ConfigError::Invalid("auth")); - } + fn cli_entry(&self) -> Option<&ProviderEntry> { + self.providers + .iter() + .find(|entry| matches!(entry.wire, ProviderWire::ClaudeCodeCli { .. })) + } + + fn validate_leases(&self, cli_provider: Option<&str>) -> Result<(), ConfigError> { let Some(socket) = &self.lease_socket else { return if self.lease_holders.is_empty() { Ok(()) @@ -268,6 +350,18 @@ impl ClaudeConnectorConfig { if self.lease_max_ms == 0 { return Err(ConfigError::Invalid("lease_max_ms")); } + let Some(cli_id) = cli_provider else { + return Err(ConfigError::Invalid("lease_socket")); + }; + let has_cli_meter_target = self.cli_entry().is_some_and(|entry| match &entry.wire { + ProviderWire::ClaudeCodeCli { meter_model, .. } => { + meter_model.is_some() || self.models.iter().any(|model| model.provider == cli_id) + } + _ => false, + }); + if !has_cli_meter_target { + return Err(ConfigError::Invalid("meter_model")); + } let mut users = BTreeSet::new(); if self.lease_holders.is_empty() || !self.lease_holders.iter().all(|lease| { @@ -276,7 +370,7 @@ impl ClaudeConnectorConfig { .callers .iter() .any(|caller| caller.caller_runtime_id == lease.caller_id) - && lease.provider == crate::config::PROVIDER + && lease.provider == cli_id && is_systemd_unit_name(&lease.unit) && users.insert(lease.unix_user.as_str()) }) @@ -286,33 +380,6 @@ impl ClaudeConnectorConfig { Ok(()) } - fn backend_config(&self) -> ClaudeCodeConfig { - ClaudeCodeConfig { - claude_binary: self.claude_binary.clone(), - claude_binary_sha256: self.claude_binary_sha256, - work_dir: self.work_dir.clone(), - config_dir: self.config_dir.clone(), - prompt_dir: self.prompt_dir.clone(), - token_credential: self.token_credential.clone(), - handle_secret_credential: self.handle_secret_credential.clone(), - instance: self.instance.clone(), - limits: ClaudeCodeLimits { - deadline: Duration::from_millis(self.deadline_ms), - max_line_bytes: self.max_line_bytes, - max_total_bytes: self.max_total_bytes, - stderr_tail_bytes: self.stderr_tail_bytes, - }, - } - } - - fn messages_config(&self) -> MessagesConfig { - MessagesConfig { - key_credential: self.token_credential.clone(), - deadline: Duration::from_millis(self.deadline_ms), - max_response_bytes: self.max_total_bytes, - } - } - fn serve_limits(&self) -> ServeLimits { ServeLimits { max_frame_bytes: self.max_frame_bytes, @@ -323,6 +390,60 @@ impl ClaudeConnectorConfig { } } +fn backend_config_for(entry: &ProviderEntry) -> Option { + let ProviderWire::ClaudeCodeCli { + binary, + binary_sha256, + work_dir, + config_dir, + prompt_dir, + handle_secret_credential, + instance, + deadline_ms, + max_line_bytes, + max_total_bytes, + stderr_tail_bytes, + .. + } = &entry.wire + else { + return None; + }; + let token_credential = entry.credential.as_ref()?.clone(); + Some(ClaudeCodeConfig { + claude_binary: binary.clone(), + claude_binary_sha256: *binary_sha256, + work_dir: work_dir.clone(), + config_dir: config_dir.clone(), + prompt_dir: prompt_dir.clone(), + token_credential, + handle_secret_credential: handle_secret_credential.clone(), + instance: instance.clone(), + limits: ClaudeCodeLimits { + deadline: Duration::from_millis(*deadline_ms), + max_line_bytes: *max_line_bytes, + max_total_bytes: *max_total_bytes, + stderr_tail_bytes: *stderr_tail_bytes, + }, + }) +} + +#[cfg(unix)] +fn messages_config_for(entry: &ProviderEntry) -> Option { + let ProviderWire::AnthropicMessages { + deadline_ms, + max_response_bytes, + .. + } = &entry.wire + else { + return None; + }; + Some(MessagesConfig { + key_credential: entry.credential.clone().unwrap_or_default(), + deadline: Duration::from_millis(*deadline_ms), + max_response_bytes: *max_response_bytes, + }) +} + /// A systemd service unit name: `name.service` or `name@instance.service`. fn is_systemd_unit_name(text: &str) -> bool { if text.len() > 256 { @@ -352,35 +473,84 @@ fn is_trimmed_nonempty(text: &str) -> bool { !text.is_empty() && text.trim() == text } -/// The loose shape of a model id, only to catch typos: -/// `claude--`, then an optional `-` and an optional -/// `-YYYYMMDD`, the family lowercase letters. No shape can tell an alias from -/// a canonical id, so the known list is `allowed_models` itself; an alias that slips in fails its first -/// call, when the stream's `init.model` differs from the request. -fn has_model_id_form(model: &str) -> bool { - let Some(rest) = model.strip_prefix(MODEL_PREFIX) else { - return false; +fn is_valid_identity(text: &str) -> bool { + is_trimmed_nonempty(text) && text.len() <= MAX_IDENTITY_BYTES +} + +/// Accepts `https://` URLs and loopback-IP `http://` URLs; rejects userinfo, +/// query strings, fragments, whitespace, control characters, and trailing `/`. +/// Returns `Ok(true)` when the host is a loopback `IpAddr`, `Ok(false)` otherwise. +fn validate_base_url(url: &str) -> Result { + if url.is_empty() + || url.ends_with('/') + || url.chars().any(|c| c.is_whitespace() || c.is_control()) + || url.contains(['?', '#', '\\']) + { + return Err(ConfigError::Invalid("base_url")); + } + let (is_http, rest) = if let Some(rest) = url.strip_prefix("https://") { + (false, rest) + } else if let Some(rest) = url.strip_prefix("http://") { + (true, rest) + } else { + return Err(ConfigError::Invalid("base_url")); }; - let digits = |part: &str, most: usize| { - (1..=most).contains(&part.len()) && part.bytes().all(|byte| byte.is_ascii_digit()) + let (authority, path) = match rest.split_once('/') { + Some((authority, path)) => (authority, Some(path)), + None => (rest, None), }; - let date = |part: &str| part.len() == 8 && digits(part, 8); - let mut parts = rest.split('-'); - let family = parts.next().unwrap_or(""); - let tail: Vec<&str> = parts.collect(); - let Some((major, after)) = tail.split_first() else { - return false; + if authority.is_empty() || authority.contains('@') { + return Err(ConfigError::Invalid("base_url")); + } + if let Some(path) = path + && (path.is_empty() || path.split('/').any(str::is_empty)) + { + return Err(ConfigError::Invalid("base_url")); + } + let (host, port) = parse_authority(authority).ok_or(ConfigError::Invalid("base_url"))?; + if let Some(port) = port + && (port.is_empty() + || !port.bytes().all(|b| b.is_ascii_digit()) + || !port.parse::().is_ok_and(|p| p > 0)) + { + return Err(ConfigError::Invalid("base_url")); + } + let is_loopback = host.parse::().is_ok_and(|ip| ip.is_loopback()); + if is_http && !is_loopback { + return Err(ConfigError::Invalid("base_url")); + } + Ok(is_loopback) +} + +fn parse_authority(authority: &str) -> Option<(&str, Option<&str>)> { + if let Some(after_open) = authority.strip_prefix('[') { + let (host, rest) = after_open.split_once(']')?; + host.parse::().ok()?; + let port = if rest.is_empty() { + None + } else { + Some(rest.strip_prefix(':')?) + }; + return Some((host, port)); + } + if authority.contains(['[', ']']) { + return None; + } + let (host, port) = match authority.rsplit_once(':') { + Some((host, port)) => (host, Some(port)), + None => (authority, None), }; - let after_ok = match after { - [] => true, - [one] => digits(one, 2) || date(one), - [minor, last] => digits(minor, 2) && date(last), - _ => false, - }; - !family.is_empty() - && family.bytes().all(|byte| byte.is_ascii_lowercase()) - && digits(major, 2) - && after_ok + if host.is_empty() + || host.starts_with('.') + || host.ends_with('.') + || host.contains("..") + || !host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-')) + { + return None; + } + Some((host, port)) } /// One file name under `$CREDENTIALS_DIRECTORY`, never a path. @@ -469,32 +639,88 @@ impl StderrSink for LogSink { } } +struct MissingCredentialsDirectory; + +impl TokenSource for MissingCredentialsDirectory { + fn read(&self) -> Option> { + None + } + + fn missing(&self) -> &'static str { + "credentials_directory" + } +} + +fn token_source_in( + creds_dir: Option<&Path>, + name: &str, + field: &'static str, +) -> Box { + match creds_dir { + Some(dir) => Box::new(CredentialTokenSource::in_directory(dir, name).for_field(field)), + None => Box::new(MissingCredentialsDirectory), + } +} + +fn entry_readiness(entry: &ProviderEntry, creds_dir: Option<&Path>) -> Result<(), ConfigError> { + match &entry.wire { + ProviderWire::ClaudeCodeCli { .. } => { + let backend = backend_config_for(entry).ok_or_else(|| ConfigError::UnusableEntry { + id: entry.id.clone(), + field: "credential", + })?; + #[cfg(unix)] + check_prompt_dir(&backend.prompt_dir).map_err(|_| ConfigError::UnusableEntry { + id: entry.id.clone(), + field: "prompt_dir", + })?; + let tokens = token_source_in(creds_dir, &backend.token_credential, "credential"); + let handle_secret = token_source_in( + creds_dir, + &backend.handle_secret_credential, + "handle_secret_credential", + ); + readiness(&backend, tokens.as_ref(), handle_secret.as_ref()).map_err(|field| { + ConfigError::UnusableEntry { + id: entry.id.clone(), + field, + } + }) + } + ProviderWire::AnthropicMessages { .. } => { + if let Some(credential) = &entry.credential { + let source = token_source_in(creds_dir, credential, "credential"); + if source.read().is_none() { + return Err(ConfigError::UnusableEntry { + id: entry.id.clone(), + field: source.missing(), + }); + } + } + Ok(()) + } + ProviderWire::OpenAiChat { .. } => Err(ConfigError::Invalid("providers")), + } +} + /// Everything `serve` needs true before it binds, in one place so that /// `config check` passes exactly what `serve` will start: the prompt -/// directory, the other directories, the credential, the pin, the connection -/// key and the frame and connection bounds. Returns the admitted callers. +/// directory, the other directories, every entry's credential, the pin, the +/// connection key and the frame and connection bounds. Returns the admitted callers. fn readiness_of(config: &ClaudeConnectorConfig) -> Result, ConfigError> { + let creds_dir = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from); + readiness_of_in(config, creds_dir.as_deref()) +} + +fn readiness_of_in( + config: &ClaudeConnectorConfig, + creds_dir: Option<&Path>, +) -> Result, ConfigError> { config.validate()?; let admissions = load_admissions(&config.callers)?; config.serve_limits().validate(&admissions)?; - match config.auth { - // The CLI is never spawned on a key: its binary, directories and - // handle secret are not this backend's, only the key is. - ClaudeAuth::ApiKey => MessagesBackend::new(config.messages_config()) - .ready() - .map_err(ConfigError::Unusable)?, - ClaudeAuth::OAuthToken => { - #[cfg(unix)] - check_prompt_dir(&config.prompt_dir)?; - let backend = config.backend_config(); - readiness( - &backend, - &CredentialTokenSource::from_environment(backend.token_credential.clone()), - &CredentialTokenSource::from_environment(backend.handle_secret_credential.clone()) - .for_field("handle_secret_credential"), - ) - .map_err(ConfigError::Unusable)?; - } + for entry in &config.providers { + entry_readiness(entry, creds_dir)?; } if config.lease_socket.is_some() { lease_holders_of(config)?; @@ -556,9 +782,11 @@ fn start_leases( max_lease_ms: config.lease_max_ms, max_connections: config.max_connections, }; - let tokens = Arc::new(CredentialTokenSource::from_environment( - config.token_credential.clone(), - )); + let cli_cred = config + .cli_entry() + .and_then(|entry| entry.credential.as_ref()) + .ok_or(ConfigError::Unusable("providers"))?; + let tokens = Arc::new(CredentialTokenSource::from_environment(cli_cred.clone())); std::thread::Builder::new() .name("claude-lease-listener".to_string()) .spawn(move || { @@ -589,20 +817,14 @@ pub fn serve_config(path: &Path) -> Result<(), ConfigError> { serve_config_with(path, |_| ()) } -/// Maps every caller's allowed model to the provider tag selected by -/// `config.auth`. Cut 2 replaces this with the v3 `providers` and `models` tables. +/// Maps every configured model to its configured provider entry id. #[cfg(any(unix, test))] fn routes_for(config: &ClaudeConnectorConfig) -> Result { - let provider = match config.auth { - ClaudeAuth::OAuthToken => crate::config::PROVIDER, - ClaudeAuth::ApiKey => crate::messages::PROVIDER, - }; ProviderRoutes::new( config - .callers + .models .iter() - .flat_map(|caller| caller.allowed_models.iter()) - .map(|model| (model.clone(), provider.to_string())), + .map(|model| (model.id.clone(), model.provider.clone())), ) .map_err(|error| ConfigError::from(ServeError::Service(error))) } @@ -618,17 +840,27 @@ fn serve_config_with( let admissions = readiness_of(&config)?; let listen = config.validate()?; let routes = routes_for(&config)?; - // The CLI backend on a subscription token, the Messages backend on a key. - let claude = (config.auth == ClaudeAuth::OAuthToken).then(|| { - Arc::new(ClaudeCodeBackend::new( - config.backend_config(), - Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))), - )) - }); - let backend: Arc = match &claude { - Some(claude) => claude.clone(), - None => Arc::new(MessagesBackend::new(config.messages_config())), + let [entry] = config.providers.as_slice() else { + return Err(ConfigError::Unusable("providers")); }; + let (claude, backend): (Option>, Arc) = + match &entry.wire { + ProviderWire::ClaudeCodeCli { .. } if entry.id == crate::config::PROVIDER => { + let claude = Arc::new(ClaudeCodeBackend::new( + backend_config_for(entry).ok_or(ConfigError::Unusable("providers"))?, + Box::new(LogSink(std::sync::Mutex::new(std::io::stderr()))), + )); + let backend: Arc = claude.clone(); + (Some(claude), backend) + } + ProviderWire::AnthropicMessages { .. } if entry.id == crate::messages::PROVIDER => { + let messages = Arc::new(MessagesBackend::new( + messages_config_for(entry).ok_or(ConfigError::Unusable("providers"))?, + )); + (None, messages) + } + _ => return Err(ConfigError::Unusable("providers")), + }; let listener = TcpListener::bind(listen).map_err(|_| ConfigError::Listen)?; let service = Arc::new(Mutex::new( TransportService::open( @@ -665,6 +897,25 @@ mod tests { use sha2::Digest; use super::*; + use crate::{EffortMap, ForcedToolChoice, OutputSchemaSupport}; + + fn test_model(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, + } + } /// A log that a test can read back. #[derive(Clone, Default)] @@ -712,23 +963,29 @@ mod tests { let config = ClaudeConnectorConfig { listen: "127.0.0.1:0".to_string(), replay_store: at("replay.cc"), - claude_binary: at("claude"), - claude_binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(), - work_dir: at("work"), - config_dir: at("home"), - prompt_dir: at("prompts"), - 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![ProviderEntry { + id: crate::config::PROVIDER.to_string(), + credential: Some("claude-token".to_string()), + wire: ProviderWire::ClaudeCodeCli { + binary: at("claude"), + binary_sha256: sha2::Sha256::digest(script.as_bytes()).into(), + work_dir: at("work"), + config_dir: at("home"), + prompt_dir: at("prompts"), + 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, + }, + }], + models: vec![test_model("claude-haiku-5-5", crate::config::PROVIDER)], callers: vec![CallerConfig { caller_runtime_id: "persona-a-caller".to_string(), connection_key_file: at("caller.key"), @@ -876,53 +1133,169 @@ mod tests { max_payload_bytes: MIN_PAYLOAD_BYTES, max_output_tokens: 4_096, }; - let mut config = ClaudeConnectorConfig { + let config = ClaudeConnectorConfig { listen: "127.0.0.1:0".to_string(), replay_store: PathBuf::from("/tmp/replay.cc"), - claude_binary: PathBuf::from("/tmp/claude"), - claude_binary_sha256: [1; 32], - work_dir: PathBuf::from("/tmp/work"), - config_dir: PathBuf::from("/tmp/home"), - prompt_dir: PathBuf::from("/tmp/prompts"), - 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: 8_192, max_frame_bytes: 2 << 20, max_connections: 8, socket_timeout_ms: 10_000, max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "anthropic-primary".to_string(), + credential: Some("anthropic-key".to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://api.anthropic.com".to_string(), + deadline_ms: 600_000, + max_response_bytes: 64 << 20, + }, + }, + ProviderEntry { + id: "local-stub".to_string(), + credential: None, + wire: ProviderWire::AnthropicMessages { + base_url: "http://127.0.0.1:9000".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + test_model("claude-haiku-5-5", "anthropic-primary"), + test_model("claude-sonnet-5-5", "anthropic-primary"), + test_model("custom-model", "local-stub"), + ], callers: vec![ - caller_with("caller-a", &["claude-haiku-5-5", "claude-sonnet-5-5"]), - caller_with("caller-b", &["claude-sonnet-5-5", "claude-opus-5-1"]), + caller_with("caller-a", &["claude-haiku-5-5", "custom-model"]), + caller_with("caller-b", &["claude-sonnet-5-5"]), ], lease_socket: None, lease_holders: Vec::new(), lease_max_ms: 3_600_000, }; - let oauth_routes = routes_for(&config).unwrap(); - for model in ["claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-1"] { - assert_eq!( - oauth_routes.provider_for(model), - Some(crate::config::PROVIDER) - ); - } - assert_eq!(oauth_routes.provider_for("unlisted-model"), None); + let routes = routes_for(&config).unwrap(); + assert_eq!( + routes.provider_for("claude-haiku-5-5"), + Some("anthropic-primary") + ); + assert_eq!( + routes.provider_for("claude-sonnet-5-5"), + Some("anthropic-primary") + ); + assert_eq!(routes.provider_for("custom-model"), Some("local-stub")); + assert_eq!(routes.provider_for("unlisted-model"), None); + } - config.auth = ClaudeAuth::ApiKey; - let api_routes = routes_for(&config).unwrap(); - for model in ["claude-haiku-5-5", "claude-sonnet-5-5", "claude-opus-5-1"] { - assert_eq!( - api_routes.provider_for(model), - Some(crate::messages::PROVIDER) - ); + #[test] + fn readiness_of_in_checks_every_entry_and_names_failing_id_without_leaking_secret() { + const SECRET_A: &str = "canary-secret-alpha-91c2"; + const SECRET_B: &str = "canary-secret-beta-47f0"; + const CRED_A: &str = "canary-cred-a"; + const CRED_B: &str = "canary-cred-b"; + + let dir = + std::env::temp_dir().join(format!("claude-connector-ready-in-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let creds = dir.join("creds"); + std::fs::create_dir_all(&creds).unwrap(); + let key_file = dir.join("caller.key"); + std::fs::write(&key_file, "k".repeat(48)).unwrap(); + std::fs::write(creds.join(CRED_A), SECRET_A).unwrap(); + std::fs::write(creds.join(CRED_B), SECRET_B).unwrap(); + + let config = ClaudeConnectorConfig { + listen: "127.0.0.1:0".to_string(), + replay_store: dir.join("replay.cc"), + max_frame_bytes: 2 << 20, + max_connections: 8, + socket_timeout_ms: 10_000, + max_expiry_skew_ms: 300_000, + providers: vec![ + ProviderEntry { + id: "provider-one".to_string(), + credential: Some(CRED_A.to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://one.example.test".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "provider-two".to_string(), + credential: Some(CRED_B.to_string()), + wire: ProviderWire::AnthropicMessages { + base_url: "https://two.example.test".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ProviderEntry { + id: "loopback-keyless".to_string(), + credential: None, + wire: ProviderWire::AnthropicMessages { + base_url: "http://127.0.0.1:8080".to_string(), + deadline_ms: 60_000, + max_response_bytes: 16 << 20, + }, + }, + ], + models: vec![ + test_model("model-one", "provider-one"), + test_model("model-two", "provider-two"), + test_model("model-local", "loopback-keyless"), + ], + callers: vec![CallerConfig { + caller_runtime_id: "caller-a".to_string(), + connection_key_file: key_file, + connection_key_epoch: 1, + allowed_models: vec!["model-one".to_string(), "model-two".to_string()], + max_concurrent_requests: 2, + max_payload_bytes: MIN_PAYLOAD_BYTES, + max_output_tokens: 4_096, + }], + lease_socket: None, + lease_holders: Vec::new(), + lease_max_ms: 3_600_000, + }; + + assert!(readiness_of_in(&config, Some(&creds)).is_ok()); + + // Missing credentials directory names the first entry needing one. + let no_dir = readiness_of_in(&config, None).unwrap_err(); + assert!(matches!( + no_dir, + ConfigError::UnusableEntry { ref id, field: "credentials_directory" } + if id == "provider-one" + )); + + // Empty credential on the second entry fails naming `provider-two` and never leaks secrets. + std::fs::write(creds.join(CRED_B), "").unwrap(); + let empty = readiness_of_in(&config, Some(&creds)).unwrap_err(); + let rendered = format!("{empty} {empty:?}"); + assert!( + matches!( + empty, + ConfigError::UnusableEntry { ref id, field: "credential" } + if id == "provider-two" + ), + "{rendered}" + ); + assert!(rendered.contains("provider-two"), "{rendered}"); + for secret in [SECRET_A, SECRET_B, CRED_A, CRED_B] { + assert!(!rendered.contains(secret), "leaked {secret}: {rendered}"); } - assert_eq!(api_routes.provider_for("unlisted-model"), None); + + // Missing credential file on the second entry also fails naming `provider-two`. + std::fs::remove_file(creds.join(CRED_B)).unwrap(); + let missing = readiness_of_in(&config, Some(&creds)).unwrap_err(); + assert!(matches!( + missing, + ConfigError::UnusableEntry { ref id, field: "credential" } + if id == "provider-two" + )); + + let _ = std::fs::remove_dir_all(&dir); } #[cfg(unix)] diff --git a/crates/claude-connector/src/lib.rs b/crates/claude-connector/src/lib.rs index 141c366..5e1e18b 100644 --- a/crates/claude-connector/src/lib.rs +++ b/crates/claude-connector/src/lib.rs @@ -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, }; diff --git a/crates/claude-connector/src/main.rs b/crates/claude-connector/src/main.rs index 5ce5e89..d366be8 100644 --- a/crates/claude-connector/src/main.rs +++ b/crates/claude-connector/src/main.rs @@ -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 { + self.single.get(name).cloned() + } + fn text(&self, name: &'static str) -> Result { 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 { - 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 { + 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 { + 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 { + 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 { + match self.text(name)?.as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => Err(Failure::Malformed(name)), + } + } + + fn provider_entry(&self, provider_id: &str) -> Result { + 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 { + 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::, 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(()) } diff --git a/crates/claude-connector/tests/config_document.rs b/crates/claude-connector/tests/config_document.rs index 7a69e64..3d03dca 100644 --- a/crates/claude-connector/tests/config_document.rs +++ b/crates/claude-connector/tests/config_document.rs @@ -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::().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 { +fn cli_init_flags(scratch: &Scratch, extra: &[&str]) -> Vec { let path = |name: &str| scratch.path(name).to_string_lossy().into_owned(); let mut flags: Vec = [ "--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 { &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 { + let path = |name: &str| scratch.path(name).to_string_lossy().into_owned(); + let mut flags: Vec = [ + "--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, - #[cultcache(key = 19)] - lease_socket: Option, - #[cultcache(key = 20)] - lease_holders: Vec, - #[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::().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}"); } }