Skip to main content

pidge_core/
account.rs

1//! Account types: represents a single Microsoft account signed into pidge.
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5
6/// Where pidge stores OAuth tokens for an account.
7///
8/// `Keychain` is the OS-native credential store (macOS Keychain, Windows
9/// Credential Manager, Linux libsecret): encrypted, OS-managed access control.
10/// `File` is a JSON file at `~/.config/pidge/tokens/<email>.json` with mode 0600
11/// (user-only read/write). The file backend is useful for headless or dev
12/// scenarios where the keychain prompts are friction, but it stores refresh
13/// tokens in plaintext on disk and is less safe than the keychain.
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "lowercase")]
16pub enum TokenStorage {
17    #[default]
18    Keychain,
19    File,
20}
21
22/// A signed-in Microsoft account.
23///
24/// This is metadata only, no tokens. Tokens live in the OS keychain
25/// or in a per-account file at `~/.config/pidge/tokens/<email>.json`,
26/// keyed by `email`. The `storage` field tells pidge which backend to look in.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Account {
29    pub email: String,
30    pub tenant_id: String,
31    pub home_account_id: String,
32    pub added_at: DateTime<Utc>,
33    #[serde(default)]
34    pub storage: TokenStorage,
35    /// Which service the account lives at (Microsoft when absent, and not
36    /// written for Microsoft so existing config files stay as they are).
37    #[serde(
38        default,
39        skip_serializing_if = "crate::provider::ProviderKind::is_microsoft"
40    )]
41    pub provider: crate::provider::ProviderKind,
42}
43
44impl Account {
45    /// Well-known tenant ID for personal Microsoft accounts (outlook.com, live.com, hotmail.com).
46    /// Microsoft documents this as the "MSA" tenant.
47    pub const PERSONAL_MSA_TENANT: &'static str = "9188040d-6c67-4c5b-b112-36a304b66dad";
48
49    /// True if this account is a personal Microsoft account.
50    pub fn is_personal(&self) -> bool {
51        self.tenant_id == Self::PERSONAL_MSA_TENANT
52    }
53
54    /// A short human label for the tenant: "personal MSA" for MSA, GUID prefix
55    /// otherwise. Returns "(unknown)" when the tenant_id is empty (e.g. an
56    /// account added before pidge requested the `openid` scope; gets
57    /// auto-backfilled on the next Graph call).
58    pub fn tenant_label(&self) -> String {
59        if self.is_personal() {
60            "personal MSA".to_string()
61        } else if self.tenant_id.is_empty() {
62            "(unknown)".to_string()
63        } else {
64            let prefix: String = self.tenant_id.chars().take(8).collect();
65            format!("{prefix}…")
66        }
67    }
68
69    /// Short human-readable label for the account's provider / kind. Today
70    /// we only support Microsoft, so this distinguishes personal MSA (Outlook
71    /// / Live / Hotmail) from organizational M365 tenants. As we add Gmail,
72    /// IMAP, etc., this becomes a stored field rather than a derived one.
73    pub fn provider_label(&self) -> &'static str {
74        if self.provider == crate::provider::ProviderKind::Google {
75            "Gmail"
76        } else if self.is_personal() {
77            "Outlook"
78        } else {
79            "M365"
80        }
81    }
82
83    /// Machine-readable provider identifier, used in `--json` output and any
84    /// future config-file lookups. Stays stable as labels change.
85    pub fn provider_id(&self) -> &'static str {
86        if self.provider == crate::provider::ProviderKind::Google {
87            "gmail"
88        } else if self.is_personal() {
89            "outlook"
90        } else {
91            "m365"
92        }
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    fn make_account(tenant_id: &str) -> Account {
101        Account {
102            email: "x@example.com".into(),
103            tenant_id: tenant_id.into(),
104            home_account_id: "home".into(),
105            added_at: DateTime::parse_from_rfc3339("2026-05-13T22:00:00Z")
106                .unwrap()
107                .to_utc(),
108            storage: TokenStorage::default(),
109            provider: Default::default(),
110        }
111    }
112
113    #[test]
114    fn token_storage_default_is_keychain() {
115        assert!(matches!(TokenStorage::default(), TokenStorage::Keychain));
116    }
117
118    #[test]
119    fn token_storage_serializes_lowercase() {
120        assert_eq!(
121            serde_json::to_string(&TokenStorage::Keychain).unwrap(),
122            "\"keychain\""
123        );
124        assert_eq!(
125            serde_json::to_string(&TokenStorage::File).unwrap(),
126            "\"file\""
127        );
128    }
129
130    #[test]
131    fn account_without_storage_field_deserializes_as_keychain() {
132        let yaml = r#"
133email: a@b.com
134tenant_id: tid
135home_account_id: hid
136added_at: "2026-05-13T22:00:00Z"
137"#;
138        let a: Account = serde_norway::from_str(yaml).unwrap();
139        assert!(matches!(a.storage, TokenStorage::Keychain));
140    }
141
142    #[test]
143    fn personal_msa_tenant_is_recognised() {
144        assert!(make_account(Account::PERSONAL_MSA_TENANT).is_personal());
145    }
146
147    #[test]
148    fn org_tenant_is_not_personal() {
149        assert!(!make_account("11111111-2222-3333-4444-555555555555").is_personal());
150    }
151
152    #[test]
153    fn tenant_label_for_msa() {
154        assert_eq!(
155            make_account(Account::PERSONAL_MSA_TENANT).tenant_label(),
156            "personal MSA"
157        );
158    }
159
160    #[test]
161    fn tenant_label_for_org_truncates_to_8_chars() {
162        assert_eq!(
163            make_account("11111111-2222-3333-4444-555555555555").tenant_label(),
164            "11111111…"
165        );
166    }
167
168    #[test]
169    fn provider_label_for_personal_msa_is_outlook() {
170        let a = make_account(Account::PERSONAL_MSA_TENANT);
171        assert_eq!(a.provider_label(), "Outlook");
172        assert_eq!(a.provider_id(), "outlook");
173    }
174
175    #[test]
176    fn provider_label_for_org_tenant_is_m365() {
177        let a = make_account("11111111-2222-3333-4444-555555555555");
178        assert_eq!(a.provider_label(), "M365");
179        assert_eq!(a.provider_id(), "m365");
180    }
181}