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