1use std::path::{Path, PathBuf};
16use std::process::{Command, Stdio};
17use std::time::{Duration, Instant};
18
19use serde::Deserialize;
20
21use crate::finding::{Finding, Severity};
22use crate::gateway::{OpenProject, SubscriptionTraffic};
23
24const COMPONENT: &str = "gateway";
25
26pub const NOT_SUPPORTED: &str = "Your platform configuration doesn't support subscription traffic \
29 through visdom gateway. Contact your platform administrator or \
30 use Claude API key or agent hooks";
31
32pub const ALTERNATIVES: &str = "Claude API key (the project pays): visdom --billing project init; \
34 agent hooks: visdom --mode hooks init";
35
36pub fn is_not_supported(why: &str) -> bool {
38 why.starts_with(NOT_SUPPORTED)
39}
40
41pub fn traffic_finding(traffic: SubscriptionTraffic) -> Finding {
45 const ID: &str = "gateway.subscription";
46 let why = match traffic {
47 SubscriptionTraffic::Allowed => {
48 return Finding::new(
49 COMPONENT,
50 ID,
51 Severity::Ok,
52 "the AI Gateway takes calls paid by a Claude subscription",
53 )
54 }
55 SubscriptionTraffic::Denied => "the AI Gateway is set to deny subscription traffic",
56 SubscriptionTraffic::Unpublished => {
57 "the AI Gateway does not say that it takes subscription traffic (a version from \
58 before it could)"
59 }
60 };
61 Finding::new(
62 COMPONENT,
63 ID,
64 Severity::Error,
65 format!("{NOT_SUPPORTED}\n ({why}) {ALTERNATIVES}"),
66 )
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
71pub enum ClaudeLogin {
72 Subscription {
74 plan: Option<String>,
75 },
76 SignedOut,
77 Other {
79 method: String,
80 },
81 Unknown(String),
83}
84
85pub fn read_auth_status(stdout: &str) -> ClaudeLogin {
89 #[derive(Deserialize)]
90 #[serde(rename_all = "camelCase")]
91 struct Status {
92 #[serde(default)]
93 logged_in: bool,
94 #[serde(default)]
95 auth_method: Option<String>,
96 #[serde(default)]
97 subscription_type: Option<String>,
98 #[serde(default)]
99 stored_claude_ai_login: bool,
100 }
101 let Ok(status) = serde_json::from_str::<Status>(stdout.trim()) else {
102 return ClaudeLogin::Unknown(
103 "`claude auth status` did not answer in JSON (a Claude Code too old for it?)"
104 .to_string(),
105 );
106 };
107 let method = status.auth_method.unwrap_or_default();
108 let plan = status
109 .subscription_type
110 .clone()
111 .filter(|p| !p.trim().is_empty());
112 if status.logged_in
116 && method == "claude.ai"
117 && plan
118 .as_deref()
119 .is_some_and(|p| p.eq_ignore_ascii_case("free"))
120 {
121 return ClaudeLogin::Other {
122 method: "a claude.ai account without a paid plan".to_string(),
123 };
124 }
125 let subscription_method = method == "claude.ai" || method == "oauth_token";
129 if status.logged_in && (subscription_method || status.stored_claude_ai_login) {
130 return ClaudeLogin::Subscription {
131 plan: status.subscription_type.filter(|p| !p.trim().is_empty()),
132 };
133 }
134 if !status.logged_in || method.is_empty() || method == "none" {
135 return ClaudeLogin::SignedOut;
136 }
137 ClaudeLogin::Other { method }
138}
139
140const AUTH_STATUS_TIMEOUT: Duration = Duration::from_secs(10);
142
143pub fn claude_login(program: &str, agent_args: &[String], private_dir: &Path) -> ClaudeLogin {
148 let (settings, callers) = probe_settings(agent_args);
149 let text = serde_json::Value::Object(settings).to_string();
150 let (value, file) = if callers {
154 match crate::agents::via_gateway::write_private_file(private_dir, &text) {
155 Ok(file) => (file.to_string_lossy().into_owned(), Some(file)),
156 Err(why) => return ClaudeLogin::Unknown(why),
157 }
158 } else {
159 (text, None)
160 };
161 let login = ask_auth_status(program, &value);
162 if let Some(file) = file {
163 let _ = std::fs::remove_file(file);
164 }
165 login
166}
167
168pub fn probe_settings(agent_args: &[String]) -> (serde_json::Map<String, serde_json::Value>, bool) {
175 let (given, _) = crate::agents::via_gateway::split_settings(agent_args);
176 let mut settings = serde_json::Map::new();
177 for value in &given {
178 if let Ok(read) = crate::agents::via_gateway::read_settings(value) {
179 settings.extend(read);
180 }
181 }
182 let mut env = match settings.remove("env") {
183 Some(serde_json::Value::Object(env)) => env,
184 _ => serde_json::Map::new(),
185 };
186 for name in ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] {
187 env.insert(name.to_string(), "".into());
188 }
189 for switch in crate::agents::via_gateway::CLAUDE_OTHER_PROVIDERS {
190 env.insert(switch.to_string(), "0".into());
191 }
192 settings.insert("env".to_string(), env.into());
193 settings.insert("apiKeyHelper".to_string(), "".into());
194 (settings, !given.is_empty())
195}
196
197fn ask_auth_status(program: &str, settings: &str) -> ClaudeLogin {
199 let mut cmd = Command::new(program);
200 cmd.arg("--settings")
201 .arg(settings)
202 .args(["auth", "status"])
203 .stdin(Stdio::null())
204 .stdout(Stdio::piped())
205 .stderr(Stdio::null());
206 for name in ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"]
207 .into_iter()
208 .chain(crate::agents::via_gateway::CLAUDE_OTHER_PROVIDERS)
209 {
210 cmd.env_remove(name);
211 }
212 let mut child = match cmd.spawn() {
213 Ok(child) => child,
214 Err(e) => {
215 return ClaudeLogin::Unknown(format!("`{program} auth status` could not be run: {e}"))
216 }
217 };
218 let started = Instant::now();
219 loop {
220 match child.try_wait() {
221 Ok(Some(_)) => break,
222 Ok(None) if started.elapsed() < AUTH_STATUS_TIMEOUT => {
223 std::thread::sleep(Duration::from_millis(25))
224 }
225 _ => {
226 let _ = child.kill();
227 let _ = child.wait();
228 return ClaudeLogin::Unknown(format!(
229 "`{program} auth status` did not answer within {} seconds",
230 AUTH_STATUS_TIMEOUT.as_secs()
231 ));
232 }
233 }
234 }
235 let mut out = String::new();
236 if let Some(mut stdout) = child.stdout.take() {
237 use std::io::Read;
238 let _ = stdout.read_to_string(&mut out);
239 }
240 read_auth_status(&out)
242}
243
244pub fn login_finding(login: &ClaudeLogin) -> Finding {
247 const ID: &str = "gateway.claude_login";
248 const SIGN_IN: &str = "start `claude` and run /login with your claude.ai account";
249 match login {
250 ClaudeLogin::Subscription { plan } => Finding::new(
251 COMPONENT,
252 ID,
253 Severity::Ok,
254 match plan {
255 Some(plan) => {
256 format!("Claude Code is signed in with a claude.ai subscription ({plan})")
257 }
258 None => "Claude Code is signed in with a claude.ai subscription".to_string(),
259 },
260 ),
261 ClaudeLogin::SignedOut => Finding::new(
262 COMPONENT,
263 ID,
264 Severity::Error,
265 format!(
266 "Claude Code is not signed in, so there is no subscription to pay for its calls: \
267 {SIGN_IN}"
268 ),
269 ),
270 ClaudeLogin::Other { method } => Finding::new(
271 COMPONENT,
272 ID,
273 Severity::Error,
274 format!(
275 "Claude Code is signed in with {}, not a claude.ai subscription: {SIGN_IN}",
276 match method.as_str() {
277 "api_key" => "an API key (Anthropic Console)".to_string(),
278 said if said.starts_with("a ") => said.to_string(),
279 other => format!("`{other}`"),
280 }
281 ),
282 ),
283 ClaudeLogin::Unknown(why) => Finding::new(
285 COMPONENT,
286 ID,
287 Severity::Error,
288 format!(
289 "whether Claude Code is signed in with a claude.ai subscription could not be \
290 checked: {why}. Make sure Claude Code is installed and recent (`claude \
291 update`), then {SIGN_IN}"
292 ),
293 ),
294 }
295}
296
297#[derive(Clone, Debug, PartialEq, Eq)]
300pub struct ModelUse {
301 pub model: Option<String>,
302 pub source: Option<String>,
303}
304
305pub struct ClaudeEnv {
312 layers: Vec<(String, serde_json::Map<String, serde_json::Value>)>,
313}
314
315impl ClaudeEnv {
316 pub fn read(
317 managed: &Path,
318 home: &Path,
319 project_dir: Option<&Path>,
320 agent_args: &[String],
321 ) -> ClaudeEnv {
322 let mut files: Vec<(String, Option<serde_json::Map<String, serde_json::Value>>)> =
323 vec![(managed.display().to_string(), read_json(managed))];
324 let (given, _) = crate::agents::via_gateway::split_settings(agent_args);
327 if !given.is_empty() {
328 let mut merged = serde_json::Map::new();
329 for value in &given {
330 if let Ok(settings) = crate::agents::via_gateway::read_settings(value) {
331 merged.extend(settings);
332 }
333 }
334 files.push(("--settings given to Claude Code".to_string(), Some(merged)));
335 }
336 if let Some(dir) = project_dir {
337 for name in [".claude/settings.local.json", ".claude/settings.json"] {
338 let path = dir.join(name);
339 files.push((path.display().to_string(), read_json(&path)));
340 }
341 }
342 let user = claude_config_dir(home).join("settings.json");
343 files.push((user.display().to_string(), read_json(&user)));
344 let layers = files
345 .into_iter()
346 .filter_map(|(at, settings)| {
347 let env = settings?.get("env")?.as_object()?.clone();
348 Some((at, env))
349 })
350 .collect();
351 ClaudeEnv { layers }
352 }
353
354 pub fn get(
357 &self,
358 name: &str,
359 process: &dyn Fn(&str) -> Option<String>,
360 ) -> Option<(String, String)> {
361 self.layers
362 .iter()
363 .find_map(|(at, env)| {
364 env.get(name)
365 .and_then(|v| v.as_str())
366 .map(|v| (v.to_string(), format!("`env` in {at}")))
367 })
368 .or_else(|| process(name).map(|v| (v, IN_ENVIRONMENT.to_string())))
369 }
370}
371
372pub fn models_in_use(
378 configured: Option<&str>,
379 agent_args: &[String],
380 env: &dyn Fn(&str) -> Option<(String, String)>,
381) -> Vec<ModelUse> {
382 let named = |name: &str| {
387 env(name).and_then(|(value, at)| {
388 let source = Some(format!("{name} in {at}"));
389 if !value.trim().is_empty() {
390 Some(ModelUse {
391 model: Some(value),
392 source,
393 })
394 } else if at != IN_ENVIRONMENT {
395 Some(ModelUse {
396 model: None,
397 source,
398 })
399 } else {
400 None
401 }
402 })
403 };
404 let option = |name: &str| {
405 let eq = format!("{name}=");
406 agent_args
407 .iter()
408 .take_while(|a| *a != "--")
409 .enumerate()
410 .find_map(|(i, arg)| {
411 if arg == name {
412 agent_args.get(i + 1).cloned()
413 } else {
414 arg.strip_prefix(&eq).map(String::from)
415 }
416 })
417 .filter(|v| !v.trim().is_empty())
418 };
419 let ours = || ModelUse {
420 model: configured.map(String::from),
421 source: None,
422 };
423 let main = match option("--model") {
424 Some(model) => ModelUse {
425 model: Some(model),
426 source: Some("--model given to Claude Code".to_string()),
427 },
428 None => named("ANTHROPIC_MODEL").unwrap_or_else(ours),
429 };
430 let small = named("ANTHROPIC_DEFAULT_HAIKU_MODEL").unwrap_or_else(ours);
431 let fallback = option("--fallback-model").map(|model| ModelUse {
433 model: Some(model),
434 source: Some("--fallback-model given to Claude Code".to_string()),
435 });
436 let mut uses = Vec::new();
437 let others = OTHER_MODEL_SETTINGS.iter().filter_map(|name| named(name));
440 let all = [main, small]
441 .into_iter()
442 .chain(fallback)
443 .chain(others)
444 .flat_map(|used| resolve_selector(used, &named));
445 for used in all {
446 if !uses.contains(&used) {
447 uses.push(used);
448 }
449 }
450 uses
451}
452
453const IN_ENVIRONMENT: &str = "the environment";
455
456fn resolve_selector(used: ModelUse, named: &dyn Fn(&str) -> Option<ModelUse>) -> Vec<ModelUse> {
462 let Some(model) = used.model.as_deref() else {
463 return vec![used];
464 };
465 let bare = model
466 .trim()
467 .trim_end_matches("[1m]")
468 .trim_end_matches("[1M]")
469 .to_ascii_lowercase();
470 let families: &[&str] = match bare.as_str() {
471 "sonnet" => &["SONNET"],
472 "opus" => &["OPUS"],
473 "haiku" => &["HAIKU"],
474 "opusplan" => &["OPUS", "SONNET"],
475 _ => return vec![used],
476 };
477 let given = used
478 .source
479 .clone()
480 .unwrap_or_else(|| "visdom's model setting".to_string());
481 families
482 .iter()
483 .map(|family| {
484 let setting = format!("ANTHROPIC_DEFAULT_{family}_MODEL");
485 match named(&setting) {
486 Some(target) => ModelUse {
487 source: Some(format!(
488 "{}, which `{model}` ({given}) stands for",
489 target.source.unwrap_or_else(|| setting.clone())
490 )),
491 model: target.model,
492 },
493 None => ModelUse {
495 model: Some(model.to_string()),
496 source: Some(format!(
497 "{given}; `{model}` is Claude Code's own model unless {setting} names \
498 an alias"
499 )),
500 },
501 }
502 })
503 .collect()
504}
505
506pub const OTHER_MODEL_SETTINGS: [&str; 4] = [
510 "ANTHROPIC_SMALL_FAST_MODEL",
511 "ANTHROPIC_DEFAULT_SONNET_MODEL",
512 "ANTHROPIC_DEFAULT_OPUS_MODEL",
513 "CLAUDE_CODE_SUBAGENT_MODEL",
514];
515
516pub fn model_finding(
522 uses: &[ModelUse],
523 source: Option<&str>,
524 project: &OpenProject,
525 config_key: &str,
526) -> Finding {
527 const ID: &str = "gateway.subscription_model";
528 let Some(eligible) = project.subscription_aliases() else {
529 return Finding::new(
530 COMPONENT,
531 ID,
532 Severity::Error,
533 format!(
534 "the AI Gateway does not say which model aliases of the project `{}` take calls \
535 paid by a Claude subscription (a version from before it could), so none can be \
536 relied on: ask your platform administrator to update it, or use --billing \
537 project",
538 project.slug
539 ),
540 );
541 };
542 for used in uses {
543 let finding = one_model_finding(
544 used.model.as_deref(),
545 used.source.as_deref().or(source),
546 used.source.is_some(),
547 &eligible,
548 project,
549 config_key,
550 );
551 if finding.severity != Severity::Ok {
552 return finding;
553 }
554 }
555 let names: Vec<String> = uses
556 .iter()
557 .filter_map(|u| u.model.as_deref())
558 .map(|m| format!("`{m}`"))
559 .collect();
560 Finding::new(
561 COMPONENT,
562 ID,
563 Severity::Ok,
564 format!(
565 "the model alias {} takes calls paid by a Claude subscription",
566 names.join(" and ")
567 ),
568 )
569}
570
571fn one_model_finding(
574 model: Option<&str>,
575 source: Option<&str>,
576 outside: bool,
577 eligible: &[String],
578 project: &OpenProject,
579 config_key: &str,
580) -> Finding {
581 const ID: &str = "gateway.subscription_model";
582 let set = match (outside, source) {
583 (true, Some(source)) => format!("change {source}"),
584 _ => format!(
585 "set {config_key} under [gateway] in your visdom config, or VISDOM_GATEWAY_MODEL"
586 ),
587 };
588 if eligible.is_empty() {
589 return Finding::new(
590 COMPONENT,
591 ID,
592 Severity::Error,
593 format!(
594 "no model alias of the project `{}` takes calls paid by a Claude subscription \
595 (only aliases served by Anthropic directly do): ask a project operator for one, \
596 or use --billing project",
597 project.slug
598 ),
599 );
600 }
601 let names = eligible.join(", ");
602 match model {
603 Some(model) if eligible.iter().any(|alias| alias == model) => Finding::new(
604 COMPONENT,
605 ID,
606 Severity::Ok,
607 format!("the model alias `{model}` takes calls paid by a Claude subscription"),
608 ),
609 Some(model) => Finding::new(
610 COMPONENT,
611 ID,
612 Severity::Error,
613 format!(
614 "the model alias `{model}`{} does not take calls paid by a Claude subscription \
615 (only aliases served by Anthropic directly do; the gateway refuses it): {set} to \
616 one that does — {names}",
617 source.map(|s| format!(" ({s})")).unwrap_or_default()
618 ),
619 ),
620 None => Finding::new(
621 COMPONENT,
622 ID,
623 Severity::Error,
624 format!(
625 "no model alias is set, and Claude Code's own default is not one the gateway \
626 takes a subscription call on: {set} to one that does — {names}"
627 ),
628 ),
629 }
630}
631
632pub fn eligible_of(project: &OpenProject, available: &[String]) -> Vec<String> {
635 let eligible = project.subscription_aliases().unwrap_or_default();
636 available
637 .iter()
638 .filter(|alias| eligible.contains(alias))
639 .cloned()
640 .collect()
641}
642
643fn day(at: i64) -> String {
645 chrono::DateTime::from_timestamp(at, 0)
646 .map(|t| t.format("%Y-%m-%d").to_string())
647 .unwrap_or_else(|| at.to_string())
648}
649
650#[derive(Clone, Debug, PartialEq, Eq)]
652pub enum KeyState {
653 Accepted { expires_at: i64 },
656 NoneKept,
658 KeptRefused,
660 Failed(String),
662}
663
664pub fn key_finding(state: &KeyState) -> Finding {
666 const ID: &str = "gateway.subscription_key";
667 match state {
668 KeyState::Accepted { expires_at } => Finding::new(
669 COMPONENT,
670 ID,
671 Severity::Ok,
672 format!(
673 "your subscription key is accepted by the AI Gateway; it expires on {} and \
674 `visdom` renews it a week before",
675 day(*expires_at)
676 ),
677 ),
678 KeyState::NoneKept => Finding::new(
679 COMPONENT,
680 ID,
681 Severity::Info,
682 "no subscription key is kept yet: `visdom` gets one when it starts Claude Code",
683 ),
684 KeyState::KeptRefused => Finding::new(
685 COMPONENT,
686 ID,
687 Severity::Warn,
688 "the AI Gateway no longer accepts your kept subscription key: `visdom` gets a new \
689 one when it starts Claude Code",
690 ),
691 KeyState::Failed(why) => Finding::new(COMPONENT, ID, Severity::Error, why.clone()),
692 }
693}
694
695pub fn managed_settings_path() -> PathBuf {
699 if let Some(path) = std::env::var_os("VISDOM_CLAUDE_MANAGED_SETTINGS") {
700 return PathBuf::from(path);
701 }
702 if cfg!(target_os = "macos") {
703 PathBuf::from("/Library/Application Support/ClaudeCode/managed-settings.json")
704 } else if cfg!(windows) {
705 PathBuf::from(r"C:\Program Files\ClaudeCode\managed-settings.json")
706 } else {
707 PathBuf::from("/etc/claude-code/managed-settings.json")
708 }
709}
710
711fn claude_config_dir(home: &Path) -> PathBuf {
714 std::env::var_os("CLAUDE_CONFIG_DIR")
715 .filter(|v| !v.is_empty())
716 .map(PathBuf::from)
717 .unwrap_or_else(|| home.join(".claude"))
718}
719
720fn read_json(path: &Path) -> Option<serde_json::Map<String, serde_json::Value>> {
721 let text = std::fs::read_to_string(path).ok()?;
722 match serde_json::from_str(&text) {
723 Ok(serde_json::Value::Object(map)) => Some(map),
724 _ => None,
725 }
726}
727
728fn is_set(value: Option<&serde_json::Value>) -> bool {
729 value
730 .and_then(|v| v.as_str())
731 .is_some_and(|v| !v.trim().is_empty())
732}
733
734pub fn managed_takeovers(settings: &serde_json::Map<String, serde_json::Value>) -> Vec<String> {
737 let mut found = Vec::new();
738 if is_set(settings.get("apiKeyHelper")) {
739 found.push("`apiKeyHelper` (its key is sent instead of your subscription)".to_string());
740 }
741 if let Some(method) = settings.get("forceLoginMethod").and_then(|v| v.as_str()) {
742 if method != "claudeai" {
743 found.push(format!(
744 "`forceLoginMethod = {method}` (a claude.ai login is not allowed)"
745 ));
746 }
747 }
748 let env = settings.get("env").and_then(|v| v.as_object());
749 for (name, what, even_empty) in [
752 (
753 "ANTHROPIC_API_KEY",
754 "its key is sent instead of your subscription",
755 false,
756 ),
757 (
758 "ANTHROPIC_AUTH_TOKEN",
759 "its token is sent instead of your subscription",
760 false,
761 ),
762 (
763 "ANTHROPIC_BASE_URL",
764 "the session is sent past the gateway",
765 true,
766 ),
767 (
768 "ANTHROPIC_CUSTOM_HEADERS",
769 "they replace the headers that carry your subscription key",
770 true,
771 ),
772 ] {
773 let value = env.and_then(|env| env.get(name));
774 if is_set(value) || (even_empty && value.is_some()) {
775 found.push(format!("`{name}` in `env` ({what})"));
776 }
777 }
778 for switch in crate::agents::via_gateway::CLAUDE_OTHER_PROVIDERS {
781 let on = env
782 .and_then(|env| env.get(switch))
783 .map(|v| match v {
784 serde_json::Value::String(s) => {
785 !matches!(s.trim().to_ascii_lowercase().as_str(), "" | "0" | "false")
786 }
787 serde_json::Value::Bool(b) => *b,
788 serde_json::Value::Number(n) => n.as_f64() != Some(0.0),
789 _ => false,
790 })
791 .unwrap_or(false);
792 if on {
793 found.push(format!(
794 "`{switch}` in `env` (the session is sent to another provider, past the gateway)"
795 ));
796 }
797 }
798 found
799}
800
801pub fn settings_finding(managed: &Path, home: &Path, project_dir: Option<&Path>) -> Finding {
808 const ID: &str = "gateway.claude_settings";
809 if let Some(settings) = read_json(managed) {
810 let found = managed_takeovers(&settings);
811 if !found.is_empty() {
812 return Finding::new(
813 COMPONENT,
814 ID,
815 Severity::Error,
816 format!(
817 "the Claude Code settings your organisation manages ({}) set {}: they come \
818 after visdom's, so a session on your subscription cannot work. Ask whoever \
819 manages them, or use --billing project",
820 managed.display(),
821 found.join(", ")
822 ),
823 );
824 }
825 }
826 let mut own = vec![claude_config_dir(home).join("settings.json")];
827 if let Some(dir) = project_dir {
828 own.push(dir.join(".claude/settings.json"));
829 own.push(dir.join(".claude/settings.local.json"));
830 }
831 let helpers: Vec<String> = own
832 .iter()
833 .filter(|path| read_json(path).is_some_and(|s| is_set(s.get("apiKeyHelper"))))
834 .map(|path| path.display().to_string())
835 .collect();
836 if !helpers.is_empty() {
837 return Finding::new(
838 COMPONENT,
839 ID,
840 Severity::Warn,
841 format!(
842 "`apiKeyHelper` in {}: set aside in sessions `visdom` starts, but a Claude Code \
843 started without it (after `source <(visdom env)`) sends that key instead of \
844 your subscription",
845 helpers.join(", ")
846 ),
847 );
848 }
849 Finding::new(
850 COMPONENT,
851 ID,
852 Severity::Ok,
853 "nothing in Claude Code's settings takes the session over from your claude.ai login",
854 )
855}
856
857#[cfg(test)]
858mod tests {
859 use super::*;
860 use crate::gateway::ProjectModel;
861
862 #[test]
863 fn the_platforms_message_is_the_product_owners_word_for_word() {
864 assert_eq!(
865 NOT_SUPPORTED,
866 "Your platform configuration doesn't support subscription traffic through visdom \
867 gateway. Contact your platform administrator or use Claude API key or agent hooks"
868 );
869 for traffic in [
870 SubscriptionTraffic::Denied,
871 SubscriptionTraffic::Unpublished,
872 ] {
873 let finding = traffic_finding(traffic);
874 assert_eq!(finding.severity, Severity::Error);
875 assert_eq!(finding.message.lines().next(), Some(NOT_SUPPORTED));
876 assert!(finding.message.contains("--billing project"), "{finding:?}");
877 assert!(finding.message.contains("--mode hooks"), "{finding:?}");
878 assert!(is_not_supported(&finding.message));
879 }
880 assert_eq!(
881 traffic_finding(SubscriptionTraffic::Allowed).severity,
882 Severity::Ok
883 );
884 }
885
886 #[test]
887 fn auth_status_tells_a_subscription_from_anything_else() {
888 let sub = r#"{"loggedIn":true,"authMethod":"claude.ai","subscriptionType":"team"}"#;
889 assert_eq!(
890 read_auth_status(sub),
891 ClaudeLogin::Subscription {
892 plan: Some("team".to_string())
893 }
894 );
895 let free = r#"{"loggedIn":true,"authMethod":"claude.ai","subscriptionType":"free"}"#;
897 let login = read_auth_status(free);
898 assert!(matches!(login, ClaudeLogin::Other { .. }), "{login:?}");
899 let finding = login_finding(&login);
900 assert_eq!(finding.severity, Severity::Error);
901 assert!(
902 finding.message.contains("without a paid plan"),
903 "{finding:?}"
904 );
905 let helper = r#"{"loggedIn":true,"authMethod":"api_key","storedClaudeAiLogin":true}"#;
907 assert!(matches!(
908 read_auth_status(helper),
909 ClaudeLogin::Subscription { .. }
910 ));
911 let console = r#"{"loggedIn":true,"authMethod":"api_key","apiKeySource":"/login"}"#;
912 assert_eq!(
913 read_auth_status(console),
914 ClaudeLogin::Other {
915 method: "api_key".to_string()
916 }
917 );
918 let out = r#"{"loggedIn":false,"authMethod":"none"}"#;
919 assert_eq!(read_auth_status(out), ClaudeLogin::SignedOut);
920 assert!(matches!(
921 read_auth_status("Usage: claude [options]"),
922 ClaudeLogin::Unknown(_)
923 ));
924 }
925
926 #[test]
927 fn a_login_that_is_not_a_subscription_names_the_fix() {
928 let finding = login_finding(&ClaudeLogin::SignedOut);
929 assert_eq!(finding.severity, Severity::Error);
930 assert!(finding.message.contains("/login"), "{finding:?}");
931 let finding = login_finding(&ClaudeLogin::Other {
932 method: "api_key".to_string(),
933 });
934 assert_eq!(finding.severity, Severity::Error);
935 assert!(finding.message.contains("Anthropic Console"), "{finding:?}");
936 assert!(finding.message.contains("/login"), "{finding:?}");
937 let finding = login_finding(&ClaudeLogin::Unknown("x".to_string()));
939 assert_eq!(finding.severity, Severity::Error);
940 assert!(finding.message.contains("claude update"), "{finding:?}");
941 }
942
943 fn project(models: Option<&[(&str, bool)]>) -> OpenProject {
944 OpenProject {
945 id: "p-1".to_string(),
946 slug: "alpha".to_string(),
947 name: "Alpha".to_string(),
948 models: models.map(|models| {
949 models
950 .iter()
951 .map(|(alias, subscription)| ProjectModel {
952 alias: alias.to_string(),
953 subscription: *subscription,
954 })
955 .collect()
956 }),
957 }
958 }
959
960 #[test]
961 fn the_alias_must_take_subscription_calls_and_the_ones_that_do_are_named() {
962 let alpha = project(Some(&[
963 ("gpt-general", false),
964 ("claude-sonnet", true),
965 ("claude-opus", true),
966 ]));
967 let ours = |model: Option<&str>| {
968 vec![ModelUse {
969 model: model.map(String::from),
970 source: None,
971 }]
972 };
973 let ok = model_finding(
974 &ours(Some("claude-sonnet")),
975 None,
976 &alpha,
977 "claude_code_model",
978 );
979 assert_eq!(
980 (ok.id, ok.severity),
981 ("gateway.subscription_model", Severity::Ok)
982 );
983 let bad = model_finding(
984 &ours(Some("gpt-general")),
985 Some("VISDOM_GATEWAY_MODEL in the environment"),
986 &alpha,
987 "claude_code_model",
988 );
989 assert_eq!(bad.severity, Severity::Error);
990 assert!(
991 bad.message.contains("claude-sonnet, claude-opus"),
992 "{bad:?}"
993 );
994 assert!(bad
995 .message
996 .contains("VISDOM_GATEWAY_MODEL in the environment"));
997 assert!(bad.message.contains("claude_code_model"), "{bad:?}");
998 let none = model_finding(&ours(None), None, &alpha, "claude_code_model");
999 assert_eq!(none.severity, Severity::Error);
1000 assert!(none.message.contains("claude-sonnet"), "{none:?}");
1001
1002 let nothing = model_finding(
1003 &ours(Some("gpt-general")),
1004 None,
1005 &project(Some(&[("gpt-general", false)])),
1006 "claude_code_model",
1007 );
1008 assert_eq!(nothing.severity, Severity::Error);
1009 assert!(nothing.message.contains("--billing project"), "{nothing:?}");
1010
1011 let silent = model_finding(&ours(Some("x")), None, &project(None), "claude_code_model");
1013 assert_eq!(silent.severity, Severity::Error);
1014 assert!(silent.message.contains("--billing project"), "{silent:?}");
1015
1016 let env = |name: &str| {
1019 (name == "ANTHROPIC_DEFAULT_HAIKU_MODEL")
1020 .then(|| ("gpt-general".to_string(), "the environment".to_string()))
1021 };
1022 let uses = models_in_use(Some("claude-sonnet"), &[], &env);
1023 assert_eq!(uses.len(), 2, "{uses:?}");
1024 let small = model_finding(&uses, None, &alpha, "claude_code_model");
1025 assert_eq!(small.severity, Severity::Error);
1026 assert!(
1027 small
1028 .message
1029 .contains("change ANTHROPIC_DEFAULT_HAIKU_MODEL in the environment"),
1030 "{small:?}"
1031 );
1032 }
1033
1034 #[test]
1035 fn the_models_in_use_are_the_agents_options_then_the_environment_then_visdoms() {
1036 let none = |_: &str| None;
1037 assert_eq!(
1038 models_in_use(Some("claude-sonnet"), &[], &none),
1039 [ModelUse {
1040 model: Some("claude-sonnet".to_string()),
1041 source: None
1042 }]
1043 );
1044 let env = |name: &str| {
1045 (name == "ANTHROPIC_MODEL")
1046 .then(|| ("claude-opus".to_string(), "the environment".to_string()))
1047 };
1048 let uses = models_in_use(Some("claude-sonnet"), &[], &env);
1049 assert_eq!(uses[0].model.as_deref(), Some("claude-opus"));
1050 assert_eq!(uses[1].model.as_deref(), Some("claude-sonnet"));
1051 let args = ["--model=gpt-general".to_string(), "-p".to_string()];
1052 let uses = models_in_use(Some("claude-sonnet"), &args, &env);
1053 assert_eq!(uses[0].model.as_deref(), Some("gpt-general"));
1054 assert_eq!(
1055 uses[0].source.as_deref(),
1056 Some("--model given to Claude Code")
1057 );
1058 let prompt = ["--".to_string(), "--model".to_string(), "x".to_string()];
1059 assert_eq!(
1060 models_in_use(Some("claude-sonnet"), &prompt, &none)[0]
1061 .model
1062 .as_deref(),
1063 Some("claude-sonnet"),
1064 "after `--` it is the prompt's"
1065 );
1066 }
1067
1068 fn uses_with(
1069 args: &[&str],
1070 vars: &'static [(&'static str, &'static str, &'static str)],
1071 ) -> Vec<ModelUse> {
1072 let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
1073 let env = move |name: &str| {
1074 vars.iter()
1075 .find(|(n, ..)| *n == name)
1076 .map(|(_, v, at)| (v.to_string(), at.to_string()))
1077 };
1078 models_in_use(Some("claude-sonnet"), &args, &env)
1079 }
1080
1081 #[test]
1082 fn claude_codes_selectors_stand_for_their_default_model_settings() {
1083 let uses = uses_with(
1085 &["--model", "sonnet"],
1086 &[(
1087 "ANTHROPIC_DEFAULT_SONNET_MODEL",
1088 "claude-sonnet",
1089 "the environment",
1090 )],
1091 );
1092 assert!(
1093 uses.iter()
1094 .all(|u| u.model.as_deref() == Some("claude-sonnet")),
1095 "{uses:?}"
1096 );
1097 let source = uses[0].source.as_deref().unwrap();
1098 assert!(
1099 source.contains("ANTHROPIC_DEFAULT_SONNET_MODEL"),
1100 "{source}"
1101 );
1102 assert!(source.contains("`sonnet`"), "{source}");
1103 let uses = uses_with(&["--model=opus[1m]"], &[]);
1105 assert_eq!(uses[0].model.as_deref(), Some("opus[1m]"));
1106 assert!(uses[0]
1107 .source
1108 .as_deref()
1109 .unwrap()
1110 .contains("ANTHROPIC_DEFAULT_OPUS_MODEL"));
1111 let uses = uses_with(
1113 &[],
1114 &[
1115 ("ANTHROPIC_MODEL", "opusplan", "the environment"),
1116 (
1117 "ANTHROPIC_DEFAULT_OPUS_MODEL",
1118 "claude-opus",
1119 "the environment",
1120 ),
1121 (
1122 "ANTHROPIC_DEFAULT_SONNET_MODEL",
1123 "claude-sonnet",
1124 "the environment",
1125 ),
1126 ],
1127 );
1128 let models: Vec<_> = uses.iter().filter_map(|u| u.model.as_deref()).collect();
1129 assert!(models.contains(&"claude-opus") && models.contains(&"claude-sonnet"));
1130 assert!(!models.contains(&"opusplan"), "{models:?}");
1131 }
1132
1133 #[test]
1134 fn the_fallback_model_is_checked_too() {
1135 let uses = uses_with(&["-p", "hi", "--fallback-model", "gpt-general"], &[]);
1136 let fallback = uses
1137 .iter()
1138 .find(|u| u.model.as_deref() == Some("gpt-general"))
1139 .unwrap();
1140 assert_eq!(
1141 fallback.source.as_deref(),
1142 Some("--fallback-model given to Claude Code")
1143 );
1144 let alpha = project(Some(&[("claude-sonnet", true), ("gpt-general", false)]));
1145 let finding = model_finding(&uses, None, &alpha, "claude_code_model");
1146 assert_eq!(finding.severity, Severity::Error);
1147 assert!(finding.message.contains("--fallback-model"), "{finding:?}");
1148 }
1149
1150 #[test]
1151 fn a_blank_model_in_a_settings_layer_is_claude_codes_own_default() {
1152 let uses = uses_with(&[], &[("ANTHROPIC_MODEL", " ", "the environment")]);
1154 assert_eq!(uses[0].model.as_deref(), Some("claude-sonnet"));
1155 let uses = uses_with(
1157 &[],
1158 &[(
1159 "ANTHROPIC_MODEL",
1160 "",
1161 "`env` in /home/u/.claude/settings.json",
1162 )],
1163 );
1164 assert_eq!(uses[0].model, None);
1165 let alpha = project(Some(&[("claude-sonnet", true)]));
1166 let finding = model_finding(&uses, None, &alpha, "claude_code_model");
1167 assert_eq!(finding.severity, Severity::Error);
1168 assert!(
1169 finding
1170 .message
1171 .contains("change ANTHROPIC_MODEL in `env` in /home/u/.claude/settings.json"),
1172 "{finding:?}"
1173 );
1174 }
1175
1176 #[test]
1177 fn the_login_probe_keeps_the_callers_settings_under_the_launchs() {
1178 let args = [
1179 "--settings".to_string(),
1180 r#"{"env":{"CLAUDE_CODE_OAUTH_TOKEN":"sk-ant-oat01-x","ANTHROPIC_API_KEY":"sk"},"apiKeyHelper":"mine"}"#
1181 .to_string(),
1182 ];
1183 let (settings, callers) = probe_settings(&args);
1184 assert!(callers);
1185 let env = settings["env"].as_object().unwrap();
1186 assert_eq!(env["CLAUDE_CODE_OAUTH_TOKEN"], "sk-ant-oat01-x");
1187 assert_eq!(env["ANTHROPIC_API_KEY"], "");
1188 assert_eq!(env["CLAUDE_CODE_USE_BEDROCK"], "0");
1189 assert_eq!(settings["apiKeyHelper"], "");
1190 let (_, callers) = probe_settings(&[]);
1191 assert!(!callers);
1192 let token = r#"{"loggedIn":true,"authMethod":"oauth_token","apiProvider":"firstParty"}"#;
1194 assert_eq!(
1195 read_auth_status(token),
1196 ClaudeLogin::Subscription { plan: None }
1197 );
1198 }
1199
1200 #[test]
1201 fn a_model_in_claude_codes_settings_wins_over_the_environment() {
1202 let dir = tempfile::TempDir::new().unwrap();
1203 let home = dir.path().join("home");
1204 let repo = dir.path().join("repo");
1205 let managed = dir.path().join("managed-settings.json");
1206 std::fs::create_dir_all(home.join(".claude")).unwrap();
1207 std::fs::create_dir_all(repo.join(".claude")).unwrap();
1208 std::fs::write(
1209 home.join(".claude/settings.json"),
1210 r#"{"env":{"ANTHROPIC_MODEL":"from-user","ANTHROPIC_DEFAULT_HAIKU_MODEL":"small-user"}}"#,
1211 )
1212 .unwrap();
1213 std::fs::write(
1214 repo.join(".claude/settings.json"),
1215 r#"{"env":{"ANTHROPIC_MODEL":"from-project"}}"#,
1216 )
1217 .unwrap();
1218 let process = |_: &str| Some("from-process".to_string());
1219 let env = ClaudeEnv::read(&managed, &home, Some(&repo), &[]);
1220 let (model, at) = env.get("ANTHROPIC_MODEL", &process).unwrap();
1221 assert_eq!(model, "from-project");
1222 assert!(at.contains(".claude/settings.json"), "{at}");
1223 assert_eq!(
1224 env.get("ANTHROPIC_DEFAULT_HAIKU_MODEL", &process)
1225 .unwrap()
1226 .0,
1227 "small-user"
1228 );
1229 assert_eq!(
1230 env.get("OTHER", &process).unwrap(),
1231 ("from-process".to_string(), "the environment".to_string())
1232 );
1233 let args = [
1234 "--settings".to_string(),
1235 r#"{"env":{"ANTHROPIC_MODEL":"first"}}"#.to_string(),
1236 "--settings".to_string(),
1237 r#"{"env":{"ANTHROPIC_MODEL":"from-flag"}}"#.to_string(),
1238 ];
1239 let env = ClaudeEnv::read(&managed, &home, Some(&repo), &args);
1240 let (model, at) = env.get("ANTHROPIC_MODEL", &process).unwrap();
1241 assert_eq!(
1242 (model.as_str(), at.as_str()),
1243 ("from-flag", "`env` in --settings given to Claude Code")
1244 );
1245 let replaced = [
1248 "--settings".to_string(),
1249 r#"{"env":{"ANTHROPIC_MODEL":"first"}}"#.to_string(),
1250 "--settings".to_string(),
1251 r#"{"env":{"OTHER":"1"}}"#.to_string(),
1252 ];
1253 let env = ClaudeEnv::read(&managed, &home, Some(&repo), &replaced);
1254 assert_eq!(
1255 env.get("ANTHROPIC_MODEL", &process).unwrap().0,
1256 "from-project"
1257 );
1258 let named = |name: &str| {
1260 (name == "CLAUDE_CODE_SUBAGENT_MODEL")
1261 .then(|| ("gpt-general".to_string(), "the environment".to_string()))
1262 };
1263 let uses = models_in_use(Some("claude-sonnet"), &[], &named);
1264 assert_eq!(uses.len(), 2, "{uses:?}");
1265 assert_eq!(uses[1].model.as_deref(), Some("gpt-general"));
1266 std::fs::write(&managed, r#"{"env":{"ANTHROPIC_MODEL":"managed"}}"#).unwrap();
1267 let env = ClaudeEnv::read(&managed, &home, Some(&repo), &args);
1268 assert_eq!(env.get("ANTHROPIC_MODEL", &process).unwrap().0, "managed");
1269 }
1270
1271 #[test]
1272 fn only_eligible_aliases_are_offered() {
1273 let available = ["gpt-general".to_string(), "claude-sonnet".to_string()];
1274 let alpha = project(Some(&[("claude-sonnet", true), ("gpt-general", false)]));
1275 assert_eq!(eligible_of(&alpha, &available), ["claude-sonnet"]);
1276 assert!(eligible_of(&project(None), &available).is_empty());
1277 }
1278
1279 #[test]
1280 fn the_key_is_reported_with_its_expiry_date() {
1281 let at = chrono::DateTime::parse_from_rfc3339("2026-12-27T10:00:00Z")
1282 .unwrap()
1283 .timestamp();
1284 let finding = key_finding(&KeyState::Accepted { expires_at: at });
1285 assert_eq!(
1286 (finding.id, finding.severity),
1287 ("gateway.subscription_key", Severity::Ok)
1288 );
1289 assert!(finding.message.contains("2026-12-27"), "{finding:?}");
1290 assert_eq!(key_finding(&KeyState::NoneKept).severity, Severity::Info);
1291 assert_eq!(key_finding(&KeyState::KeptRefused).severity, Severity::Warn);
1292 let failed = key_finding(&KeyState::Failed(NOT_SUPPORTED.to_string()));
1293 assert_eq!(failed.severity, Severity::Error);
1294 }
1295
1296 #[test]
1297 fn managed_settings_that_take_the_session_over_are_named() {
1298 let settings = |text: &str| match serde_json::from_str(text).unwrap() {
1299 serde_json::Value::Object(map) => map,
1300 _ => unreachable!(),
1301 };
1302 assert!(managed_takeovers(&settings(r#"{"forceLoginMethod":"claudeai"}"#)).is_empty());
1303 assert!(managed_takeovers(&settings(r#"{"apiKeyHelper":""}"#)).is_empty());
1304 let found = managed_takeovers(&settings(
1305 r#"{"apiKeyHelper":"get-key","forceLoginMethod":"console",
1306 "env":{"ANTHROPIC_API_KEY":"sk","ANTHROPIC_BASE_URL":"https://x","OTHER":"1"}}"#,
1307 ));
1308 assert_eq!(found.len(), 4, "{found:?}");
1309 assert!(found[1].contains("forceLoginMethod = console"), "{found:?}");
1310 let found = managed_takeovers(&settings(
1312 r#"{"env":{"ANTHROPIC_API_KEY":"","ANTHROPIC_CUSTOM_HEADERS":""}}"#,
1313 ));
1314 assert_eq!(found.len(), 1, "{found:?}");
1315 assert!(found[0].contains("ANTHROPIC_CUSTOM_HEADERS"), "{found:?}");
1316 let found = managed_takeovers(&settings(
1318 r#"{"env":{"CLAUDE_CODE_USE_BEDROCK":"1","CLAUDE_CODE_USE_VERTEX":"0","CLAUDE_CODE_USE_FOUNDRY":false}}"#,
1319 ));
1320 assert_eq!(found.len(), 1, "{found:?}");
1321 assert!(found[0].contains("CLAUDE_CODE_USE_BEDROCK"), "{found:?}");
1322 }
1323
1324 #[test]
1325 fn settings_are_an_error_when_managed_and_a_warning_when_the_developers() {
1326 let dir = tempfile::TempDir::new().unwrap();
1327 let home = dir.path().join("home");
1328 let repo = dir.path().join("repo");
1329 let managed = dir.path().join("managed-settings.json");
1330 std::fs::create_dir_all(home.join(".claude")).unwrap();
1331 std::fs::create_dir_all(repo.join(".claude")).unwrap();
1332 let clean = settings_finding(&managed, &home, Some(&repo));
1333 assert_eq!(
1334 (clean.id, clean.severity),
1335 ("gateway.claude_settings", Severity::Ok)
1336 );
1337 std::fs::write(
1338 repo.join(".claude/settings.local.json"),
1339 r#"{"apiKeyHelper":"echo sk"}"#,
1340 )
1341 .unwrap();
1342 let own = settings_finding(&managed, &home, Some(&repo));
1343 assert_eq!(own.severity, Severity::Warn);
1344 assert!(own.message.contains("settings.local.json"), "{own:?}");
1345 std::fs::write(&managed, r#"{"forceLoginMethod":"console"}"#).unwrap();
1346 let theirs = settings_finding(&managed, &home, Some(&repo));
1347 assert_eq!(theirs.severity, Severity::Error);
1348 assert!(theirs.message.contains("--billing project"), "{theirs:?}");
1349 }
1350}