OXYGENHUB

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

422 of 471 lines run, 61 of 86 functions · run #316 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.
372351×
pub fn hub_of(url: &str) -> Option<String> {
382351×
    let (scheme, rest) = url.split_once("://")?;
39419×
    let scheme = scheme.to_ascii_lowercase();
40419×
    if scheme != "http" && scheme != "https" {
41102×
        return None;
42317×
    }
43317×
    let host = rest.split(['/', '?', '#']).next()?;
44
    // Never key a hub on credentials embedded in the URL.
45317×
    let host = host.rsplit('@').next()?;
46317×
    if host.is_empty() {
470×
        return None;
48317×
    }
49317×
    Some(format!("{scheme}://{}", host.to_ascii_lowercase()))
502351×
}
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
    /// An agent's grant token for keyless signing (oxygenhub#241), when it
87
    /// is in the file (not with a helper).
88
    pub grant: Option<String>,
89
}
90
91
/// Where a saved token went.
92
#[derive(Clone, Debug, PartialEq, Eq)]
93
pub enum Stored {
94
    /// The credentials file, owner-only.
95
    File(PathBuf),
96
    /// A credential helper, by its `auth.helper` value.
97
    Helper(String),
98
}
99
100
/// The credential store of one oxy home directory.
101
#[derive(Clone, Debug)]
102
pub struct Credentials {
103
    home: PathBuf,
104
}
105
106
impl Credentials {
107
    /// The store in `home` (an oxy home directory).
1081288×
    pub fn at(home: impl Into<PathBuf>) -> Credentials {
1091288×
        Credentials { home: home.into() }
1101288×
    }
111
112
    /// The store in the user's oxy home directory.
113247×
    pub fn user() -> Credentials {
114247×
        Credentials::at(crate::repo::default_home())
115247×
    }
116
117
    /// `credentials.toml` in the home directory.
118113×
    pub fn path(&self) -> PathBuf {
119113×
        self.home.join("credentials.toml")
120113×
    }
121
122
    /// The configured credential helper (`auth.helper` in the user file).
12352×
    pub fn helper(&self) -> Option<String> {
12452×
        crate::repo::read_config_file(&self.home.join("config.toml"))
12552×
            .ok()?
12652×
            .remove("auth.helper")
12752×
            .filter(|h| !h.trim().is_empty())
12852×
    }
129
130
    /// Every hub in the file, tokens as stored there (none with a helper).
1311×
    pub fn entries(&self) -> Result<Vec<HubEntry>, String> {
1321×
        Ok(self.read()?.into_values().collect())
1331×
    }
134
135
    /// Whether the file can be read by anyone but its owner, in which case
136
    /// lookups ignore it.
13735×
    pub fn too_open(&self) -> bool {
138
        #[cfg(unix)]
139
        {
140
            use std::os::unix::fs::PermissionsExt;
14135×
            if let Ok(m) = std::fs::metadata(self.path()) {
14210×
                return m.permissions().mode() & 0o077 != 0;
14325×
            }
144
        }
14525×
        false
14635×
    }
147
148
    /// The entry for `hub`, its token fetched from the helper if one is set.
14939×
    pub fn get(&self, hub: &str) -> Result<Option<HubEntry>, String> {
15039×
        let entry = self.read()?.remove(hub);
15139×
        let helper = self.helper();
15239×
        let mut entry = match (entry, &helper) {
1539×
            (Some(e), _) => e,
154
            // A helper may hold a token stored before the file was cleared.
1550×
            (None, Some(_)) => HubEntry {
1560×
                hub: hub.to_string(),
1570×
                ..HubEntry::default()
1580×
            },
15930×
            (None, None) => return Ok(None),
160
        };
1619×
        if entry.token.is_none() {
1623×
            if let Some(h) = &helper {
1632×
                entry.token = run_helper(h, "get", hub, None)?;
1641×
            }
1656×
        }
1669×
        if entry.token.is_none()
1671×
            && entry.account.is_none()
1681×
            && entry.ca.is_none()
1691×
            && entry.grant.is_none()
170
        {
1710×
            return Ok(None);
1729×
        }
1739×
        Ok(Some(entry))
17439×
    }
175
176
    /// Save a token (and what is known about it) for `hub`.
1777×
    pub fn save(
1787×
        &self,
1797×
        hub: &str,
1807×
        token: &str,
1817×
        account: Option<&str>,
1827×
        ca: Option<&Path>,
1837×
    ) -> Result<Stored, String> {
1847×
        let mut all = self.read()?;
1857×
        let helper = self.helper();
1867×
        let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry {
1877×
            hub: hub.to_string(),
1887×
            ..HubEntry::default()
1897×
        });
1907×
        entry.account = account.map(String::from).or(entry.account.take());
1917×
        if let Some(ca) = ca {
1921×
            entry.ca = Some(ca.to_path_buf());
1936×
        }
1947×
        let stored = match &helper {
1951×
            Some(h) => {
1961×
                run_helper(h, "store", hub, Some(token))?;
1971×
                entry.token = None;
1981×
                Stored::Helper(h.clone())
199
            }
200
            None => {
2016×
                entry.token = Some(token.to_string());
2026×
                Stored::File(self.path())
203
            }
204
        };
2057×
        self.write(&all)?;
2067×
        forget_cached();
2077×
        Ok(stored)
2087×
    }
209
210
    /// Save an agent's grant token for `hub` (keyless signing, spec §14.7):
211
    /// in the file, or the helper under its own user name.
2122×
    pub fn save_grant(&self, hub: &str, token: &str) -> Result<Stored, String> {
2132×
        let mut all = self.read()?;
2142×
        let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry {
2151×
            hub: hub.to_string(),
2161×
            ..HubEntry::default()
2171×
        });
2182×
        let stored = match self.helper() {
2190×
            Some(h) => {
2200×
                run_helper_as(&h, "store", hub, GRANT_USER, Some(token))?;
2210×
                entry.grant = None;
2220×
                Stored::Helper(h)
223
            }
224
            None => {
2252×
                entry.grant = Some(token.to_string());
2262×
                Stored::File(self.path())
227
            }
228
        };
2292×
        self.write(&all)?;
2302×
        Ok(stored)
2312×
    }
232
233
    /// The agent grant token kept for `hub`, if any.
2342×
    pub fn grant(&self, hub: &str) -> Result<Option<String>, String> {
2352×
        if let Some(g) = self.read()?.get(hub).and_then(|e| e.grant.clone()) {
2361×
            return Ok(Some(g));
2371×
        }
2381×
        match self.helper() {
2390×
            Some(h) => run_helper_as(&h, "get", hub, GRANT_USER, None),
2401×
            None => Ok(None),
241
        }
2422×
    }
243
244
    /// Remove `hub` from the file and the helper; returns what it held,
245
    /// with the token, so the caller can revoke it.
2462×
    pub fn remove(&self, hub: &str) -> Result<Option<HubEntry>, String> {
2472×
        let found = self.get(hub)?;
2482×
        let mut all = self.read()?;
2492×
        if all.remove(hub).is_some() {
2502×
            self.write(&all)?;
2510×
        }
2522×
        if let Some(h) = self.helper() {
2531×
            run_helper(&h, "erase", hub, None)?;
2541×
        }
2552×
        forget_cached();
2562×
        Ok(found)
2572×
    }
258
25953×
    fn read(&self) -> Result<BTreeMap<String, HubEntry>, String> {
26053×
        let path = self.path();
26153×
        let text = match std::fs::read_to_string(&path) {
26220×
            Ok(t) => t,
26333×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
2640×
            Err(e) => return Err(format!("reading {}: {e}", path.display())),
265
        };
26620×
        let mut out = BTreeMap::new();
26720×
        let mut current: Option<HubEntry> = None;
268132×
        for (n, line) in text.lines().enumerate() {
269132×
            let line = line.trim();
270132×
            if line.is_empty() || line.starts_with('#') {
27148×
                continue;
27284×
            }
27384×
            if let Some(hub) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
27428×
                if let Some(e) = current.take() {
2758×
                    out.insert(e.hub.clone(), e);
27620×
                }
27728×
                current = Some(HubEntry {
27828×
                    hub: hub.trim().to_string(),
27928×
                    ..HubEntry::default()
28028×
                });
28128×
                continue;
28256×
            }
28356×
            let bad = || {
2840×
                format!(
285
                    "{} line {}: expected key = \"value\"",
2860×
                    path.display(),
2870×
                    n + 1
288
                )
2890×
            };
29056×
            let (k, v) = line.split_once('=').ok_or_else(bad)?;
29156×
            let v = unquote(v.trim()).ok_or_else(bad)?;
29256×
            let Some(e) = current.as_mut() else {
2930×
                return Err(format!(
2940×
                    "{} line {}: a key before any [hub] section",
2950×
                    path.display(),
2960×
                    n + 1
2970×
                ));
298
            };
29956×
            match k.trim() {
30056×
                "account" => e.account = Some(v),
30138×
                "token" => e.token = Some(v),
30214×
                "ca" => e.ca = Some(PathBuf::from(v)),
3035×
                "grant" => e.grant = Some(v),
304
                // Unknown keys are kept out of lookups, not fatal.
3050×
                _ => {}
306
            }
307
        }
30820×
        if let Some(e) = current {
30920×
            out.insert(e.hub.clone(), e);
31020×
        }
31120×
        Ok(out)
31253×
    }
313
31411×
    fn write(&self, all: &BTreeMap<String, HubEntry>) -> Result<(), String> {
31511×
        let mut text =
31611×
            String::from("# oxy credentials: a token for each hub. Keep this file private.\n");
31712×
        for e in all.values() {
31812×
            text.push_str(&format!("\n[{}]\n", e.hub));
31912×
            if let Some(a) = &e.account {
3208×
                text.push_str(&format!("account = {}\n", quote(a)));
3218×
            }
32212×
            if let Some(t) = &e.token {
32310×
                text.push_str(&format!("token = {}\n", quote(t)));
32410×
            }
32512×
            if let Some(c) = &e.ca {
3262×
                text.push_str(&format!("ca = {}\n", quote(&c.to_string_lossy())));
32710×
            }
32812×
            if let Some(g) = &e.grant {
3293×
                text.push_str(&format!("grant = {}\n", quote(g)));
3309×
            }
331
        }
33211×
        let path = self.path();
33311×
        std::fs::create_dir_all(&self.home)
33411×
            .map_err(|e| format!("creating {}: {e}", self.home.display()))?;
33511×
        crate::durable::write_atomic_private(&path, text.as_bytes())
33611×
            .map_err(|e| format!("writing {}: {e}", path.display()))
33711×
    }
338
339
    /// The stored token and CA for `url`'s hub, if any: memoized, so a
340
    /// helper runs once per hub in a process. A file anyone else can read
341
    /// is ignored, with a warning.
3421288×
    pub fn lookup(&self, url: &str) -> (Option<String>, Option<PathBuf>) {
3431288×
        let Some(hub) = hub_of(url) else {
3441127×
            return (None, None);
345
        };
346161×
        let key = (self.home.clone(), hub.clone());
347161×
        if let Some(hit) = cache().lock().unwrap().get(&key) {
348128×
            return hit.clone();
34933×
        }
35033×
        let found = if self.too_open() {
3511×
            warn_once(&format!(
3521×
                "warning: {} can be read by other users, so oxy ignores it; run chmod 600 on it",
3531×
                self.path().display()
3541×
            ));
3551×
            (None, None)
356
        } else {
35732×
            match self.get(&hub) {
3583×
                Ok(Some(e)) => (e.token, e.ca),
35929×
                Ok(None) => (None, None),
3600×
                Err(e) => {
3610×
                    warn_once(&format!("warning: credentials for {hub}: {e}"));
3620×
                    (None, None)
363
                }
364
            }
365
        };
36633×
        cache().lock().unwrap().insert(key, found.clone());
36733×
        found
3681288×
    }
369
370
    /// Options for reaching `url` without a configured remote: `$OXY_TOKEN`
371
    /// and `$OXY_CA`, else what this store holds for its hub.
3721282×
    pub fn options_for(&self, url: &str) -> RemoteOptions {
3731282×
        let env_token = std::env::var("OXY_TOKEN").ok().filter(|t| !t.is_empty());
3741282×
        let env_ca = std::env::var("OXY_CA").ok().map(PathBuf::from);
3751282×
        let (token, ca) = match (&env_token, &env_ca) {
3760×
            (Some(_), Some(_)) => (None, None),
3771282×
            _ => self.lookup(url),
378
        };
3791282×
        RemoteOptions {
3801282×
            token: env_token.or(token),
3811282×
            ca: env_ca.or(ca),
3821282×
            ..RemoteOptions::default()
3831282×
        }
3841282×
    }
385
}
386
387
type Cache = Mutex<HashMap<(PathBuf, String), (Option<String>, Option<PathBuf>)>>;
388
389203×
fn cache() -> &'static Cache {
390
    static CACHE: OnceLock<Cache> = OnceLock::new();
391203×
    CACHE.get_or_init(Default::default)
392203×
}
393
3949×
fn forget_cached() {
3959×
    cache().lock().unwrap().clear();
3969×
}
397
3982×
pub(crate) fn warn_once(message: &str) {
399
    static SEEN: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
4002×
    if SEEN
4012×
        .get_or_init(Default::default)
4022×
        .lock()
4032×
        .unwrap()
4042×
        .insert(message.to_string())
4052×
    {
4062×
        eprintln!("{message}");
4072×
    }
4082×
}
409
41023×
fn quote(v: &str) -> String {
41123×
    let mut out = String::from('"');
412134×
    for c in v.chars() {
413134×
        match c {
4142×
            '"' => out.push_str("\\\""),
4150×
            '\\' => out.push_str("\\\\"),
4160×
            '\n' => out.push_str("\\n"),
417132×
            c => out.push(c),
418
        }
419
    }
42023×
    out.push('"');
42123×
    out
42223×
}
423
42456×
fn unquote(v: &str) -> Option<String> {
42556×
    let inner = v.strip_prefix('"')?.strip_suffix('"')?;
42656×
    let mut out = String::new();
42756×
    let mut chars = inner.chars();
428385×
    while let Some(c) = chars.next() {
429329×
        if c == '\\' {
4308×
            match chars.next()? {
4310×
                'n' => out.push('\n'),
4328×
                c => out.push(c),
433
            }
434321×
        } else {
435321×
            out.push(c);
436321×
        }
437
    }
43856×
    Some(out)
43956×
}
440
441
/// Run a credential helper (Git's protocol): `get`, `store` or `erase` for
442
/// `hub`. `get` returns the password the helper answered with.
443
///
444
/// `auth.helper` is a helper name (run as `git credential-NAME`), an
445
/// absolute path, or a shell command after `!`, as in Git.
4464×
fn run_helper(
4474×
    helper: &str,
4484×
    action: &str,
4494×
    hub: &str,
4504×
    token: Option<&str>,
4514×
) -> Result<Option<String>, String> {
4524×
    run_helper_as(helper, action, hub, HELPER_USER, token)
4534×
}
454
455
/// The helper's user name for an agent's grant token, beside the hub's
456
/// own token.
457
const GRANT_USER: &str = "oxy-agent-grant";
458
4594×
fn run_helper_as(
4604×
    helper: &str,
4614×
    action: &str,
4624×
    hub: &str,
4634×
    user: &str,
4644×
    token: Option<&str>,
4654×
) -> Result<Option<String>, String> {
4664×
    let (protocol, host) = hub
4674×
        .split_once("://")
4684×
        .ok_or_else(|| format!("{hub} is not a hub URL"))?;
4694×
    let mut cmd = if let Some(shell) = helper.strip_prefix('!') {
4704×
        let mut c = Command::new("sh");
4714×
        c.arg("-c").arg(format!("{shell} {action}"));
4724×
        c
4730×
    } else if Path::new(helper).is_absolute() {
4740×
        let mut c = Command::new(helper);
4750×
        c.arg(action);
4760×
        c
477
    } else {
4780×
        let mut c = Command::new("git");
4790×
        c.arg(format!("credential-{helper}")).arg(action);
4800×
        c
481
    };
4824×
    let mut input = format!("protocol={protocol}\nhost={host}\nusername={user}\n");
4834×
    if let Some(t) = token {
4841×
        input.push_str(&format!("password={t}\n"));
4853×
    }
4864×
    input.push('\n');
4874×
    let mut child = cmd
4884×
        .stdin(Stdio::piped())
4894×
        .stdout(Stdio::piped())
4904×
        .stderr(Stdio::inherit())
4914×
        .spawn()
4924×
        .map_err(|e| format!("running credential helper {helper:?}: {e}"))?;
493
    // A helper need not read what it is told (an `erase` may just remove
494
    // its file and exit); as Git does, a closed pipe is no error. Whether
495
    // the helper succeeded is its exit status.
4964×
    match child
4974×
        .stdin
4984×
        .take()
4994×
        .expect("piped")
5004×
        .write_all(input.as_bytes())
501
    {
5020×
        Err(e) if e.kind() != std::io::ErrorKind::BrokenPipe => {
5030×
            return Err(format!("credential helper {helper:?}: {e}"));
504
        }
5054×
        _ => {}
506
    }
5074×
    let out = child
5084×
        .wait_with_output()
5094×
        .map_err(|e| format!("credential helper {helper:?}: {e}"))?;
5104×
    if !out.status.success() {
5110×
        return Err(format!("credential helper {helper:?} {action} failed"));
5124×
    }
5134×
    if action != "get" {
5142×
        return Ok(None);
5152×
    }
5162×
    Ok(String::from_utf8_lossy(&out.stdout)
5172×
        .lines()
5182×
        .find_map(|l| l.strip_prefix("password="))
5192×
        .map(String::from)
5202×
        .filter(|p| !p.is_empty()))
5214×
}
522
523
#[cfg(test)]
524
mod tests {
525
    use super::*;
526
527
    /// oxygenhub#241: an agent's grant token is kept beside the hub's own
528
    /// token, owner-only, and read back without disturbing it.
529
    #[test]
5301×
    fn a_grant_token_is_kept_beside_the_hub_token() {
5311×
        let dir = tempfile::tempdir().unwrap();
5321×
        let store = Credentials::at(dir.path());
5331×
        let hub = "https://oxygenhub.io";
5341×
        assert_eq!(store.grant(hub).unwrap(), None);
5351×
        store.save(hub, "oxyhub_t", Some("andy"), None).unwrap();
5361×
        store.save_grant(hub, "oxyagent_g").unwrap();
5371×
        assert_eq!(store.grant(hub).unwrap().as_deref(), Some("oxyagent_g"));
5381×
        let e = store.get(hub).unwrap().unwrap();
5391×
        assert_eq!(e.token.as_deref(), Some("oxyhub_t"));
5401×
        assert_eq!(e.account.as_deref(), Some("andy"));
541
        // A grant alone is an entry too.
5421×
        store
5431×
            .save_grant("https://elsewhere.example", "oxyagent_h")
5441×
            .unwrap();
5451×
        assert!(store.get("https://elsewhere.example").unwrap().is_some());
546
        #[cfg(unix)]
547
        {
548
            use std::os::unix::fs::PermissionsExt;
5491×
            let mode = std::fs::metadata(store.path())
5501×
                .unwrap()
5511×
                .permissions()
5521×
                .mode();
5531×
            assert_eq!(mode & 0o077, 0, "owner only");
554
        }
5551×
    }
556
557
    #[test]
5581×
    fn hubs_are_scheme_host_and_port() {
5591×
        assert_eq!(
5601×
            hub_of("https://OxygenHub.io/doomsdayone/metalgear").as_deref(),
561
            Some("https://oxygenhub.io")
562
        );
5631×
        assert_eq!(
5641×
            hub_of("http://127.0.0.1:7300/a/b").as_deref(),
565
            Some("http://127.0.0.1:7300")
566
        );
5671×
        assert_eq!(
5681×
            hub_of("https://user:[email protected]/x").as_deref(),
569
            Some("https://hub.example")
570
        );
5711×
        assert_eq!(hub_of("/srv/repo"), None);
5721×
        assert_eq!(hub_of("file:///srv/repo"), None);
5731×
    }
574
575
    #[test]
5761×
    fn tokens_go_over_https_or_to_this_machine() {
5771×
        assert!(token_allowed("https://oxygenhub.io/a/b"));
5781×
        assert!(token_allowed("http://127.0.0.1:7300/a/b"));
5791×
        assert!(token_allowed("http://localhost/a"));
5801×
        assert!(token_allowed("http://[::1]:8080/a"));
5811×
        assert!(!token_allowed("http://oxygenhub.io/a/b"));
5821×
        assert!(!token_allowed("http://10.0.0.1/a"));
5831×
        assert!(!token_allowed("http://127.0.0.1.evil.example/a"));
5841×
    }
585
586
    #[test]
5871×
    fn save_get_and_remove_round_trip_privately() {
5881×
        let dir = tempfile::tempdir().unwrap();
5891×
        let store = Credentials::at(dir.path());
5901×
        assert_eq!(store.get("https://hub.example").unwrap(), None);
5911×
        let stored = store
5921×
            .save("https://hub.example", "tok\"en", Some("andy"), None)
5931×
            .unwrap();
5941×
        assert_eq!(stored, Stored::File(store.path()));
5951×
        store
5961×
            .save(
5971×
                "http://127.0.0.1:7300",
5981×
                "local",
5991×
                None,
6001×
                Some(Path::new("/ca.pem")),
601
            )
6021×
            .unwrap();
6031×
        let e = store.get("https://hub.example").unwrap().unwrap();
6041×
        assert_eq!(e.token.as_deref(), Some("tok\"en"));
6051×
        assert_eq!(e.account.as_deref(), Some("andy"));
6061×
        assert!(!store.too_open());
6071×
        assert_eq!(
6081×
            store.lookup("https://hub.example/o/r"),
6091×
            (Some("tok\"en".into()), None)
610
        );
611
        // Another host, scheme or port gets nothing.
6121×
        assert_eq!(store.lookup("https://other.example/o/r"), (None, None));
6131×
        assert_eq!(store.lookup("http://hub.example/o/r"), (None, None));
6141×
        assert_eq!(store.lookup("https://hub.example:8443/o/r"), (None, None));
6151×
        let gone = store.remove("https://hub.example").unwrap().unwrap();
6161×
        assert_eq!(gone.token.as_deref(), Some("tok\"en"));
6171×
        assert_eq!(store.lookup("https://hub.example/o/r"), (None, None));
6181×
        assert_eq!(store.entries().unwrap().len(), 1);
6191×
    }
620
621
    #[cfg(unix)]
622
    #[test]
6231×
    fn a_file_others_can_read_is_ignored() {
624
        use std::os::unix::fs::PermissionsExt;
6251×
        let dir = tempfile::tempdir().unwrap();
6261×
        let store = Credentials::at(dir.path());
6271×
        store.save("https://open.example", "t", None, None).unwrap();
6281×
        let mode = std::fs::metadata(store.path())
6291×
            .unwrap()
6301×
            .permissions()
6311×
            .mode();
6321×
        assert_eq!(mode & 0o777, 0o600);
6331×
        std::fs::set_permissions(store.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
6341×
        assert!(store.too_open());
6351×
        assert_eq!(store.lookup("https://open.example/o/r"), (None, None));
6361×
    }
637
638
    #[cfg(unix)]
639
    #[test]
6401×
    fn a_helper_keeps_the_token_out_of_the_file() {
6411×
        let dir = tempfile::tempdir().unwrap();
6421×
        let vault = dir.path().join("vault");
643
        // A helper that keeps one password in a file, as a keyring would.
6441×
        let helper = format!(
645
            "!f() {{ case $1 in get) [ -f {v} ] && echo password=$(cat {v});; store) sed -n 's/^password=//p' > {v};; erase) rm -f {v};; esac; }}; f",
6461×
            v = vault.display()
647
        );
6481×
        std::fs::write(
6491×
            dir.path().join("config.toml"),
6501×
            format!("auth.helper = \"{helper}\"\n"),
651
        )
6521×
        .unwrap();
6531×
        let store = Credentials::at(dir.path());
6541×
        assert!(store.helper().is_some());
6551×
        let stored = store
6561×
            .save("https://hub.example", "secret", Some("andy"), None)
6571×
            .unwrap();
6581×
        assert!(matches!(stored, Stored::Helper(_)));
6591×
        let text = std::fs::read_to_string(store.path()).unwrap();
6601×
        assert!(!text.contains("secret"), "{text}");
6611×
        assert_eq!(
6621×
            store
6631×
                .get("https://hub.example")
6641×
                .unwrap()
6651×
                .unwrap()
6661×
                .token
6671×
                .as_deref(),
668
            Some("secret")
669
        );
6701×
        store.remove("https://hub.example").unwrap();
6711×
        assert!(!vault.exists());
6721×
    }
673
}