Skip to main content

ibridge_auth/
source.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Where an Apple ID and app-specific password are loaded from.
4
5use std::collections::HashMap;
6use std::fs;
7use std::path::PathBuf;
8
9use ibridge_core::AppleId;
10
11use crate::credentials::{AuthError, Credentials};
12use crate::platform::is_mode_0600;
13
14/// Keychain service name for the app-specific password.
15const KEYRING_SERVICE: &str = "ibridge";
16
17/// Loads credentials for one account.
18#[trait_variant::make(Send)]
19pub trait CredentialSource {
20    /// Reads the Apple ID and app-specific password.
21    ///
22    /// # Errors
23    ///
24    /// Returns [`AuthError::Unavailable`] when the source has no usable secret.
25    /// The error text never includes the secret.
26    async fn credentials(&self) -> Result<Credentials, AuthError>;
27}
28
29/// OS keychain entry under the service name `ibridge`.
30///
31/// The process chooses the store, which tests replace with the in-memory mock.
32/// This type never opens the login keychain itself.
33#[derive(Debug)]
34pub struct KeyringSource {
35    apple_id: AppleId,
36}
37
38impl KeyringSource {
39    /// Reads the password stored for `apple_id`.
40    #[must_use]
41    pub const fn new(apple_id: AppleId) -> Self {
42        Self { apple_id }
43    }
44}
45
46#[expect(
47    clippy::unused_async_trait_impl,
48    reason = "the keychain read is synchronous"
49)]
50impl CredentialSource for KeyringSource {
51    async fn credentials(&self) -> Result<Credentials, AuthError> {
52        let entry = keyring_core::Entry::new(KEYRING_SERVICE, self.apple_id.as_str())
53            .map_err(|_| AuthError::Unavailable)?;
54        let secret = entry.get_password().map_err(|_| AuthError::Unavailable)?;
55        Ok(Credentials::new(self.apple_id.clone(), secret))
56    }
57}
58
59/// A `KEY=VALUE` file that must be mode `0600`.
60///
61/// Accepts `IBRIDGE_APPLE_ID` and `IBRIDGE_APP_PASSWORD`, and falls back to
62/// `IBRIDGE_TEST_APPLE_ID` and `IBRIDGE_TEST_APP_PASSWORD` when those are absent.
63#[derive(Debug)]
64pub struct FileSource {
65    path: PathBuf,
66}
67
68impl FileSource {
69    /// Reads credentials from `path` after checking its mode.
70    #[must_use]
71    pub fn new(path: impl Into<PathBuf>) -> Self {
72        Self { path: path.into() }
73    }
74}
75
76#[expect(
77    clippy::unused_async_trait_impl,
78    reason = "the file read is synchronous"
79)]
80impl CredentialSource for FileSource {
81    async fn credentials(&self) -> Result<Credentials, AuthError> {
82        if !is_mode_0600(&self.path) {
83            return Err(AuthError::Unavailable);
84        }
85        let text = fs::read_to_string(&self.path).map_err(|_| AuthError::Unavailable)?;
86        credentials_from_pairs(&pairs(&text))
87    }
88}
89
90/// Process environment variables `IBRIDGE_APPLE_ID` and `IBRIDGE_APP_PASSWORD`.
91#[derive(Debug, Default)]
92pub struct EnvSource;
93
94impl EnvSource {
95    /// Reads the process environment.
96    #[must_use]
97    pub const fn new() -> Self {
98        Self
99    }
100}
101
102#[expect(
103    clippy::unused_async_trait_impl,
104    reason = "the environment read is synchronous"
105)]
106impl CredentialSource for EnvSource {
107    async fn credentials(&self) -> Result<Credentials, AuthError> {
108        let id = std::env::var("IBRIDGE_APPLE_ID").map_err(|_| AuthError::Unavailable)?;
109        let secret = std::env::var("IBRIDGE_APP_PASSWORD").map_err(|_| AuthError::Unavailable)?;
110        let apple_id = AppleId::try_from(id.as_str()).map_err(|_| AuthError::Unavailable)?;
111        Ok(Credentials::new(apple_id, secret))
112    }
113}
114
115fn pairs(text: &str) -> HashMap<&str, &str> {
116    let mut pairs = HashMap::new();
117    for line in text.lines() {
118        let line = line.trim();
119        if line.is_empty() || line.starts_with('#') {
120            continue;
121        }
122        let Some((key, value)) = line.split_once('=') else {
123            continue;
124        };
125        pairs.insert(key.trim(), value.trim());
126    }
127    pairs
128}
129
130fn credentials_from_pairs(pairs: &HashMap<&str, &str>) -> Result<Credentials, AuthError> {
131    let id = field(pairs, "IBRIDGE_APPLE_ID", "IBRIDGE_TEST_APPLE_ID")?;
132    let secret = field(pairs, "IBRIDGE_APP_PASSWORD", "IBRIDGE_TEST_APP_PASSWORD")?;
133    let apple_id = AppleId::try_from(id).map_err(|_| AuthError::Unavailable)?;
134    Ok(Credentials::new(apple_id, secret))
135}
136
137fn field<'a>(
138    pairs: &HashMap<&str, &'a str>,
139    primary: &str,
140    fallback: &str,
141) -> Result<&'a str, AuthError> {
142    [primary, fallback]
143        .into_iter()
144        .find_map(|key| pairs.get(key).copied().filter(|value| !value.is_empty()))
145        .ok_or(AuthError::Unavailable)
146}