Skip to main content

pidge_core/
config.rs

1//! Persistent configuration file for pidge.
2//!
3//! Path: `${XDG_CONFIG_HOME:-~/.config}/pidge/config.yaml`.
4//! Contains only non-sensitive metadata; tokens live in the OS keychain.
5
6use std::path::{Path, PathBuf};
7
8use serde::{Deserialize, Serialize};
9
10use crate::account::Account;
11use crate::error::CoreError;
12
13#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(default)]
15pub struct Config {
16    pub accounts: Vec<Account>,
17    pub defaults: Defaults,
18    pub trusted_senders: Vec<String>,
19    pub classify: ClassifyConfig,
20    /// Guardrails: action class -> "allow" | "confirm" | "deny".
21    /// Classes: send, delete, cancel, rsvp, bulk, unsubscribe.
22    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
23    pub guardrails: std::collections::BTreeMap<String, String>,
24    /// The Google OAuth client for Gmail accounts (bring your own, see
25    /// docs/gmail.md). `PIDGE_GOOGLE_CLIENT_ID` / `PIDGE_GOOGLE_CLIENT_SECRET`
26    /// override it.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub google: Option<GoogleClient>,
29}
30
31/// A Google Cloud "Desktop app" OAuth client.
32#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
33pub struct GoogleClient {
34    pub client_id: String,
35    /// Google issues desktop clients a secret that is not confidential.
36    pub client_secret: String,
37}
38
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(default)]
41pub struct Defaults {
42    pub send: Option<String>,
43    pub calendar: Option<String>,
44}
45
46/// User-configurable defaults for `pidge ai classify`. Every field is
47/// optional; an unset field falls back to a built-in default at call time.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(default)]
50pub struct ClassifyConfig {
51    /// Default classification prompt (instructions + valid outputs).
52    pub prompt: Option<String>,
53    /// Default batch concurrency.
54    pub parallel: Option<usize>,
55    /// Whether to cache classifications by message-id + prompt hash.
56    pub cache: Option<bool>,
57    /// Optional allowed-label set for validation.
58    pub labels: Vec<String>,
59}
60
61impl Config {
62    /// Default path: `${XDG_CONFIG_HOME:-~/.config}/pidge/config.yaml`.
63    pub fn default_path() -> Result<PathBuf, CoreError> {
64        let dir = crate::paths::config_dir().ok_or(CoreError::NoConfigDir)?;
65        std::fs::create_dir_all(&dir)?;
66        Ok(dir.join("config.yaml"))
67    }
68
69    /// Load the config from the default path. If the file doesn't exist, returns `Config::default()`.
70    pub fn load() -> Result<Self, CoreError> {
71        let path = Self::default_path()?;
72        Self::load_from(&path)
73    }
74
75    /// Load from a specific path. Useful for tests.
76    pub fn load_from(path: &Path) -> Result<Self, CoreError> {
77        if !path.exists() {
78            return Ok(Self::default());
79        }
80        let text = std::fs::read_to_string(path)?;
81        Ok(serde_norway::from_str(&text)?)
82    }
83
84    /// Save the config to the default path.
85    pub fn save(&self) -> Result<(), CoreError> {
86        let path = Self::default_path()?;
87        self.save_to(&path)
88    }
89
90    /// Save to a specific path. Useful for tests.
91    pub fn save_to(&self, path: &Path) -> Result<(), CoreError> {
92        let text = serde_norway::to_string(self)?;
93        // Written whole or not at all: a crash mid-write must not leave a
94        // half file that later fails to parse (guardrails then fail closed).
95        let tmp = path.with_extension("yaml.tmp");
96        std::fs::write(&tmp, text)?;
97        std::fs::rename(&tmp, path)?;
98        Ok(())
99    }
100
101    /// Add or replace an account by email. If this is the first account,
102    /// also sets it as the default send AND default calendar account.
103    pub fn add_account(&mut self, account: Account) {
104        if let Some(existing) = self.accounts.iter_mut().find(|a| a.email == account.email) {
105            *existing = account;
106            return;
107        }
108        if self.accounts.is_empty() {
109            self.defaults.send = Some(account.email.clone());
110            self.defaults.calendar = Some(account.email.clone());
111        }
112        self.accounts.push(account);
113    }
114
115    /// Remove an account by email. Returns the removed account.
116    /// If the removed account was a default, that default is cleared.
117    pub fn remove_account(&mut self, email: &str) -> Option<Account> {
118        let idx = self.accounts.iter().position(|a| a.email == email)?;
119        let removed = self.accounts.remove(idx);
120        if self.defaults.send.as_deref() == Some(email) {
121            self.defaults.send = None;
122        }
123        if self.defaults.calendar.as_deref() == Some(email) {
124            self.defaults.calendar = None;
125        }
126        Some(removed)
127    }
128
129    /// Set the default send account. Errors if the email isn't a known signed-in account.
130    pub fn set_default_send(&mut self, email: &str) -> Result<(), CoreError> {
131        if !self.accounts.iter().any(|a| a.email == email) {
132            return Err(CoreError::UnknownAccount {
133                email: email.to_string(),
134            });
135        }
136        self.defaults.send = Some(email.to_string());
137        Ok(())
138    }
139
140    /// Set the default calendar account. Errors if the email isn't a known signed-in account.
141    pub fn set_default_calendar(&mut self, email: &str) -> Result<(), CoreError> {
142        if !self.accounts.iter().any(|a| a.email == email) {
143            return Err(CoreError::UnknownAccount {
144                email: email.to_string(),
145            });
146        }
147        self.defaults.calendar = Some(email.to_string());
148        Ok(())
149    }
150
151    /// Find an account by email.
152    pub fn find(&self, email: &str) -> Option<&Account> {
153        self.accounts.iter().find(|a| a.email == email)
154    }
155
156    /// Add an email to the trusted-senders list (case-insensitive). Idempotent.
157    pub fn add_trusted_sender(&mut self, email: &str) {
158        let lower = email.to_lowercase();
159        if !self
160            .trusted_senders
161            .iter()
162            .any(|s| s.to_lowercase() == lower)
163        {
164            self.trusted_senders.push(email.to_string());
165        }
166    }
167
168    /// Remove an email from the trusted-senders list (case-insensitive).
169    /// Returns true if it was present, false if it wasn't (idempotent either way).
170    pub fn remove_trusted_sender(&mut self, email: &str) -> bool {
171        let lower = email.to_lowercase();
172        let before = self.trusted_senders.len();
173        self.trusted_senders.retain(|s| s.to_lowercase() != lower);
174        before != self.trusted_senders.len()
175    }
176
177    /// Case-insensitive check for whether an email is in the trusted-senders list.
178    pub fn is_sender_trusted(&self, email: &str) -> bool {
179        let lower = email.to_lowercase();
180        self.trusted_senders
181            .iter()
182            .any(|s| s.to_lowercase() == lower)
183    }
184
185    /// Read a dotted config key as a display string, or `None` if unset.
186    pub fn get_key(&self, key: &str) -> Option<String> {
187        match key {
188            "classify.prompt" => self.classify.prompt.clone(),
189            "classify.parallel" => self.classify.parallel.map(|n| n.to_string()),
190            "classify.cache" => self.classify.cache.map(|b| b.to_string()),
191            "classify.labels" => {
192                if self.classify.labels.is_empty() {
193                    None
194                } else {
195                    Some(self.classify.labels.join(","))
196                }
197            }
198            _ => {
199                if let Some(class) = key.strip_prefix("guardrails.") {
200                    return self.guardrails.get(class).cloned();
201                }
202                None
203            }
204        }
205    }
206
207    /// Valid guardrail action classes.
208    pub const GUARDRAIL_CLASSES: [&'static str; 6] =
209        ["send", "delete", "cancel", "rsvp", "bulk", "unsubscribe"];
210
211    /// Set a dotted config key from a string value. Errors on unknown key or
212    /// unparseable value.
213    pub fn set_key(&mut self, key: &str, value: &str) -> Result<(), CoreError> {
214        match key {
215            "classify.prompt" => self.classify.prompt = Some(value.to_string()),
216            "classify.parallel" => {
217                let n: usize = value
218                    .trim()
219                    .parse()
220                    .map_err(|_| CoreError::InvalidConfigValue {
221                        key: key.to_string(),
222                        value: value.to_string(),
223                    })?;
224                self.classify.parallel = Some(n);
225            }
226            "classify.cache" => {
227                let b = match value.trim() {
228                    "true" => true,
229                    "false" => false,
230                    _ => {
231                        return Err(CoreError::InvalidConfigValue {
232                            key: key.to_string(),
233                            value: value.to_string(),
234                        });
235                    }
236                };
237                self.classify.cache = Some(b);
238            }
239            "classify.labels" => {
240                self.classify.labels = value
241                    .split(',')
242                    .map(|s| s.trim().to_string())
243                    .filter(|s| !s.is_empty())
244                    .collect();
245            }
246            _ => {
247                if let Some(class) = key.strip_prefix("guardrails.") {
248                    if !Self::GUARDRAIL_CLASSES.contains(&class) {
249                        return Err(CoreError::UnknownConfigKey {
250                            key: key.to_string(),
251                        });
252                    }
253                    if !["allow", "confirm", "deny"].contains(&value.trim()) {
254                        return Err(CoreError::InvalidConfigValue {
255                            key: key.to_string(),
256                            value: value.to_string(),
257                        });
258                    }
259                    self.guardrails
260                        .insert(class.to_string(), value.trim().to_string());
261                    return Ok(());
262                }
263                return Err(CoreError::UnknownConfigKey {
264                    key: key.to_string(),
265                });
266            }
267        }
268        Ok(())
269    }
270
271    /// Revert a dotted config key to its unset/default state.
272    pub fn unset_key(&mut self, key: &str) -> Result<(), CoreError> {
273        match key {
274            "classify.prompt" => self.classify.prompt = None,
275            "classify.parallel" => self.classify.parallel = None,
276            "classify.cache" => self.classify.cache = None,
277            "classify.labels" => self.classify.labels.clear(),
278            _ => {
279                if let Some(class) = key.strip_prefix("guardrails.") {
280                    if !Self::GUARDRAIL_CLASSES.contains(&class) {
281                        return Err(CoreError::UnknownConfigKey {
282                            key: key.to_string(),
283                        });
284                    }
285                    self.guardrails.remove(class);
286                    return Ok(());
287                }
288                return Err(CoreError::UnknownConfigKey {
289                    key: key.to_string(),
290                });
291            }
292        }
293        Ok(())
294    }
295
296    /// Every settable config key, for `pidge config show`/help.
297    pub const KNOWN_KEYS: &'static [&'static str] = &[
298        "classify.prompt",
299        "classify.parallel",
300        "classify.cache",
301        "classify.labels",
302    ];
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use chrono::TimeZone;
309
310    fn make_account(email: &str) -> Account {
311        Account {
312            email: email.into(),
313            tenant_id: "tid".into(),
314            home_account_id: "home".into(),
315            added_at: chrono::Utc.with_ymd_and_hms(2026, 5, 13, 22, 0, 0).unwrap(),
316            storage: crate::TokenStorage::default(),
317            provider: Default::default(),
318        }
319    }
320
321    #[test]
322    fn empty_config_serializes_and_deserializes() {
323        let c = Config::default();
324        let yaml = serde_norway::to_string(&c).unwrap();
325        let c2: Config = serde_norway::from_str(&yaml).unwrap();
326        assert_eq!(c, c2);
327    }
328
329    /// Pins the exact bytes `save_to` writes, so a YAML library change can
330    /// never silently alter users' config files.
331    fn golden_config() -> Config {
332        let mut c = Config::default();
333        c.add_account(make_account("a@b.com"));
334        let mut file_acct = make_account("personal@outlook.com");
335        file_acct.tenant_id = Account::PERSONAL_MSA_TENANT.into();
336        file_acct.storage = crate::TokenStorage::File;
337        c.add_account(file_acct);
338        c.set_default_calendar("personal@outlook.com").unwrap();
339        c.trusted_senders = vec!["maria@mklab.se".into(), "yes".into(), "".into()];
340        c.classify.prompt = Some("Classify: invoice or receipt?\nAnswer with one word.\n".into());
341        c.classify.parallel = Some(8);
342        c.classify.cache = Some(false);
343        c.classify.labels = vec!["invoice".into(), "null".into(), "1.0".into()];
344        c.guardrails.insert("send".into(), "confirm".into());
345        c.guardrails.insert("delete".into(), "deny".into());
346        c
347    }
348
349    #[test]
350    fn config_yaml_output_is_byte_stable() {
351        let tmp = tempfile::TempDir::new().unwrap();
352        let path = tmp.path().join("config.yaml");
353        golden_config().save_to(&path).unwrap();
354        let written = std::fs::read_to_string(&path).unwrap();
355        assert_eq!(written, GOLDEN_YAML);
356        assert_eq!(Config::load_from(&path).unwrap(), golden_config());
357        let empty = serde_norway::to_string(&Config::default()).unwrap();
358        assert_eq!(empty, GOLDEN_EMPTY_YAML);
359    }
360
361    const GOLDEN_YAML: &str = r"accounts:
362- email: a@b.com
363  tenant_id: tid
364  home_account_id: home
365  added_at: 2026-05-13T22:00:00Z
366  storage: keychain
367- email: personal@outlook.com
368  tenant_id: 9188040d-6c67-4c5b-b112-36a304b66dad
369  home_account_id: home
370  added_at: 2026-05-13T22:00:00Z
371  storage: file
372defaults:
373  send: a@b.com
374  calendar: personal@outlook.com
375trusted_senders:
376- maria@mklab.se
377- yes
378- ''
379classify:
380  prompt: |
381    Classify: invoice or receipt?
382    Answer with one word.
383  parallel: 8
384  cache: false
385  labels:
386  - invoice
387  - 'null'
388  - '1.0'
389guardrails:
390  delete: deny
391  send: confirm
392";
393    const GOLDEN_EMPTY_YAML: &str = r"accounts: []
394defaults:
395  send: null
396  calendar: null
397trusted_senders: []
398classify:
399  prompt: null
400  parallel: null
401  cache: null
402  labels: []
403";
404
405    #[test]
406    fn first_added_account_becomes_both_defaults() {
407        let mut c = Config::default();
408        c.add_account(make_account("a@b.com"));
409        assert_eq!(c.defaults.send.as_deref(), Some("a@b.com"));
410        assert_eq!(c.defaults.calendar.as_deref(), Some("a@b.com"));
411    }
412
413    #[test]
414    fn second_added_account_does_not_change_defaults() {
415        let mut c = Config::default();
416        c.add_account(make_account("a@b.com"));
417        c.add_account(make_account("c@d.com"));
418        assert_eq!(c.defaults.send.as_deref(), Some("a@b.com"));
419        assert_eq!(c.defaults.calendar.as_deref(), Some("a@b.com"));
420        assert_eq!(c.accounts.len(), 2);
421    }
422
423    #[test]
424    fn removing_default_account_clears_default() {
425        let mut c = Config::default();
426        c.add_account(make_account("a@b.com"));
427        c.add_account(make_account("c@d.com"));
428        c.remove_account("a@b.com");
429        assert_eq!(c.defaults.send, None);
430        assert_eq!(c.defaults.calendar, None);
431    }
432
433    #[test]
434    fn set_default_send_for_unknown_account_errors() {
435        let mut c = Config::default();
436        c.add_account(make_account("a@b.com"));
437        assert!(matches!(
438            c.set_default_send("ghost@nowhere.com"),
439            Err(CoreError::UnknownAccount { .. })
440        ));
441    }
442
443    #[test]
444    fn config_roundtrips_through_file() {
445        let tmp = tempfile::TempDir::new().unwrap();
446        let path = tmp.path().join("config.yaml");
447
448        let mut c = Config::default();
449        c.add_account(make_account("a@b.com"));
450        c.add_account(make_account("c@d.com"));
451        c.set_default_calendar("c@d.com").unwrap();
452        c.save_to(&path).unwrap();
453
454        let c2 = Config::load_from(&path).unwrap();
455        assert_eq!(c, c2);
456    }
457
458    #[test]
459    fn add_trusted_sender_is_idempotent() {
460        let mut c = Config::default();
461        c.add_trusted_sender("a@b.com");
462        c.add_trusted_sender("a@b.com");
463        assert_eq!(c.trusted_senders.len(), 1);
464    }
465
466    #[test]
467    fn add_trusted_sender_is_case_insensitive() {
468        let mut c = Config::default();
469        c.add_trusted_sender("Maria@MKLab.se");
470        c.add_trusted_sender("maria@mklab.se");
471        assert_eq!(c.trusted_senders.len(), 1);
472    }
473
474    #[test]
475    fn remove_trusted_sender_returns_true_when_present() {
476        let mut c = Config::default();
477        c.add_trusted_sender("a@b.com");
478        assert!(c.remove_trusted_sender("a@b.com"));
479        assert!(c.trusted_senders.is_empty());
480    }
481
482    #[test]
483    fn remove_trusted_sender_returns_false_when_absent() {
484        let mut c = Config::default();
485        assert!(!c.remove_trusted_sender("ghost@nowhere.com"));
486    }
487
488    #[test]
489    fn remove_trusted_sender_is_case_insensitive() {
490        let mut c = Config::default();
491        c.add_trusted_sender("Maria@MKLab.se");
492        assert!(c.remove_trusted_sender("MARIA@mklab.SE"));
493        assert!(c.trusted_senders.is_empty());
494    }
495
496    #[test]
497    fn is_sender_trusted_case_insensitive() {
498        let mut c = Config::default();
499        c.add_trusted_sender("Maria@MKLab.se");
500        assert!(c.is_sender_trusted("maria@mklab.se"));
501        assert!(c.is_sender_trusted("MARIA@MKLAB.SE"));
502        assert!(!c.is_sender_trusted("anna@mklab.se"));
503    }
504
505    #[test]
506    fn config_with_missing_trusted_senders_loads_as_empty() {
507        let yaml = "accounts: []\ndefaults: {}\n";
508        let c: Config = serde_norway::from_str(yaml).unwrap();
509        assert!(c.trusted_senders.is_empty());
510    }
511
512    #[test]
513    fn classify_config_defaults_are_empty() {
514        let c = Config::default();
515        assert!(c.classify.prompt.is_none());
516        assert!(c.classify.parallel.is_none());
517        assert!(c.classify.cache.is_none());
518        assert!(c.classify.labels.is_empty());
519    }
520
521    #[test]
522    fn classify_config_roundtrips_through_yaml() {
523        let mut c = Config::default();
524        c.classify.prompt = Some("Classify it".into());
525        c.classify.parallel = Some(8);
526        c.classify.cache = Some(true);
527        c.classify.labels = vec!["invoice".into(), "receipt".into()];
528        let yaml = serde_norway::to_string(&c).unwrap();
529        let back: Config = serde_norway::from_str(&yaml).unwrap();
530        assert_eq!(back.classify.prompt.as_deref(), Some("Classify it"));
531        assert_eq!(back.classify.parallel, Some(8));
532        assert_eq!(back.classify.labels, vec!["invoice", "receipt"]);
533    }
534
535    #[test]
536    fn config_set_get_unset_roundtrip() {
537        let mut c = Config::default();
538        c.set_key("classify.parallel", "8").unwrap();
539        assert_eq!(c.get_key("classify.parallel"), Some("8".to_string()));
540        c.set_key("classify.labels", "invoice,receipt,ticket")
541            .unwrap();
542        assert_eq!(
543            c.get_key("classify.labels"),
544            Some("invoice,receipt,ticket".to_string())
545        );
546        c.set_key("classify.cache", "true").unwrap();
547        assert_eq!(c.get_key("classify.cache"), Some("true".to_string()));
548        c.unset_key("classify.parallel").unwrap();
549        assert_eq!(c.get_key("classify.parallel"), None);
550    }
551
552    #[test]
553    fn config_set_rejects_unknown_key_and_bad_value() {
554        let mut c = Config::default();
555        assert!(c.set_key("classify.nope", "x").is_err());
556        assert!(c.set_key("classify.parallel", "notanumber").is_err());
557        assert!(c.set_key("classify.cache", "maybe").is_err());
558    }
559}