Skip to main content

ibridge_auth/
call.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! The password a hosted call opened, visible to the code that runs that call.
4//!
5//! A hosted server opens the password from the caller's token for one tool call.
6//! Code that needs it, such as a pool opening a new connection, reads it here
7//! instead of keeping a copy of its own.
8
9use std::future::Future;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12
13use crate::credentials::Credentials;
14
15/// What iCloud said to the logins one call made.
16///
17/// A server counts rejected logins toward revoking a credential, so it needs to
18/// know what the server answered, not only that the call failed.
19#[derive(Debug, Default)]
20pub struct LoginLog {
21    rejected: AtomicBool,
22    accepted: AtomicBool,
23}
24
25impl LoginLog {
26    /// An empty log.
27    #[must_use]
28    pub fn new() -> Self {
29        Self::default()
30    }
31
32    /// Whether a login in this call was refused for its password.
33    #[must_use]
34    pub fn rejected(&self) -> bool {
35        self.rejected.load(Ordering::SeqCst)
36    }
37
38    /// Whether a login in this call was accepted.
39    #[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
54/// Runs `work` with `credentials` visible to [`call_credentials`] and logins noted in `log`.
55///
56/// The scope ends with `work`. A task `work` spawns does not inherit it.
57pub 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
65/// Passes the current call's credentials to `read`.
66///
67/// Returns `None` outside [`with_call_credentials`].
68pub fn call_credentials<T>(read: impl FnOnce(&Credentials) -> T) -> Option<T> {
69    CALL.try_with(|call| read(&call.credentials)).ok()
70}
71
72/// What a server said to a login.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum LoginVerdict {
76    /// The server accepted the password.
77    Accepted,
78    /// The server refused the password.
79    Rejected,
80}
81
82/// Notes the result of a login the current call made. Does nothing outside a call.
83///
84/// Report only the server's verdict on the password, not a network failure or throttling.
85pub 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}