printobserver_oneharness/
sign_in.rs1use std::path::{Path, PathBuf};
17
18use oneharness_core::io::usage::{CLAUDE_IDENTITY_ENV, CODEX_IDENTITY_ENV};
19
20use crate::config::{ConfigError, EnvAssignment, HarnessIdentity};
21
22pub const HARNESS_DIRECTORY: &str = "harness";
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct HarnessSignIn {
29 identity: &'static str,
32 config_env: &'static str,
34 program: &'static str,
36 arguments: &'static [&'static str],
38}
39
40pub const SIGN_INS: [HarnessSignIn; 2] = [
47 HarnessSignIn {
48 identity: "claude-code",
49 config_env: CLAUDE_IDENTITY_ENV,
50 program: "claude",
51 arguments: &["auth", "login"],
53 },
54 HarnessSignIn {
55 identity: "codex",
56 config_env: CODEX_IDENTITY_ENV,
57 program: "codex",
58 arguments: &["login", "--device-auth"],
60 },
61];
62
63impl HarnessSignIn {
64 #[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 #[must_use]
74 pub fn supported() -> Vec<&'static str> {
75 SIGN_INS.iter().map(|entry| entry.identity).collect()
76 }
77
78 #[must_use]
80 pub const fn identity(&self) -> &'static str {
81 self.identity
82 }
83
84 #[must_use]
86 pub const fn config_env(&self) -> &'static str {
87 self.config_env
88 }
89
90 #[must_use]
93 pub const fn program(&self) -> &'static str {
94 self.program
95 }
96
97 #[must_use]
99 pub const fn arguments(&self) -> &'static [&'static str] {
100 self.arguments
101 }
102
103 #[must_use]
106 pub fn directory(&self, state_dir: &Path) -> PathBuf {
107 state_dir.join(HARNESS_DIRECTORY).join(self.identity)
108 }
109
110 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 #[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 pub fn assignment(&self, directory: &Path) -> Result<EnvAssignment, ConfigError> {
153 EnvAssignment::new(&format!("{}={}", self.config_env, directory.display()))
154 }
155}
156
157#[cfg(unix)]
159const PRIVATE_DIRECTORY: u32 = 0o700;
160
161fn 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#[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#[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 #[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 #[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 #[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 #[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 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 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 #[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 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}