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 / launch.rs

507 lines · 18224 bytes Raw Blame History
1//! `switchboard launch <alias>`: open the official, unmodified `claude` in
2//! one profile's own settings folder (ADR 0030 phase 1, issue #592).
3//!
4//! The profile folder comes from the rule file (`settings_dir` of an account
5//! whose program is `claude`). Switchboard sets `CLAUDE_CONFIG_DIR` itself and
6//! never passes an inherited one. The environment `claude` sees is built from
7//! an explicit allowlist, so every credential-selecting variable in Claude
8//! Code's authentication precedence (API key, bearer token, OAuth token,
9//! Anthropic profile, federation, Bedrock / Vertex / Foundry, base URL) and
10//! every cloud credential variable stays behind. Proxy variables pass only
11//! when the rule file lists them under `[launch] pass_env`.
12//!
13//! This module plans and checks; it never starts a process and never opens a
14//! credentials file. Starting the process is the `Spawner`'s job: the
15//! `switchboard` binary holds the real one, tests use `FakeSpawner`.
16
17use crate::account::{Account, Credential, Provider};
18use crate::rules::RuleTable;
19use std::collections::BTreeMap;
20use std::ffi::{OsStr, OsString};
21use std::fmt;
22use std::fs;
23use std::io;
24use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
25use std::path::{Path, PathBuf};
26
27/// Every credential-selecting variable named in issue #592. None of these is
28/// ever passed to `claude`. The allowlist below already drops them; this list exists so doctor can name them and tests can
29/// prove the allowlist covers them.
30pub const STRIPPED_ENV: &[&str] = &[
31 "ANTHROPIC_API_KEY",
32 "ANTHROPIC_AUTH_TOKEN",
33 "CLAUDE_CODE_OAUTH_TOKEN",
34 "ANTHROPIC_PROFILE",
35 "ANTHROPIC_FEDERATION_RULE_ID",
36 "ANTHROPIC_ORGANIZATION_ID",
37 "CLAUDE_CODE_USE_BEDROCK",
38 "CLAUDE_CODE_USE_VERTEX",
39 "CLAUDE_CODE_USE_FOUNDRY",
40 "ANTHROPIC_BASE_URL",
41];
42
43/// Variable families that can carry or select a credential (cloud provider
44/// keys, Anthropic Vertex / Bedrock settings, Claude Code switches). Never
45/// passed, whatever the allowlist or the rule file says.
46pub const STRIPPED_PREFIXES: &[&str] = &["ANTHROPIC_", "CLAUDE_", "AWS_", "GOOGLE_", "AZURE_"];
47
48/// Proxy variables. They pass only when the rule file lists them, because a
49/// proxy URL can carry a user name and password.
50pub const PROXY_ENV: &[&str] = &[
51 "HTTP_PROXY",
52 "HTTPS_PROXY",
53 "NO_PROXY",
54 "ALL_PROXY",
55 "http_proxy",
56 "https_proxy",
57 "no_proxy",
58 "all_proxy",
59];
60
61/// Variables passed from the shell when present: what a terminal program
62/// needs to find itself, draw, and open the browser for the operator's own
63/// sign-in. Nothing here selects or carries an Anthropic credential.
64const ALLOWED_ENV: &[&str] = &[
65 "PATH",
66 "HOME",
67 "USER",
68 "LOGNAME",
69 "SHELL",
70 "TERM",
71 "COLORTERM",
72 "TERM_PROGRAM",
73 "TERM_PROGRAM_VERSION",
74 "LANG",
75 "LANGUAGE",
76 "TZ",
77 "TMPDIR",
78 "DISPLAY",
79 "WAYLAND_DISPLAY",
80 "XDG_RUNTIME_DIR",
81 "DBUS_SESSION_BUS_ADDRESS",
82 "BROWSER",
83 "EDITOR",
84 "VISUAL",
85 // Design choice: claude and the tools it runs (git push) may use the
86 // operator's ssh agent. The agent socket signs; it never hands out keys.
87 "SSH_AUTH_SOCK",
88];
89
90/// Locale variables (`LC_ALL`, `LC_CTYPE`, ...) pass as a family.
91const ALLOWED_PREFIXES: &[&str] = &["LC_"];
92
93/// The file Claude Code keeps its login in, inside the profile folder (Claude
94/// Code authentication docs, "Credential management"). Switchboard only ever
95/// checks that it exists and reads its permission bits.
96pub const CREDENTIALS_FILE: &str = ".credentials.json";
97
98/// The variable Claude Code reads to find a profile folder.
99pub const CONFIG_DIR_VAR: &str = "CLAUDE_CONFIG_DIR";
100
101/// The program name that marks an account as a Claude Code profile.
102pub const CLAUDE_PROGRAM: &str = "claude";
103
104/// An environment: variable name to value.
105pub type Env = BTreeMap<OsString, OsString>;
106
107/// True for a variable that selects or carries a credential and must never
108/// reach `claude`: a listed name or one of the stripped families.
109pub fn is_credential_selecting(name: &str) -> bool {
110 STRIPPED_ENV.contains(&name) || STRIPPED_PREFIXES.iter().any(|p| name.starts_with(p))
111}
112
113fn allowed(name: &str) -> bool {
114 ALLOWED_ENV.contains(&name) || ALLOWED_PREFIXES.iter().any(|p| name.starts_with(p))
115}
116
117/// Build the environment for `claude` from the inherited one: allowlisted
118/// names, plus listed proxy names, minus every credential-selecting name,
119/// plus `CLAUDE_CONFIG_DIR` set to `config_dir` (any inherited value is
120/// dropped). Non-UTF-8 names are dropped.
121pub fn launch_env(inherited: &Env, config_dir: &Path, pass_env: &[String]) -> Env {
122 let mut out = Env::new();
123 for (k, v) in inherited {
124 let Some(name) = k.to_str() else { continue };
125 let listed_proxy = PROXY_ENV.contains(&name) && pass_env.iter().any(|p| p.as_str() == name);
126 if (allowed(name) || listed_proxy) && !is_credential_selecting(name) {
127 let v = if name == "PATH" {
128 absolute_path_entries(v)
129 } else {
130 v.clone()
131 };
132 out.insert(k.clone(), v);
133 }
134 }
135 out.insert(
136 OsString::from(CONFIG_DIR_VAR),
137 config_dir.as_os_str().to_owned(),
138 );
139 out
140}
141
142fn is_executable_file(p: &Path) -> bool {
143 fs::metadata(p)
144 .map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
145 .unwrap_or(false)
146}
147
148/// Find `program` the way a shell would: a name containing `/` is used as
149/// given only when absolute (a relative one is never run), anything else is
150/// searched for in the absolute entries of `path` (a `PATH` value). Only an
151/// executable regular file counts.
152pub fn find_program(program: &str, path: Option<&OsStr>) -> Option<PathBuf> {
153 if program.contains('/') {
154 let p = PathBuf::from(program);
155 return (p.is_absolute() && is_executable_file(&p)).then_some(p);
156 }
157 std::env::split_paths(path?)
158 .filter(|dir| dir.is_absolute())
159 .map(|dir| dir.join(program))
160 .find(|p| is_executable_file(p))
161}
162
163fn is_claude_program(program: &str) -> bool {
164 Path::new(program).file_name() == Some(OsStr::new(CLAUDE_PROGRAM))
165}
166
167/// Every Claude Code profile in the rule file: Anthropic accounts served by
168/// `claude` with their own settings folder, in file order.
169pub fn claude_profiles(rules: &RuleTable) -> Vec<(&Account, &Path)> {
170 rules
171 .accounts()
172 .iter()
173 .filter_map(|a| match &a.credential {
174 Credential::SettingsFolder(dir)
175 if a.provider == Provider::Anthropic && is_claude_program(&a.program) =>
176 {
177 Some((a, dir.as_path()))
178 }
179 _ => None,
180 })
181 .collect()
182}
183
184/// Look up one Claude Code profile by alias (its account id).
185pub fn profile<'a>(
186 rules: &'a RuleTable,
187 alias: &str,
188) -> Result<(&'a Account, &'a Path), LaunchError> {
189 let profiles = claude_profiles(rules);
190 if let Some(found) = profiles.iter().find(|(a, _)| a.id.as_str() == alias) {
191 return Ok(*found);
192 }
193 if rules.accounts().iter().any(|a| a.id.as_str() == alias) {
194 return Err(LaunchError::NotAClaudeProfile {
195 alias: alias.to_string(),
196 });
197 }
198 Err(LaunchError::UnknownAlias {
199 alias: alias.to_string(),
200 known: profiles.iter().map(|(a, _)| a.id.to_string()).collect(),
201 })
202}
203
204/// Everything needed to start `claude` for one profile.
205#[derive(Clone, PartialEq, Eq)]
206pub struct LaunchPlan {
207 pub alias: String,
208 /// Resolved path of the executable, so nothing searches `PATH` again.
209 pub program: PathBuf,
210 pub config_dir: PathBuf,
211 /// The complete environment `claude` gets; the spawner clears everything
212 /// else.
213 pub env: Env,
214}
215
216/// Shows variable names only, never values.
217impl fmt::Debug for LaunchPlan {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 let names: Vec<_> = self.env.keys().map(|k| k.to_string_lossy()).collect();
220 f.debug_struct("LaunchPlan")
221 .field("alias", &self.alias)
222 .field("program", &self.program)
223 .field("config_dir", &self.config_dir)
224 .field("env_names", &names)
225 .finish()
226 }
227}
228
229/// State of a profile folder that is fit to use.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum DirState {
232 /// Not created yet; the first launch creates it with mode 0700.
233 Missing,
234 /// A real folder (not a link) that only the owner can open.
235 Private,
236}
237
238/// Why a profile folder is not fit to use.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub enum DirProblem {
241 NotADirectory,
242 /// Owned by another user; `uid` is the owner's.
243 NotOwner {
244 uid: u32,
245 },
246 /// Resolves (through links) to the folder of this other profile.
247 SharedWith(String),
248 /// A symbolic link could point two profiles at one folder.
249 Symlink,
250 /// Group or others have some access; `mode` is the permission bits.
251 TooOpen {
252 mode: u32,
253 },
254 Io(String),
255}
256
257impl fmt::Display for DirProblem {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 match self {
260 DirProblem::NotADirectory => f.write_str("exists but is not a folder"),
261 DirProblem::Symlink => {
262 f.write_str("is a symbolic link; each profile needs its own real folder")
263 }
264 DirProblem::TooOpen { mode } => write!(
265 f,
266 "has mode {mode:03o}; only you may open it (run: chmod 700 on the folder)"
267 ),
268 DirProblem::Io(m) => write!(f, "cannot be checked: {m}"),
269 DirProblem::NotOwner { uid } => {
270 write!(f, "belongs to user id {uid}, not to you")
271 }
272 DirProblem::SharedWith(o) => write!(
273 f,
274 "is the same folder as profile {o:?}; each profile needs its own folder"
275 ),
276 }
277 }
278}
279
280/// The effective user id of this process: the owner of `/proc/self`
281/// (Linux). `None` when it cannot be read.
282pub fn current_uid() -> Option<u32> {
283 fs::metadata("/proc/self").ok().map(|m| m.uid())
284}
285
286/// Check a profile folder without changing it: it must be a real folder (not
287/// a link), owned by the current user, with no access for group or others.
288pub fn check_profile_dir(path: &Path) -> Result<DirState, DirProblem> {
289 let uid = current_uid().ok_or_else(|| DirProblem::Io("cannot tell the current user".into()))?;
290 check_profile_dir_owned_by(path, uid)
291}
292
293/// `check_profile_dir` against an explicit owner `uid` (tests use this to
294/// exercise the wrong-owner case without a second user).
295pub fn check_profile_dir_owned_by(path: &Path, uid: u32) -> Result<DirState, DirProblem> {
296 let meta = match fs::symlink_metadata(path) {
297 Ok(m) => m,
298 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(DirState::Missing),
299 Err(e) => return Err(DirProblem::Io(e.kind().to_string())),
300 };
301 if meta.file_type().is_symlink() {
302 return Err(DirProblem::Symlink);
303 }
304 if !meta.is_dir() {
305 return Err(DirProblem::NotADirectory);
306 }
307 if meta.uid() != uid {
308 return Err(DirProblem::NotOwner { uid: meta.uid() });
309 }
310 let mode = meta.permissions().mode() & 0o777;
311 if mode & 0o077 != 0 {
312 return Err(DirProblem::TooOpen { mode });
313 }
314 Ok(DirState::Private)
315}
316
317/// Make sure the profile folder exists and is private: create it with mode
318/// 0700 if missing, refuse it if it is a link, not a folder, or open to
319/// others. Never loosens or silently fixes an existing folder.
320pub fn prepare_profile_dir(path: &Path) -> Result<(), LaunchError> {
321 let fail = |problem| LaunchError::ProfileDir {
322 path: path.to_path_buf(),
323 problem,
324 };
325 match check_profile_dir(path).map_err(fail)? {
326 DirState::Private => Ok(()),
327 DirState::Missing => {
328 if let Some(parent) = path.parent() {
329 fs::create_dir_all(parent)
330 .map_err(|e| fail(DirProblem::Io(e.kind().to_string())))?;
331 }
332 fs::DirBuilder::new()
333 .mode(0o700)
334 .create(path)
335 .map_err(|e| fail(DirProblem::Io(e.kind().to_string())))?;
336 // The process umask can only remove bits; set them exactly.
337 fs::set_permissions(path, fs::Permissions::from_mode(0o700))
338 .map_err(|e| fail(DirProblem::Io(e.kind().to_string())))?;
339 match check_profile_dir(path).map_err(fail)? {
340 DirState::Private => Ok(()),
341 DirState::Missing => Err(fail(DirProblem::Io("vanished after create".into()))),
342 }
343 }
344 }
345}
346
347/// Plan a launch: find the profile, build its environment, and find the
348/// executable on the cleaned `PATH`. Changes nothing on disk.
349pub fn plan_launch(
350 rules: &RuleTable,
351 alias: &str,
352 inherited: &Env,
353) -> Result<LaunchPlan, LaunchError> {
354 let (account, dir) = profile(rules, alias)?;
355 if let Some(other) = folder_shared_with(rules, alias, dir) {
356 return Err(LaunchError::ProfileDir {
357 path: dir.to_path_buf(),
358 problem: DirProblem::SharedWith(other),
359 });
360 }
361 let env = launch_env(inherited, dir, rules.pass_env());
362 let program = find_program(
363 &account.program,
364 env.get(OsStr::new("PATH")).map(|p| p.as_os_str()),
365 )
366 .ok_or_else(|| LaunchError::ExecutableNotFound {
367 program: account.program.clone(),
368 })?;
369 Ok(LaunchPlan {
370 alias: alias.to_string(),
371 program,
372 config_dir: dir.to_path_buf(),
373 env,
374 })
375}
376
377/// Starts the planned program. The real one (in the `switchboard` binary)
378/// clears the environment, sets exactly `plan.env`, and hands the terminal to
379/// `claude`.
380pub trait Spawner {
381 /// Returns the program's exit code.
382 fn spawn(&mut self, plan: &LaunchPlan) -> Result<i32, LaunchError>;
383}
384
385/// Records plans instead of starting anything; answers `exit_code`.
386#[derive(Debug, Default)]
387pub struct FakeSpawner {
388 pub plans: Vec<LaunchPlan>,
389 pub exit_code: i32,
390}
391
392impl Spawner for FakeSpawner {
393 fn spawn(&mut self, plan: &LaunchPlan) -> Result<i32, LaunchError> {
394 self.plans.push(plan.clone());
395 Ok(self.exit_code)
396 }
397}
398
399/// Plan, prepare the private profile folder, then start `claude` once.
400/// Manual launch may open any Claude Code profile in the rule file; route
401/// rules do not apply here.
402pub fn launch(
403 rules: &RuleTable,
404 alias: &str,
405 inherited: &Env,
406 spawner: &mut dyn Spawner,
407) -> Result<i32, LaunchError> {
408 let plan = plan_launch(rules, alias, inherited)?;
409 prepare_profile_dir(&plan.config_dir)?;
410 spawner.spawn(&plan)
411}
412
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub enum LaunchError {
415 /// No account has this id. `known` lists the Claude Code profiles.
416 UnknownAlias {
417 alias: String,
418 known: Vec<String>,
419 },
420 /// The account exists but is not a Claude Code profile.
421 NotAClaudeProfile {
422 alias: String,
423 },
424 /// The program is not an executable file on the cleaned `PATH`.
425 ExecutableNotFound {
426 program: String,
427 },
428 ProfileDir {
429 path: PathBuf,
430 problem: DirProblem,
431 },
432 /// The operating system refused to start the program.
433 Spawn {
434 program: PathBuf,
435 message: String,
436 },
437}
438
439impl fmt::Display for LaunchError {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 match self {
442 LaunchError::UnknownAlias { alias, known } => {
443 if known.is_empty() {
444 write!(f, "no profile named {alias:?}; the rule file has no Claude Code profiles")
445 } else {
446 write!(f, "no profile named {alias:?}; profiles: {}", known.join(", "))
447 }
448 }
449 LaunchError::NotAClaudeProfile { alias } => write!(
450 f,
451 "{alias:?} is not a Claude Code profile (it needs provider = \"anthropic\", program = \"claude\" and a settings_dir)"
452 ),
453 LaunchError::ExecutableNotFound { program } => {
454 write!(f, "program {program:?} not found as an executable file on PATH")
455 }
456 LaunchError::ProfileDir { path, problem } => {
457 write!(f, "profile folder {} {problem}", path.display())
458 }
459 LaunchError::Spawn { program, message } => {
460 write!(f, "could not start {}: {message}", program.display())
461 }
462 }
463 }
464}
465
466impl std::error::Error for LaunchError {}
467
468/// Keep only absolute entries of a `PATH` value, so neither `claude` nor the
469/// tools it runs search the working folder (empty, `.` or relative entries).
470fn absolute_path_entries(path: &OsStr) -> OsString {
471 let kept: Vec<PathBuf> = std::env::split_paths(path)
472 .filter(|p| p.is_absolute())
473 .collect();
474 std::env::join_paths(kept).unwrap_or_default()
475}
476
477/// Where `path` really points: the nearest existing ancestor resolved
478/// through links, with the not-yet-created rest appended.
479fn resolve(path: &Path) -> PathBuf {
480 let mut rest = Vec::new();
481 let mut cur = path;
482 loop {
483 if let Ok(real) = fs::canonicalize(cur) {
484 return rest.iter().rev().fold(real, |acc, part| acc.join(part));
485 }
486 match (cur.parent(), cur.file_name()) {
487 (Some(parent), Some(name)) => {
488 rest.push(name.to_owned());
489 cur = parent;
490 }
491 _ => return path.to_path_buf(),
492 }
493 }
494}
495
496/// The other account whose settings folder resolves to the same place as
497/// `alias`'s folder, if any. The rule file already refuses identical text and
498/// `..`; this catches links on the way.
499pub fn folder_shared_with(rules: &RuleTable, alias: &str, dir: &Path) -> Option<String> {
500 let mine = resolve(dir);
501 rules.accounts().iter().find_map(|a| match &a.credential {
502 Credential::SettingsFolder(other) if a.id.as_str() != alias && resolve(other) == mine => {
503 Some(a.id.to_string())
504 }
505 _ => None,
506 })
507}