Files
optimclaw/src/config/sandbox.rs
T
11c5e25422 feat(setup): Anthropic OAuth onboarding with setup-token support (#384)
* feat(setup): add Anthropic OAuth and Codex OAuth onboarding flows

Add OAuth token authentication as an alternative to API keys during
onboarding for both Anthropic (via `claude login`) and OpenAI/Codex
(via `~/.codex/auth.json`).

Key changes:
- New `AnthropicOAuthProvider` using `Authorization: Bearer` header
  (rig-core hardcodes `x-api-key` which rejects OAuth tokens)
- Wizard auth method selector: "Direct API Key" vs "OAuth Token"
  for both Anthropic and OpenAI providers
- Codex token extraction from `$CODEX_HOME/auth.json` / `~/.codex/auth.json`
- Claude Code sandbox sub-step in Docker setup (checks for credentials)
- Secret injection mappings for `ANTHROPIC_OAUTH_TOKEN` and `CODEX_OAUTH_TOKEN`
- `CODEX_OAUTH_TOKEN` falls back to `OPENAI_API_KEY` (same Bearer auth)

Supersedes #143 which had a broken auth flow (OAuth token sent as
x-api-key → 401). Credit to @bigguybobby for the original approach.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: persist OAuth tokens in bootstrap .env and re-extract at startup

OAuth tokens stored only in the secrets DB were invisible to
Config::from_env() which runs before the DB connects (chicken-and-egg).

Two fixes:
1. write_bootstrap_env() now persists ANTHROPIC_OAUTH_TOKEN and
   CODEX_OAUTH_TOKEN to ~/.ironclaw/.env (same pattern as NEARAI_API_KEY)
2. main.rs re-extracts a fresh token from the OS credential store
   (macOS Keychain / ~/.claude/.credentials.json) before config resolution,
   handling token expiry (8-12h) gracefully

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: persist all LLM credentials in bootstrap .env, not just NEAR AI

All providers had the same chicken-and-egg issue: API keys stored in the
secrets DB were invisible to Config::from_env() which runs before DB
connects. Only NEARAI_API_KEY was written to bootstrap .env.

Now write_bootstrap_env() persists all credential env vars:
NEARAI_API_KEY, ANTHROPIC_API_KEY, ANTHROPIC_OAUTH_TOKEN, OPENAI_API_KEY,
CODEX_OAUTH_TOKEN, LLM_API_KEY, TINFOIL_API_KEY.

Also: setup_api_key_provider() now sets the env var during the wizard
session so write_bootstrap_env() can pick it up.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: address security review findings for OAuth onboarding

- Extract "oauth-placeholder" to named OAUTH_PLACEHOLDER constant shared
  across config and wizard to prevent silent drift
- Document plaintext credential tradeoff in write_bootstrap_env (API keys
  stored with 0o600 permissions, recommend full-disk encryption)
- Add blocking "Press Enter" wait in Anthropic OAuth retry flow so user
  has time to run `claude login` in another terminal
- Add escape hatch from manual OAuth paste back to API key flow (empty
  input switches to setup_api_key_provider)
- Fix Retry-After header: parse u64 seconds into Duration before passing
  to LlmError::RateLimited
- Make config::llm module pub(crate) for constant visibility
- Use .bearer_auth() instead of manual format!("Bearer {}")
- Remove response body from debug log (may contain PII)
- Update Anthropic API version to 2024-10-22

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* security: remove plaintext credentials from bootstrap .env

Credentials (API keys, OAuth tokens) were being written in plaintext to
~/.ironclaw/.env to work around a chicken-and-egg problem: Config::from_env()
runs before the encrypted secrets DB is connected.

Instead of storing secrets on disk, LlmConfig::resolve() now defers
gracefully when credentials are missing — it returns None for the provider
config instead of hard-erroring with MissingRequired. After the DB connects,
AppBuilder::build_all() loads secrets from encrypted storage via
inject_llm_keys_from_secrets() and re-resolves the config.

For Anthropic OAuth tokens (which expire in 8-12h), the secret injection
step also tries the OS credential store (macOS Keychain / Linux
credentials.json) for a fresh token, overriding the potentially stale
copy in the DB.

Changes:
- LlmConfig::resolve(): OpenAI, Anthropic, OpenAI-compatible, and Tinfoil
  all return None instead of MissingRequired when credentials are absent
- write_bootstrap_env(): no longer writes any credential env vars
- inject_llm_keys_from_secrets(): refreshes Anthropic OAuth from OS
  credential store before overlay is finalized
- main.rs: removed OAuth re-extraction hack (no longer needed)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: load OS credential store tokens even without secrets DB

The OAuth token extraction from macOS Keychain / Linux credentials files
was only running inside inject_llm_keys_from_secrets(), which requires
the encrypted secrets DB. When no master key is configured, init_secrets()
returned early — skipping both DB secret loading AND OS credential store
extraction, leaving the Anthropic OAuth token unavailable.

Split into two paths:
- inject_llm_keys_from_secrets(): loads from encrypted DB + OS stores
- inject_os_credentials(): loads from OS stores only (no DB needed)

init_secrets() now calls inject_os_credentials() and re-resolves config
even in the no-master-key early-return path, so `claude login` tokens
are always available regardless of secrets DB state.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: add anthropic-beta header required for OAuth authentication

Anthropic's api.anthropic.com requires the `anthropic-beta: oauth-2025-04-20`
header to accept OAuth Bearer tokens. Without it, the API returns 401
"OAuth authentication is currently not supported."

Also reverts API version to 2023-06-01 since the OAuth beta flag does
not support the 2024-10-22 version (returns 400 "not a valid version").

This was the same bug that caused PR #143's 401 errors — the beta header
was missing entirely.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Anthropic and OpenAI model resolution respects selected_model

The Anthropic and OpenAI config resolution ignored settings.selected_model
entirely, only checking the provider-specific env var (ANTHROPIC_MODEL,
OPENAI_MODEL) and falling back to a hardcoded default. This meant the
model chosen during onboarding wizard was silently overridden.

Now follows the same pattern as NearAI and OpenAI-compatible:
env var > settings.selected_model > hardcoded default.

Also deduplicated the Anthropic config construction (two identical
branches for API key vs OAuth now share model/base_url resolution).

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* test: add provider resolution tests for all LLM backends

Covers deferred resolution (no credentials → None instead of error),
credential presence, model selection fallback chain, and OAuth token
routing for Anthropic, OpenAI, Tinfoil, Ollama, and NearAI.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: handle nested tokens.access_token format in Codex auth.json

Codex CLI stores OAuth tokens in a nested format under
tokens.access_token (ChatGPT OAuth flow), not at the top level.
Also adds ENV_MUTEX to Codex token tests for thread safety.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* refactor: remove Codex OAuth onboarding (incompatible with OpenAI API)

Codex CLI OAuth tokens use a different endpoint
(chatgpt.com/backend-api/codex) and the Responses API wire format,
not api.openai.com with Chat Completions. The tokens lack the
model.request scope needed for the platform API, so they can't be
used as drop-in OPENAI_API_KEY replacements.

Removes: extract_codex_oauth_token(), wizard Codex OAuth flow,
CODEX_OAUTH_TOKEN env var support, and related tests.

OpenAI onboarding now uses direct API key only.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* style: fix formatting for CI (cargo fmt)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: address Gemini review feedback

- Use ? operator for ANTHROPIC_MODEL/BASE_URL env resolution instead of
  .ok().flatten() to propagate ConfigErrors consistently
- Skip Tool messages without tool_call_id with a warning instead of
  using unwrap_or_default() which would send empty string to Anthropic
- Extract credential check into closure to reduce duplication in
  Claude Code sandbox setup

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* refactor(review): address PR review feedback for OAuth onboarding

- Gate ANTHROPIC_OAUTH_TOKEN resolution to Anthropic provider only
  (was needlessly checked for all registry providers)
- Add 3 regression tests for OAuth config resolution:
  - oauth_token sets placeholder api_key
  - real api_key takes priority over oauth
  - non-Anthropic providers don't pick up oauth_token
- Validate OAuth token prefix (sk-ant-oat) in wizard to catch
  accidentally pasted API keys
- Improve error body read handling in AnthropicOAuthProvider
  (was silently swallowing read errors with unwrap_or_default)
- Remove extra blank line in write_bootstrap_env
- Remove stale blank line in RegistryProviderConfig doc comment

[skip-regression-check]

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: address PR #384 review comments

Blocker:
- Replace OnceLock<HashMap> with LazyLock<Mutex<HashMap>> for INJECTED_VARS
  so both inject_os_credentials() and inject_llm_keys_from_secrets() merge
  data instead of the second caller silently dropping its entries.

High:
- Add 401 retry with OS credential store re-extraction in
  AnthropicOAuthProvider, recovering from expired OAuth tokens (~8-12h)
  without manual intervention.
- Fix comment in app.rs: ~/.codex/auth.json → ~/.claude/.credentials.json.

Medium:
- Remove unsafe { std::env::set_var } from wizard; use thread-safe
  inject_single_var() overlay instead (safe on multi-threaded Tokio).
- Add post-init validation in AppBuilder: fail early with clear error when
  LLM_BACKEND is set but no credentials were resolved after secret injection.
- Add sk-ant-oat prefix validation in parse_oauth_access_token().
- Only route to AnthropicOAuthProvider when api_key is missing or equals
  OAUTH_PLACEHOLDER (API key takes priority over OAuth token).
- Teach fetch_anthropic_models() to use Bearer auth when only OAuth token
  is available (model listing no longer fails for OAuth-only users).

Low:
- Use optional_env() in wizard credential checks to read from injected
  overlay, not just raw env vars.

[skip-regression-check]

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* style: cargo fmt

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: [email protected] <[email protected]>
2026-03-07 20:59:17 +00:00

452 lines
16 KiB
Rust

use crate::config::helpers::{optional_env, parse_bool_env, parse_optional_env, parse_string_env};
use crate::error::ConfigError;
/// Docker sandbox configuration.
#[derive(Debug, Clone)]
pub struct SandboxModeConfig {
/// Whether the Docker sandbox is enabled.
pub enabled: bool,
/// Sandbox policy: "readonly", "workspace_write", or "full_access".
pub policy: String,
/// Command timeout in seconds.
pub timeout_secs: u64,
/// Memory limit in megabytes.
pub memory_limit_mb: u64,
/// CPU shares (relative weight).
pub cpu_shares: u32,
/// Docker image for the sandbox.
pub image: String,
/// Whether to auto-pull the image if not found.
pub auto_pull_image: bool,
/// Additional domains to allow through the network proxy.
pub extra_allowed_domains: Vec<String>,
}
impl Default for SandboxModeConfig {
fn default() -> Self {
Self {
enabled: true,
policy: "readonly".to_string(),
timeout_secs: 120,
memory_limit_mb: 2048,
cpu_shares: 1024,
image: "ironclaw-worker:latest".to_string(),
auto_pull_image: true,
extra_allowed_domains: Vec::new(),
}
}
}
impl SandboxModeConfig {
pub(crate) fn resolve() -> Result<Self, ConfigError> {
let extra_domains = optional_env("SANDBOX_EXTRA_DOMAINS")?
.map(|s| s.split(',').map(|d| d.trim().to_string()).collect())
.unwrap_or_default();
Ok(Self {
enabled: parse_bool_env("SANDBOX_ENABLED", true)?,
policy: parse_string_env("SANDBOX_POLICY", "readonly")?,
timeout_secs: parse_optional_env("SANDBOX_TIMEOUT_SECS", 120)?,
memory_limit_mb: parse_optional_env("SANDBOX_MEMORY_LIMIT_MB", 2048)?,
cpu_shares: parse_optional_env("SANDBOX_CPU_SHARES", 1024)?,
image: parse_string_env("SANDBOX_IMAGE", "ironclaw-worker:latest")?,
auto_pull_image: parse_bool_env("SANDBOX_AUTO_PULL", true)?,
extra_allowed_domains: extra_domains,
})
}
/// Convert to SandboxConfig for the sandbox module.
pub fn to_sandbox_config(&self) -> crate::sandbox::SandboxConfig {
use crate::sandbox::SandboxPolicy;
use std::time::Duration;
let policy = self.policy.parse().unwrap_or(SandboxPolicy::ReadOnly);
let mut allowlist = crate::sandbox::default_allowlist();
allowlist.extend(self.extra_allowed_domains.clone());
crate::sandbox::SandboxConfig {
enabled: self.enabled,
policy,
timeout: Duration::from_secs(self.timeout_secs),
memory_limit_mb: self.memory_limit_mb,
cpu_shares: self.cpu_shares,
network_allowlist: allowlist,
image: self.image.clone(),
auto_pull_image: self.auto_pull_image,
proxy_port: 0, // Auto-assign
}
}
}
/// Claude Code sandbox configuration.
#[derive(Debug, Clone)]
pub struct ClaudeCodeConfig {
/// Whether Claude Code sandbox mode is available.
pub enabled: bool,
/// Host directory containing Claude auth config (not mounted into containers;
/// auth is handled via ANTHROPIC_API_KEY env var instead).
pub config_dir: std::path::PathBuf,
/// Claude model to use (e.g. "sonnet", "opus").
pub model: String,
/// Maximum agentic turns before stopping.
pub max_turns: u32,
/// Memory limit in MB for Claude Code containers (heavier than workers).
pub memory_limit_mb: u64,
/// Allowed tool patterns for Claude Code permission settings.
///
/// Written to `/workspace/.claude/settings.json` before spawning the CLI.
/// Provides defense-in-depth: only explicitly listed tools are auto-approved.
/// Any new/unknown tools would require interactive approval (which times out
/// in the non-interactive container, failing safely).
///
/// Patterns follow Claude Code syntax: `"Bash(*)"`, `"Read"`, `"Edit(*)"`, etc.
pub allowed_tools: Vec<String>,
}
/// Default allowed tools for Claude Code inside containers.
///
/// These cover all standard Claude Code tools needed for autonomous operation.
/// The Docker container provides the primary security boundary; this allowlist
/// provides defense-in-depth by preventing any future unknown tools from being
/// silently auto-approved.
fn default_claude_code_allowed_tools() -> Vec<String> {
[
// File system -- glob patterns match Claude Code's settings.json format
"Read(*)",
"Write(*)",
"Edit(*)",
"Glob(*)",
"Grep(*)",
"NotebookEdit(*)",
// Execution
"Bash(*)",
"Task(*)",
// Network
"WebFetch(*)",
"WebSearch(*)",
]
.into_iter()
.map(String::from)
.collect()
}
impl Default for ClaudeCodeConfig {
fn default() -> Self {
Self {
enabled: false,
config_dir: dirs::home_dir()
.unwrap_or_else(|| std::path::PathBuf::from("."))
.join(".claude"),
model: "sonnet".to_string(),
max_turns: 50,
memory_limit_mb: 4096,
allowed_tools: default_claude_code_allowed_tools(),
}
}
}
impl ClaudeCodeConfig {
/// Load from environment variables only (used inside containers where
/// there is no database or full config).
pub fn from_env() -> Self {
match Self::resolve() {
Ok(c) => c,
Err(e) => {
tracing::warn!("Failed to resolve ClaudeCodeConfig: {e}, using defaults");
Self::default()
}
}
}
/// Extract the OAuth access token from the host's credential store.
///
/// On macOS: reads from Keychain (`Claude Code-credentials` service).
/// On Linux: reads from `~/.claude/.credentials.json`.
///
/// Returns the access token if found. The token typically expires in
/// 8-12 hours, which is sufficient for any single container job.
pub fn extract_oauth_token() -> Option<String> {
// macOS: extract from Keychain
if cfg!(target_os = "macos") {
match std::process::Command::new("security")
.args([
"find-generic-password",
"-s",
"Claude Code-credentials",
"-w",
])
.output()
{
Ok(output) if output.status.success() => {
if let Ok(json) = String::from_utf8(output.stdout) {
return parse_oauth_access_token(json.trim());
}
}
Ok(_) => {
tracing::debug!("No Claude Code credentials in macOS Keychain");
}
Err(e) => {
tracing::debug!("Failed to query macOS Keychain: {e}");
}
}
}
// Linux / fallback: read from ~/.claude/.credentials.json
if let Some(home) = dirs::home_dir() {
let creds_path = home.join(".claude").join(".credentials.json");
if let Ok(json) = std::fs::read_to_string(&creds_path) {
return parse_oauth_access_token(&json);
}
}
None
}
pub(crate) fn resolve() -> Result<Self, ConfigError> {
let defaults = Self::default();
Ok(Self {
enabled: parse_bool_env("CLAUDE_CODE_ENABLED", defaults.enabled)?,
config_dir: optional_env("CLAUDE_CONFIG_DIR")?
.map(std::path::PathBuf::from)
.unwrap_or(defaults.config_dir),
model: parse_string_env("CLAUDE_CODE_MODEL", defaults.model)?,
max_turns: parse_optional_env("CLAUDE_CODE_MAX_TURNS", defaults.max_turns)?,
memory_limit_mb: parse_optional_env(
"CLAUDE_CODE_MEMORY_LIMIT_MB",
defaults.memory_limit_mb,
)?,
allowed_tools: optional_env("CLAUDE_CODE_ALLOWED_TOOLS")?
.map(|s| {
s.split(',')
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty())
.collect()
})
.unwrap_or(defaults.allowed_tools),
})
}
}
/// Parse the OAuth access token from a Claude Code credentials JSON blob.
///
/// Expected shape: `{"claudeAiOauth": {"accessToken": "sk-ant-oat01-..."}}`
fn parse_oauth_access_token(json: &str) -> Option<String> {
let creds: serde_json::Value = serde_json::from_str(json).ok()?;
let token = creds["claudeAiOauth"]["accessToken"].as_str()?;
// Validate that the token looks like a real OAuth token before using it.
// Claude CLI tokens start with "sk-ant-oat".
if !token.starts_with("sk-ant-oat") {
tracing::debug!("Ignoring credential store token with unexpected prefix");
return None;
}
Some(token.to_string())
}
#[cfg(test)]
mod tests {
use crate::config::sandbox::*;
// ── SandboxModeConfig defaults ──────────────────────────────────
#[test]
fn sandbox_mode_config_default_values() {
let cfg = SandboxModeConfig::default();
assert!(cfg.enabled);
assert_eq!(cfg.policy, "readonly");
assert_eq!(cfg.timeout_secs, 120);
assert_eq!(cfg.memory_limit_mb, 2048);
assert_eq!(cfg.cpu_shares, 1024);
assert_eq!(cfg.image, "ironclaw-worker:latest");
assert!(cfg.auto_pull_image);
assert!(cfg.extra_allowed_domains.is_empty());
}
#[test]
fn sandbox_mode_config_custom_values() {
let cfg = SandboxModeConfig {
enabled: false,
policy: "full_access".to_string(),
timeout_secs: 600,
memory_limit_mb: 4096,
cpu_shares: 512,
image: "custom-worker:v2".to_string(),
auto_pull_image: false,
extra_allowed_domains: vec!["example.com".to_string()],
};
assert!(!cfg.enabled);
assert_eq!(cfg.policy, "full_access");
assert_eq!(cfg.timeout_secs, 600);
assert_eq!(cfg.memory_limit_mb, 4096);
assert_eq!(cfg.cpu_shares, 512);
assert_eq!(cfg.image, "custom-worker:v2");
assert!(!cfg.auto_pull_image);
assert_eq!(cfg.extra_allowed_domains, vec!["example.com"]);
}
#[test]
fn sandbox_mode_to_sandbox_config_propagates_fields() {
let mode = SandboxModeConfig {
enabled: true,
policy: "workspace_write".to_string(),
timeout_secs: 300,
memory_limit_mb: 1024,
cpu_shares: 2048,
image: "test:latest".to_string(),
auto_pull_image: false,
extra_allowed_domains: vec!["custom.example.com".to_string()],
};
let sc = mode.to_sandbox_config();
assert!(sc.enabled);
assert_eq!(sc.policy, crate::sandbox::SandboxPolicy::WorkspaceWrite);
assert_eq!(sc.timeout, std::time::Duration::from_secs(300));
assert_eq!(sc.memory_limit_mb, 1024);
assert_eq!(sc.cpu_shares, 2048);
assert_eq!(sc.image, "test:latest");
assert!(!sc.auto_pull_image);
// extra domain should be in the allowlist
assert!(
sc.network_allowlist
.contains(&"custom.example.com".to_string()),
"expected custom domain in allowlist"
);
}
#[test]
fn sandbox_mode_to_sandbox_config_invalid_policy_falls_back_to_readonly() {
let mode = SandboxModeConfig {
policy: "garbage_value".to_string(),
..SandboxModeConfig::default()
};
let sc = mode.to_sandbox_config();
assert_eq!(sc.policy, crate::sandbox::SandboxPolicy::ReadOnly);
}
#[test]
fn sandbox_mode_to_sandbox_config_includes_default_allowlist() {
let mode = SandboxModeConfig::default();
let sc = mode.to_sandbox_config();
// The default allowlist from sandbox module should be non-empty
assert!(
!sc.network_allowlist.is_empty(),
"default allowlist should not be empty"
);
}
// ── ClaudeCodeConfig defaults ───────────────────────────────────
#[test]
fn claude_code_config_default_values() {
let cfg = ClaudeCodeConfig::default();
assert!(!cfg.enabled);
assert_eq!(cfg.model, "sonnet");
assert_eq!(cfg.max_turns, 50);
assert_eq!(cfg.memory_limit_mb, 4096);
assert!(cfg.config_dir.ends_with(".claude"));
// Should have all the standard tools
assert!(!cfg.allowed_tools.is_empty());
assert!(cfg.allowed_tools.contains(&"Bash(*)".to_string()));
assert!(cfg.allowed_tools.contains(&"Read(*)".to_string()));
assert!(cfg.allowed_tools.contains(&"Edit(*)".to_string()));
assert!(cfg.allowed_tools.contains(&"Write(*)".to_string()));
assert!(cfg.allowed_tools.contains(&"Grep(*)".to_string()));
assert!(cfg.allowed_tools.contains(&"WebFetch(*)".to_string()));
}
#[test]
fn claude_code_config_custom_values() {
let cfg = ClaudeCodeConfig {
enabled: true,
config_dir: std::path::PathBuf::from("/opt/claude"),
model: "opus".to_string(),
max_turns: 100,
memory_limit_mb: 8192,
allowed_tools: vec!["Read(*)".to_string(), "Bash(*)".to_string()],
};
assert!(cfg.enabled);
assert_eq!(cfg.config_dir, std::path::PathBuf::from("/opt/claude"));
assert_eq!(cfg.model, "opus");
assert_eq!(cfg.max_turns, 100);
assert_eq!(cfg.memory_limit_mb, 8192);
assert_eq!(cfg.allowed_tools.len(), 2);
}
// ── parse_oauth_access_token ────────────────────────────────────
#[test]
fn parse_oauth_token_valid() {
let json = r#"{"claudeAiOauth": {"accessToken": "sk-ant-oat01-fake"}}"#;
let token = parse_oauth_access_token(json);
assert_eq!(token, Some("sk-ant-oat01-fake".to_string()));
}
#[test]
fn parse_oauth_token_missing_access_token() {
let json = r#"{"claudeAiOauth": {}}"#;
assert_eq!(parse_oauth_access_token(json), None);
}
#[test]
fn parse_oauth_token_missing_oauth_key() {
let json = r#"{"someOtherKey": {"accessToken": "tok"}}"#;
assert_eq!(parse_oauth_access_token(json), None);
}
#[test]
fn parse_oauth_token_invalid_json() {
assert_eq!(parse_oauth_access_token("not json at all"), None);
}
#[test]
fn parse_oauth_token_empty_string() {
assert_eq!(parse_oauth_access_token(""), None);
}
#[test]
fn parse_oauth_token_nested_extra_fields() {
let json = r#"{
"claudeAiOauth": {
"accessToken": "sk-ant-oat01-real-token",
"refreshToken": "rt-abc",
"expiresAt": 1700000000
}
}"#;
assert_eq!(
parse_oauth_access_token(json),
Some("sk-ant-oat01-real-token".to_string())
);
}
#[test]
fn parse_oauth_token_access_token_is_not_string() {
let json = r#"{"claudeAiOauth": {"accessToken": 12345}}"#;
assert_eq!(parse_oauth_access_token(json), None);
}
#[test]
fn parse_oauth_token_rejects_invalid_prefix() {
let json = r#"{"claudeAiOauth": {"accessToken": "not-an-oauth-token"}}"#;
assert_eq!(parse_oauth_access_token(json), None);
}
// ── default_claude_code_allowed_tools ───────────────────────────
#[test]
fn default_allowed_tools_has_expected_count() {
let tools = default_claude_code_allowed_tools();
// 10 tools: Read, Write, Edit, Glob, Grep, NotebookEdit, Bash, Task, WebFetch, WebSearch
assert_eq!(tools.len(), 10);
}
#[test]
fn default_allowed_tools_all_have_glob_pattern() {
let tools = default_claude_code_allowed_tools();
for tool in &tools {
assert!(
tool.ends_with("(*)"),
"tool '{tool}' should end with '(*)' glob pattern"
);
}
}
}