Skip to main content

token_manager/
state.rs

1use anyhow::{Result, ensure};
2use serde::{Deserialize, Serialize};
3use std::{
4    fs,
5    io::Write,
6    os::unix::fs::{OpenOptionsExt, PermissionsExt},
7    path::{Path, PathBuf},
8    time::{SystemTime, UNIX_EPOCH},
9};
10
11static WRITE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12
13pub fn now() -> u64 {
14    SystemTime::now()
15        .duration_since(UNIX_EPOCH)
16        .unwrap_or_default()
17        .as_secs()
18}
19#[derive(Clone, Serialize, Deserialize)]
20#[serde(tag = "type", content = "reference", rename_all = "snake_case")]
21pub enum Credential {
22    None,
23    Keyring(String),
24    Env(String),
25    File(PathBuf),
26}
27#[derive(Clone, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct Account {
30    pub name: String,
31    pub provider: String,
32    pub provider_fingerprint: String,
33    pub credential: Credential,
34}
35#[derive(Default, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct Config {
38    pub accounts: Vec<Account>,
39}
40pub fn private_directory(path: &Path) -> Result<()> {
41    ensure!(
42        !path.is_symlink(),
43        "private directory must not be a symlink"
44    );
45    fs::create_dir_all(path)?;
46    fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
47    Ok(())
48}
49pub fn read_private(path: &Path) -> Result<Vec<u8>> {
50    ensure!(!path.is_symlink(), "private files must not be symlinks");
51    let meta = path.metadata()?;
52    ensure!(
53        meta.is_file() && meta.len() <= 1048576 && meta.permissions().mode() & 0o077 == 0,
54        "private file must be regular, bounded and mode 0600 or stricter"
55    );
56    Ok(fs::read(path)?)
57}
58pub fn atomic_write(path: &Path, data: &[u8]) -> Result<()> {
59    let parent = path
60        .parent()
61        .ok_or_else(|| anyhow::anyhow!("missing parent directory"))?;
62    private_directory(parent)?;
63    ensure!(!path.is_symlink(), "refusing to replace symlink");
64    let temporary = parent.join(format!(
65        ".write-{}-{}",
66        std::process::id(),
67        WRITE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
68    ));
69    (|| -> Result<()> {
70        let mut file = fs::OpenOptions::new()
71            .write(true)
72            .create_new(true)
73            .mode(0o600)
74            .open(&temporary)?;
75        file.write_all(data)?;
76        file.sync_all()?;
77        fs::rename(&temporary, path)?;
78        Ok(())
79    })()
80}
81pub fn load(path: &Path) -> Result<Config> {
82    if !path.exists() {
83        return Ok(Config::default());
84    }
85    let config: Config = serde_json::from_slice(&read_private(path)?)
86        .map_err(|_| anyhow::anyhow!("invalid account configuration"))?;
87    ensure!(config.accounts.len() <= 64, "at most 64 accounts supported");
88    let mut names = std::collections::HashSet::new();
89    for account in &config.accounts {
90        ensure!(
91            crate::provider::identifier(&account.name)
92                && crate::provider::identifier(&account.provider),
93            "invalid account identity"
94        );
95        ensure!(names.insert(&account.name), "duplicate account name");
96    }
97    Ok(config)
98}
99
100pub struct EditLock(PathBuf);
101impl EditLock {
102    pub fn acquire(root: &Path) -> Result<Self> {
103        let path = root.join("accounts.lock");
104        let mut file = fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path)
105            .map_err(|_|anyhow::anyhow!("Account edit lock exists; finish the other edit, or inspect accounts.lock after an interrupted edit"))?;
106        write!(file, "{}", std::process::id())?;
107        Ok(Self(path))
108    }
109}
110impl Drop for EditLock {
111    fn drop(&mut self) {
112        let _ = fs::remove_file(&self.0);
113    }
114}