Skip to main content

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}
49
50/// Every harness identity this program can sign in, and there is no other.
51///
52/// Each sign-in is the one that harness's own help names: `claude auth login`
53/// ("Sign in to your Anthropic account"), and `codex login` in its device-code
54/// form, which is the one that completes on a machine with no browser — the
55/// board beside a printer is reached over a terminal.
56pub const SIGN_INS: [HarnessSignIn; 2] = [
57    HarnessSignIn {
58        identity: "claude-code",
59        config_env: CLAUDE_IDENTITY_ENV,
60        program: "claude",
61        // 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.
62        arguments: &["auth", "login"],
63        // 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.
64        npm_program: Some("node_modules/@anthropic-ai/claude-code/bin/claude.exe"),
65        // llmlint: ignore[contracts_have_one_source_or_a_drift_gate] See suppressions.toml.
66        session_env: &["DISABLE_AUTOUPDATER=1"],
67    },
68    HarnessSignIn {
69        identity: "codex",
70        config_env: CODEX_IDENTITY_ENV,
71        program: "codex",
72        // 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.
73        arguments: &["login", "--device-auth"],
74        npm_program: None,
75        session_env: &[],
76    },
77];
78
79impl HarnessSignIn {
80    /// The entry for one configured harness, when this program can sign it in.
81    #[must_use]
82    pub fn of(harness: &HarnessIdentity) -> Option<&'static Self> {
83        SIGN_INS
84            .iter()
85            .find(|entry| entry.identity == harness.as_str())
86    }
87
88    /// Every identity this program can sign in, in the order declared.
89    #[must_use]
90    pub fn supported() -> Vec<&'static str> {
91        SIGN_INS.iter().map(|entry| entry.identity).collect()
92    }
93
94    /// The identity, as a configuration selects it.
95    #[must_use]
96    pub const fn identity(&self) -> &'static str {
97        self.identity
98    }
99
100    /// The variable selecting the directory this harness keeps its sign-in in.
101    #[must_use]
102    pub const fn config_env(&self) -> &'static str {
103        self.config_env
104    }
105
106    /// The program `OneHarness` runs for this identity, which is the program
107    /// the sign-in is made with.
108    #[must_use]
109    pub const fn program(&self) -> &'static str {
110        self.program
111    }
112
113    /// What every turn on this harness runs with beyond its sign-in.
114    ///
115    /// # Errors
116    ///
117    /// Returns the [`ConfigError`] of an assignment that is none, which no entry
118    /// of [`SIGN_INS`] is held to writing.
119    pub fn session_assignments(&self) -> Result<Vec<EnvAssignment>, ConfigError> {
120        self.session_env
121            .iter()
122            .map(|assigned| EnvAssignment::new(assigned))
123            .collect()
124    }
125
126    /// The arguments of this harness's own interactive sign-in.
127    #[must_use]
128    pub const fn arguments(&self) -> &'static [&'static str] {
129        self.arguments
130    }
131
132    /// The native program behind npm's launcher, when a search of `path` finds
133    /// that launcher and no program of the harness's own name.
134    ///
135    /// On Windows npm installs a harness as a `.cmd` launcher, and a program
136    /// started by name is looked for as an `.exe` alone, so neither the sign-in
137    /// nor a turn finds it; a batch file would also be refused the multi-line
138    /// prompt a turn passes. The launcher only runs the native program in npm's
139    /// package, so that program is started instead. Elsewhere npm links the
140    /// program under its own name, which the search finds first, and this
141    /// answers `None` — as it does for a launcher whose package is not beside
142    /// it, which is then left to fail by name the way a missing program does.
143    #[must_use]
144    pub fn program_behind_launcher(&self, path: &OsStr) -> Option<PathBuf> {
145        let relative = self.npm_program?;
146        let native = format!("{}{}", self.program, std::env::consts::EXE_SUFFIX);
147        let launcher = format!("{}.cmd", self.program);
148        let mut behind = None;
149        for directory in std::env::split_paths(path) {
150            if directory.join(&native).is_file() {
151                return None;
152            }
153            if behind.is_none() && directory.join(&launcher).is_file() {
154                behind = Some(directory.join(relative)).filter(|program| program.is_file());
155            }
156        }
157        behind
158    }
159
160    /// The program to start for this harness under a search path: the one
161    /// behind npm's launcher where that is all the search finds, and otherwise
162    /// the program by its own name, for the operating system to find.
163    #[must_use]
164    pub fn program_on(&self, path: &OsStr) -> PathBuf {
165        self.program_behind_launcher(path)
166            .unwrap_or_else(|| PathBuf::from(self.program))
167    }
168
169    /// The directory this identity keeps its sign-in in, under one state
170    /// directory.
171    #[must_use]
172    pub fn directory(&self, state_dir: &Path) -> PathBuf {
173        state_dir.join(HARNESS_DIRECTORY).join(self.identity)
174    }
175
176    /// That directory, created where it is not there yet, and readable by its
177    /// owner alone whether it was just created or was already there.
178    ///
179    /// On Unix each level is given mode `0700`. Windows has no modes: a
180    /// directory created there carries the access the state directory grants,
181    /// so on Windows that directory is what keeps the sign-in private.
182    ///
183    /// The state directory is the one this program was configured with, which
184    /// is resolved where it is configured. Below it, each of the two levels is
185    /// created on its own rather than recursively, so neither is ever reached
186    /// through a symlink.
187    ///
188    /// # Errors
189    ///
190    /// Returns [`std::io::ErrorKind::InvalidInput`] when something other than a
191    /// directory is at either level — a symlink included, since a sign-in kept
192    /// through one is kept wherever it points — and the operating system's own
193    /// error when the state directory is not there, or a level cannot be created
194    /// or made private.
195    pub fn prepare(&self, state_dir: &Path) -> std::io::Result<PathBuf> {
196        let directory = self.directory(state_dir);
197        for level in [state_dir.join(HARNESS_DIRECTORY), directory.clone()] {
198            real_directory(&level)?;
199            // Stated on every preparation rather than trusted: a creation mode
200            // is narrowed by the process's own mask, and a directory that was
201            // already there may have been widened since. Only its owner can
202            // change its mode, so a directory another user owns is refused.
203            #[cfg(unix)]
204            std::fs::set_permissions(
205                &level,
206                std::os::unix::fs::PermissionsExt::from_mode(PRIVATE_DIRECTORY),
207            )?;
208        }
209        Ok(directory)
210    }
211
212    /// The assignment that points this harness at one directory.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`ConfigError::EnvAssignmentMalformed`] when the directory's
217    /// path is not text an environment can carry.
218    pub fn assignment(&self, directory: &Path) -> Result<EnvAssignment, ConfigError> {
219        EnvAssignment::new(&format!("{}={}", self.config_env, directory.display()))
220    }
221}
222
223/// The mode each level of a sign-in's directory is kept at, where there are modes.
224#[cfg(unix)]
225const PRIVATE_DIRECTORY: u32 = 0o700;
226
227/// One directory, created with no access for anybody but its owner where it
228/// is not there, and refused where something other than a directory is.
229fn real_directory(path: &Path) -> std::io::Result<()> {
230    match std::fs::symlink_metadata(path) {
231        Ok(found) if found.is_dir() => Ok(()),
232        Ok(_) => Err(std::io::Error::new(
233            std::io::ErrorKind::InvalidInput,
234            format!("{} is something other than a directory", path.display()),
235        )),
236        Err(error) if error.kind() == std::io::ErrorKind::NotFound => create_directory(path),
237        Err(error) => Err(error),
238    }
239}
240
241/// Create one directory, with no access for anybody but its owner.
242#[cfg(unix)]
243fn create_directory(path: &Path) -> std::io::Result<()> {
244    use std::os::unix::fs::DirBuilderExt as _;
245
246    std::fs::DirBuilder::new()
247        .mode(PRIVATE_DIRECTORY)
248        .create(path)
249}
250
251/// Create one directory, carrying the access its parent grants.
252#[cfg(not(unix))]
253fn create_directory(path: &Path) -> std::io::Result<()> {
254    std::fs::create_dir(path)
255}
256
257#[cfg(test)]
258mod tests {
259    use oneharness_core::io::usage::{CLAUDE_IDENTITY_ENV, CODEX_IDENTITY_ENV};
260
261    use super::{HARNESS_DIRECTORY, HarnessSignIn, SIGN_INS};
262    use crate::config::HarnessIdentity;
263
264    /// The table carries the two identities a supervisor is configured with,
265    /// each selected by `OneHarness`'s own variable for it.
266    #[test]
267    fn the_table_carries_claude_code_and_codex_under_oneharnesss_own_variables() {
268        let found: Vec<(&str, &str)> = SIGN_INS
269            .iter()
270            .map(|entry| (entry.identity(), entry.config_env()))
271            .collect();
272
273        assert_eq!(
274            found,
275            vec![
276                ("claude-code", CLAUDE_IDENTITY_ENV),
277                ("codex", CODEX_IDENTITY_ENV)
278            ]
279        );
280    }
281
282    /// Every identity is one `OneHarness` runs, and the program is the one its
283    /// registry names for it — so a registry that renames a program fails here.
284    #[test]
285    fn every_identity_is_one_oneharness_runs() {
286        for entry in &SIGN_INS {
287            let spec = oneharness_core::domain::harness::by_id(entry.identity())
288                .unwrap_or_else(|| panic!("OneHarness runs no `{}`", entry.identity()));
289            assert_eq!(entry.program(), spec.default_bin);
290            assert!(
291                !entry.arguments().is_empty(),
292                "`{}` declares no sign-in",
293                entry.identity()
294            );
295        }
296    }
297
298    /// A configured harness is found by its identity, and one outside the
299    /// table is not.
300    #[test]
301    fn a_harness_outside_the_table_has_no_entry() {
302        let codex = HarnessIdentity::new("codex").expect("an identity");
303        let copilot = HarnessIdentity::new("copilot").expect("an identity");
304
305        assert_eq!(
306            HarnessSignIn::of(&codex).map(HarnessSignIn::identity),
307            Some("codex")
308        );
309        assert_eq!(HarnessSignIn::of(&copilot), None);
310        assert_eq!(HarnessSignIn::supported(), vec!["claude-code", "codex"]);
311    }
312
313    /// The directory is created private under the state directory, and one
314    /// already there keeps what it holds and is made private again.
315    #[test]
316    fn the_directory_is_created_private_under_the_state_directory() {
317        let state = std::env::temp_dir().join(format!(
318            "printobserver-sign-in-{}-{}",
319            std::process::id(),
320            std::time::SystemTime::now()
321                .duration_since(std::time::UNIX_EPOCH)
322                .expect("the clock is past the epoch")
323                .as_nanos()
324        ));
325        let entry = &SIGN_INS[0];
326        std::fs::create_dir_all(&state).expect("a state directory");
327
328        let prepared = entry.prepare(&state).expect("the directory is created");
329
330        assert_eq!(prepared, state.join(HARNESS_DIRECTORY).join("claude-code"));
331        assert!(prepared.is_dir(), "no directory was created");
332        #[cfg(unix)]
333        {
334            let mode = mode_of(&prepared);
335            assert_eq!(mode, 0o700, "the directory is mode {mode:o}");
336        }
337
338        std::fs::write(prepared.join("signed-in"), "kept").expect("the directory is writable");
339        #[cfg(unix)]
340        std::fs::set_permissions(
341            &prepared,
342            std::os::unix::fs::PermissionsExt::from_mode(0o755),
343        )
344        .expect("the directory is widened");
345        let again = entry.prepare(&state).expect("the directory is there");
346        #[cfg(unix)]
347        {
348            let narrowed = mode_of(&again);
349            assert_eq!(
350                narrowed, 0o700,
351                "a widened directory was left mode {narrowed:o}"
352            );
353        }
354        let kept = std::fs::read_to_string(again.join("signed-in"));
355        let assigned = entry.assignment(&again).map(|found| found.to_string());
356
357        // A symlink where a directory belongs is refused rather than followed.
358        let elsewhere = state.join("elsewhere");
359        std::fs::create_dir_all(&elsewhere).expect("a directory to point at");
360        std::fs::create_dir_all(state.join(HARNESS_DIRECTORY)).expect("the harness level");
361        link_directory(&elsewhere, &SIGN_INS[1].directory(&state));
362        let through_a_symlink = SIGN_INS[1].prepare(&state).map_err(|error| error.kind());
363
364        // And one at the level every harness's directory is kept in.
365        let linked_state = state.join("linked-state");
366        std::fs::create_dir_all(&linked_state).expect("a second state directory");
367        link_directory(&elsewhere, &linked_state.join(HARNESS_DIRECTORY));
368        let through_a_linked_level = entry.prepare(&linked_state).map_err(|error| error.kind());
369        std::fs::remove_dir_all(&state).expect("the state directory is removable");
370
371        assert_eq!(kept.expect("what it held is kept"), "kept");
372        assert_eq!(
373            through_a_symlink,
374            Err(std::io::ErrorKind::InvalidInput),
375            "a symlink in the directory's place was prepared"
376        );
377        assert_eq!(
378            through_a_linked_level,
379            Err(std::io::ErrorKind::InvalidInput),
380            "a symlink in the harness level's place was followed"
381        );
382        assert_eq!(
383            assigned.expect("an assignment"),
384            format!("{CLAUDE_IDENTITY_ENV}={}", again.display())
385        );
386    }
387
388    /// A directory's permission bits.
389    #[cfg(unix)]
390    fn mode_of(path: &std::path::Path) -> u32 {
391        use std::os::unix::fs::PermissionsExt as _;
392
393        std::fs::metadata(path)
394            .expect("the directory is there")
395            .permissions()
396            .mode()
397            & 0o777
398    }
399
400    /// A symbolic link to a directory, the way this platform makes one.
401    fn link_directory(target: &std::path::Path, link: &std::path::Path) {
402        #[cfg(unix)]
403        let linked = std::os::unix::fs::symlink(target, link);
404        #[cfg(windows)]
405        let linked = std::os::windows::fs::symlink_dir(target, link);
406        linked.expect("a symlink where a directory belongs");
407    }
408}