1use std::future::Future;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12
13use crate::credentials::Credentials;
14
15#[derive(Debug, Default)]
20pub struct LoginLog {
21 rejected: AtomicBool,
22 accepted: AtomicBool,
23}
24
25impl LoginLog {
26 #[must_use]
28 pub fn new() -> Self {
29 Self::default()
30 }
31
32 #[must_use]
34 pub fn rejected(&self) -> bool {
35 self.rejected.load(Ordering::SeqCst)
36 }
37
38 #[must_use]
40 pub fn accepted(&self) -> bool {
41 self.accepted.load(Ordering::SeqCst)
42 }
43}
44
45struct Call {
46 credentials: Arc<Credentials>,
47 log: Arc<LoginLog>,
48}
49
50tokio::task_local! {
51 static CALL: Call;
52}
53
54pub async fn with_call_credentials<F: Future>(
58 credentials: Arc<Credentials>,
59 log: Arc<LoginLog>,
60 work: F,
61) -> F::Output {
62 CALL.scope(Call { credentials, log }, work).await
63}
64
65pub fn call_credentials<T>(read: impl FnOnce(&Credentials) -> T) -> Option<T> {
69 CALL.try_with(|call| read(&call.credentials)).ok()
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum LoginVerdict {
76 Accepted,
78 Rejected,
80}
81
82pub fn report_login(verdict: LoginVerdict) {
86 let _ = CALL.try_with(|call| {
87 let flag = match verdict {
88 LoginVerdict::Accepted => &call.log.accepted,
89 LoginVerdict::Rejected => &call.log.rejected,
90 };
91 flag.store(true, Ordering::SeqCst);
92 });
93}
94
95#[cfg(test)]
96mod tests {
97 use std::sync::Arc;
98
99 use ibridge_core::AppleId;
100
101 use super::{LoginLog, LoginVerdict, call_credentials, report_login, with_call_credentials};
102 use crate::credentials::Credentials;
103
104 #[tokio::test]
105 async fn credentials_are_visible_only_inside_the_call() {
106 let apple_id = AppleId::try_from("ada@icloud.com").expect("apple id");
107 let credentials = Arc::new(Credentials::new(apple_id, "pw-1"));
108 assert!(
109 call_credentials(|_| ()).is_none(),
110 "nothing before the call"
111 );
112
113 let log = Arc::new(LoginLog::new());
114 let seen = with_call_credentials(Arc::clone(&credentials), Arc::clone(&log), async {
115 report_login(LoginVerdict::Rejected);
116 call_credentials(|inside| inside.with_secret(ToOwned::to_owned))
117 })
118 .await;
119 report_login(LoginVerdict::Accepted);
120
121 assert_eq!(seen.as_deref(), Some("pw-1"), "the call reads its password");
122 assert!(log.rejected(), "a login reported inside the call is logged");
123 assert!(!log.accepted(), "a login reported outside the call is not");
124 assert!(call_credentials(|_| ()).is_none(), "nothing after the call");
125 assert_eq!(
126 Arc::strong_count(&credentials),
127 1,
128 "the scope gave back its copy"
129 );
130 }
131}