OXYGENHUB

Coverage / crates/oxy-core/src/credentials.rs 89.2%

364 of 408 lines run, 55 of 77 functions · run #292 on main · run missed

1
//! Per-user credentials for hubs: one sign-in serves every repository on a
2
//! hub, and nothing secret is written into a checkout.
3
//!
4
//! The store is `credentials.toml` in the user's oxy directory (see
5
//! [`crate::repo::default_home`]), one section per hub:
6
//!
7
//! ```text
8
//! [https://oxygenhub.io]
9
//! account = "andymccall"
10
//! token = "oxyhub_…"
11
//! ```
12
//!
13
//! A hub is a scheme, host and port: a token is only ever sent to the hub
14
//! it was stored for. The file is written readable by its owner only, and
15
//! is ignored with a warning when anyone else can read it. With
16
//! `auth.helper` set in the user's `config.toml`, tokens go to that helper
17
//! instead (Git's credential-helper protocol, so `libsecret`,
18
//! `osxkeychain` and `manager` keep them in the system keyring) and the
19
//! file keeps only what is not secret.
20
//!
21
//! A token is sent over `https`, or over plain `http` to this machine only
22
//! ([`token_allowed`]); hub transports drop it on any redirect.
23
24
use crate::protocol::RemoteOptions;
25
use std::collections::{BTreeMap, HashMap};
26
use std::io::Write;
27
use std::path::{Path, PathBuf};
28
use std::process::{Command, Stdio};
29
use std::sync::{Mutex, OnceLock};
30
31
/// The user name oxy's tokens are stored under in a credential helper, so
32
/// they stay apart from Git credentials for the same host.
33
const HELPER_USER: &str = "oxy-token";
34
35
/// The hub of a URL: `scheme://host[:port]`, lower case, for `http` and
36
/// `https` URLs only.
372287×
pub fn hub_of(url: &str) -> Option<String> {
382287×
    let (scheme, rest) = url.split_once("://")?;
39435×
    let scheme = scheme.to_ascii_lowercase();
40435×
    if scheme != "http" && scheme != "https" {
41102×
        return None;
42333×
    }
43333×
    let host = rest.split(['/', '?', '#']).next()?;
44
    // Never key a hub on credentials embedded in the URL.
45333×
    let host = host.rsplit('@').next()?;
46333×
    if host.is_empty() {
470×
        return None;
48333×
    }
49333×
    Some(format!("{scheme}://{}", host.to_ascii_lowercase()))
502287×
}
51
52
/// Whether a token may be sent to `url`: always over `https`, and over
53
/// plain `http` only to this machine (a hub under test, or a runner's own).
5415×
pub fn token_allowed(url: &str) -> bool {
5515×
    let Some(hub) = hub_of(url) else {
560×
        return true;
57
    };
5815×
    match hub.split_once("://") {
5915×
        Some(("https", _)) => true,
6014×
        Some((_, host)) => {
6114×
            let name = match host.strip_prefix('[') {
621×
                Some(v6) => v6.split(']').next().unwrap_or(""),
6313×
                None => host.rsplit_once(':').map_or(host, |(h, _)| h),
64
            };
6514×
            name == "localhost"
6613×
                || name == "::1"
6712×
                || name
6812×
                    .parse::<std::net::Ipv4Addr>()
6912×
                    .is_ok_and(|a| a.is_loopback())
70
        }
710×
        None => false,
72
    }
7315×
}
74
75
/// What the store holds for one hub.
76
#[derive(Clone, Debug, Default, PartialEq, Eq)]
77
pub struct HubEntry {
78
    /// `scheme://host[:port]`.
79
    pub hub: String,
80
    /// The account the token signs in as, recorded at sign-in.
81
    pub account: Option<String>,
82
    /// The token, when it is in the file (not with a helper).
83
    pub token: Option<String>,
84
    /// Extra roots to trust for this hub (a self-signed hub).
85
    pub ca: Option<PathBuf>,
86
}
87
88
/// Where a saved token went.
89
#[derive(Clone, Debug, PartialEq, Eq)]
90
pub enum Stored {
91
    /// The credentials file, owner-only.
92
    File(PathBuf),
93
    /// A credential helper, by its `auth.helper` value.
94
    Helper(String),
95
}
96
97
/// The credential store of one oxy home directory.
98
#[derive(Clone, Debug)]
99
pub struct Credentials {
100
    home: PathBuf,
101
}
102
103
impl Credentials {
104
    /// The store in `home` (an oxy home directory).
1051250×
    pub fn at(home: impl Into<PathBuf>) -> Credentials {
1061250×
        Credentials { home: home.into() }
1071250×
    }
108
109
    /// The store in the user's oxy home directory.
110237×
    pub fn user() -> Credentials {
111237×
        Credentials::at(crate::repo::default_home())
112237×
    }
113
114
    /// `credentials.toml` in the home directory.
11599×
    pub fn path(&self) -> PathBuf {
11699×
        self.home.join("credentials.toml")
11799×
    }
118
119
    /// The configured credential helper (`auth.helper` in the user file).
12046×
    pub fn helper(&self) -> Option<String> {
12146×
        crate::repo::read_config_file(&self.home.join("config.toml"))
12246×
            .ok()?
12346×
            .remove("auth.helper")
12446×
            .filter(|h| !h.trim().is_empty())
12546×
    }
126
127
    /// Every hub in the file, tokens as stored there (none with a helper).
1281×
    pub fn entries(&self) -> Result<Vec<HubEntry>, String> {
1291×
        Ok(self.read()?.into_values().collect())
1301×
    }
131
132
    /// Whether the file can be read by anyone but its owner, in which case
133
    /// lookups ignore it.
13435×
    pub fn too_open(&self) -> bool {
135
        #[cfg(unix)]
136
        {
137
            use std::os::unix::fs::PermissionsExt;
13835×
            if let Ok(m) = std::fs::metadata(self.path()) {
13910×
                return m.permissions().mode() & 0o077 != 0;
14025×
            }
141
        }
14225×
        false
14335×
    }
144
145
    /// The entry for `hub`, its token fetched from the helper if one is set.
14637×
    pub fn get(&self, hub: &str) -> Result<Option<HubEntry>, String> {
14737×
        let entry = self.read()?.remove(hub);
14837×
        let helper = self.helper();
14937×
        let mut entry = match (entry, &helper) {
1507×
            (Some(e), _) => e,
151
            // A helper may hold a token stored before the file was cleared.
1520×
            (None, Some(_)) => HubEntry {
1530×
                hub: hub.to_string(),
1540×
                ..HubEntry::default()
1550×
            },
15630×
            (None, None) => return Ok(None),
157
        };
1587×
        if entry.token.is_none() {
1592×
            if let Some(h) = &helper {
1602×
                entry.token = run_helper(h, "get", hub, None)?;
1610×
            }
1625×
        }
1637×
        if entry.token.is_none() && entry.account.is_none() && entry.ca.is_none() {
1640×
            return Ok(None);
1657×
        }
1667×
        Ok(Some(entry))
16737×
    }
168
169
    /// Save a token (and what is known about it) for `hub`.
1706×
    pub fn save(
1716×
        &self,
1726×
        hub: &str,
1736×
        token: &str,
1746×
        account: Option<&str>,
1756×
        ca: Option<&Path>,
1766×
    ) -> Result<Stored, String> {
1776×
        let mut all = self.read()?;
1786×
        let helper = self.helper();
1796×
        let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry {
1806×
            hub: hub.to_string(),
1816×
            ..HubEntry::default()
1826×
        });
1836×
        entry.account = account.map(String::from).or(entry.account.take());
1846×
        if let Some(ca) = ca {
1851×
            entry.ca = Some(ca.to_path_buf());
1865×
        }
1876×
        let stored = match &helper {
1881×
            Some(h) => {
1891×
                run_helper(h, "store", hub, Some(token))?;
1901×
                entry.token = None;
1911×
                Stored::Helper(h.clone())
192
            }
193
            None => {
1945×
                entry.token = Some(token.to_string());
1955×
                Stored::File(self.path())
196
            }
197
        };
1986×
        self.write(&all)?;
1996×
        forget_cached();
2006×
        Ok(stored)
2016×
    }
202
203
    /// Remove `hub` from the file and the helper; returns what it held,
204
    /// with the token, so the caller can revoke it.
2052×
    pub fn remove(&self, hub: &str) -> Result<Option<HubEntry>, String> {
2062×
        let found = self.get(hub)?;
2072×
        let mut all = self.read()?;
2082×
        if all.remove(hub).is_some() {
2092×
            self.write(&all)?;
2100×
        }
2112×
        if let Some(h) = self.helper() {
2121×
            run_helper(&h, "erase", hub, None)?;
2131×
        }
2142×
        forget_cached();
2152×
        Ok(found)
2162×
    }
217
21846×
    fn read(&self) -> Result<BTreeMap<String, HubEntry>, String> {
21946×
        let path = self.path();
22046×
        let text = match std::fs::read_to_string(&path) {
22115×
            Ok(t) => t,
22231×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
2230×
            Err(e) => return Err(format!("reading {}: {e}", path.display())),
224
        };
22515×
        let mut out = BTreeMap::new();
22615×
        let mut current: Option<HubEntry> = None;
227100×
        for (n, line) in text.lines().enumerate() {
228100×
            let line = line.trim();
229100×
            if line.is_empty() || line.starts_with('#') {
23037×
                continue;
23163×
            }
23263×
            if let Some(hub) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
23322×
                if let Some(e) = current.take() {
2347×
                    out.insert(e.hub.clone(), e);
23515×
                }
23622×
                current = Some(HubEntry {
23722×
                    hub: hub.trim().to_string(),
23822×
                    ..HubEntry::default()
23922×
                });
24022×
                continue;
24141×
            }
24241×
            let bad = || {
2430×
                format!(
244
                    "{} line {}: expected key = \"value\"",
2450×
                    path.display(),
2460×
                    n + 1
247
                )
2480×
            };
24941×
            let (k, v) = line.split_once('=').ok_or_else(bad)?;
25041×
            let v = unquote(v.trim()).ok_or_else(bad)?;
25141×
            let Some(e) = current.as_mut() else {
2520×
                return Err(format!(
2530×
                    "{} line {}: a key before any [hub] section",
2540×
                    path.display(),
2550×
                    n + 1
2560×
                ));
257
            };
25841×
            match k.trim() {
25941×
                "account" => e.account = Some(v),
26028×
                "token" => e.token = Some(v),
2619×
                "ca" => e.ca = Some(PathBuf::from(v)),
262
                // Unknown keys are kept out of lookups, not fatal.
2630×
                _ => {}
264
            }
265
        }
26615×
        if let Some(e) = current {
26715×
            out.insert(e.hub.clone(), e);
26815×
        }
26915×
        Ok(out)
27046×
    }
271
2728×
    fn write(&self, all: &BTreeMap<String, HubEntry>) -> Result<(), String> {
2738×
        let mut text =
2748×
            String::from("# oxy credentials: a token for each hub. Keep this file private.\n");
2758×
        for e in all.values() {
2768×
            text.push_str(&format!("\n[{}]\n", e.hub));
2778×
            if let Some(a) = &e.account {
2785×
                text.push_str(&format!("account = {}\n", quote(a)));
2795×
            }
2808×
            if let Some(t) = &e.token {
2817×
                text.push_str(&format!("token = {}\n", quote(t)));
2827×
            }
2838×
            if let Some(c) = &e.ca {
2842×
                text.push_str(&format!("ca = {}\n", quote(&c.to_string_lossy())));
2856×
            }
286
        }
2878×
        let path = self.path();
2888×
        std::fs::create_dir_all(&self.home)
2898×
            .map_err(|e| format!("creating {}: {e}", self.home.display()))?;
2908×
        crate::durable::write_atomic_private(&path, text.as_bytes())
2918×
            .map_err(|e| format!("writing {}: {e}", path.display()))
2928×
    }
293
294
    /// The stored token and CA for `url`'s hub, if any: memoized, so a
295
    /// helper runs once per hub in a process. A file anyone else can read
296
    /// is ignored, with a warning.
2971251×
    pub fn lookup(&self, url: &str) -> (Option<String>, Option<PathBuf>) {
2981251×
        let Some(hub) = hub_of(url) else {
2991082×
            return (None, None);
300
        };
301169×
        let key = (self.home.clone(), hub.clone());
302169×
        if let Some(hit) = cache().lock().unwrap().get(&key) {
303136×
            return hit.clone();
30433×
        }
30533×
        let found = if self.too_open() {
3061×
            warn_once(&format!(
3071×
                "warning: {} can be read by other users, so oxy ignores it; run chmod 600 on it",
3081×
                self.path().display()
3091×
            ));
3101×
            (None, None)
311
        } else {
31232×
            match self.get(&hub) {
3133×
                Ok(Some(e)) => (e.token, e.ca),
31429×
                Ok(None) => (None, None),
3150×
                Err(e) => {
3160×
                    warn_once(&format!("warning: credentials for {hub}: {e}"));
3170×
                    (None, None)
318
                }
319
            }
320
        };
32133×
        cache().lock().unwrap().insert(key, found.clone());
32233×
        found
3231251×
    }
324
325
    /// Options for reaching `url` without a configured remote: `$OXY_TOKEN`
326
    /// and `$OXY_CA`, else what this store holds for its hub.
3271245×
    pub fn options_for(&self, url: &str) -> RemoteOptions {
3281245×
        let env_token = std::env::var("OXY_TOKEN").ok().filter(|t| !t.is_empty());
3291245×
        let env_ca = std::env::var("OXY_CA").ok().map(PathBuf::from);
3301245×
        let (token, ca) = match (&env_token, &env_ca) {
3310×
            (Some(_), Some(_)) => (None, None),
3321245×
            _ => self.lookup(url),
333
        };
3341245×
        RemoteOptions {
3351245×
            token: env_token.or(token),
3361245×
            ca: env_ca.or(ca),
3371245×
            ..RemoteOptions::default()
3381245×
        }
3391245×
    }
340
}
341
342
type Cache = Mutex<HashMap<(PathBuf, String), (Option<String>, Option<PathBuf>)>>;
343
344210×
fn cache() -> &'static Cache {
345
    static CACHE: OnceLock<Cache> = OnceLock::new();
346210×
    CACHE.get_or_init(Default::default)
347210×
}
348
3498×
fn forget_cached() {
3508×
    cache().lock().unwrap().clear();
3518×
}
352
3532×
pub(crate) fn warn_once(message: &str) {
354
    static SEEN: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
3552×
    if SEEN
3562×
        .get_or_init(Default::default)
3572×
        .lock()
3582×
        .unwrap()
3592×
        .insert(message.to_string())
3602×
    {
3612×
        eprintln!("{message}");
3622×
    }
3632×
}
364
36514×
fn quote(v: &str) -> String {
36614×
    let mut out = String::from('"');
36768×
    for c in v.chars() {
36868×
        match c {
3692×
            '"' => out.push_str("\\\""),
3700×
            '\\' => out.push_str("\\\\"),
3710×
            '\n' => out.push_str("\\n"),
37266×
            c => out.push(c),
373
        }
374
    }
37514×
    out.push('"');
37614×
    out
37714×
}
378
37941×
fn unquote(v: &str) -> Option<String> {
38041×
    let inner = v.strip_prefix('"')?.strip_suffix('"')?;
38141×
    let mut out = String::new();
38241×
    let mut chars = inner.chars();
383260×
    while let Some(c) = chars.next() {
384219×
        if c == '\\' {
3858×
            match chars.next()? {
3860×
                'n' => out.push('\n'),
3878×
                c => out.push(c),
388
            }
389211×
        } else {
390211×
            out.push(c);
391211×
        }
392
    }
39341×
    Some(out)
39441×
}
395
396
/// Run a credential helper (Git's protocol): `get`, `store` or `erase` for
397
/// `hub`. `get` returns the password the helper answered with.
398
///
399
/// `auth.helper` is a helper name (run as `git credential-NAME`), an
400
/// absolute path, or a shell command after `!`, as in Git.
4014×
fn run_helper(
4024×
    helper: &str,
4034×
    action: &str,
4044×
    hub: &str,
4054×
    token: Option<&str>,
4064×
) -> Result<Option<String>, String> {
4074×
    let (protocol, host) = hub
4084×
        .split_once("://")
4094×
        .ok_or_else(|| format!("{hub} is not a hub URL"))?;
4104×
    let mut cmd = if let Some(shell) = helper.strip_prefix('!') {
4114×
        let mut c = Command::new("sh");
4124×
        c.arg("-c").arg(format!("{shell} {action}"));
4134×
        c
4140×
    } else if Path::new(helper).is_absolute() {
4150×
        let mut c = Command::new(helper);
4160×
        c.arg(action);
4170×
        c
418
    } else {
4190×
        let mut c = Command::new("git");
4200×
        c.arg(format!("credential-{helper}")).arg(action);
4210×
        c
422
    };
4234×
    let mut input = format!("protocol={protocol}\nhost={host}\nusername={HELPER_USER}\n");
4244×
    if let Some(t) = token {
4251×
        input.push_str(&format!("password={t}\n"));
4263×
    }
4274×
    input.push('\n');
4284×
    let mut child = cmd
4294×
        .stdin(Stdio::piped())
4304×
        .stdout(Stdio::piped())
4314×
        .stderr(Stdio::inherit())
4324×
        .spawn()
4334×
        .map_err(|e| format!("running credential helper {helper:?}: {e}"))?;
4344×
    child
4354×
        .stdin
4364×
        .take()
4374×
        .expect("piped")
4384×
        .write_all(input.as_bytes())
4394×
        .map_err(|e| format!("credential helper {helper:?}: {e}"))?;
4404×
    let out = child
4414×
        .wait_with_output()
4424×
        .map_err(|e| format!("credential helper {helper:?}: {e}"))?;
4434×
    if !out.status.success() {
4440×
        return Err(format!("credential helper {helper:?} {action} failed"));
4454×
    }
4464×
    if action != "get" {
4472×
        return Ok(None);
4482×
    }
4492×
    Ok(String::from_utf8_lossy(&out.stdout)
4502×
        .lines()
4512×
        .find_map(|l| l.strip_prefix("password="))
4522×
        .map(String::from)
4532×
        .filter(|p| !p.is_empty()))
4544×
}
455
456
#[cfg(test)]
457
mod tests {
458
    use super::*;
459
460
    #[test]
4611×
    fn hubs_are_scheme_host_and_port() {
4621×
        assert_eq!(
4631×
            hub_of("https://OxygenHub.io/doomsdayone/metalgear").as_deref(),
464
            Some("https://oxygenhub.io")
465
        );
4661×
        assert_eq!(
4671×
            hub_of("http://127.0.0.1:7300/a/b").as_deref(),
468
            Some("http://127.0.0.1:7300")
469
        );
4701×
        assert_eq!(
4711×
            hub_of("https://user:[email protected]/x").as_deref(),
472
            Some("https://hub.example")
473
        );
4741×
        assert_eq!(hub_of("/srv/repo"), None);
4751×
        assert_eq!(hub_of("file:///srv/repo"), None);
4761×
    }
477
478
    #[test]
4791×
    fn tokens_go_over_https_or_to_this_machine() {
4801×
        assert!(token_allowed("https://oxygenhub.io/a/b"));
4811×
        assert!(token_allowed("http://127.0.0.1:7300/a/b"));
4821×
        assert!(token_allowed("http://localhost/a"));
4831×
        assert!(token_allowed("http://[::1]:8080/a"));
4841×
        assert!(!token_allowed("http://oxygenhub.io/a/b"));
4851×
        assert!(!token_allowed("http://10.0.0.1/a"));
4861×
        assert!(!token_allowed("http://127.0.0.1.evil.example/a"));
4871×
    }
488
489
    #[test]
4901×
    fn save_get_and_remove_round_trip_privately() {
4911×
        let dir = tempfile::tempdir().unwrap();
4921×
        let store = Credentials::at(dir.path());
4931×
        assert_eq!(store.get("https://hub.example").unwrap(), None);
4941×
        let stored = store
4951×
            .save("https://hub.example", "tok\"en", Some("andy"), None)
4961×
            .unwrap();
4971×
        assert_eq!(stored, Stored::File(store.path()));
4981×
        store
4991×
            .save(
5001×
                "http://127.0.0.1:7300",
5011×
                "local",
5021×
                None,
5031×
                Some(Path::new("/ca.pem")),
504
            )
5051×
            .unwrap();
5061×
        let e = store.get("https://hub.example").unwrap().unwrap();
5071×
        assert_eq!(e.token.as_deref(), Some("tok\"en"));
5081×
        assert_eq!(e.account.as_deref(), Some("andy"));
5091×
        assert!(!store.too_open());
5101×
        assert_eq!(
5111×
            store.lookup("https://hub.example/o/r"),
5121×
            (Some("tok\"en".into()), None)
513
        );
514
        // Another host, scheme or port gets nothing.
5151×
        assert_eq!(store.lookup("https://other.example/o/r"), (None, None));
5161×
        assert_eq!(store.lookup("http://hub.example/o/r"), (None, None));
5171×
        assert_eq!(store.lookup("https://hub.example:8443/o/r"), (None, None));
5181×
        let gone = store.remove("https://hub.example").unwrap().unwrap();
5191×
        assert_eq!(gone.token.as_deref(), Some("tok\"en"));
5201×
        assert_eq!(store.lookup("https://hub.example/o/r"), (None, None));
5211×
        assert_eq!(store.entries().unwrap().len(), 1);
5221×
    }
523
524
    #[cfg(unix)]
525
    #[test]
5261×
    fn a_file_others_can_read_is_ignored() {
527
        use std::os::unix::fs::PermissionsExt;
5281×
        let dir = tempfile::tempdir().unwrap();
5291×
        let store = Credentials::at(dir.path());
5301×
        store.save("https://open.example", "t", None, None).unwrap();
5311×
        let mode = std::fs::metadata(store.path())
5321×
            .unwrap()
5331×
            .permissions()
5341×
            .mode();
5351×
        assert_eq!(mode & 0o777, 0o600);
5361×
        std::fs::set_permissions(store.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
5371×
        assert!(store.too_open());
5381×
        assert_eq!(store.lookup("https://open.example/o/r"), (None, None));
5391×
    }
540
541
    #[cfg(unix)]
542
    #[test]
5431×
    fn a_helper_keeps_the_token_out_of_the_file() {
5441×
        let dir = tempfile::tempdir().unwrap();
5451×
        let vault = dir.path().join("vault");
546
        // A helper that keeps one password in a file, as a keyring would.
5471×
        let helper = format!(
548
            "!f() {{ case $1 in get) [ -f {v} ] && echo password=$(cat {v});; store) sed -n 's/^password=//p' > {v};; erase) rm -f {v};; esac; }}; f",
5491×
            v = vault.display()
550
        );
5511×
        std::fs::write(
5521×
            dir.path().join("config.toml"),
5531×
            format!("auth.helper = \"{helper}\"\n"),
554
        )
5551×
        .unwrap();
5561×
        let store = Credentials::at(dir.path());
5571×
        assert!(store.helper().is_some());
5581×
        let stored = store
5591×
            .save("https://hub.example", "secret", Some("andy"), None)
5601×
            .unwrap();
5611×
        assert!(matches!(stored, Stored::Helper(_)));
5621×
        let text = std::fs::read_to_string(store.path()).unwrap();
5631×
        assert!(!text.contains("secret"), "{text}");
5641×
        assert_eq!(
5651×
            store
5661×
                .get("https://hub.example")
5671×
                .unwrap()
5681×
                .unwrap()
5691×
                .token
5701×
                .as_deref(),
571
            Some("secret")
572
        );
5731×
        store.remove("https://hub.example").unwrap();
5741×
        assert!(!vault.exists());
5751×
    }
576
}