返回 CodeWhale
xai_credentials.rs
根目录 / crates / config / src / xai_credentials.rs
1 //! Naming and cleanup policy for Codewhale-owned xAI OAuth generations.
2 //!
3 //! Config stores only a validated basename. Callers can therefore never turn
4 //! the generation pointer into an arbitrary path read or deletion primitive.
5
6 #[cfg(any(not(unix), test))]
7 use std::fs;
8 use std::fs::File;
9 use std::io::Read as _;
10 use std::path::{Component, Path, PathBuf};
11 #[cfg(not(windows))]
12 use std::sync::atomic::{AtomicU64, Ordering};
13 use std::sync::{Mutex, OnceLock};
14 #[cfg(not(windows))]
15 use std::time::{SystemTime, UNIX_EPOCH};
16
17 use crate::private_directory::validate_owned_file_handle;
18 #[cfg(all(windows, test))]
19 use crate::private_directory::{
20 fail_next_windows_post_persist_validation, normalize_windows_path_for_comparison,
21 verify_windows_owner_only_handle,
22 };
23 use anyhow::{Context, Result, bail};
24
25 pub const XAI_OAUTH_GENERATION_PREFIX: &str = "xai-auth-";
26 pub const XAI_OAUTH_GENERATION_SUFFIX: &str = ".json";
27 pub const LEGACY_XAI_OAUTH_FILE_NAME: &str = "xai-auth.json";
28 pub const CHATGPT_OAUTH_GENERATION_PREFIX: &str = "chatgpt-auth-";
29 pub const CHATGPT_OAUTH_GENERATION_SUFFIX: &str = ".json";
30 pub const LEGACY_CHATGPT_OAUTH_FILE_NAME: &str = "chatgpt-oauth.json";
31 pub const CLAUDE_OAUTH_GENERATION_PREFIX: &str = "claude-auth-";
32 pub const CLAUDE_OAUTH_GENERATION_SUFFIX: &str = ".json";
33 pub const LEGACY_CLAUDE_OAUTH_FILE_NAME: &str = "claude-oauth.json";
34 /// Stable local host and registration metadata, retained across token logout.
35 pub const CHATGPT_HOST_FILE_NAME: &str = "chatgpt-host.json";
36 const XAI_OAUTH_LIFECYCLE_LOCK_FILE_NAME: &str = ".xai-oauth.lock";
37 const XAI_OAUTH_FILE_LIMIT: u64 = 1024 * 1024;
38
39 /// Stable handle to Codewhale's private xAI OAuth directory.
40 ///
41 /// The lexical `$CODEWHALE_HOME/credentials` boundary is retained verbatim.
42 /// Unix opens every component relative to the preceding directory with
43 /// `O_NOFOLLOW`; Windows keeps non-delete-shared handles to every component and
44 /// rejects reparse points. Holding this value therefore pins the directory
45 /// identity for the duration of one lifecycle operation.
46 #[derive(Debug)]
47 pub struct XaiOAuthCredentialStore {
48 directory: PathBuf,
49 private: crate::private_directory::PrivateDirectory,
50 }
51
52 /// Files retired from an active xAI OAuth epoch before a mode switch commits.
53 ///
54 /// Unix hides original names behind private tombstones immediately. Windows
55 /// relies on the lifecycle lock, then deletes exact handles after commit. A
56 /// failed config mutation restores or retains the prior files; a successful
57 /// mutation removes them.
58 #[derive(Debug)]
59 pub struct XaiOAuthRevocation {
60 retired: Vec<(String, String)>,
61 }
62
63 #[must_use]
64 pub fn is_valid_xai_oauth_generation(value: &str) -> bool {
65 is_valid_owned_oauth_generation(
66 value,
67 XAI_OAUTH_GENERATION_PREFIX,
68 XAI_OAUTH_GENERATION_SUFFIX,
69 )
70 }
71
72 pub fn validate_xai_oauth_generation(value: &str) -> Result<&str> {
73 if !is_valid_xai_oauth_generation(value) {
74 bail!(
75 "invalid Codewhale-owned xAI OAuth generation; expected xai-auth-<32 lowercase hex>.json"
76 );
77 }
78 Ok(value)
79 }
80
81 #[must_use]
82 pub fn is_valid_chatgpt_oauth_generation(value: &str) -> bool {
83 is_valid_owned_oauth_generation(
84 value,
85 CHATGPT_OAUTH_GENERATION_PREFIX,
86 CHATGPT_OAUTH_GENERATION_SUFFIX,
87 )
88 }
89
90 pub fn validate_chatgpt_oauth_generation(value: &str) -> Result<&str> {
91 if !is_valid_chatgpt_oauth_generation(value) {
92 bail!(
93 "invalid Codewhale-owned ChatGPT OAuth generation; expected chatgpt-auth-<32 lowercase hex>.json"
94 );
95 }
96 Ok(value)
97 }
98
99 pub fn is_valid_claude_oauth_generation(value: &str) -> bool {
100 is_valid_owned_oauth_generation(
101 value,
102 CLAUDE_OAUTH_GENERATION_PREFIX,
103 CLAUDE_OAUTH_GENERATION_SUFFIX,
104 )
105 }
106
107 fn is_valid_owned_oauth_generation(value: &str, prefix: &str, suffix: &str) -> bool {
108 let path = Path::new(value);
109 if path.components().count() != 1
110 || !matches!(path.components().next(), Some(Component::Normal(_)))
111 || path.file_name().and_then(|name| name.to_str()) != Some(value)
112 {
113 return false;
114 }
115 let Some(id) = value
116 .strip_prefix(prefix)
117 .and_then(|value| value.strip_suffix(suffix))
118 else {
119 return false;
120 };
121 id.len() == 32
122 && id
123 .bytes()
124 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
125 }
126
127 pub fn xai_oauth_credentials_dir() -> Result<PathBuf> {
128 lexical_absolute_path(&crate::codewhale_home()?.join("credentials"))
129 }
130
131 /// Make an owned path absolute without resolving any filesystem component.
132 /// Canonicalization is deliberately forbidden here: following an existing
133 /// `credentials` symlink would erase the lexical Codewhale-owned boundary and
134 /// turn an external directory into an apparently valid destination.
135 fn lexical_absolute_path(path: &Path) -> Result<PathBuf> {
136 let absolute = if path.is_absolute() {
137 path.to_path_buf()
138 } else {
139 std::env::current_dir()
140 .context("resolving the Codewhale credentials directory")?
141 .join(path)
142 };
143 if absolute
144 .components()
145 .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
146 {
147 bail!(
148 "Codewhale credentials directory must be lexically normalized: {}",
149 crate::quote_os_path(&absolute)
150 );
151 }
152 Ok(absolute)
153 }
154
155 pub fn xai_oauth_generation_path(generation: &str) -> Result<PathBuf> {
156 Ok(xai_oauth_credentials_dir()?.join(validate_xai_oauth_generation(generation)?))
157 }
158
159 pub fn legacy_xai_oauth_path() -> Result<PathBuf> {
160 Ok(xai_oauth_credentials_dir()?.join(LEGACY_XAI_OAUTH_FILE_NAME))
161 }
162
163 pub fn chatgpt_oauth_generation_path(generation: &str) -> Result<PathBuf> {
164 Ok(xai_oauth_credentials_dir()?.join(validate_chatgpt_oauth_generation(generation)?))
165 }
166
167 pub fn legacy_chatgpt_oauth_path() -> Result<PathBuf> {
168 Ok(xai_oauth_credentials_dir()?.join(LEGACY_CHATGPT_OAUTH_FILE_NAME))
169 }
170
171 /// Serialize every Codewhale-owned xAI OAuth lifecycle mutation across threads
172 /// and processes while pinning the lexical credentials directory.
173 ///
174 /// Lock order is always xAI lifecycle first, then config document. Callers must
175 /// not invoke this function recursively.
176 pub fn with_xai_oauth_lifecycle_lock<T>(
177 operation: impl FnOnce(&XaiOAuthCredentialStore) -> Result<T>,
178 ) -> Result<T> {
179 static PROCESS_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
180 let _process_guard = PROCESS_LOCK
181 .get_or_init(|| Mutex::new(()))
182 .lock()
183 .map_err(|_| anyhow::anyhow!("xAI OAuth lifecycle lock was poisoned"))?;
184 let store = XaiOAuthCredentialStore::open()?;
185 let lock_file = store.open_lock_file()?;
186 let mut lock = fd_lock::RwLock::new(lock_file);
187 let _guard = lock.write().with_context(|| {
188 format!(
189 "failed to acquire xAI OAuth lifecycle lock in {}",
190 crate::quote_os_path(store.directory())
191 )
192 })?;
193 operation(&store)
194 }
195
196 /// Run an authority mode switch while the prior owned OAuth epoch is hidden
197 /// from concurrent Codewhale readers. A failed authority mutation restores the
198 /// old files; a successful mutation permanently removes them.
199 pub fn with_xai_oauth_revocation_transaction<T>(
200 operation: impl FnOnce() -> Result<T>,
201 ) -> Result<T> {
202 with_xai_oauth_lifecycle_lock(|store| {
203 let revocation = store.stage_revocation()?;
204 match operation() {
205 Ok(value) => {
206 revocation.commit(store).context(
207 "xAI OAuth authority changed, but retired owned credentials could not be removed",
208 )?;
209 Ok(value)
210 }
211 Err(error) => {
212 if let Err(rollback) = revocation.rollback(store) {
213 return Err(error).context(format!(
214 "also failed to restore the prior xAI OAuth epoch: {rollback:#}"
215 ));
216 }
217 Err(error)
218 }
219 }
220 })
221 }
222
223 impl XaiOAuthCredentialStore {
224 fn open() -> Result<Self> {
225 let directory = xai_oauth_credentials_dir()?;
226 open_owned_credentials_directory(&directory)
227 }
228
229 #[must_use]
230 pub fn directory(&self) -> &Path {
231 &self.directory
232 }
233
234 pub fn path_for(&self, name: &str) -> Result<PathBuf> {
235 validate_owned_auth_name(name)?;
236 Ok(self.directory.join(name))
237 }
238
239 pub fn read_to_string(&self, name: &str) -> Result<Option<String>> {
240 validate_owned_auth_name(name)?;
241 let Some(mut file) = self.open_owned_file_for_read(name)? else {
242 return Ok(None);
243 };
244 let metadata =
245 validate_owned_file_handle(&file, &self.directory.join(name), self.private.guard())?;
246 if metadata.len() > XAI_OAUTH_FILE_LIMIT {
247 bail!(
248 "Codewhale-owned xAI OAuth file {} exceeds the {} byte limit",
249 crate::quote_os_path(&self.directory.join(name)),
250 XAI_OAUTH_FILE_LIMIT
251 );
252 }
253 let mut bytes = Vec::with_capacity(metadata.len() as usize);
254 (&mut file)
255 .take(XAI_OAUTH_FILE_LIMIT + 1)
256 .read_to_end(&mut bytes)
257 .with_context(|| {
258 format!(
259 "reading Codewhale-owned xAI OAuth file {}",
260 crate::quote_os_path(&self.directory.join(name))
261 )
262 })?;
263 if bytes.len() as u64 > XAI_OAUTH_FILE_LIMIT {
264 bail!(
265 "Codewhale-owned xAI OAuth file {} exceeds the {} byte limit",
266 crate::quote_os_path(&self.directory.join(name)),
267 XAI_OAUTH_FILE_LIMIT
268 );
269 }
270 String::from_utf8(bytes).map(Some).map_err(|_| {
271 anyhow::anyhow!(
272 "Codewhale-owned xAI OAuth file {} is not valid UTF-8",
273 crate::quote_os_path(&self.directory.join(name))
274 )
275 })
276 }
277
278 pub fn write(&self, name: &str, bytes: &[u8], allow_replace: bool) -> Result<()> {
279 validate_owned_auth_name(name)?;
280 anyhow::ensure!(
281 bytes.len() as u64 <= XAI_OAUTH_FILE_LIMIT,
282 "refusing oversized xAI OAuth credential payload"
283 );
284 self.write_owned_file(name, bytes, allow_replace)
285 }
286
287 pub fn remove(&self, name: &str) -> Result<bool> {
288 validate_owned_auth_name(name)?;
289 self.remove_raw(name)
290 }
291
292 pub fn clear_all(&self) -> Result<usize> {
293 let mut removed = 0;
294 for name in self.owned_auth_names()? {
295 if self.remove(&name)? {
296 removed += 1;
297 }
298 }
299 Ok(removed)
300 }
301
302 pub fn clear_chatgpt(&self) -> Result<usize> {
303 let mut removed = 0;
304 for name in owned_auth_names_for(self, is_chatgpt_owned_auth_name)? {
305 if self.remove(&name)? {
306 removed += 1;
307 }
308 }
309 Ok(removed)
310 }
311
312 pub fn clear_claude(&self) -> Result<usize> {
313 let mut removed = 0;
314 for name in owned_auth_names_for(self, |name| {
315 name == LEGACY_CLAUDE_OAUTH_FILE_NAME || is_valid_claude_oauth_generation(name)
316 })? {
317 if self.remove(&name)? {
318 removed += 1;
319 }
320 }
321 Ok(removed)
322 }
323
324 /// Stage every active owned credential before a config mode switch. The
325 /// generation basename is the OAuth epoch; the lifecycle lock prevents a
326 /// stale Codewhale reader from using it while authority changes.
327 pub fn stage_revocation(&self) -> Result<XaiOAuthRevocation> {
328 #[cfg(windows)]
329 {
330 // Every Codewhale reader/writer takes the lifecycle lock, so a
331 // Windows mode switch can retain the exact active basenames until
332 // the config commit succeeds. `commit` then opens each leaf with
333 // DELETE access and marks that exact handle for deletion. This
334 // avoids path-based rename races and makes rollback a no-op.
335 Ok(XaiOAuthRevocation {
336 retired: self
337 .owned_auth_names()?
338 .into_iter()
339 .map(|name| (name, String::new()))
340 .collect(),
341 })
342 }
343
344 #[cfg(not(windows))]
345 {
346 static COUNTER: AtomicU64 = AtomicU64::new(0);
347 let nonce = SystemTime::now()
348 .duration_since(UNIX_EPOCH)
349 .unwrap_or_default()
350 .as_nanos();
351 let mut retired = Vec::new();
352 for (index, name) in self.owned_auth_names()?.into_iter().enumerate() {
353 let tombstone = format!(
354 ".xai-oauth-retired-{}-{nonce}-{}-{index}.tmp",
355 std::process::id(),
356 COUNTER.fetch_add(1, Ordering::Relaxed)
357 );
358 if let Err(error) = self.rename_raw(&name, &tombstone) {
359 let rollback = XaiOAuthRevocation { retired };
360 if let Err(rollback_error) = rollback.rollback(self) {
361 return Err(error).context(format!(
362 "also failed to restore previously retired xAI OAuth files: {rollback_error:#}"
363 ));
364 }
365 return Err(error);
366 }
367 retired.push((name, tombstone));
368 }
369 Ok(XaiOAuthRevocation { retired })
370 }
371 }
372
373 fn owned_auth_names(&self) -> Result<Vec<String>> {
374 owned_auth_names_in_store(self)
375 }
376
377 fn open_lock_file(&self) -> Result<File> {
378 self.open_internal_file(XAI_OAUTH_LIFECYCLE_LOCK_FILE_NAME)
379 }
380 }
381
382 #[cfg(unix)]
383 fn owned_auth_names_in_store(store: &XaiOAuthCredentialStore) -> Result<Vec<String>> {
384 use std::ffi::CStr;
385 use std::os::fd::AsRawFd as _;
386
387 // `fdopendir` consumes its descriptor, so enumerate through a duplicate of
388 // the pinned directory handle. No pathname is resolved after the store is
389 // opened, even if the lexical directory is renamed or replaced.
390 // SAFETY: duplicates the live store descriptor; CLOEXEC keeps it out of children.
391 let duplicated = unsafe {
392 libc::fcntl(
393 store.private.directory_handle.as_raw_fd(),
394 libc::F_DUPFD_CLOEXEC,
395 0,
396 )
397 };
398 if duplicated < 0 {
399 return Err(std::io::Error::last_os_error())
400 .context("duplicating Codewhale credentials directory handle");
401 }
402 // SAFETY: `duplicated` is an owned directory descriptor. `closedir` below
403 // assumes ownership on the successful conversion.
404 let stream = unsafe { libc::fdopendir(duplicated) };
405 if stream.is_null() {
406 let error = std::io::Error::last_os_error();
407 // SAFETY: `fdopendir` failed and therefore did not consume the fd.
408 unsafe { libc::close(duplicated) };
409 return Err(error).context("enumerating Codewhale credentials directory");
410 }
411 let mut names = Vec::new();
412 loop {
413 // SAFETY: `stream` remains live until `closedir`; each returned entry
414 // is valid until the next call and copied before then.
415 let entry = unsafe { libc::readdir(stream) };
416 if entry.is_null() {
417 break;
418 }
419 // SAFETY: POSIX `dirent::d_name` is NUL terminated.
420 let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) };
421 let Ok(name) = name.to_str() else {
422 continue;
423 };
424 if name == LEGACY_XAI_OAUTH_FILE_NAME || is_valid_xai_oauth_generation(name) {
425 names.push(name.to_string());
426 }
427 }
428 // SAFETY: `stream` is still owned and has not previously been closed.
429 if unsafe { libc::closedir(stream) } != 0 {
430 return Err(std::io::Error::last_os_error())
431 .context("closing Codewhale credentials directory enumeration");
432 }
433 names.sort();
434 Ok(names)
435 }
436
437 #[cfg(unix)]
438 fn owned_auth_names_for(
439 store: &XaiOAuthCredentialStore,
440 accept: fn(&str) -> bool,
441 ) -> Result<Vec<String>> {
442 use std::ffi::CStr;
443 use std::os::fd::AsRawFd as _;
444
445 // SAFETY: duplicates the live store descriptor; CLOEXEC keeps it out of children.
446 let duplicated = unsafe {
447 libc::fcntl(
448 store.private.directory_handle.as_raw_fd(),
449 libc::F_DUPFD_CLOEXEC,
450 0,
451 )
452 };
453 if duplicated < 0 {
454 return Err(std::io::Error::last_os_error())
455 .context("duplicating Codewhale credentials directory handle");
456 }
457 // SAFETY: `duplicated` is an owned directory descriptor. `closedir` below
458 // assumes ownership on the successful conversion.
459 let stream = unsafe { libc::fdopendir(duplicated) };
460 if stream.is_null() {
461 let error = std::io::Error::last_os_error();
462 // SAFETY: `fdopendir` failed and therefore did not consume the fd.
463 unsafe { libc::close(duplicated) };
464 return Err(error).context("enumerating Codewhale credentials directory");
465 }
466 let mut names = Vec::new();
467 loop {
468 // SAFETY: `stream` remains live until `closedir`; each returned entry
469 // is valid until the next call and copied before then.
470 let entry = unsafe { libc::readdir(stream) };
471 if entry.is_null() {
472 break;
473 }
474 // SAFETY: POSIX `dirent::d_name` is NUL terminated.
475 let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) };
476 let Ok(name) = name.to_str() else {
477 continue;
478 };
479 if accept(name) {
480 names.push(name.to_string());
481 }
482 }
483 // SAFETY: `stream` is still owned and has not previously been closed.
484 if unsafe { libc::closedir(stream) } != 0 {
485 return Err(std::io::Error::last_os_error())
486 .context("closing Codewhale credentials directory enumeration");
487 }
488 names.sort();
489 Ok(names)
490 }
491
492 #[cfg(not(unix))]
493 fn owned_auth_names_in_store(store: &XaiOAuthCredentialStore) -> Result<Vec<String>> {
494 let mut names = Vec::new();
495 let entries = fs::read_dir(&store.directory).with_context(|| {
496 format!(
497 "failed to inspect Codewhale credentials directory {}",
498 crate::quote_os_path(&store.directory)
499 )
500 })?;
501 for entry in entries {
502 let entry = entry.with_context(|| {
503 format!(
504 "failed to inspect Codewhale credentials directory {}",
505 crate::quote_os_path(&store.directory)
506 )
507 })?;
508 let name = entry.file_name();
509 let Some(name) = name.to_str() else {
510 continue;
511 };
512 if name == LEGACY_XAI_OAUTH_FILE_NAME || is_valid_xai_oauth_generation(name) {
513 names.push(name.to_string());
514 }
515 }
516 names.sort();
517 Ok(names)
518 }
519
520 #[cfg(not(unix))]
521 fn owned_auth_names_for(
522 store: &XaiOAuthCredentialStore,
523 accept: fn(&str) -> bool,
524 ) -> Result<Vec<String>> {
525 let mut names = Vec::new();
526 let entries = fs::read_dir(&store.directory).with_context(|| {
527 format!(
528 "failed to inspect Codewhale credentials directory {}",
529 crate::quote_os_path(&store.directory)
530 )
531 })?;
532 for entry in entries {
533 let entry = entry.with_context(|| {
534 format!(
535 "failed to inspect Codewhale credentials directory {}",
536 crate::quote_os_path(&store.directory)
537 )
538 })?;
539 let name = entry.file_name();
540 let Some(name) = name.to_str() else {
541 continue;
542 };
543 if accept(name) {
544 names.push(name.to_string());
545 }
546 }
547 names.sort();
548 Ok(names)
549 }
550
551 impl XaiOAuthRevocation {
552 /// Restore the old epoch after a config mutation fails. Restoration is
553 /// fail-closed: an unexpected replacement at an original name is never
554 /// overwritten.
555 pub fn rollback(self, store: &XaiOAuthCredentialStore) -> Result<()> {
556 #[cfg(windows)]
557 {
558 let _ = store;
559 Ok(())
560 }
561 #[cfg(not(windows))]
562 {
563 let mut first_error = None;
564 for (original, tombstone) in self.retired.into_iter().rev() {
565 let result = store.rename_raw(&tombstone, &original).with_context(|| {
566 format!(
567 "restoring retired xAI OAuth file {}",
568 crate::quote_os_path(&store.directory.join(original))
569 )
570 });
571 if result.is_err() && first_error.is_none() {
572 first_error = result.err();
573 }
574 }
575 if let Some(error) = first_error {
576 return Err(error);
577 }
578 Ok(())
579 }
580 }
581
582 /// Permanently remove retired bytes after the replacement config commits.
583 pub fn commit(self, store: &XaiOAuthCredentialStore) -> Result<usize> {
584 let mut removed = 0;
585 for (_original, _tombstone) in self.retired {
586 #[cfg(windows)]
587 let target = _original;
588 #[cfg(not(windows))]
589 let target = _tombstone;
590 if store.remove_raw(&target)? {
591 removed += 1;
592 }
593 }
594 Ok(removed)
595 }
596 }
597
598 fn validate_owned_auth_name(name: &str) -> Result<()> {
599 anyhow::ensure!(
600 name == LEGACY_XAI_OAUTH_FILE_NAME
601 || name == LEGACY_CHATGPT_OAUTH_FILE_NAME
602 || name == CHATGPT_HOST_FILE_NAME
603 || name == LEGACY_CLAUDE_OAUTH_FILE_NAME
604 || is_valid_claude_oauth_generation(name)
605 || is_valid_xai_oauth_generation(name)
606 || is_valid_chatgpt_oauth_generation(name),
607 "invalid Codewhale-owned OAuth basename"
608 );
609 Ok(())
610 }
611
612 fn is_chatgpt_owned_auth_name(name: &str) -> bool {
613 name == LEGACY_CHATGPT_OAUTH_FILE_NAME || is_valid_chatgpt_oauth_generation(name)
614 }
615
616 fn open_owned_credentials_directory(directory: &Path) -> Result<XaiOAuthCredentialStore> {
617 // Sign-in has to work on a filesystem that cannot express ownership, or it
618 // cannot work there at all: HarmonyOS hmdfs reports the logged-in user's
619 // uid and a group-writable mode for every object an app creates and refuses
620 // `chmod`, so the strict proof can never hold. The trusting admission keeps
621 // the no-follow walk, the single-link check and atomic publication, and
622 // relies on the mount's own access control for the rest — the same tradeoff
623 // the file-backed secret store already makes on that mount, with the same
624 // warning.
625 Ok(XaiOAuthCredentialStore {
626 directory: directory.to_path_buf(),
627 private: crate::private_directory::PrivateDirectory::open_trusting_mount(directory)?,
628 })
629 }
630
631 impl XaiOAuthCredentialStore {
632 fn open_owned_file_for_read(&self, name: &str) -> Result<Option<File>> {
633 self.private.open_owned_file_for_read(name)
634 }
635 fn open_internal_file(&self, name: &str) -> Result<File> {
636 self.private.open_internal_file(name)
637 }
638 fn write_owned_file(&self, name: &str, bytes: &[u8], allow_replace: bool) -> Result<()> {
639 self.private.write_owned_file(name, bytes, allow_replace)
640 }
641 fn remove_raw(&self, name: &str) -> Result<bool> {
642 self.private.remove_raw(name)
643 }
644 #[cfg(not(windows))]
645 fn rename_raw(&self, from: &str, to: &str) -> Result<()> {
646 self.private.rename_raw(from, to)
647 }
648 }
649
650 /// Delete one superseded generation after its replacement pointer committed.
651 /// The basename is validated before any filesystem access.
652 pub fn remove_xai_oauth_generation(generation: &str) -> Result<bool> {
653 let generation = validate_xai_oauth_generation(generation)?;
654 with_xai_oauth_lifecycle_lock(|store| store.remove(generation))
655 }
656
657 /// Explicit logout policy: remove the legacy Codewhale-owned file and every
658 /// valid generated xAI OAuth file. Unknown files in the credentials directory
659 /// are never touched.
660 pub fn clear_all_xai_oauth_credentials() -> Result<usize> {
661 with_xai_oauth_lifecycle_lock(XaiOAuthCredentialStore::clear_all)
662 }
663
664 pub fn clear_all_chatgpt_oauth_credentials() -> Result<usize> {
665 with_xai_oauth_lifecycle_lock(XaiOAuthCredentialStore::clear_chatgpt)
666 }
667
668 /// Clears every Codewhale-owned ChatGPT OAuth file without re-entering the
669 /// lifecycle lock. Only for code already running inside
670 /// [`with_xai_oauth_lifecycle_lock`] or [`with_xai_oauth_revocation_transaction`];
671 /// everyone else must call [`clear_all_chatgpt_oauth_credentials`], which
672 /// takes the lock. The lifecycle lock is a non-reentrant in-process mutex, so
673 /// a nested call would deadlock the logout path (seen as CI hangs on the
674 /// `logout_*` tests).
675 pub fn clear_all_chatgpt_oauth_credentials_locked() -> Result<usize> {
676 let store = XaiOAuthCredentialStore::open()?;
677 XaiOAuthCredentialStore::clear_chatgpt(&store)
678 }
679
680 pub fn clear_all_claude_oauth_credentials_locked() -> Result<usize> {
681 XaiOAuthCredentialStore::clear_claude(&XaiOAuthCredentialStore::open()?)
682 }
683
684 pub fn remove_chatgpt_oauth_generation(generation: &str) -> Result<bool> {
685 let generation = validate_chatgpt_oauth_generation(generation)?;
686 with_xai_oauth_lifecycle_lock(|store| store.remove(generation))
687 }
688
689 #[cfg(test)]
690 mod tests {
691 use super::*;
692
693 #[test]
694 fn credentials_directory_preserves_lexical_identity() {
695 let directory = tempfile::tempdir().expect("temp dir");
696 let lexical = directory.path().join("missing").join("credentials");
697 assert_eq!(
698 lexical_absolute_path(&lexical).expect("preserve lexical path"),
699 lexical
700 );
701 assert!(!lexical.exists());
702 assert!(
703 lexical_absolute_path(&directory.path().join("missing/../escape")).is_err(),
704 "owned credential roots must reject traversal components"
705 );
706 }
707
708 #[test]
709 fn generation_names_are_strict_basenames() {
710 let valid = "xai-auth-0123456789abcdef0123456789abcdef.json";
711 assert!(is_valid_xai_oauth_generation(valid));
712 for invalid in [
713 "../xai-auth-0123456789abcdef0123456789abcdef.json",
714 "/tmp/xai-auth-0123456789abcdef0123456789abcdef.json",
715 "xai-auth-0123456789ABCDEF0123456789ABCDEF.json",
716 "xai-auth-short.json",
717 "xai-auth.json",
718 ] {
719 assert!(!is_valid_xai_oauth_generation(invalid), "{invalid}");
720 }
721 let chatgpt = "chatgpt-auth-0123456789abcdef0123456789abcdef.json";
722 assert!(is_valid_chatgpt_oauth_generation(chatgpt));
723 assert!(!is_valid_chatgpt_oauth_generation(valid));
724 assert!(!is_valid_xai_oauth_generation(chatgpt));
725 assert!(!is_valid_chatgpt_oauth_generation(
726 "../chatgpt-auth-0123456789abcdef0123456789abcdef.json"
727 ));
728 }
729
730 #[test]
731 fn logout_cleanup_removes_only_owned_xai_files() {
732 let directory = tempfile::tempdir().expect("temp dir");
733 let directory = directory.path().canonicalize().expect("canonical temp dir");
734 let store = open_owned_credentials_directory(&directory).expect("open store");
735 let generation = "xai-auth-0123456789abcdef0123456789abcdef.json";
736 store
737 .write(generation, b"secret", false)
738 .expect("generation");
739 store
740 .write(LEGACY_XAI_OAUTH_FILE_NAME, b"legacy", false)
741 .expect("legacy");
742 fs::write(directory.join("other-provider.json"), "keep").expect("other provider");
743
744 assert_eq!(store.clear_all().expect("clear"), 2);
745 assert!(directory.join("other-provider.json").exists());
746 assert!(!directory.join(generation).exists());
747 assert!(!directory.join("xai-auth.json").exists());
748 }
749
750 #[test]
751 fn logout_cleanup_removes_chatgpt_files_without_touching_xai() {
752 let directory = tempfile::tempdir().expect("temp dir");
753 let directory = directory.path().canonicalize().expect("canonical temp dir");
754 let store = open_owned_credentials_directory(&directory).expect("open store");
755 let chatgpt = "chatgpt-auth-0123456789abcdef0123456789abcdef.json";
756 let xai = "xai-auth-0123456789abcdef0123456789abcdef.json";
757 store.write(chatgpt, b"chatgpt", false).expect("chatgpt");
758 store.write(xai, b"xai", false).expect("xai");
759 store
760 .write(CHATGPT_HOST_FILE_NAME, b"host", false)
761 .expect("host");
762 store
763 .write(LEGACY_CHATGPT_OAUTH_FILE_NAME, b"legacy", false)
764 .expect("legacy chatgpt");
765
766 assert_eq!(store.clear_chatgpt().expect("clear chatgpt"), 2);
767 assert!(directory.join(xai).exists());
768 assert!(directory.join(CHATGPT_HOST_FILE_NAME).exists());
769 assert!(!directory.join(chatgpt).exists());
770 assert!(!directory.join(LEGACY_CHATGPT_OAUTH_FILE_NAME).exists());
771 }
772
773 #[cfg(unix)]
774 #[test]
775 fn unix_store_pins_directory_identity_across_lexical_path_swap() {
776 use std::os::unix::fs::symlink;
777
778 let root = tempfile::tempdir().expect("temp dir");
779 let root = root.path().canonicalize().expect("canonical temp root");
780 let credentials = root.join("credentials");
781 fs::create_dir(&credentials).expect("credentials");
782 let store = open_owned_credentials_directory(&credentials).expect("open pinned store");
783 let parked = root.join("parked-credentials");
784 let external = root.join("external-owner");
785 fs::create_dir(&external).expect("external directory");
786 fs::rename(&credentials, &parked).expect("park credentials");
787 symlink(&external, &credentials).expect("replace lexical path with symlink");
788
789 let generation = "xai-auth-0123456789abcdef0123456789abcdef.json";
790 store
791 .write(generation, b"pinned bytes", false)
792 .expect("write through pinned directory handle");
793
794 assert_eq!(fs::read(parked.join(generation)).unwrap(), b"pinned bytes");
795 assert!(!external.join(generation).exists());
796 assert_eq!(
797 store.read_to_string(generation).unwrap().as_deref(),
798 Some("pinned bytes")
799 );
800 }
801
802 #[cfg(unix)]
803 #[test]
804 fn unix_store_rejects_symlinked_root_component_and_hardlinked_leaf() {
805 use std::os::unix::fs::symlink;
806
807 let root = tempfile::tempdir().expect("temp dir");
808 let root = root.path().canonicalize().expect("canonical temp root");
809 let real = root.join("real-home");
810 fs::create_dir(&real).expect("real home");
811 let linked = root.join("linked-home");
812 symlink(&real, &linked).expect("home symlink");
813 assert!(
814 open_owned_credentials_directory(&linked.join("credentials")).is_err(),
815 "owned roots must reject every symlink component"
816 );
817
818 let credentials = real.join("credentials");
819 let store = open_owned_credentials_directory(&credentials).expect("safe store");
820 let generation = "xai-auth-fedcba9876543210fedcba9876543210.json";
821 store
822 .write(generation, b"secret", false)
823 .expect("seed generation");
824 fs::hard_link(
825 credentials.join(generation),
826 credentials.join("attacker-hardlink"),
827 )
828 .expect("hardlink fixture");
829 assert!(
830 store.read_to_string(generation).is_err(),
831 "owned reads must reject multiply-linked credential files"
832 );
833 }
834
835 #[cfg(windows)]
836 #[test]
837 fn windows_owned_path_identity_is_case_insensitive_and_lossless() {
838 use std::ffi::OsString;
839 use std::os::windows::ffi::OsStringExt as _;
840
841 assert_eq!(
842 normalize_windows_path_for_comparison(Path::new(r"C:\Users\Alice\Credentials"))
843 .unwrap(),
844 normalize_windows_path_for_comparison(Path::new(r"\\?\c:\users\ALICE\credentials"))
845 .unwrap()
846 );
847 let invalid = PathBuf::from(OsString::from_wide(&[
848 b'C' as u16,
849 b':' as u16,
850 b'\\' as u16,
851 0xd800,
852 ]));
853 assert!(normalize_windows_path_for_comparison(&invalid).is_err());
854 }
855
856 #[cfg(windows)]
857 #[test]
858 fn windows_post_persist_failure_exact_deletes_new_and_replacement_generations() {
859 fn assert_directory_empty(path: &Path) {
860 let entries = fs::read_dir(path)
861 .expect("read credentials directory")
862 .collect::<std::io::Result<Vec<_>>>()
863 .expect("read credential entries");
864 assert!(
865 entries.is_empty(),
866 "rejected credential bytes must leave no durable file: {entries:?}"
867 );
868 }
869
870 let root = tempfile::tempdir().expect("temp dir");
871 let root = root.path().canonicalize().expect("canonical temp root");
872 let credentials = root.join("new-credentials");
873 let store = open_owned_credentials_directory(&credentials).expect("open secure store");
874 let generation = "xai-auth-0123456789abcdef0123456789abcdef.json";
875 let generation_path = credentials.join(generation);
876 fail_next_windows_post_persist_validation(&generation_path);
877 let error = store
878 .write(generation, b"new credential bytes", false)
879 .expect_err("post-persist validation must fail");
880 assert!(error.to_string().contains("injected post-persistence"));
881 assert_directory_empty(&credentials);
882
883 let replacement_credentials = root.join("replacement-credentials");
884 let replacement_store = open_owned_credentials_directory(&replacement_credentials)
885 .expect("open replacement store");
886 let replacement_path = replacement_credentials.join(generation);
887 replacement_store
888 .write(generation, b"prior credential bytes", false)
889 .expect("seed prior generation");
890 fail_next_windows_post_persist_validation(&replacement_path);
891 let error = replacement_store
892 .write(generation, b"replacement credential bytes", true)
893 .expect_err("replacement validation must fail");
894 assert!(error.to_string().contains("injected post-persistence"));
895 assert!(
896 !replacement_path.exists(),
897 "a rejected replacement deliberately fails closed instead of restoring by path"
898 );
899 assert_directory_empty(&replacement_credentials);
900 }
901
902 #[cfg(windows)]
903 #[test]
904 fn windows_store_secures_every_new_owned_object_for_the_current_user() {
905 let root = tempfile::tempdir().expect("temp dir");
906 let root = root.path().canonicalize().expect("canonical temp root");
907 let credentials = root.join("credentials");
908 let store = open_owned_credentials_directory(&credentials).expect("open secure store");
909
910 let directory = store
911 .private
912 ._component_handles
913 .last()
914 .expect("final credentials directory handle");
915 verify_windows_owner_only_handle(directory).expect("current-user-only directory");
916
917 let lock = store.open_lock_file().expect("create lifecycle lock");
918 validate_owned_file_handle(
919 &lock,
920 &credentials.join(XAI_OAUTH_LIFECYCLE_LOCK_FILE_NAME),
921 store.private.guard(),
922 )
923 .expect("current-user-only lifecycle lock");
924
925 let generation = "xai-auth-0123456789abcdef0123456789abcdef.json";
926 store
927 .write(generation, b"credential bytes", false)
928 .expect("write secure generation");
929 let generation_file = store
930 .open_owned_file_for_read(generation)
931 .expect("open generation")
932 .expect("generation exists");
933 validate_owned_file_handle(
934 &generation_file,
935 &credentials.join(generation),
936 store.private.guard(),
937 )
938 .expect("current-user-only generation");
939 }
940
941 #[cfg(windows)]
942 #[test]
943 fn windows_store_rejects_reparse_component_and_hardlinked_leaf() {
944 let root = tempfile::tempdir().expect("temp dir");
945 let root = root.path().canonicalize().expect("canonical temp root");
946 let real = root.join("real-home");
947 fs::create_dir(&real).expect("real home");
948 let linked = root.join("linked-home");
949 if std::os::windows::fs::symlink_dir(&real, &linked).is_ok() {
950 assert!(
951 open_owned_credentials_directory(&linked.join("credentials")).is_err(),
952 "owned roots must reject junctions and directory reparse points"
953 );
954 }
955
956 let credentials = real.join("credentials");
957 let store = open_owned_credentials_directory(&credentials).expect("safe store");
958 let generation = "xai-auth-fedcba9876543210fedcba9876543210.json";
959 store
960 .write(generation, b"secret", false)
961 .expect("seed generation");
962 fs::hard_link(
963 credentials.join(generation),
964 credentials.join("attacker-hardlink"),
965 )
966 .expect("hardlink fixture");
967 assert!(
968 store.read_to_string(generation).is_err(),
969 "owned reads must reject multiply-linked credential files"
970 );
971 }
972 }
973
973 lines RUST