printobserver_oneharness/sign_in.rs
1//! The harness identities this program can sign in, and where each keeps it.
2//!
3//! A harness keeps its configuration and its authentication in one directory,
4//! and one environment variable selects which. The service runs as a system
5//! user with no home and cannot see anybody else's, so every identity here
6//! keeps that directory under the state directory instead — the one place the
7//! service's unit lets it write — and the sign-in command and every supervision
8//! turn are pointed at the same one.
9//!
10//! [`SIGN_INS`] is the whole of what that takes, as data. Each variable is
11//! `OneHarness`'s own constant rather than a spelling of it, and each program
12//! is held by this crate's own tests to the one `OneHarness`'s registry runs
13//! for that identity. Nothing here runs either: the command-line program runs
14//! the sign-in, and `OneHarness` runs the turns.
15
16use std::ffi::OsStr;
17use std::path::{Path, PathBuf};
18
19use oneharness_core::io::usage::{CLAUDE_IDENTITY_ENV, CODEX_IDENTITY_ENV};
20
21use crate::config::{ConfigError, EnvAssignment, HarnessIdentity};
22
23/// The directory under the state directory every identity's own directory is
24/// kept in.
25pub const HARNESS_DIRECTORY: &str = "harness";
26
27/// One harness identity this program can sign in.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct HarnessSignIn {
30 /// The identity, as `OneHarness` names it and a configuration selects it.
31 // llmlint: ignore[invalid_states_unrepresentable] `HarnessIdentity` owns a `String` and cannot be built in a const table. The fields are private, so `SIGN_INS` is the only place an entry is constructed, and this crate's tests hold every identity to one OneHarness's registry runs.
32 identity: &'static str,
33 /// The variable selecting the directory that harness keeps its sign-in in.
34 config_env: &'static str,
35 /// The program `OneHarness` runs for that identity.
36 program: &'static str,
37 /// The arguments of that harness's own interactive sign-in.
38 arguments: &'static [&'static str],
39 /// Where npm's package keeps the native program, relative to the directory
40 /// npm writes the program's `.cmd` launcher into, for a harness npm installs
41 /// as a native program behind that launcher. `None` for one it does not.
42 npm_program: Option<&'static str>,
43 /// What every turn on this harness runs with beyond its sign-in, as
44 /// `NAME=value`: a program that replaces itself while a print is supervised
45 /// leaves the next turn with no program to start.
46 // llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
47 session_env: &'static [&'static str],
48 /// That harness's own command answering whether it is signed in, when
49 /// this program knows one; `None` for a harness it knows none of.
50 status: Option<SignInStatus>,
51}
52
53/// One harness's own command answering whether it is signed in, and the one
54/// field of its answer that says so.
55///
56/// Only that field is ever read. The rest of what the command prints — an
57/// account, an organization, whatever a later release adds — is never kept,
58/// logged or echoed, because a check that repeated it would be a way for the
59/// sign-in's own details to leave the directory it is kept in.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct SignInStatus {
62 /// The command's arguments, after the harness's own program.
63 arguments: &'static [&'static str],
64 /// The top-level field of its JSON answer that is `true` when signed in.
65 signed_in_field: &'static str,
66}
67
68impl SignInStatus {
69 /// The command's arguments, after the harness's own program.
70 #[must_use]
71 pub const fn arguments(&self) -> &'static [&'static str] {
72 self.arguments
73 }
74
75 /// Whether what the command printed says the harness is signed in: the
76 /// declared field when it is a boolean, and `None` when the answer is not
77 /// a JSON object carrying one — which says nothing either way.
78 #[must_use]
79 pub fn signed_in(&self, printed: &str) -> Option<bool> {
80 serde_json::from_str::<serde_json::Value>(printed.trim())
81 .ok()?
82 .get(self.signed_in_field)?
83 .as_bool()
84 }
85}
86
87/// Every harness identity this program can sign in, and there is no other.
88///
89/// Each sign-in is the one that harness's own help names: `claude auth login`
90/// ("Sign in to your Anthropic account"), and `codex login` in its device-code
91/// form, which is the one that completes on a machine with no browser — the
92/// board beside a printer is reached over a terminal.
93pub const SIGN_INS: [HarnessSignIn; 2] = [
94 HarnessSignIn {
95 identity: "claude-code",
96 config_env: CLAUDE_IDENTITY_ENV,
97 program: "claude",
98 // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] A third-party CLI's login command has no machine-readable source: OneHarness declares each harness's program, which the tests hold `program` to, but not its sign-in. This is read from `claude auth login --help`, and a gate drift check would have to install and run the paid provider's CLI.
99 arguments: &["auth", "login"],
100 // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] npm's layout for this package has no machine-readable source: the package's own `bin` entry names `bin/claude.exe`, which its install step replaces with the platform's native program, and the `claude.cmd` launcher npm writes beside `node_modules` runs that file.
101 npm_program: Some("node_modules/@anthropic-ai/claude-code/bin/claude.exe"),
102 // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] See suppressions.toml.
103 session_env: &["DISABLE_AUTOUPDATER=1"],
104 // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] A third-party CLI's status command has no machine-readable source: this is read from `claude auth status --help`, which answers a JSON object whose `loggedIn` says whether it is signed in, and a gate drift check would have to install and run the paid provider's CLI.
105 status: Some(SignInStatus {
106 arguments: &["auth", "status", "--json"],
107 signed_in_field: "loggedIn",
108 }),
109 },
110 HarnessSignIn {
111 identity: "codex",
112 config_env: CODEX_IDENTITY_ENV,
113 program: "codex",
114 // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] A third-party CLI's login command has no machine-readable source: OneHarness declares each harness's program, which the tests hold `program` to, but not its sign-in. This is read from `codex login --help`, and a gate drift check would have to install and run the paid provider's CLI.
115 arguments: &["login", "--device-auth"],
116 npm_program: None,
117 session_env: &[],
118 // No status command this program knows the answer of: whether it is
119 // signed in is then decided by its turn alone.
120 status: None,
121 },
122];
123
124impl HarnessSignIn {
125 /// The entry for one configured harness, when this program can sign it in.
126 #[must_use]
127 pub fn of(harness: &HarnessIdentity) -> Option<&'static Self> {
128 SIGN_INS
129 .iter()
130 .find(|entry| entry.identity == harness.as_str())
131 }
132
133 /// Every identity this program can sign in, in the order declared.
134 #[must_use]
135 pub fn supported() -> Vec<&'static str> {
136 SIGN_INS.iter().map(|entry| entry.identity).collect()
137 }
138
139 /// The identity, as a configuration selects it.
140 #[must_use]
141 pub const fn identity(&self) -> &'static str {
142 self.identity
143 }
144
145 /// The variable selecting the directory this harness keeps its sign-in in.
146 #[must_use]
147 pub const fn config_env(&self) -> &'static str {
148 self.config_env
149 }
150
151 /// The program `OneHarness` runs for this identity, which is the program
152 /// the sign-in is made with.
153 #[must_use]
154 pub const fn program(&self) -> &'static str {
155 self.program
156 }
157
158 /// What every turn on this harness runs with beyond its sign-in.
159 ///
160 /// # Errors
161 ///
162 /// Returns the [`ConfigError`] of an assignment that is none, which no entry
163 /// of [`SIGN_INS`] is held to writing.
164 pub fn session_assignments(&self) -> Result<Vec<EnvAssignment>, ConfigError> {
165 self.session_env
166 .iter()
167 .map(|assigned| EnvAssignment::new(assigned))
168 .collect()
169 }
170
171 /// The arguments of this harness's own interactive sign-in.
172 #[must_use]
173 pub const fn arguments(&self) -> &'static [&'static str] {
174 self.arguments
175 }
176
177 /// This harness's own command answering whether it is signed in, when
178 /// this program knows one.
179 #[must_use]
180 pub const fn status_command(&self) -> Option<&SignInStatus> {
181 self.status.as_ref()
182 }
183
184 /// The native program behind npm's launcher, when a search of `path` finds
185 /// that launcher and no program of the harness's own name.
186 ///
187 /// On Windows npm installs a harness as a `.cmd` launcher, and a program
188 /// started by name is looked for as an `.exe` alone, so neither the sign-in
189 /// nor a turn finds it; a batch file would also be refused the multi-line
190 /// prompt a turn passes. The launcher only runs the native program in npm's
191 /// package, so that program is started instead. Elsewhere npm links the
192 /// program under its own name, which the search finds first, and this
193 /// answers `None` — as it does for a launcher whose package is not beside
194 /// it, which is then left to fail by name the way a missing program does.
195 #[must_use]
196 pub fn program_behind_launcher(&self, path: &OsStr) -> Option<PathBuf> {
197 let relative = self.npm_program?;
198 let native = format!("{}{}", self.program, std::env::consts::EXE_SUFFIX);
199 let launcher = format!("{}.cmd", self.program);
200 let mut behind = None;
201 for directory in std::env::split_paths(path) {
202 if directory.join(&native).is_file() {
203 return None;
204 }
205 if behind.is_none() && directory.join(&launcher).is_file() {
206 behind = Some(directory.join(relative)).filter(|program| program.is_file());
207 }
208 }
209 behind
210 }
211
212 /// The program to start for this harness under a search path: the one
213 /// behind npm's launcher where that is all the search finds, and otherwise
214 /// the program by its own name, for the operating system to find.
215 #[must_use]
216 pub fn program_on(&self, path: &OsStr) -> PathBuf {
217 self.program_behind_launcher(path)
218 .unwrap_or_else(|| PathBuf::from(self.program))
219 }
220
221 /// The directory this identity keeps its sign-in in, under one state
222 /// directory.
223 #[must_use]
224 pub fn directory(&self, state_dir: &Path) -> PathBuf {
225 state_dir.join(HARNESS_DIRECTORY).join(self.identity)
226 }
227
228 /// That directory, created where it is not there yet, and readable by its
229 /// owner alone whether it was just created or was already there.
230 ///
231 /// On Unix each level is given mode `0700`. Windows has no modes: a
232 /// directory created there carries the access the state directory grants,
233 /// so on Windows that directory is what keeps the sign-in private.
234 ///
235 /// The state directory is the one this program was configured with, which
236 /// is resolved where it is configured. Below it, each of the two levels is
237 /// created on its own rather than recursively, so neither is ever reached
238 /// through a symlink.
239 ///
240 /// # Errors
241 ///
242 /// Returns [`std::io::ErrorKind::InvalidInput`] when something other than a
243 /// directory is at either level — a symlink included, since a sign-in kept
244 /// through one is kept wherever it points — and the operating system's own
245 /// error when the state directory is not there, or a level cannot be created
246 /// or made private.
247 pub fn prepare(&self, state_dir: &Path) -> std::io::Result<PathBuf> {
248 let directory = self.directory(state_dir);
249 for level in [state_dir.join(HARNESS_DIRECTORY), directory.clone()] {
250 real_directory(&level)?;
251 // Stated on every preparation rather than trusted: a creation mode
252 // is narrowed by the process's own mask, and a directory that was
253 // already there may have been widened since. Only its owner can
254 // change its mode, so a directory another user owns is refused.
255 #[cfg(unix)]
256 std::fs::set_permissions(
257 &level,
258 std::os::unix::fs::PermissionsExt::from_mode(PRIVATE_DIRECTORY),
259 )?;
260 }
261 Ok(directory)
262 }
263
264 /// The assignment that points this harness at one directory.
265 ///
266 /// # Errors
267 ///
268 /// Returns [`ConfigError::EnvAssignmentMalformed`] when the directory's
269 /// path is not text an environment can carry.
270 pub fn assignment(&self, directory: &Path) -> Result<EnvAssignment, ConfigError> {
271 EnvAssignment::new(&format!("{}={}", self.config_env, directory.display()))
272 }
273}
274
275/// The mode each level of a sign-in's directory is kept at, where there are modes.
276#[cfg(unix)]
277const PRIVATE_DIRECTORY: u32 = 0o700;
278
279/// One directory, created with no access for anybody but its owner where it
280/// is not there, and refused where something other than a directory is.
281fn real_directory(path: &Path) -> std::io::Result<()> {
282 match std::fs::symlink_metadata(path) {
283 Ok(found) if found.is_dir() => Ok(()),
284 Ok(_) => Err(std::io::Error::new(
285 std::io::ErrorKind::InvalidInput,
286 format!("{} is something other than a directory", path.display()),
287 )),
288 Err(error) if error.kind() == std::io::ErrorKind::NotFound => create_directory(path),
289 Err(error) => Err(error),
290 }
291}
292
293/// Create one directory, with no access for anybody but its owner.
294#[cfg(unix)]
295fn create_directory(path: &Path) -> std::io::Result<()> {
296 use std::os::unix::fs::DirBuilderExt as _;
297
298 std::fs::DirBuilder::new()
299 .mode(PRIVATE_DIRECTORY)
300 .create(path)
301}
302
303/// Create one directory, carrying the access its parent grants.
304#[cfg(not(unix))]
305fn create_directory(path: &Path) -> std::io::Result<()> {
306 std::fs::create_dir(path)
307}
308
309#[cfg(test)]
310mod tests {
311 use oneharness_core::io::usage::{CLAUDE_IDENTITY_ENV, CODEX_IDENTITY_ENV};
312
313 use super::{HARNESS_DIRECTORY, HarnessSignIn, SIGN_INS};
314 use crate::config::HarnessIdentity;
315
316 /// The table carries the two identities a supervisor is configured with,
317 /// each selected by `OneHarness`'s own variable for it.
318 #[test]
319 fn the_table_carries_claude_code_and_codex_under_oneharnesss_own_variables() {
320 let found: Vec<(&str, &str)> = SIGN_INS
321 .iter()
322 .map(|entry| (entry.identity(), entry.config_env()))
323 .collect();
324
325 assert_eq!(
326 found,
327 vec![
328 ("claude-code", CLAUDE_IDENTITY_ENV),
329 ("codex", CODEX_IDENTITY_ENV)
330 ]
331 );
332 }
333
334 /// Every identity is one `OneHarness` runs, and the program is the one its
335 /// registry names for it — so a registry that renames a program fails here.
336 #[test]
337 fn every_identity_is_one_oneharness_runs() {
338 for entry in &SIGN_INS {
339 let spec = oneharness_core::domain::harness::by_id(entry.identity())
340 .unwrap_or_else(|| panic!("OneHarness runs no `{}`", entry.identity()));
341 assert_eq!(entry.program(), spec.default_bin);
342 assert!(
343 !entry.arguments().is_empty(),
344 "`{}` declares no sign-in",
345 entry.identity()
346 );
347 }
348 }
349
350 /// A configured harness is found by its identity, and one outside the
351 /// table is not.
352 #[test]
353 fn a_harness_outside_the_table_has_no_entry() {
354 let codex = HarnessIdentity::new("codex").expect("an identity");
355 let copilot = HarnessIdentity::new("copilot").expect("an identity");
356
357 assert_eq!(
358 HarnessSignIn::of(&codex).map(HarnessSignIn::identity),
359 Some("codex")
360 );
361 assert_eq!(HarnessSignIn::of(&copilot), None);
362 assert_eq!(HarnessSignIn::supported(), vec!["claude-code", "codex"]);
363 }
364
365 /// Claude Code is asked its own status command and read for `loggedIn`;
366 /// Codex declares none, so its sign-in is decided by its turn alone.
367 #[test]
368 fn claude_code_declares_its_status_command_and_codex_none() {
369 let claude = SIGN_INS[0]
370 .status_command()
371 .expect("Claude Code declares one");
372 assert_eq!(claude.arguments(), ["auth", "status", "--json"]);
373 assert_eq!(claude.signed_in(r#"{"loggedIn": true}"#), Some(true));
374 assert_eq!(
375 claude.signed_in("{\"loggedIn\": false, \"authMethod\": \"none\"}\n"),
376 Some(false)
377 );
378 assert_eq!(SIGN_INS[1].status_command(), None);
379 }
380
381 /// An answer that is not a JSON object carrying the field as a boolean
382 /// says nothing either way, rather than reading as signed out.
383 #[test]
384 fn an_answer_without_the_field_as_a_boolean_says_nothing() {
385 let claude = SIGN_INS[0]
386 .status_command()
387 .expect("Claude Code declares one");
388 for printed in [
389 "",
390 "Logged in as somebody",
391 r#"{"authMethod": "none"}"#,
392 r#"{"loggedIn": "yes"}"#,
393 r#"[{"loggedIn": true}]"#,
394 ] {
395 assert_eq!(claude.signed_in(printed), None, "{printed:?}");
396 }
397 }
398
399 /// The directory is created private under the state directory, and one
400 /// already there keeps what it holds and is made private again.
401 #[test]
402 fn the_directory_is_created_private_under_the_state_directory() {
403 let state = std::env::temp_dir().join(format!(
404 "printobserver-sign-in-{}-{}",
405 std::process::id(),
406 std::time::SystemTime::now()
407 .duration_since(std::time::UNIX_EPOCH)
408 .expect("the clock is past the epoch")
409 .as_nanos()
410 ));
411 let entry = &SIGN_INS[0];
412 std::fs::create_dir_all(&state).expect("a state directory");
413
414 let prepared = entry.prepare(&state).expect("the directory is created");
415
416 assert_eq!(prepared, state.join(HARNESS_DIRECTORY).join("claude-code"));
417 assert!(prepared.is_dir(), "no directory was created");
418 #[cfg(unix)]
419 {
420 let mode = mode_of(&prepared);
421 assert_eq!(mode, 0o700, "the directory is mode {mode:o}");
422 }
423
424 std::fs::write(prepared.join("signed-in"), "kept").expect("the directory is writable");
425 #[cfg(unix)]
426 std::fs::set_permissions(
427 &prepared,
428 std::os::unix::fs::PermissionsExt::from_mode(0o755),
429 )
430 .expect("the directory is widened");
431 let again = entry.prepare(&state).expect("the directory is there");
432 #[cfg(unix)]
433 {
434 let narrowed = mode_of(&again);
435 assert_eq!(
436 narrowed, 0o700,
437 "a widened directory was left mode {narrowed:o}"
438 );
439 }
440 let kept = std::fs::read_to_string(again.join("signed-in"));
441 let assigned = entry.assignment(&again).map(|found| found.to_string());
442
443 // A symlink where a directory belongs is refused rather than followed.
444 let elsewhere = state.join("elsewhere");
445 std::fs::create_dir_all(&elsewhere).expect("a directory to point at");
446 std::fs::create_dir_all(state.join(HARNESS_DIRECTORY)).expect("the harness level");
447 link_directory(&elsewhere, &SIGN_INS[1].directory(&state));
448 let through_a_symlink = SIGN_INS[1].prepare(&state).map_err(|error| error.kind());
449
450 // And one at the level every harness's directory is kept in.
451 let linked_state = state.join("linked-state");
452 std::fs::create_dir_all(&linked_state).expect("a second state directory");
453 link_directory(&elsewhere, &linked_state.join(HARNESS_DIRECTORY));
454 let through_a_linked_level = entry.prepare(&linked_state).map_err(|error| error.kind());
455 std::fs::remove_dir_all(&state).expect("the state directory is removable");
456
457 assert_eq!(kept.expect("what it held is kept"), "kept");
458 assert_eq!(
459 through_a_symlink,
460 Err(std::io::ErrorKind::InvalidInput),
461 "a symlink in the directory's place was prepared"
462 );
463 assert_eq!(
464 through_a_linked_level,
465 Err(std::io::ErrorKind::InvalidInput),
466 "a symlink in the harness level's place was followed"
467 );
468 assert_eq!(
469 assigned.expect("an assignment"),
470 format!("{CLAUDE_IDENTITY_ENV}={}", again.display())
471 );
472 }
473
474 /// A directory's permission bits.
475 #[cfg(unix)]
476 fn mode_of(path: &std::path::Path) -> u32 {
477 use std::os::unix::fs::PermissionsExt as _;
478
479 std::fs::metadata(path)
480 .expect("the directory is there")
481 .permissions()
482 .mode()
483 & 0o777
484 }
485
486 /// A symbolic link to a directory, the way this platform makes one.
487 fn link_directory(target: &std::path::Path, link: &std::path::Path) {
488 #[cfg(unix)]
489 let linked = std::os::unix::fs::symlink(target, link);
490 #[cfg(windows)]
491 let linked = std::os::windows::fs::symlink_dir(target, link);
492 linked.expect("a symlink where a directory belongs");
493 }
494}