claude-connector: guard AnthropicMessages endpoint and credential in serve_config_with

Require base_url == messages::ENDPOINT and entry.credential.is_some() in
Cut 2a single-entry serve_config_with, and return None from
messages_config_for when credential is absent instead of synthesizing an
empty credential string. Add behavioural tests pinning fail-closed
Unusable("providers") on custom base_url and keyless loopback entries.
This commit is contained in:
Meta Vens 2026-12-04 00:13:36 +01:00
commit 0d9b7eec70
2 changed files with 179 additions and 3 deletions

View file

@ -437,8 +437,9 @@ fn messages_config_for(entry: &ProviderEntry) -> Option<MessagesConfig> {
else {
return None;
};
let key_credential = entry.credential.as_ref()?.clone();
Some(MessagesConfig {
key_credential: entry.credential.clone().unwrap_or_default(),
key_credential,
deadline: Duration::from_millis(*deadline_ms),
max_response_bytes: *max_response_bytes,
})
@ -853,7 +854,11 @@ fn serve_config_with(
let backend: Arc<dyn ProviderBackend> = claude.clone();
(Some(claude), backend)
}
ProviderWire::AnthropicMessages { .. } if entry.id == crate::messages::PROVIDER => {
ProviderWire::AnthropicMessages { base_url, .. }
if entry.id == crate::messages::PROVIDER
&& base_url == crate::messages::ENDPOINT
&& entry.credential.is_some() =>
{
let messages = Arc::new(MessagesBackend::new(
messages_config_for(entry).ok_or(ConfigError::Unusable("providers"))?,
));
@ -932,6 +937,9 @@ mod tests {
}
}
#[cfg(unix)]
static CREDENTIALS_ENV_LOCK: Mutex<()> = Mutex::new(());
/// `serve` starts the meter beside the listener, wired to the backend's own
/// cell: it makes no call while nobody asks, and once a lease is asked for
/// it runs the claude binary and serve stays up. The binary is a script
@ -941,6 +949,10 @@ mod tests {
fn serve_config_starts_the_meter_and_stays_up() {
use std::os::unix::fs::PermissionsExt;
let _env_guard = CREDENTIALS_ENV_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
const CALL: &str = include_str!("../tests/fixtures/claude-2.1.312-meter-call.jsonl");
let dir =
std::env::temp_dir().join(format!("claude-connector-serve-{}", std::process::id()));
@ -1040,6 +1052,170 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn serve_config_single_entry_messages_guards_and_fails_closed() {
let _env_guard = CREDENTIALS_ENV_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let dir = std::env::temp_dir().join(format!(
"claude-connector-serve-messages-{}",
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("api-key"), "sk-ant-test-key").unwrap();
let make_config =
|providers: Vec<ProviderEntry>, model_provider: &str| 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,
models: vec![test_model("claude-haiku-5-5", model_provider)],
callers: vec![CallerConfig {
caller_runtime_id: "persona-a-caller".to_string(),
connection_key_file: key_file.clone(),
connection_key_epoch: 1,
allowed_models: vec!["claude-haiku-5-5".to_string()],
max_concurrent_requests: 4,
max_payload_bytes: 1 << 20,
max_output_tokens: 32_768,
}],
lease_socket: None,
lease_holders: Vec::new(),
lease_max_ms: 3_600_000,
};
let messages_entry = |id: &str, base_url: &str, cred: Option<&str>| ProviderEntry {
id: id.to_string(),
credential: cred.map(String::from),
wire: ProviderWire::AnthropicMessages {
base_url: base_url.to_string(),
deadline_ms: 60_000,
max_response_bytes: 16 << 20,
},
};
assert!(
messages_config_for(&messages_entry(
crate::messages::PROVIDER,
"http://127.0.0.1:18080",
None
))
.is_none()
);
let cfg_path = dir.join("connector.cc");
// SAFETY: guarded by CREDENTIALS_ENV_LOCK across all in-process tests touching CREDENTIALS_DIRECTORY.
unsafe { std::env::set_var("CREDENTIALS_DIRECTORY", &creds) };
// Keyless loopback passes readiness_of_in and fails closed in serve_config_with.
let keyless_loopback = make_config(
vec![messages_entry(
crate::messages::PROVIDER,
"http://127.0.0.1:18080",
None,
)],
crate::messages::PROVIDER,
);
assert!(readiness_of_in(&keyless_loopback, None).is_ok());
write_config(&cfg_path, &keyless_loopback).unwrap();
assert!(matches!(
serve_config_with(&cfg_path, |_| ()),
Err(ConfigError::Unusable("providers"))
));
// Custom base_url (loopback or HTTPS) with credential also fails closed in serve_config_with.
for custom_url in ["http://127.0.0.1:18080", "https://staging.example.test"] {
let custom = make_config(
vec![messages_entry(
crate::messages::PROVIDER,
custom_url,
Some("api-key"),
)],
crate::messages::PROVIDER,
);
write_config(&cfg_path, &custom).unwrap();
assert!(
matches!(
serve_config_with(&cfg_path, |_| ()),
Err(ConfigError::Unusable("providers"))
),
"expected Unusable(\"providers\") for {custom_url}"
);
}
// Non-matching id or multi-provider config fails closed in serve_config_with.
let wrong_id = make_config(
vec![messages_entry(
"custom-messages",
crate::messages::ENDPOINT,
Some("api-key"),
)],
"custom-messages",
);
write_config(&cfg_path, &wrong_id).unwrap();
assert!(matches!(
serve_config_with(&cfg_path, |_| ()),
Err(ConfigError::Unusable("providers"))
));
let multi = make_config(
vec![
messages_entry(
crate::messages::PROVIDER,
crate::messages::ENDPOINT,
Some("api-key"),
),
messages_entry("local-stub", "http://127.0.0.1:18080", None),
],
crate::messages::PROVIDER,
);
write_config(&cfg_path, &multi).unwrap();
assert!(matches!(
serve_config_with(&cfg_path, |_| ()),
Err(ConfigError::Unusable("providers"))
));
// Default ENDPOINT + credential with matching id serves cleanly.
let valid_messages = make_config(
vec![messages_entry(
crate::messages::PROVIDER,
crate::messages::ENDPOINT,
Some("api-key"),
)],
crate::messages::PROVIDER,
);
write_config(&cfg_path, &valid_messages).unwrap();
let started_flag = Arc::new(Mutex::new(false));
let started_clone = started_flag.clone();
let path_for_thread = cfg_path.clone();
let served = std::thread::spawn(move || {
serve_config_with(&path_for_thread, |_| {
*started_clone.lock().unwrap() = true;
})
});
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !*started_flag.lock().unwrap() {
assert!(
std::time::Instant::now() < deadline,
"serve_config_with never started for valid AnthropicMessages: {:?}",
served.is_finished()
);
std::thread::sleep(Duration::from_millis(10));
}
assert!(!served.is_finished());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn serve_errors_name_a_field_or_stage_and_never_a_stored_value() {
const CANARY: &str = "canary-path-8e2a";

View file

@ -53,7 +53,7 @@ use crate::backend::TokenSource;
/// The provider tag on every receipt and every reasoning block of this
/// backend; distinct from the CLI backend's tag.
pub(crate) const PROVIDER: &str = "anthropic-messages";
const ENDPOINT: &str = "https://api.anthropic.com";
pub(crate) const ENDPOINT: &str = "https://api.anthropic.com";
const API_VERSION: &str = "2026-10-21";
/// The longest provider message a receipt carries.
const MESSAGE_BYTES: usize = 2048;