claude-connector: authenticate the child with an API key on its own descriptor (typed auth field, no meter in key mode)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3f87b19a2d
commit
13eb070e60
11 changed files with 189 additions and 23 deletions
|
|
@ -278,7 +278,7 @@ pub fn ask(args: &AskArgs) -> Result<String, AskError> {
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
use crate::config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
use crate::handle::{SessionStore, plan};
|
||||
use model_connector::ToolDefinition;
|
||||
|
||||
|
|
@ -315,6 +315,7 @@ mod tests {
|
|||
prompt_dir: "/p".into(),
|
||||
token_credential: "t".into(),
|
||||
handle_secret_credential: "h".into(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
instance: "i".into(),
|
||||
limits: ClaudeCodeLimits {
|
||||
deadline: Duration::from_secs(1),
|
||||
|
|
|
|||
|
|
@ -261,7 +261,7 @@ impl ClaudeCodeBackend {
|
|||
deadline,
|
||||
&request.model,
|
||||
request.output_schema_json.as_deref(),
|
||||
&self.quota,
|
||||
self.config.auth.is_metered().then_some(&*self.quota),
|
||||
);
|
||||
child.kill();
|
||||
child.wait();
|
||||
|
|
@ -367,7 +367,7 @@ fn read_stream(
|
|||
deadline: Instant,
|
||||
model: &str,
|
||||
schema: Option<&str>,
|
||||
quota: &QuotaCell,
|
||||
quota: Option<&QuotaCell>,
|
||||
) -> Result<Finished, Failure> {
|
||||
let mut state = StreamState::new(model, schema, quota);
|
||||
let finished = loop {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use model_connector::{
|
|||
};
|
||||
|
||||
use super::*;
|
||||
use crate::config::ClaudeCodeLimits;
|
||||
use crate::config::{ClaudeAuth, ClaudeCodeLimits};
|
||||
use crate::handle::{FsSessionStore, SessionStore};
|
||||
use crate::launch::ChildEnv;
|
||||
|
||||
|
|
@ -19,6 +19,8 @@ const CANARY_TOKEN: &str = "canary-oauth-token-value";
|
|||
/// The variable the connector's own environment must never hand on.
|
||||
const TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";
|
||||
const TOKEN_FD_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
||||
const KEY_FD_ENV: &str = "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR";
|
||||
const CANARY_KEY: &str = "canary-api-key-value";
|
||||
const MODEL: &str = "claude-haiku-5-5";
|
||||
const INSTANCE: &str = "persona-a";
|
||||
const SESSION: &str = "11111111-2222-3333-4444-555555555555";
|
||||
|
|
@ -333,6 +335,7 @@ fn config(dir: &Path, instance: &str, limits: ClaudeCodeLimits) -> ClaudeCodeCon
|
|||
config_dir: PathBuf::from("/cfg"),
|
||||
prompt_dir: dir.join("prompts"),
|
||||
token_credential: "claude-token".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
instance: instance.to_string(),
|
||||
limits,
|
||||
|
|
@ -674,6 +677,92 @@ fn child_env_is_cleared_and_names_the_token_descriptor_never_the_token() {
|
|||
assert!(!format!("{result:?}").contains(CANARY_TOKEN));
|
||||
}
|
||||
|
||||
// ---- API key authentication ----
|
||||
|
||||
/// A rig whose child authenticates with an API key.
|
||||
fn api_rig(scripts: Vec<Script>) -> Rig {
|
||||
let mut rig = rig(scripts);
|
||||
rig.backend.config.auth = ClaudeAuth::ApiKey;
|
||||
rig.backend.tokens = Box::new(FixedToken(Some(CANARY_KEY)));
|
||||
rig
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_mode_names_the_key_descriptor_and_never_the_key_or_the_oauth_variable() {
|
||||
let rig = api_rig(vec![structured_script()]);
|
||||
let result = rig.run(schema_request());
|
||||
let seen = rig.seen();
|
||||
let mut names: Vec<&str> = seen.env.iter().map(|(name, _)| name.as_str()).collect();
|
||||
names.sort();
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
KEY_FD_ENV,
|
||||
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
|
||||
"CLAUDE_CONFIG_DIR",
|
||||
"HOME",
|
||||
"PATH"
|
||||
]
|
||||
);
|
||||
assert!(seen.env.contains(&(KEY_FD_ENV.to_string(), "3".to_string())));
|
||||
// The key travels beside the environment, to the port, alone.
|
||||
assert_eq!(seen.token, CANARY_KEY);
|
||||
let everything = format!(
|
||||
"{:?} {:?} {:?} {result:?}",
|
||||
seen.env, seen.argv, rig.backend.config
|
||||
);
|
||||
assert!(!everything.contains(CANARY_KEY));
|
||||
let sunk = String::from_utf8(rig.sink.0.lock().unwrap().clone()).unwrap();
|
||||
assert!(!sunk.contains(CANARY_KEY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_mode_reads_no_plan_and_the_cell_stays_empty() {
|
||||
let rig = api_rig(vec![structured_script()]);
|
||||
rig.run(schema_request());
|
||||
assert!(quota_of(&rig).windows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_mode_still_feeds_the_cell_and_names_the_oauth_descriptor() {
|
||||
let rig = rig(vec![structured_script()]);
|
||||
rig.run(schema_request());
|
||||
assert!(!quota_of(&rig).windows.is_empty());
|
||||
let seen = rig.seen();
|
||||
assert!(seen.env.iter().any(|(name, _)| name == TOKEN_FD_ENV));
|
||||
assert!(seen.env.iter().all(|(name, _)| name != KEY_FD_ENV));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_api_key_fails_before_spawn() {
|
||||
let mut rig = api_rig(vec![ok_script(SESSION, "x")]);
|
||||
rig.backend.tokens = Box::new(FixedToken(None));
|
||||
let (kind, _, usage) = failure_of(&rig.run(request(vec![user("hi")])));
|
||||
assert_eq!(kind, FailureKind::Authentication);
|
||||
assert_eq!(usage, Some(usage_zero()));
|
||||
assert_eq!(rig.spawns(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_api_key_is_not_ready() {
|
||||
let dir = sandbox();
|
||||
let (work, cfg) = (dir.path().join("work"), dir.path().join("cfg"));
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
std::fs::create_dir_all(&cfg).unwrap();
|
||||
let mut config = config(dir.path(), INSTANCE, limits());
|
||||
config.work_dir = work;
|
||||
config.config_dir = cfg;
|
||||
config.auth = ClaudeAuth::ApiKey;
|
||||
assert_eq!(
|
||||
readiness(&config, &FixedToken(None), &FixedSecret(Some(SECRET))),
|
||||
Err("token_credential")
|
||||
);
|
||||
assert_eq!(
|
||||
readiness(&config, &FixedToken(Some(CANARY_KEY)), &FixedSecret(Some(SECRET))),
|
||||
Ok(())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_token_never_reaches_a_message_an_event_or_a_debug_form() {
|
||||
// A failing run, so a message is built, and the env's own Debug.
|
||||
|
|
@ -2469,6 +2558,31 @@ mod real {
|
|||
assert!(held.contains(&3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_key_reaches_the_child_on_its_pipe_and_nowhere_else() {
|
||||
let probe = TempDir::new();
|
||||
let body = format!(
|
||||
"fd=\"${KEY_FD_ENV}\"\neval \"cat <&$fd\" > '{d}/key'\nenv > '{d}/env'\nprintf '%s\n' \"$@\" > '{d}/argv'\nprintf '%s' \"${TOKEN_FD_ENV}\" > '{d}/oauth'\n{lines}",
|
||||
d = probe.path().display(),
|
||||
lines = printf_lines(&good_lines())
|
||||
);
|
||||
let mut fake = fake(&body, limits());
|
||||
fake.backend.config.auth = ClaudeAuth::ApiKey;
|
||||
fake.backend.tokens = Box::new(FixedToken(Some(CANARY_KEY)));
|
||||
let result = fake.run(request(vec![user("hello")]));
|
||||
assert!(matches!(
|
||||
outcome(&result),
|
||||
TransportOutcome::Completed { .. }
|
||||
));
|
||||
let read = |name: &str| std::fs::read_to_string(probe.path().join(name)).unwrap();
|
||||
assert_eq!(read("key"), CANARY_KEY, "the pipe holds the key");
|
||||
assert_eq!(read("oauth"), "", "the OAuth variable is not set");
|
||||
assert!(!read("env").contains(CANARY_KEY) && !read("argv").contains(CANARY_KEY));
|
||||
assert!(read("env").contains(&format!("{KEY_FD_ENV}=3")));
|
||||
let sunk = String::from_utf8(fake.sink.0.lock().unwrap().clone()).unwrap();
|
||||
assert!(!sunk.contains(CANARY_KEY) && !format!("{result:?}").contains(CANARY_KEY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_token_too_large_for_a_pipe_is_refused_at_its_bound_not_hung() {
|
||||
let fake = fake("exit 0", limits());
|
||||
|
|
|
|||
|
|
@ -6,6 +6,34 @@ use std::time::Duration;
|
|||
/// kit treats each backend's state as foreign to the other.
|
||||
pub(crate) const PROVIDER: &str = "claude-code";
|
||||
|
||||
/// Which credential the child authenticates with. One choice for the whole
|
||||
/// connector; the credential itself is the systemd credential
|
||||
/// [`ClaudeCodeConfig::token_credential`] names, and it reaches the child on a
|
||||
/// pipe whichever this is.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ClaudeAuth {
|
||||
/// The subscription's OAuth token. The plan's usage is metered.
|
||||
#[default]
|
||||
OAuthToken,
|
||||
/// An Anthropic API key. Nothing is metered: a key has no subscription plan.
|
||||
ApiKey,
|
||||
}
|
||||
|
||||
impl ClaudeAuth {
|
||||
/// The variable that tells the CLI which descriptor holds the credential.
|
||||
pub(crate) fn fd_var(self) -> &'static str {
|
||||
match self {
|
||||
Self::OAuthToken => "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
|
||||
Self::ApiKey => "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the credential has a subscription plan to meter.
|
||||
pub(crate) fn is_metered(self) -> bool {
|
||||
self == Self::OAuthToken
|
||||
}
|
||||
}
|
||||
|
||||
/// What the connector's binary hands the backend. Every path is absolute.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClaudeCodeConfig {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ use crate::unit::SystemdUnits;
|
|||
#[cfg(unix)]
|
||||
use crate::meter;
|
||||
use crate::{
|
||||
ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource, StderrSink,
|
||||
ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, CredentialTokenSource,
|
||||
StderrSink,
|
||||
};
|
||||
|
||||
const CONFIG_KEY: &str = "runtime";
|
||||
|
|
@ -106,6 +107,10 @@ pub struct ClaudeConnectorConfig {
|
|||
/// least 32 bytes), the key every handle is authenticated with.
|
||||
#[cultcache(key = 22)]
|
||||
pub handle_secret_credential: String,
|
||||
/// Which credential `token_credential` holds: the subscription token, or an
|
||||
/// Anthropic API key. A document without this field is the token.
|
||||
#[cultcache(key = 23, default)]
|
||||
pub auth: ClaudeAuth,
|
||||
}
|
||||
|
||||
/// A refusal. It names the field or stage that failed and nothing the
|
||||
|
|
@ -280,6 +285,7 @@ impl ClaudeConnectorConfig {
|
|||
config_dir: self.config_dir.clone(),
|
||||
prompt_dir: self.prompt_dir.clone(),
|
||||
token_credential: self.token_credential.clone(),
|
||||
auth: self.auth,
|
||||
handle_secret_credential: self.handle_secret_credential.clone(),
|
||||
instance: self.instance.clone(),
|
||||
limits: ClaudeCodeLimits {
|
||||
|
|
@ -565,10 +571,13 @@ fn serve_config_with(
|
|||
.map_err(|error| ConfigError::from(ServeError::Service(error)))?,
|
||||
));
|
||||
// The meter is running before the first lease can ask, so that lease can
|
||||
// wait for its first read.
|
||||
// wait for its first read. An API key has no subscription plan to read:
|
||||
// no meter runs, the cell stays empty, and no lease waits for it.
|
||||
let quota = backend.quota();
|
||||
meter::start(quota.clone(), Box::new(backend.clone()))
|
||||
.map_err(|_| ConfigError::Serving("meter"))?;
|
||||
if config.auth.is_metered() {
|
||||
meter::start(quota.clone(), Box::new(backend.clone()))
|
||||
.map_err(|_| ConfigError::Serving("meter"))?;
|
||||
}
|
||||
started("a);
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(socket) = &config.lease_socket {
|
||||
|
|
@ -640,6 +649,7 @@ mod tests {
|
|||
instance: "persona-a".to_string(),
|
||||
token_credential: "claude-token".to_string(),
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
deadline_ms: 600_000,
|
||||
max_line_bytes: 4 << 20,
|
||||
max_total_bytes: 64 << 20,
|
||||
|
|
|
|||
|
|
@ -13,12 +13,10 @@ use model_connector::{ProviderRequest, ReasoningEffort};
|
|||
use crate::config::ClaudeCodeConfig;
|
||||
use crate::handle::Plan;
|
||||
|
||||
/// The variable that tells the CLI which file descriptor holds its credential.
|
||||
/// The token itself never enters the environment: the process port writes it
|
||||
/// into a pipe and hands the child the read end at [`TOKEN_FD`].
|
||||
pub(crate) const TOKEN_FD_VAR: &str = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR";
|
||||
/// The descriptor number the child finds the token pipe at: the first one
|
||||
/// after stdin, stdout and stderr.
|
||||
/// The credential never enters the environment, whichever `ClaudeAuth` it is:
|
||||
/// the process port writes it into a pipe and hands the child the read end at
|
||||
/// [`TOKEN_FD`], the first descriptor after stdin, stdout and stderr, and the
|
||||
/// environment names that descriptor.
|
||||
pub(crate) const TOKEN_FD: i32 = 3;
|
||||
const CHILD_PATH: &str = "/usr/local/bin:/usr/bin:/bin";
|
||||
|
||||
|
|
@ -50,7 +48,7 @@ pub(crate) fn child_env(config: &ClaudeCodeConfig, request: &ProviderRequest) ->
|
|||
"CLAUDE_CODE_MAX_OUTPUT_TOKENS",
|
||||
request.max_output_tokens.to_string(),
|
||||
),
|
||||
(TOKEN_FD_VAR, TOKEN_FD.to_string()),
|
||||
(config.auth.fd_var(), TOKEN_FD.to_string()),
|
||||
])
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ mod stream;
|
|||
mod unit;
|
||||
|
||||
pub use backend::{ClaudeCodeBackend, CredentialTokenSource, StderrSink, TokenSource};
|
||||
pub use config::{ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
pub use config::{ClaudeAuth, ClaudeCodeConfig, ClaudeCodeLimits};
|
||||
pub use daemon::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, check_ready, load_config, write_config,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ use std::process::ExitCode;
|
|||
|
||||
use claude_connector::ask::{self, AskArgs, AskError};
|
||||
use claude_connector::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, MIN_SECRET_BYTES, check_ready,
|
||||
load_config, write_config,
|
||||
};
|
||||
use model_connector::{CallerConfig, LeaseTurn, frame_bytes_for_payload};
|
||||
|
|
@ -159,7 +159,8 @@ const CALLER: [&str; 5] = [
|
|||
"--max-output-tokens",
|
||||
];
|
||||
|
||||
const INIT: [&str; 21] = [
|
||||
const INIT: [&str; 22] = [
|
||||
"--auth",
|
||||
"--listen",
|
||||
"--replay-store",
|
||||
"--claude-binary",
|
||||
|
|
@ -240,6 +241,15 @@ impl Flags {
|
|||
.map_err(|_| Failure::Malformed(name))
|
||||
}
|
||||
|
||||
/// Which credential `--token-credential` names: `oauth-token` (the default) or `api-key`.
|
||||
fn auth(&self) -> Result<ClaudeAuth, Failure> {
|
||||
match self.single.get("--auth").map(String::as_str) {
|
||||
None | Some("oauth-token") => Ok(ClaudeAuth::OAuthToken),
|
||||
Some("api-key") => Ok(ClaudeAuth::ApiKey),
|
||||
Some(_) => Err(Failure::Malformed("--auth")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of turn a leasing account serves: `self` or `persona`.
|
||||
fn turn(&self) -> Result<LeaseTurn, Failure> {
|
||||
match self.text("--turn")?.as_str() {
|
||||
|
|
@ -391,6 +401,7 @@ fn init(path: &str, args: &[&str]) -> Result<(), Failure> {
|
|||
lease_callers,
|
||||
lease_max_ms: flags.number_or("--lease-max-ms", 3_600_000)?,
|
||||
handle_secret_credential: flags.text("--handle-secret-credential")?,
|
||||
auth: flags.auth()?,
|
||||
};
|
||||
// Validate before the secret file exists: a refused document leaves nothing.
|
||||
config.validate()?;
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ pub(crate) struct StreamState<'a> {
|
|||
/// Whether that schema's top type admits an object (absent counts): the
|
||||
/// structured output must be an object, never a bare scalar or array.
|
||||
schema_top_is_object: bool,
|
||||
quota: &'a QuotaCell,
|
||||
quota: Option<&'a QuotaCell>,
|
||||
session_id: Option<String>,
|
||||
texts: Vec<String>,
|
||||
message_id: Option<String>,
|
||||
|
|
@ -130,7 +130,7 @@ pub(crate) struct StreamState<'a> {
|
|||
|
||||
impl<'a> StreamState<'a> {
|
||||
/// `schema` is the request's output schema text, when it carried one.
|
||||
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: &'a QuotaCell) -> Self {
|
||||
pub(crate) fn new(model: &'a str, schema: Option<&str>, quota: Option<&'a QuotaCell>) -> Self {
|
||||
let top = schema
|
||||
.and_then(|text| serde_json::from_str::<Value>(text).ok())
|
||||
.and_then(|schema| schema.get("type").cloned());
|
||||
|
|
@ -176,7 +176,9 @@ impl<'a> StreamState<'a> {
|
|||
if let Some(info) = &line.rate_limit_info {
|
||||
self.plan_rejected |=
|
||||
info.get("status").and_then(Value::as_str) == Some("rejected");
|
||||
self.quota.observe(plan_windows(info));
|
||||
if let Some(quota) = self.quota {
|
||||
quota.observe(plan_windows(info));
|
||||
}
|
||||
}
|
||||
Step::More
|
||||
}
|
||||
|
|
|
|||
|
|
@ -528,7 +528,7 @@ fn stdin_and_stdout_failures_have_their_own_wording() {
|
|||
#[test]
|
||||
fn a_forced_tools_request_reaches_the_planner_is_refused_and_no_child_starts() {
|
||||
use claude_connector::{
|
||||
ChildEnv, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||
ChildEnv, ClaudeAuth, ClaudeCodeBackend, ClaudeCodeConfig, ClaudeCodeLimits, ProcessPort, RunningChild,
|
||||
SessionStore, StderrSink, TokenSource,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
|
@ -582,6 +582,7 @@ fn a_forced_tools_request_reaches_the_planner_is_refused_and_no_child_starts() {
|
|||
prompt_dir: dir.join("prompt"),
|
||||
token_credential: "t".into(),
|
||||
handle_secret_credential: "h".into(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
instance: "i".into(),
|
||||
limits: ClaudeCodeLimits {
|
||||
deadline: Duration::from_secs(5),
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use std::process::{Command, Output};
|
|||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use claude_connector::{
|
||||
ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
|
||||
ClaudeAuth, ClaudeConnectorConfig, ConfigError, LeaseCallerConfig, load_config, write_config,
|
||||
};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use model_connector::{CallerConfig, LeaseTurn};
|
||||
|
|
@ -53,6 +53,7 @@ fn valid() -> ClaudeConnectorConfig {
|
|||
instance: "persona-a".to_string(),
|
||||
token_credential: "claude-token".to_string(),
|
||||
handle_secret_credential: "claude-handle-secret".to_string(),
|
||||
auth: ClaudeAuth::OAuthToken,
|
||||
deadline_ms: 600_000,
|
||||
max_line_bytes: 4 << 20,
|
||||
max_total_bytes: 64 << 20,
|
||||
|
|
|
|||
Loading…
Reference in a new issue