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