interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-switchboard / src / doctor.rs

431 lines · 14127 bytes Raw Blame History
1//! `switchboard doctor`: check the setup without reading any secret.
2//!
3//! What it reports: the `claude` executable and its version, each profile
4//! folder (exists, real folder, private), whether each profile's credentials
5//! file is present and its permission bits (never opened), credential
6//! variables set in the shell (names only), and settings that could bring an
7//! API key back in: `apiKeyHelper` or an `env` block in the profile's
8//! `settings.json` and in the working repo's `.claude/settings.json` and
9//! `.claude/settings.local.json` (setting names only, never values). It also
10//! flags Anthropic profile files in `~/.config/anthropic` by presence,
11//! because Claude Code's precedence lets some of them outrank the claude.ai
12//! login.
13
14use crate::launch::{
15 check_profile_dir, claude_profiles, find_program, folder_shared_with, is_credential_selecting,
16 launch_env, DirProblem, DirState, Env, CONFIG_DIR_VAR, CREDENTIALS_FILE,
17};
18use crate::rules::RuleTable;
19use std::ffi::OsStr;
20use std::fmt;
21use std::fs;
22use std::io::Read;
23use std::os::unix::fs::PermissionsExt;
24use std::path::{Path, PathBuf};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
27pub enum Level {
28 Ok,
29 Warn,
30 Fail,
31}
32
33impl Level {
34 fn tag(self) -> &'static str {
35 match self {
36 Level::Ok => "[ OK ]",
37 Level::Warn => "[WARN]",
38 Level::Fail => "[FAIL]",
39 }
40 }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Finding {
45 pub level: Level,
46 /// What was checked: a profile alias, a program name, a file path.
47 pub subject: String,
48 pub message: String,
49}
50
51#[derive(Debug, Clone, Default, PartialEq, Eq)]
52pub struct Report {
53 pub findings: Vec<Finding>,
54}
55
56impl Report {
57 fn push(&mut self, level: Level, subject: impl Into<String>, message: impl Into<String>) {
58 self.findings.push(Finding {
59 level,
60 subject: subject.into(),
61 message: message.into(),
62 });
63 }
64
65 /// True when any check failed; `switchboard doctor` then exits 1.
66 pub fn failed(&self) -> bool {
67 self.findings.iter().any(|f| f.level == Level::Fail)
68 }
69
70 fn count(&self, level: Level) -> usize {
71 self.findings.iter().filter(|f| f.level == level).count()
72 }
73}
74
75impl fmt::Display for Report {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 for x in &self.findings {
78 writeln!(f, "{} {}: {}", x.level.tag(), x.subject, x.message)?;
79 }
80 write!(
81 f,
82 "doctor: {} ok, {} warnings, {} failures",
83 self.count(Level::Ok),
84 self.count(Level::Warn),
85 self.count(Level::Fail)
86 )
87 }
88}
89
90/// Asks a program for its version. The real probe (in the `switchboard`
91/// binary) runs `<program> --version` with exactly `env`; tests use
92/// `FakeProbe`.
93pub trait VersionProbe {
94 fn version(&mut self, program: &Path, env: &Env) -> Result<String, String>;
95}
96
97/// Answers a fixed result and records which programs were asked.
98#[derive(Debug)]
99pub struct FakeProbe {
100 pub answer: Result<String, String>,
101 pub calls: Vec<PathBuf>,
102}
103
104impl VersionProbe for FakeProbe {
105 fn version(&mut self, program: &Path, _env: &Env) -> Result<String, String> {
106 self.calls.push(program.to_path_buf());
107 self.answer.clone()
108 }
109}
110
111/// First line, printable characters only, at most 80 of them.
112fn tidy(s: &str) -> String {
113 s.lines()
114 .next()
115 .unwrap_or("")
116 .chars()
117 .filter(|c| !c.is_control())
118 .take(80)
119 .collect::<String>()
120 .trim()
121 .to_string()
122}
123
124/// Settings files larger than this are not parsed.
125const MAX_SETTINGS_BYTES: u64 = 1 << 20;
126
127/// Run every check. Reads only folder and file metadata, plus the JSON of
128/// non-credential settings files, of which only key names are reported.
129pub fn doctor(rules: &RuleTable, env: &Env, cwd: &Path, probe: &mut dyn VersionProbe) -> Report {
130 let mut r = Report::default();
131 let profiles = claude_profiles(rules);
132 if profiles.is_empty() {
133 r.push(
134 Level::Warn,
135 "rule file",
136 "no Claude Code profiles (accounts with provider = \"anthropic\", program = \"claude\" and a settings_dir)",
137 );
138 } else {
139 let names: Vec<&str> = profiles.iter().map(|(a, _)| a.id.as_str()).collect();
140 r.push(
141 Level::Ok,
142 "rule file",
143 format!("{} Claude Code profiles: {}", names.len(), names.join(", ")),
144 );
145 }
146
147 check_shell_env(&mut r, env);
148
149 // The environment the version probe gets: the launch allowlist, without a
150 // profile folder so no profile is touched.
151 let mut probe_env = launch_env(env, Path::new("/"), rules.pass_env());
152 probe_env.remove(OsStr::new(CONFIG_DIR_VAR));
153 let path_var = probe_env.get(OsStr::new("PATH")).cloned();
154 let mut programs: Vec<&str> = profiles.iter().map(|(a, _)| a.program.as_str()).collect();
155 programs.sort_unstable();
156 programs.dedup();
157 for program in programs {
158 match find_program(program, path_var.as_deref()) {
159 None => r.push(
160 Level::Fail,
161 program,
162 "not found as an executable file on PATH; install Claude Code or fix PATH",
163 ),
164 Some(exe) => match probe.version(&exe, &probe_env) {
165 Ok(v) => r.push(
166 Level::Ok,
167 program,
168 format!("found {}, version {}", exe.display(), tidy(&v)),
169 ),
170 Err(e) => r.push(
171 Level::Warn,
172 program,
173 format!("found {} but --version failed: {}", exe.display(), tidy(&e)),
174 ),
175 },
176 }
177 }
178
179 for (account, dir) in &profiles {
180 check_profile(&mut r, rules, account.id.as_str(), dir);
181 }
182
183 for path in repo_settings_files(cwd) {
184 scan_settings(&mut r, &path);
185 }
186
187 if let Some(home) = env.get(OsStr::new("HOME")) {
188 check_anthropic_profiles(&mut r, &Path::new(home).join(".config").join("anthropic"));
189 }
190 r
191}
192
193fn check_shell_env(r: &mut Report, env: &Env) {
194 let names: Vec<&str> = env
195 .keys()
196 .filter_map(|k| k.to_str())
197 .filter(|k| is_credential_selecting(k) && *k != CONFIG_DIR_VAR)
198 .collect();
199 if names.is_empty() {
200 r.push(Level::Ok, "shell", "no credential-selecting variables set");
201 } else {
202 r.push(
203 Level::Warn,
204 "shell",
205 format!(
206 "credential-selecting variables set: {}; launch never passes them to claude",
207 names.join(", ")
208 ),
209 );
210 }
211}
212
213fn check_profile(r: &mut Report, rules: &RuleTable, alias: &str, dir: &Path) {
214 if let Some(other) = folder_shared_with(rules, alias, dir) {
215 let p = DirProblem::SharedWith(other);
216 r.push(Level::Fail, alias, format!("folder {} {p}", dir.display()));
217 return;
218 }
219 match check_profile_dir(dir) {
220 Ok(DirState::Missing) => {
221 r.push(
222 Level::Warn,
223 alias,
224 format!(
225 "folder not created yet: {}; `switchboard launch {alias}` creates it (mode 700), then sign in",
226 dir.display()
227 ),
228 );
229 return;
230 }
231 Ok(DirState::Private) => {
232 r.push(
233 Level::Ok,
234 alias,
235 format!("folder {} is private (700)", dir.display()),
236 );
237 }
238 Err(p @ DirProblem::TooOpen { .. }) => {
239 r.push(Level::Fail, alias, format!("folder {} {p}", dir.display()));
240 }
241 Err(p) => {
242 r.push(Level::Fail, alias, format!("folder {} {p}", dir.display()));
243 return;
244 }
245 }
246 check_credentials(r, alias, &dir.join(CREDENTIALS_FILE));
247 scan_settings(r, &dir.join("settings.json"));
248}
249
250/// Presence and permission bits only. The file is never opened.
251fn check_credentials(r: &mut Report, alias: &str, path: &Path) {
252 match fs::symlink_metadata(path) {
253 Err(e) if e.kind() == std::io::ErrorKind::NotFound => r.push(
254 Level::Warn,
255 alias,
256 format!("not signed in yet (no {CREDENTIALS_FILE}); run `switchboard launch {alias}` and sign in"),
257 ),
258 Err(e) => r.push(
259 Level::Warn,
260 alias,
261 format!("cannot check {CREDENTIALS_FILE}: {}", e.kind()),
262 ),
263 Ok(m) if m.file_type().is_symlink() => r.push(
264 Level::Warn,
265 alias,
266 "credentials file present but is a symbolic link; it may be shared with another profile",
267 ),
268 Ok(m) if !m.is_file() => r.push(
269 Level::Warn,
270 alias,
271 format!("{CREDENTIALS_FILE} exists but is not a regular file"),
272 ),
273 Ok(m) => {
274 let mode = m.permissions().mode() & 0o777;
275 if mode == 0o600 {
276 r.push(Level::Ok, alias, "credentials file present (mode 600, not opened)");
277 } else {
278 r.push(
279 Level::Warn,
280 alias,
281 format!("credentials file present with mode {mode:03o}, expected 600 (not opened)"),
282 );
283 }
284 }
285 }
286}
287
288/// `.claude/settings.json` and `.claude/settings.local.json` in the working
289/// folder and, when different, in the repository root above it (the nearest
290/// folder holding `.git`).
291fn repo_settings_files(cwd: &Path) -> Vec<PathBuf> {
292 let mut roots = vec![cwd.to_path_buf()];
293 if let Some(root) = cwd.ancestors().find(|a| a.join(".git").exists()) {
294 if root != cwd {
295 roots.push(root.to_path_buf());
296 }
297 }
298 roots
299 .iter()
300 .flat_map(|root| {
301 ["settings.json", "settings.local.json"]
302 .into_iter()
303 .map(move |f| root.join(".claude").join(f))
304 })
305 .collect()
306}
307
308/// Warn on `apiKeyHelper` or an `env` block. Reports setting names only.
309fn scan_settings(r: &mut Report, path: &Path) {
310 let subject = path.display().to_string();
311 // Never follow a link into a credentials file.
312 if let Ok(real) = fs::canonicalize(path) {
313 if real.file_name() == Some(OsStr::new(CREDENTIALS_FILE)) {
314 r.push(
315 Level::Warn,
316 subject,
317 "points at a credentials file; not opened",
318 );
319 return;
320 }
321 }
322 let file = match fs::File::open(path) {
323 Ok(f) => f,
324 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
325 Err(e) => {
326 r.push(Level::Warn, subject, format!("cannot read: {}", e.kind()));
327 return;
328 }
329 };
330 let mut text = String::new();
331 if file
332 .take(MAX_SETTINGS_BYTES + 1)
333 .read_to_string(&mut text)
334 .is_err()
335 {
336 r.push(
337 Level::Warn,
338 subject,
339 "cannot read as text; apiKeyHelper and env not checked",
340 );
341 return;
342 }
343 if text.len() as u64 > MAX_SETTINGS_BYTES {
344 r.push(
345 Level::Warn,
346 subject,
347 "larger than 1 MiB; apiKeyHelper and env not checked",
348 );
349 return;
350 }
351 let value: serde_json::Value = match serde_json::from_str(&text) {
352 Ok(v) => v,
353 Err(e) => {
354 // Line and column only: the parser's own message can quote input.
355 r.push(
356 Level::Warn,
357 subject,
358 format!(
359 "cannot parse as JSON (line {}, column {}); apiKeyHelper and env not checked",
360 e.line(),
361 e.column()
362 ),
363 );
364 return;
365 }
366 };
367 let Some(obj) = value.as_object() else {
368 r.push(
369 Level::Warn,
370 subject,
371 "is not a JSON object; apiKeyHelper and env not checked",
372 );
373 return;
374 };
375 let mut clean = true;
376 if obj.contains_key("apiKeyHelper") {
377 clean = false;
378 r.push(
379 Level::Warn,
380 subject.clone(),
381 "sets apiKeyHelper: a script that can supply an API key and outrank the claude.ai login",
382 );
383 }
384 if let Some(block) = obj.get("env") {
385 clean = false;
386 let (count, risky) = match block.as_object() {
387 Some(m) => {
388 let risky: Vec<&str> = m
389 .keys()
390 .map(|k| k.as_str())
391 .filter(|k| is_credential_selecting(k))
392 .collect();
393 (m.len(), risky)
394 }
395 None => (0, Vec::new()),
396 };
397 let detail = if risky.is_empty() {
398 "none of them select a credential".to_string()
399 } else {
400 format!("credential-selecting: {}", risky.join(", "))
401 };
402 r.push(
403 Level::Warn,
404 subject.clone(),
405 format!("has an env block ({count} variables, {detail}); claude applies it after launch, so it can bring an API key back in"),
406 );
407 }
408 if clean {
409 r.push(Level::Ok, subject, "no apiKeyHelper, no env block");
410 }
411}
412
413/// Presence only. An `oidc_federation` active profile outranks the claude.ai
414/// login (Claude Code authentication docs, "Anthropic profiles and federation
415/// credentials").
416fn check_anthropic_profiles(r: &mut Report, dir: &Path) {
417 let present: Vec<&str> = ["active_config", "configs"]
418 .into_iter()
419 .filter(|n| fs::symlink_metadata(dir.join(n)).is_ok())
420 .collect();
421 if !present.is_empty() {
422 r.push(
423 Level::Warn,
424 dir.display().to_string(),
425 format!(
426 "Anthropic profile files present ({}); a federation profile there can outrank the claude.ai login; check /status in each profile",
427 present.join(", ")
428 ),
429 );
430 }
431}