1use super::{Error, Readied, Result, Settled, identify_document, nothing_signed_in, purge};
15use crate::api::Owner;
16use crate::context::Context;
17use crate::provider::{self, ProviderId};
18use crate::service::Warning;
19use crate::state::{Account, Key, Park, State};
20use crate::{home, lock, park, state, store};
21use serde_json::{Value, json};
22use std::fs::{File, OpenOptions, TryLockError};
23use std::os::unix::fs::OpenOptionsExt;
24use std::path::PathBuf;
25
26#[derive(Debug)]
27pub enum Enrolled {
28 Current { email: String },
30 SignedIn { email: String },
32 Renewed { email: String },
34 InUse { email: String, again: bool },
38}
39
40pub struct SignIn {
43 provider: ProviderId,
44 dir: PathBuf,
45 document: Value,
46 ctx: Context,
47 _one_at_a_time: File,
48}
49
50impl SignIn {
51 pub fn provider(&self) -> ProviderId {
53 self.provider
54 }
55}
56
57impl Drop for SignIn {
58 fn drop(&mut self) {
59 provider::of(self.provider).discard_signin(&self.ctx, &self.dir);
60 let _ = std::fs::remove_dir_all(&self.dir);
61 }
62}
63
64fn reserve_signin(ctx: &Context, which: ProviderId) -> Result<SignIn> {
70 let home = home::ensure(ctx).map_err(|source| Error::HomeUnwritable {
71 path: home::dir(ctx),
72 source,
73 })?;
74 let lock_path = home.join("signin.lock");
75 let one_at_a_time = OpenOptions::new()
76 .create(true)
77 .truncate(false)
78 .write(true)
79 .mode(0o600)
80 .open(&lock_path)
81 .map_err(|source| Error::HomeUnwritable {
82 path: lock_path.clone(),
83 source,
84 })?;
85 match one_at_a_time.try_lock() {
86 Ok(()) => {}
87 Err(TryLockError::WouldBlock) => return Err(Error::SignInInProgress),
88 Err(TryLockError::Error(source)) => {
89 return Err(Error::HomeUnwritable {
90 path: lock_path,
91 source,
92 });
93 }
94 }
95
96 let dir = home.join("signin");
97 for &tool in ProviderId::ALL {
103 provider::of(tool).discard_signin(ctx, &dir);
104 }
105 let _ = std::fs::remove_dir_all(&dir);
106 home::create_private(&dir).map_err(|source| Error::HomeUnwritable {
107 path: dir.clone(),
108 source,
109 })?;
110 Ok(SignIn {
111 provider: which,
112 dir,
113 document: Value::Null,
114 ctx: ctx.clone(),
115 _one_at_a_time: one_at_a_time,
116 })
117}
118
119#[cfg(test)]
122pub(super) fn planted(ctx: &Context, which: ProviderId, document: Value) -> Result<SignIn> {
123 let mut pending = reserve_signin(ctx, which)?;
124 pending.document = document;
125 Ok(pending)
126}
127
128pub fn sign_in(ctx: &Context, which: ProviderId) -> Result<SignIn> {
131 let mut pending = reserve_signin(ctx, which)?;
132 let finished = provider::of(which)
135 .sign_in(ctx, &pending.dir)
136 .stdout(std::io::stderr())
137 .status()
138 .map_err(|e| started(which, e))?
139 .success();
140 if !finished {
141 return Err(Error::SignInIncomplete);
142 }
143 pending.document = signed_in_document(ctx, which, &pending.dir)?;
144 Ok(pending)
145}
146
147fn started(which: ProviderId, e: std::io::Error) -> Error {
148 match e.kind() {
149 std::io::ErrorKind::NotFound => Error::ProgramNotFound { tool: which },
150 _ => Error::SignInIncomplete,
151 }
152}
153
154fn signed_in_document(ctx: &Context, which: ProviderId, dir: &std::path::Path) -> Result<Value> {
155 let raw = provider::of(which)
156 .read_signin(ctx, dir)?
157 .ok_or(Error::SignInIncomplete)?;
158 serde_json::from_str(&raw).map_err(|e| Error::LiveCredentialShapeUnexpected {
159 tool: which,
160 detail: e.to_string(),
161 })
162}
163
164pub struct WatchedSignIn {
168 child: std::process::Child,
169 said: Said,
170 pending: SignIn,
171}
172
173#[derive(Clone)]
180pub struct Said(std::sync::Arc<std::sync::Mutex<std::sync::mpsc::Receiver<String>>>);
181
182impl Said {
183 pub fn next(&self) -> Option<String> {
186 self.0.lock().ok()?.recv().ok()
187 }
188}
189
190impl WatchedSignIn {
191 pub fn provider(&self) -> ProviderId {
193 self.pending.provider
194 }
195
196 pub fn said(&self) -> Said {
199 self.said.clone()
200 }
201
202 pub fn paste(&mut self, line: &str) -> Result<()> {
205 use std::io::Write;
206 let stdin = self.child.stdin.as_mut().ok_or(Error::SignInIncomplete)?;
207 writeln!(stdin, "{line}").map_err(|_| Error::SignInIncomplete)?;
208 stdin.flush().map_err(|_| Error::SignInIncomplete)
209 }
210
211 pub fn finish(mut self) -> Result<SignIn> {
213 let finished = self
214 .child
215 .wait()
216 .map_err(|_| Error::SignInIncomplete)?
217 .success();
218 if !finished {
219 return Err(Error::SignInIncomplete);
220 }
221 let mut pending = self.pending;
222 pending.document =
223 signed_in_document(&pending.ctx.clone(), pending.provider, &pending.dir.clone())?;
224 Ok(pending)
225 }
226
227 pub fn cancel(mut self) {
229 let _ = self.child.kill();
230 let _ = self.child.wait();
231 }
232}
233
234pub fn sign_in_watched(ctx: &Context, which: ProviderId) -> Result<WatchedSignIn> {
236 let pending = reserve_signin(ctx, which)?;
237 let command = provider::of(which).sign_in(ctx, &pending.dir);
238 watch(command, pending).map_err(|e| started(which, e))
239}
240
241fn watch(mut command: std::process::Command, pending: SignIn) -> std::io::Result<WatchedSignIn> {
243 let mut child = command
244 .stdin(std::process::Stdio::piped())
245 .stdout(std::process::Stdio::piped())
246 .stderr(std::process::Stdio::piped())
247 .spawn()?;
248 let (say, said) = std::sync::mpsc::channel();
249 for stream in [
253 child.stdout.take().map(Readable::Out),
254 child.stderr.take().map(Readable::Err),
255 ]
256 .into_iter()
257 .flatten()
258 {
259 let say = say.clone();
260 std::thread::spawn(move || {
261 use std::io::Read;
262 let mut reader: Box<dyn Read + Send> = match stream {
263 Readable::Out(o) => Box::new(o),
264 Readable::Err(e) => Box::new(e),
265 };
266 let mut buffer = [0_u8; 1024];
267 while let Ok(read) = reader.read(&mut buffer) {
268 if read == 0 {
269 break;
270 }
271 let text = String::from_utf8_lossy(&buffer[..read]).into_owned();
272 if say.send(text).is_err() {
273 break;
274 }
275 }
276 });
277 }
278 Ok(WatchedSignIn {
279 child,
280 said: Said(std::sync::Arc::new(std::sync::Mutex::new(said))),
281 pending,
282 })
283}
284
285enum Readable {
286 Out(std::process::ChildStdout),
287 Err(std::process::ChildStderr),
288}
289
290pub fn enroll(
293 settled: Settled,
294 key: &Key,
295 signed_in: Option<SignIn>,
296) -> Result<(Enrolled, Vec<Warning>)> {
297 let Settled {
298 _exclusive,
299 mut state,
300 ctx,
301 } = settled;
302 match signed_in {
303 Some(login) if login.provider != key.provider => Err(Error::Usage(format!(
306 "that sign-in was {}'s, and `{key}` is a {} account",
307 login.provider.name(),
308 key.provider.name()
309 ))),
310 Some(login) => from_sign_in(&ctx, key, &mut state, &login),
311 None => record_current(&ctx, key, &mut state).map(|e| (e, Vec::new())),
312 }
313}
314
315fn claim(state: &State, key: &Key, owner: &Owner) -> Result<()> {
318 if let Some(taken) = state.get(key)
319 && taken.account_uuid != owner.account_uuid
320 {
321 return Err(Error::LabelTaken {
322 label: key.typed(),
323 email: taken.email.clone(),
324 });
325 }
326 if let Some(existing) = state.by_uuid(key.provider, &owner.account_uuid)
327 && existing.label != key.label
328 {
329 return Err(Error::AlreadyEnrolled {
330 tool: key.provider,
331 email: owner.email.clone(),
332 label: existing.key().typed(),
333 });
334 }
335 Ok(())
336}
337
338fn record_current(ctx: &Context, key: &Key, state: &mut State) -> Result<Enrolled> {
339 let which = key.provider;
340 let label = key.label.as_str();
341 let store = super::live_store(ctx, which)?;
344 let live =
345 store::read(&store.chain, &store.service)?.ok_or_else(|| nothing_signed_in(ctx, which))?;
346 match provider::of(which).slice(&live) {
349 Err(provider::ProviderError::NoLogin { .. }) => return Err(nothing_signed_in(ctx, which)),
350 Err(other) => return Err(super::shape(which, other)),
351 Ok(_) => {}
352 }
353 let owner = identify_document(ctx, which, &live)?;
354 claim(state, key, &owner)?;
355 let existing = state.get(key);
356 let parked = existing.and_then(|a| a.parked.clone());
357 let last_used_at = Some(ctx.now());
359 state.upsert(account(which, label, &owner, parked, last_used_at, &live));
360 state.set_active(which, Some(label.to_string()));
361 state::save(ctx, state)?;
362 Ok(Enrolled::Current { email: owner.email })
363}
364
365fn from_sign_in(
372 ctx: &Context,
373 key: &Key,
374 state: &mut State,
375 login: &SignIn,
376) -> Result<(Enrolled, Vec<Warning>)> {
377 let owner = identify_document(ctx, login.provider, &login.document)?;
378 claim(state, key, &owner)?;
379 match signed_in_now(ctx, key.provider, &owner) {
380 InUse::Theirs(live, first) => {
381 install_signed_in(ctx, key, state, login, &owner, &live, &first)
382 }
383 InUse::NotTheirs => park_signed_in(ctx, key, state, login, &owner),
384 InUse::Untold(why) => {
385 let last_in_use = state.active_for(key.provider) == Some(key.label.as_str());
388 let (enrolled, mut warnings) = park_signed_in(ctx, key, state, login, &owner)?;
389 if last_in_use {
390 warnings.push(Warning::SignInParkedNotInUse {
391 tool: key.provider,
392 label: state.typed(key),
393 why: untold(&why),
394 });
395 }
396 Ok((enrolled, warnings))
397 }
398 }
399}
400
401enum InUse {
406 Theirs(provider::LiveStore, Value),
408 NotTheirs,
410 Untold(Error),
412}
413
414fn signed_in_now(ctx: &Context, which: ProviderId, owner: &Owner) -> InUse {
415 let read = super::live_store(ctx, which)
416 .and_then(|live| super::read_live(ctx, which, &live).map(|(_, first)| (live, first)));
417 let (live, first) = match read {
418 Ok(read) => read,
419 Err(Error::LiveCredentialAbsent { .. }) => return InUse::NotTheirs,
420 Err(other) => return InUse::Untold(other),
421 };
422 match identify_document(ctx, which, &first) {
423 Ok(found) if found.account_uuid == owner.account_uuid => InUse::Theirs(live, first),
424 Ok(_) => InUse::NotTheirs,
425 Err(e) => InUse::Untold(e),
426 }
427}
428
429fn untold(error: &Error) -> String {
432 match error {
433 Error::SessionExpired { tool } => format!("{} refused its access token", tool.service()),
434 Error::IdentityUnverifiable { detail, .. }
435 | Error::LiveCredentialShapeUnexpected { detail, .. } => detail.clone(),
436 Error::LiveStoreUnsupported { reason, .. } => reason.clone(),
437 Error::LiveCredentialElsewhere { email } => {
438 format!("its config names {email}, and pitboard cannot find that login")
439 }
440 Error::Store(e) => e.to_string(),
441 other => other.code().replace('_', " "),
442 }
443}
444
445fn install_signed_in(
450 ctx: &Context,
451 key: &Key,
452 state: &mut State,
453 login: &SignIn,
454 owner: &Owner,
455 live: &provider::LiveStore,
456 first: &Value,
457) -> Result<(Enrolled, Vec<Warning>)> {
458 let which = key.provider;
459 let name = state.typed(key);
460 let not_kept = |detail: String| Error::SignInNotKept {
463 tool: which,
464 label: name.clone(),
465 detail,
466 };
467 let slice = provider::of(which)
468 .slice(&login.document)
469 .map_err(|e| super::shape(which, e))?;
470 let Readied {
471 guard,
472 before_raw,
473 next,
474 on_the_command_line,
475 ..
476 } = super::ready(ctx, which, live, first, &owner.account_uuid, &slice, &name).map_err(|e| {
477 match e {
478 Error::SignedInAccountChanged => not_kept(format!(
479 "{} was signed in to another account meanwhile",
480 which.name()
481 )),
482 other => other,
483 }
484 })?;
485
486 let written = on_the_command_line.into_iter().collect::<Vec<_>>();
487 match super::install_with(
488 which,
489 |body| store::write_raw(&live.chain, &live.service, body),
490 || store::read_raw(&live.chain, &live.service),
491 &next,
492 &before_raw,
493 &name,
494 &name,
495 ) {
496 Ok(()) => {}
497 Err(Error::SwitchRolledBack { detail, .. }) => return Err(not_kept(detail)),
499 Err(Error::SwitchUnverified { detail, .. } | Error::SwitchCorrupted { detail, .. }) => {
500 return Err(not_installed(
501 ctx, key, state, login, owner, detail, written,
502 ));
503 }
504 Err(other) => return Err(other),
505 }
506 crate::fault::point("enroll.installed");
507
508 let lock_lost = guard.as_ref().is_some_and(lock::Guard::compromised);
510 let lost = match super::holds(which, live) {
511 Ok(true) => None,
512 Ok(false) => Some("it was gone again before pitboard finished".to_string()),
513 Err(unreadable) => Some(unreadable.to_string()),
514 };
515 if let Some(detail) = lost {
516 return Err(not_installed(
517 ctx, key, state, login, owner, detail, written,
518 ));
519 }
520
521 let again = state.get(key).is_some();
522 let parked = state.get(key).and_then(|a| a.parked.clone());
523 state.upsert(account(
524 which,
525 &key.label,
526 owner,
527 parked,
528 Some(ctx.now()),
529 &login.document,
530 ));
531 state.set_active(which, Some(key.label.clone()));
532 state::save(ctx, state)?;
533 crate::fault::point("enroll.recorded");
534 drop(guard);
535
536 let still_running =
539 super::still_holding(ctx, which).map(|holding| Warning::SessionsKeepTheOldLogin {
540 label: name.clone(),
541 holding,
542 });
543 let warnings = written
544 .into_iter()
545 .chain(still_running)
546 .chain(lock_lost.then_some(Warning::LockCompromised { tool: which }))
547 .collect();
548 Ok((
549 Enrolled::InUse {
550 email: owner.email.clone(),
551 again,
552 },
553 warnings,
554 ))
555}
556
557fn not_installed(
566 ctx: &Context,
567 key: &Key,
568 state: &mut State,
569 login: &SignIn,
570 owner: &Owner,
571 detail: String,
572 mut warnings: Vec<Warning>,
573) -> Error {
574 let parked = match park_signed_in(ctx, key, state, login, owner) {
575 Ok((_, parking)) => {
576 warnings.extend(parking);
577 true
578 }
579 Err(_) => false,
580 };
581 Error::SignInNotInstalled {
582 tool: key.provider,
583 label: state.typed(key),
584 detail,
585 parked,
586 warnings,
587 }
588}
589
590fn park_signed_in(
591 ctx: &Context,
592 key: &Key,
593 state: &mut State,
594 login: &SignIn,
595 owner: &Owner,
596) -> Result<(Enrolled, Vec<Warning>)> {
597 let label = key.label.as_str();
598 let slice = provider::of(login.provider)
599 .slice(&login.document)
600 .map_err(|e| super::shape(login.provider, e))?;
601 let parking = park::price(
602 ctx,
603 login.provider,
604 &key.typed(),
605 &park::service_name(&owner.account_uuid, ctx.now_millis()),
606 &slice,
607 )?;
608 let service = park::reserve(ctx, &owner.account_uuid)?;
609 let fresh = park::store_at(ctx, key.provider, &service, &slice)?;
610 crate::fault::point("enroll.park_stored");
613 let existing = state.get(key);
614 let previous = existing.and_then(|a| a.parked.clone());
615 let renewed = existing.is_some();
616 let last_used_at = existing.and_then(|a| a.last_used_at);
617 state.upsert(account(
618 login.provider,
619 label,
620 owner,
621 previous,
622 last_used_at,
623 &login.document,
624 ));
625 state.park(key, fresh);
626 state::save(ctx, state).inspect_err(|_| {
628 let _ = store::vault_delete(ctx, &service);
629 })?;
630 crate::fault::point("enroll.park_recorded");
631 purge(ctx, state);
632 let email = owner.email.clone();
633 let enrolled = if renewed {
634 Enrolled::Renewed { email }
635 } else {
636 Enrolled::SignedIn { email }
637 };
638 Ok((enrolled, parking.into_iter().collect()))
639}
640
641fn account(
648 which: ProviderId,
649 label: &str,
650 owner: &Owner,
651 parked: Option<Park>,
652 last_used_at: Option<i64>,
653 login: &Value,
654) -> Account {
655 let detail = match which {
656 ProviderId::Claude => state::Detail::Claude {
657 organization_uuid: owner.organization_uuid.clone(),
658 oauth_account: json!({
659 "accountUuid": owner.account_uuid,
660 "emailAddress": owner.email,
661 "organizationUuid": owner.organization_uuid,
662 }),
663 },
664 ProviderId::Codex => {
665 let claims = login["tokens"]["id_token"]
666 .as_str()
667 .and_then(crate::provider::jwt::claims)
668 .unwrap_or(Value::Null);
669 let openai = "https://api.openai.com/auth";
670 state::Detail::Codex {
671 workspace_id: Some(owner.organization_uuid.clone()).filter(|id| !id.is_empty()),
672 plan: crate::provider::jwt::claim(&claims, &[openai, "chatgpt_plan_type"])
673 .map(str::to_owned),
674 }
675 }
676 };
677 Account {
678 last_used_at,
679 label: label.to_string(),
680 account_uuid: owner.account_uuid.clone(),
681 email: owner.email.clone(),
682 parked,
683 detail,
684 }
685}
686
687#[cfg(test)]
688mod tests {
689 use super::*;
690 use crate::api::scripted::Trouble;
691 use crate::store::memory::Fault;
692 use crate::switch::harness::{
693 Machine, NOW, codex_id, codex_login, codex_machine, hold, login_of, machine, oauth, renews,
694 signed_in,
695 };
696 use crate::switch::{Due, Outcome, renew_due, settle, switch};
697 use crate::time::FixedClock;
698 use std::sync::Arc;
699 use std::time::{Duration, Instant};
700
701 type Make = fn(&str) -> Machine;
702 const MACHINES: [(&str, Make); 2] = [("claude", machine), ("codex", codex_machine)];
704
705 fn in_use(m: &Machine, refresh: &str) -> bool {
707 m.live().is_some_and(|live| {
708 provider::of(m.which).fingerprint(&live) == store::fingerprint(refresh)
709 })
710 }
711
712 fn enrolled_as(m: &Machine, label: &str, login: SignIn) -> Result<(Enrolled, Vec<Warning>)> {
714 let settled = settle(&m.ctx, Some(m.which)).expect("nothing to recover").0;
715 enroll(settled, &m.key(label), Some(login))
716 }
717
718 fn park_of(m: &Machine, label: &str) -> Option<Park> {
719 state::load(&m.ctx)
720 .expect("state")
721 .get(&m.key(label))
722 .and_then(|a| a.parked.clone())
723 }
724
725 #[test]
729 fn signing_in_again_to_the_account_in_use_puts_the_new_login_in_use() {
730 for (tool, make) in MACHINES {
731 let m = make("again-in-use");
732 let vault = m.mem.vault().services();
733
734 let (enrolled, _) = enrolled_as(&m, "here", signed_in(&m, "here", "here-refresh-2"))
735 .unwrap_or_else(|e| panic!("{tool}: {e}"));
736
737 assert!(
738 matches!(
739 enrolled,
740 Enrolled::InUse { ref email, again: true } if email == "here@example.com"
741 ),
742 "{tool}: {enrolled:?}"
743 );
744 assert!(
745 in_use(&m, "here-refresh-2"),
746 "{tool}: the new login is in use"
747 );
748 assert_eq!(m.mem.vault().services(), vault, "{tool}: nothing is parked");
749 assert!(park_of(&m, "here").is_none(), "{tool}");
750 let state = state::load(&m.ctx).expect("state");
751 assert_eq!(state.active_for(m.which), Some("here"), "{tool}");
752 assert_eq!(
753 state.get(&m.key("here")).and_then(|a| a.last_used_at),
754 Some(NOW),
755 "{tool}: signing in to the account in use is using it"
756 );
757 hold(&m, &format!("{tool}, after signing in again"));
758 }
759 }
760
761 #[test]
764 fn signing_in_again_to_the_account_in_use_keeps_the_park_it_holds() {
765 for (tool, make) in MACHINES {
766 let m = make("again-keeps-park");
767 let (uuid, older) = match m.which {
768 ProviderId::Claude => ("here".to_string(), oauth("here-older", 30)),
769 ProviderId::Codex => (codex_id("here"), codex_login("here", "here-older")),
770 };
771 let service = park::reserve(&m.ctx, &uuid).expect("a free name");
772 let held = park::store_at(&m.ctx, m.which, &service, &older).expect("parked");
773 let mut state = state::load(&m.ctx).expect("state");
774 state.park(&m.key("here"), held.clone());
775 state::save(&m.ctx, &state).expect("saved");
776 let vault = m.mem.vault().services();
777
778 enrolled_as(&m, "here", signed_in(&m, "here", "here-refresh-2"))
779 .unwrap_or_else(|e| panic!("{tool}: {e}"));
780
781 assert!(in_use(&m, "here-refresh-2"), "{tool}");
782 assert_eq!(
783 park_of(&m, "here"),
784 Some(held),
785 "{tool}: the park is untouched"
786 );
787 assert_eq!(m.mem.vault().services(), vault, "{tool}");
788 hold(&m, &format!("{tool}, after signing in again beside a park"));
789 }
790 }
791
792 #[test]
796 fn the_next_switch_away_parks_the_new_login_not_the_old() {
797 for (tool, make) in MACHINES {
798 let m = make("again-then-switch");
799 enrolled_as(&m, "here", signed_in(&m, "here", "here-refresh-2"))
800 .unwrap_or_else(|e| panic!("{tool}: {e}"));
801
802 let settled = settle(&m.ctx, Some(m.which)).expect("nothing to recover").0;
803 let (outcome, _) = switch(settled, &m.key("there"))
804 .unwrap_or_else(|e| panic!("{tool}: the switch away: {e}"));
805 assert!(matches!(outcome, Outcome::Switched { .. }), "{tool}");
806
807 let parked = park_of(&m, "here").expect("the outgoing login is parked");
808 assert_eq!(
809 parked.refresh_fingerprint,
810 store::fingerprint("here-refresh-2"),
811 "{tool}: the new login is parked, not the one it replaced"
812 );
813 hold(&m, &format!("{tool}, after the switch away"));
814 }
815 }
816
817 #[test]
820 fn a_sign_in_of_another_account_is_parked_beside_the_one_in_use() {
821 for (tool, make) in MACHINES {
822 let m = make("another-parked");
823 let live = m.live();
824
825 let (enrolled, _) = enrolled_as(&m, "third", signed_in(&m, "third", "third-refresh"))
826 .unwrap_or_else(|e| panic!("{tool}: {e}"));
827
828 assert!(
829 matches!(enrolled, Enrolled::SignedIn { .. }),
830 "{tool}: {enrolled:?}"
831 );
832 assert_eq!(m.live(), live, "{tool}: the login in use is untouched");
833 assert_eq!(
834 park_of(&m, "third").map(|p| p.refresh_fingerprint),
835 Some(store::fingerprint("third-refresh")),
836 "{tool}"
837 );
838 hold(&m, &format!("{tool}, after another account's sign-in"));
839 }
840 }
841
842 #[test]
847 fn a_login_in_use_whose_account_cannot_be_told_is_not_written_over() {
848 let mut cases: Vec<(String, Machine)> = Vec::new();
849 for (name, trouble) in [
850 ("refused", Trouble::Unauthorized),
851 ("offline", Trouble::Offline),
852 ] {
853 let m = machine(&format!("untold-{name}"));
854 m.api.token_trouble("access-here-refresh", trouble);
855 cases.push((format!("claude, {name}"), m));
856 }
857 let m = codex_machine("untold");
858 let mut unreadable = codex_login("here", "here-refresh");
859 unreadable["tokens"]["id_token"] = "not a token".into();
860 m.sign_in(&unreadable);
861 cases.push(("codex".into(), m));
862
863 for (case, m) in cases {
864 let live = m.live();
865
866 let (enrolled, warnings) =
867 enrolled_as(&m, "here", signed_in(&m, "here", "here-refresh-2"))
868 .unwrap_or_else(|e| panic!("{case}: {e}"));
869
870 assert!(
871 matches!(enrolled, Enrolled::Renewed { .. }),
872 "{case}: {enrolled:?}"
873 );
874 assert_eq!(m.live(), live, "{case}: the login in use is untouched");
875 assert_eq!(
876 park_of(&m, "here").map(|p| p.refresh_fingerprint),
877 Some(store::fingerprint("here-refresh-2")),
878 "{case}: the new login is parked"
879 );
880 let said = warnings
883 .iter()
884 .find(|w| w.code() == "sign_in_parked_not_in_use")
885 .unwrap_or_else(|| panic!("{case}: {warnings:?}"))
886 .to_string();
887 assert!(
888 said.contains("parked the new login for `"),
889 "{case}: {said}"
890 );
891 assert!(
892 said.contains("goes on with the login it has"),
893 "{case}: {said}"
894 );
895 assert!(said.contains("sign in to `"), "{case}: {said}");
896 }
897 }
898
899 #[test]
902 fn a_sign_in_to_a_parked_account_is_not_warned_about_the_login_in_use() {
903 let m = machine("untold-parked");
904 m.api
905 .token_trouble("access-here-refresh", Trouble::Unauthorized);
906
907 let (enrolled, warnings) =
908 enrolled_as(&m, "there", signed_in(&m, "there", "there-refresh-2"))
909 .unwrap_or_else(|e| panic!("{e}"));
910
911 assert!(matches!(enrolled, Enrolled::Renewed { .. }), "{enrolled:?}");
912 assert!(warnings.is_empty(), "{warnings:?}");
913 }
914
915 #[test]
919 fn a_first_sign_in_to_the_account_in_use_enrols_it_with_the_new_login_in_use() {
920 for (tool, make) in MACHINES {
921 let m = make("first-in-use");
922 let mut state = state::load(&m.ctx).expect("state");
923 state.accounts.retain(|a| a.label != "here");
924 state.set_active(m.which, None);
925 state::save(&m.ctx, &state).expect("saved");
926
927 let (enrolled, _) =
928 enrolled_as(&m, "personal", signed_in(&m, "here", "here-refresh-2"))
929 .unwrap_or_else(|e| panic!("{tool}: {e}"));
930
931 assert!(
932 matches!(enrolled, Enrolled::InUse { again: false, .. }),
933 "{tool}: {enrolled:?}"
934 );
935 assert!(in_use(&m, "here-refresh-2"), "{tool}");
936 let state = state::load(&m.ctx).expect("state");
937 assert_eq!(state.active_for(m.which), Some("personal"), "{tool}");
938 hold(&m, &format!("{tool}, after enrolling the account in use"));
939 }
940 }
941
942 #[test]
945 fn the_account_in_use_changing_before_the_write_is_refused_and_nothing_is_written() {
946 for (tool, make) in MACHINES {
947 let m = make("changed-before-write");
948 let key = m.key("here");
949 let login = signed_in(&m, "here", "here-refresh-2");
950 let owner = identify_document(&m.ctx, m.which, &login.document).expect("whose");
951 let InUse::Theirs(live, first) = signed_in_now(&m.ctx, m.which, &owner) else {
952 panic!("{tool}: `here` is signed in");
953 };
954
955 m.sign_in(&login_of(&m, "other", "other-refresh"));
956 let vault = m.mem.vault().services();
957 let recorded = serde_json::to_value(state::load(&m.ctx).expect("state")).unwrap();
958 let mut state = state::load(&m.ctx).expect("state");
959 let refused =
960 install_signed_in(&m.ctx, &key, &mut state, &login, &owner, &live, &first)
961 .expect_err("refused");
962
963 assert_eq!(refused.code(), "sign_in_not_kept", "{tool}: {refused}");
964 assert!(
965 refused
966 .to_string()
967 .contains("was signed in to another account meanwhile"),
968 "{tool}: {refused}"
969 );
970 assert!(in_use(&m, "other-refresh"), "{tool}: the other login stays");
971 assert_eq!(m.mem.vault().services(), vault, "{tool}");
972 assert_eq!(
973 serde_json::to_value(state::load(&m.ctx).expect("state")).unwrap(),
974 recorded,
975 "{tool}: and nothing is recorded"
976 );
977 }
978 }
979
980 #[test]
984 fn a_new_login_that_cannot_be_written_leaves_the_old_one_in_use() {
985 for (tool, make) in MACHINES {
986 let m = make("again-write-fails");
987 let vault = m.mem.vault().services();
988 let login = signed_in(&m, "here", "here-refresh-2");
989 m.fault_live(Fault::FailWrite("refused".into()));
990
991 let failed = enrolled_as(&m, "here", login).expect_err("the write failed");
992
993 assert_eq!(failed.code(), "sign_in_not_kept", "{tool}: {failed}");
994 let said = failed.to_string();
995 assert!(said.contains("was not kept"), "{tool}: {said}");
996 assert!(
997 said.contains(&format!("pitboard enroll {} --sign-in", m.key("here"))),
998 "{tool}: {said}"
999 );
1000 assert!(!said.contains("nothing was lost"), "{tool}: {said}");
1001 assert!(in_use(&m, "here-refresh"), "{tool}");
1002 assert_eq!(m.mem.vault().services(), vault, "{tool}");
1003 }
1004 }
1005
1006 #[test]
1010 fn a_new_login_that_did_not_hold_is_parked_rather_than_lost() {
1011 for (tool, make) in MACHINES {
1012 let m = make("again-did-not-hold");
1013 let login = signed_in(&m, "here", "here-refresh-2");
1014 m.fault_live(Fault::DeletedAfterWrite);
1015
1016 let failed = enrolled_as(&m, "here", login).expect_err("it did not hold");
1017
1018 assert!(
1019 matches!(failed, Error::SignInNotInstalled { parked: true, .. }),
1020 "{tool}: {failed:?}"
1021 );
1022 assert!(
1023 failed.to_string().contains("parked, so it is not lost"),
1024 "{tool}: {failed}"
1025 );
1026 assert_eq!(
1027 park_of(&m, "here").map(|p| p.refresh_fingerprint),
1028 Some(store::fingerprint("here-refresh-2")),
1029 "{tool}"
1030 );
1031 hold(&m, &format!("{tool}, after a new login that did not hold"));
1032 }
1033 }
1034
1035 #[test]
1041 fn a_new_login_that_could_not_be_read_back_is_not_kept_beside_itself() {
1042 for (tool, make) in MACHINES {
1043 for locked in ["by the write", "after it"] {
1044 for next in ["renewal", "change"] {
1045 let at = format!("{tool}, locked {locked}, then a {next}");
1046 let m = make(&format!("unread-{}-{next}", locked.replace(' ', "-")));
1047 let login = signed_in(&m, "here", "here-refresh-2");
1048 let (store, service) = m.live_store();
1049 let failed = if locked == "by the write" {
1050 store.fault(&service, Fault::LocksAfterWrite);
1051 enrolled_as(&m, "here", login)
1052 } else {
1053 crate::fault::meanwhile(
1054 "enroll.installed",
1055 move || store.fault(&service, Fault::Unreadable("locked".into())),
1056 || enrolled_as(&m, "here", login),
1057 )
1058 }
1059 .expect_err("it could not be read back");
1060 assert!(
1061 matches!(failed, Error::SignInNotInstalled { parked: true, .. }),
1062 "{at}: {failed:?}"
1063 );
1064 assert_eq!(
1065 park_of(&m, "here").map(|p| p.refresh_fingerprint),
1066 Some(store::fingerprint("here-refresh-2")),
1067 "{at}: parked as well"
1068 );
1069
1070 m.live_store().0.heal_all();
1071 match next {
1072 "renewal" => {
1073 let later = m
1076 .ctx
1077 .clone()
1078 .with_clock(Arc::new(FixedClock::at(NOW + 11 * 86_400)));
1079 renews(&m, "here-refresh-2", "here-refresh-3");
1080 let renewed = renew_due(&later, Due::ToBeAsked);
1081 assert!(
1082 renewed.iter().all(|(key, _)| key.label != "here"),
1083 "{at}: {renewed:?}"
1084 );
1085 }
1086 _ => {
1087 settle(&m.ctx, None).expect("the next change");
1088 }
1089 }
1090 assert!(in_use(&m, "here-refresh-2"), "{at}");
1091 assert!(park_of(&m, "here").is_none(), "{at}: the copy is dropped");
1092 hold(&m, &at);
1093 }
1094 }
1095 }
1096 }
1097
1098 #[test]
1102 fn sessions_running_on_the_old_login_are_counted_and_warned_about() {
1103 for (tool, make) in MACHINES {
1104 let m = make("again-sessions");
1105 m.mem.runs("codex", 2);
1106 m.mem.runs("claude", 2);
1107
1108 let (_, warnings) = enrolled_as(&m, "here", signed_in(&m, "here", "here-refresh-2"))
1109 .unwrap_or_else(|e| panic!("{tool}: {e}"));
1110
1111 let said = warnings
1112 .iter()
1113 .find(|w| w.code() == "sessions_keep_old_login");
1114 match m.which {
1115 ProviderId::Claude => assert!(said.is_none(), "{warnings:?}"),
1116 ProviderId::Codex => {
1117 let text = said.expect("warned").to_string();
1118 assert!(text.contains("2 `codex` sessions"), "{text}");
1119 assert!(text.contains("`codex/here`'s old login"), "{text}");
1120 assert!(text.contains("Quit them and start again"), "{text}");
1121 assert!(text.contains("put the old login back"), "{text}");
1122 }
1123 }
1124 assert!(
1125 warnings
1126 .iter()
1127 .all(|w| w.code() != "sessions_still_running"),
1128 "{tool}: nobody switched away from anything: {warnings:?}"
1129 );
1130 }
1131 }
1132
1133 #[test]
1137 fn a_cancel_does_not_wait_on_a_tool_that_says_nothing() {
1138 let m = codex_machine("cancel");
1139 let pending = reserve_signin(&m.ctx, ProviderId::Codex).expect("reserved");
1140 let mut silent = std::process::Command::new("sleep");
1141 silent.arg("30");
1142 let watched = watch(silent, pending).expect("started");
1143 let said = watched.said();
1144 let reader = std::thread::spawn(move || said.next());
1145 std::thread::sleep(Duration::from_millis(100));
1146
1147 let asked = Instant::now();
1148 watched.cancel();
1149 assert_eq!(reader.join().expect("the reader"), None);
1150 assert!(
1151 asked.elapsed() < Duration::from_secs(10),
1152 "the cancel waited on the tool"
1153 );
1154 reserve_signin(&m.ctx, ProviderId::Codex)
1155 .expect("a cancelled sign-in lets the next one start");
1156 }
1157}