OXYGENHUB
◆ subrepo-pin-state oxygen / crates / oxy-core / src / credentials.rs
23.7 KiB · Rust · last changed Grant tokens reach hubs; unsetting core.sign works 18 days ago source blame history raw
ff1f62fe Andy McCall ↶ 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.
37
pub fn hub_of(url: &str) -> Option<String> {
38
    let (scheme, rest) = url.split_once("://")?;
39
    let scheme = scheme.to_ascii_lowercase();
40
    if scheme != "http" && scheme != "https" {
41
        return None;
42
    }
43
    let host = rest.split(['/', '?', '#']).next()?;
44
    // Never key a hub on credentials embedded in the URL.
45
    let host = host.rsplit('@').next()?;
46
    if host.is_empty() {
47
        return None;
48
    }
49
    Some(format!("{scheme}://{}", host.to_ascii_lowercase()))
50
}
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).
54
pub fn token_allowed(url: &str) -> bool {
55
    let Some(hub) = hub_of(url) else {
56
        return true;
57
    };
58
    match hub.split_once("://") {
59
        Some(("https", _)) => true,
60
        Some((_, host)) => {
61
            let name = match host.strip_prefix('[') {
62
                Some(v6) => v6.split(']').next().unwrap_or(""),
63
                None => host.rsplit_once(':').map_or(host, |(h, _)| h),
64
            };
65
            name == "localhost"
66
                || name == "::1"
67
                || name
68
                    .parse::<std::net::Ipv4Addr>()
69
                    .is_ok_and(|a| a.is_loopback())
70
        }
71
        None => false,
72
    }
73
}
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>,
c895bc52 Andy McCall ↶ 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>,
ff1f62fe Andy McCall ↶ 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).
108
    pub fn at(home: impl Into<PathBuf>) -> Credentials {
109
        Credentials { home: home.into() }
110
    }
111
112
    /// The store in the user's oxy home directory.
113
    pub fn user() -> Credentials {
114
        Credentials::at(crate::repo::default_home())
115
    }
116
117
    /// `credentials.toml` in the home directory.
118
    pub fn path(&self) -> PathBuf {
119
        self.home.join("credentials.toml")
120
    }
121
122
    /// The configured credential helper (`auth.helper` in the user file).
123
    pub fn helper(&self) -> Option<String> {
124
        crate::repo::read_config_file(&self.home.join("config.toml"))
125
            .ok()?
126
            .remove("auth.helper")
127
            .filter(|h| !h.trim().is_empty())
128
    }
129
130
    /// Every hub in the file, tokens as stored there (none with a helper).
131
    pub fn entries(&self) -> Result<Vec<HubEntry>, String> {
132
        Ok(self.read()?.into_values().collect())
133
    }
134
135
    /// Whether the file can be read by anyone but its owner, in which case
136
    /// lookups ignore it.
137
    pub fn too_open(&self) -> bool {
138
        #[cfg(unix)]
139
        {
140
            use std::os::unix::fs::PermissionsExt;
141
            if let Ok(m) = std::fs::metadata(self.path()) {
142
                return m.permissions().mode() & 0o077 != 0;
143
            }
144
        }
145
        false
146
    }
147
148
    /// The entry for `hub`, its token fetched from the helper if one is set.
149
    pub fn get(&self, hub: &str) -> Result<Option<HubEntry>, String> {
150
        let entry = self.read()?.remove(hub);
151
        let helper = self.helper();
152
        let mut entry = match (entry, &helper) {
153
            (Some(e), _) => e,
154
            // A helper may hold a token stored before the file was cleared.
155
            (None, Some(_)) => HubEntry {
156
                hub: hub.to_string(),
157
                ..HubEntry::default()
158
            },
159
            (None, None) => return Ok(None),
160
        };
161
        if entry.token.is_none() {
162
            if let Some(h) = &helper {
163
                entry.token = run_helper(h, "get", hub, None)?;
164
            }
165
        }
c895bc52 Andy McCall ↶ 166
        if entry.token.is_none()
167
            && entry.account.is_none()
168
            && entry.ca.is_none()
169
            && entry.grant.is_none()
170
        {
ff1f62fe Andy McCall ↶ 171
            return Ok(None);
172
        }
173
        Ok(Some(entry))
174
    }
175
176
    /// Save a token (and what is known about it) for `hub`.
177
    pub fn save(
178
        &self,
179
        hub: &str,
180
        token: &str,
181
        account: Option<&str>,
182
        ca: Option<&Path>,
183
    ) -> Result<Stored, String> {
184
        let mut all = self.read()?;
185
        let helper = self.helper();
186
        let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry {
187
            hub: hub.to_string(),
188
            ..HubEntry::default()
189
        });
190
        entry.account = account.map(String::from).or(entry.account.take());
191
        if let Some(ca) = ca {
192
            entry.ca = Some(ca.to_path_buf());
193
        }
194
        let stored = match &helper {
195
            Some(h) => {
196
                run_helper(h, "store", hub, Some(token))?;
197
                entry.token = None;
198
                Stored::Helper(h.clone())
199
            }
200
            None => {
201
                entry.token = Some(token.to_string());
202
                Stored::File(self.path())
203
            }
204
        };
205
        self.write(&all)?;
206
        forget_cached();
207
        Ok(stored)
208
    }
209
c895bc52 Andy McCall ↶ 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.
212
    pub fn save_grant(&self, hub: &str, token: &str) -> Result<Stored, String> {
213
        let mut all = self.read()?;
214
        let entry = all.entry(hub.to_string()).or_insert_with(|| HubEntry {
215
            hub: hub.to_string(),
216
            ..HubEntry::default()
217
        });
218
        let stored = match self.helper() {
219
            Some(h) => {
220
                run_helper_as(&h, "store", hub, GRANT_USER, Some(token))?;
221
                entry.grant = None;
222
                Stored::Helper(h)
223
            }
224
            None => {
225
                entry.grant = Some(token.to_string());
226
                Stored::File(self.path())
227
            }
228
        };
229
        self.write(&all)?;
230
        Ok(stored)
231
    }
232
233
    /// The agent grant token kept for `hub`, if any.
234
    pub fn grant(&self, hub: &str) -> Result<Option<String>, String> {
235
        if let Some(g) = self.read()?.get(hub).and_then(|e| e.grant.clone()) {
236
            return Ok(Some(g));
237
        }
238
        match self.helper() {
239
            Some(h) => run_helper_as(&h, "get", hub, GRANT_USER, None),
240
            None => Ok(None),
241
        }
242
    }
243
ff1f62fe Andy McCall ↶ 244
    /// Remove `hub` from the file and the helper; returns what it held,
245
    /// with the token, so the caller can revoke it.
246
    pub fn remove(&self, hub: &str) -> Result<Option<HubEntry>, String> {
247
        let found = self.get(hub)?;
248
        let mut all = self.read()?;
249
        if all.remove(hub).is_some() {
250
            self.write(&all)?;
251
        }
252
        if let Some(h) = self.helper() {
253
            run_helper(&h, "erase", hub, None)?;
254
        }
255
        forget_cached();
256
        Ok(found)
257
    }
258
259
    fn read(&self) -> Result<BTreeMap<String, HubEntry>, String> {
260
        let path = self.path();
261
        let text = match std::fs::read_to_string(&path) {
262
            Ok(t) => t,
263
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
264
            Err(e) => return Err(format!("reading {}: {e}", path.display())),
265
        };
266
        let mut out = BTreeMap::new();
267
        let mut current: Option<HubEntry> = None;
268
        for (n, line) in text.lines().enumerate() {
269
            let line = line.trim();
270
            if line.is_empty() || line.starts_with('#') {
271
                continue;
272
            }
273
            if let Some(hub) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
274
                if let Some(e) = current.take() {
275
                    out.insert(e.hub.clone(), e);
276
                }
277
                current = Some(HubEntry {
278
                    hub: hub.trim().to_string(),
279
                    ..HubEntry::default()
280
                });
281
                continue;
282
            }
283
            let bad = || {
284
                format!(
285
                    "{} line {}: expected key = \"value\"",
286
                    path.display(),
287
                    n + 1
288
                )
289
            };
290
            let (k, v) = line.split_once('=').ok_or_else(bad)?;
291
            let v = unquote(v.trim()).ok_or_else(bad)?;
292
            let Some(e) = current.as_mut() else {
293
                return Err(format!(
294
                    "{} line {}: a key before any [hub] section",
295
                    path.display(),
296
                    n + 1
297
                ));
298
            };
299
            match k.trim() {
300
                "account" => e.account = Some(v),
301
                "token" => e.token = Some(v),
302
                "ca" => e.ca = Some(PathBuf::from(v)),
c895bc52 Andy McCall ↶ 303
                "grant" => e.grant = Some(v),
ff1f62fe Andy McCall ↶ 304
                // Unknown keys are kept out of lookups, not fatal.
305
                _ => {}
306
            }
307
        }
308
        if let Some(e) = current {
309
            out.insert(e.hub.clone(), e);
310
        }
311
        Ok(out)
312
    }
313
314
    fn write(&self, all: &BTreeMap<String, HubEntry>) -> Result<(), String> {
315
        let mut text =
316
            String::from("# oxy credentials: a token for each hub. Keep this file private.\n");
317
        for e in all.values() {
318
            text.push_str(&format!("\n[{}]\n", e.hub));
319
            if let Some(a) = &e.account {
320
                text.push_str(&format!("account = {}\n", quote(a)));
321
            }
322
            if let Some(t) = &e.token {
323
                text.push_str(&format!("token = {}\n", quote(t)));
324
            }
325
            if let Some(c) = &e.ca {
326
                text.push_str(&format!("ca = {}\n", quote(&c.to_string_lossy())));
c895bc52 Andy McCall ↶ 327
            }
328
            if let Some(g) = &e.grant {
329
                text.push_str(&format!("grant = {}\n", quote(g)));
ff1f62fe Andy McCall ↶ 330
            }
331
        }
332
        let path = self.path();
333
        std::fs::create_dir_all(&self.home)
334
            .map_err(|e| format!("creating {}: {e}", self.home.display()))?;
335
        crate::durable::write_atomic_private(&path, text.as_bytes())
336
            .map_err(|e| format!("writing {}: {e}", path.display()))
337
    }
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.
342
    pub fn lookup(&self, url: &str) -> (Option<String>, Option<PathBuf>) {
343
        let Some(hub) = hub_of(url) else {
344
            return (None, None);
345
        };
346
        let key = (self.home.clone(), hub.clone());
347
        if let Some(hit) = cache().lock().unwrap().get(&key) {
348
            return hit.clone();
349
        }
350
        let found = if self.too_open() {
351
            warn_once(&format!(
352
                "warning: {} can be read by other users, so oxy ignores it; run chmod 600 on it",
353
                self.path().display()
354
            ));
355
            (None, None)
356
        } else {
357
            match self.get(&hub) {
c9635448 Andy McCall ↶ 358
                // An agent's grant token serves when the home holds no
359
                // other: the hub takes it for the owner's repositories
360
                // (keyless agents, oxygenhub#241).
361
                Ok(Some(e)) => (
362
                    e.token
363
                        .or(e.grant)
364
                        .or_else(|| self.grant(&hub).ok().flatten()),
365
                    e.ca,
366
                ),
ff1f62fe Andy McCall ↶ 367
                Ok(None) => (None, None),
368
                Err(e) => {
369
                    warn_once(&format!("warning: credentials for {hub}: {e}"));
370
                    (None, None)
371
                }
372
            }
373
        };
374
        cache().lock().unwrap().insert(key, found.clone());
375
        found
376
    }
377
378
    /// Options for reaching `url` without a configured remote: `$OXY_TOKEN`
379
    /// and `$OXY_CA`, else what this store holds for its hub.
380
    pub fn options_for(&self, url: &str) -> RemoteOptions {
381
        let env_token = std::env::var("OXY_TOKEN").ok().filter(|t| !t.is_empty());
382
        let env_ca = std::env::var("OXY_CA").ok().map(PathBuf::from);
383
        let (token, ca) = match (&env_token, &env_ca) {
384
            (Some(_), Some(_)) => (None, None),
385
            _ => self.lookup(url),
386
        };
387
        RemoteOptions {
388
            token: env_token.or(token),
389
            ca: env_ca.or(ca),
68a92484 Andy McCall ↶ 390
            ..RemoteOptions::default()
ff1f62fe Andy McCall ↶ 391
        }
392
    }
393
}
394
395
type Cache = Mutex<HashMap<(PathBuf, String), (Option<String>, Option<PathBuf>)>>;
396
397
fn cache() -> &'static Cache {
398
    static CACHE: OnceLock<Cache> = OnceLock::new();
399
    CACHE.get_or_init(Default::default)
400
}
401
402
fn forget_cached() {
403
    cache().lock().unwrap().clear();
404
}
405
68a92484 Andy McCall ↶ 406
pub(crate) fn warn_once(message: &str) {
ff1f62fe Andy McCall ↶ 407
    static SEEN: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
408
    if SEEN
409
        .get_or_init(Default::default)
410
        .lock()
411
        .unwrap()
412
        .insert(message.to_string())
413
    {
414
        eprintln!("{message}");
415
    }
416
}
417
418
fn quote(v: &str) -> String {
419
    let mut out = String::from('"');
420
    for c in v.chars() {
421
        match c {
422
            '"' => out.push_str("\\\""),
423
            '\\' => out.push_str("\\\\"),
424
            '\n' => out.push_str("\\n"),
425
            c => out.push(c),
426
        }
427
    }
428
    out.push('"');
429
    out
430
}
431
432
fn unquote(v: &str) -> Option<String> {
433
    let inner = v.strip_prefix('"')?.strip_suffix('"')?;
434
    let mut out = String::new();
435
    let mut chars = inner.chars();
436
    while let Some(c) = chars.next() {
437
        if c == '\\' {
438
            match chars.next()? {
439
                'n' => out.push('\n'),
440
                c => out.push(c),
441
            }
442
        } else {
443
            out.push(c);
444
        }
445
    }
446
    Some(out)
447
}
448
449
/// Run a credential helper (Git's protocol): `get`, `store` or `erase` for
450
/// `hub`. `get` returns the password the helper answered with.
451
///
452
/// `auth.helper` is a helper name (run as `git credential-NAME`), an
453
/// absolute path, or a shell command after `!`, as in Git.
454
fn run_helper(
455
    helper: &str,
456
    action: &str,
457
    hub: &str,
458
    token: Option<&str>,
459
) -> Result<Option<String>, String> {
c895bc52 Andy McCall ↶ 460
    run_helper_as(helper, action, hub, HELPER_USER, token)
461
}
462
463
/// The helper's user name for an agent's grant token, beside the hub's
464
/// own token.
465
const GRANT_USER: &str = "oxy-agent-grant";
466
467
fn run_helper_as(
468
    helper: &str,
469
    action: &str,
470
    hub: &str,
471
    user: &str,
472
    token: Option<&str>,
473
) -> Result<Option<String>, String> {
ff1f62fe Andy McCall ↶ 474
    let (protocol, host) = hub
475
        .split_once("://")
476
        .ok_or_else(|| format!("{hub} is not a hub URL"))?;
477
    let mut cmd = if let Some(shell) = helper.strip_prefix('!') {
478
        let mut c = Command::new("sh");
479
        c.arg("-c").arg(format!("{shell} {action}"));
480
        c
481
    } else if Path::new(helper).is_absolute() {
482
        let mut c = Command::new(helper);
483
        c.arg(action);
484
        c
485
    } else {
486
        let mut c = Command::new("git");
487
        c.arg(format!("credential-{helper}")).arg(action);
488
        c
489
    };
c895bc52 Andy McCall ↶ 490
    let mut input = format!("protocol={protocol}\nhost={host}\nusername={user}\n");
ff1f62fe Andy McCall ↶ 491
    if let Some(t) = token {
492
        input.push_str(&format!("password={t}\n"));
493
    }
494
    input.push('\n');
495
    let mut child = cmd
496
        .stdin(Stdio::piped())
497
        .stdout(Stdio::piped())
498
        .stderr(Stdio::inherit())
499
        .spawn()
500
        .map_err(|e| format!("running credential helper {helper:?}: {e}"))?;
e5f8920b Andy McCall ↶ 501
    // A helper need not read what it is told (an `erase` may just remove
502
    // its file and exit); as Git does, a closed pipe is no error. Whether
503
    // the helper succeeded is its exit status.
504
    match child
ff1f62fe Andy McCall ↶ 505
        .stdin
506
        .take()
507
        .expect("piped")
508
        .write_all(input.as_bytes())
e5f8920b Andy McCall ↶ 509
    {
510
        Err(e) if e.kind() != std::io::ErrorKind::BrokenPipe => {
511
            return Err(format!("credential helper {helper:?}: {e}"));
512
        }
513
        _ => {}
514
    }
ff1f62fe Andy McCall ↶ 515
    let out = child
516
        .wait_with_output()
517
        .map_err(|e| format!("credential helper {helper:?}: {e}"))?;
518
    if !out.status.success() {
519
        return Err(format!("credential helper {helper:?} {action} failed"));
520
    }
521
    if action != "get" {
522
        return Ok(None);
523
    }
524
    Ok(String::from_utf8_lossy(&out.stdout)
525
        .lines()
526
        .find_map(|l| l.strip_prefix("password="))
527
        .map(String::from)
528
        .filter(|p| !p.is_empty()))
529
}
530
531
#[cfg(test)]
532
mod tests {
533
    use super::*;
c895bc52 Andy McCall ↶ 534
535
    /// oxygenhub#241: an agent's grant token is kept beside the hub's own
536
    /// token, owner-only, and read back without disturbing it.
537
    #[test]
538
    fn a_grant_token_is_kept_beside_the_hub_token() {
539
        let dir = tempfile::tempdir().unwrap();
540
        let store = Credentials::at(dir.path());
541
        let hub = "https://oxygenhub.io";
542
        assert_eq!(store.grant(hub).unwrap(), None);
543
        store.save(hub, "oxyhub_t", Some("andy"), None).unwrap();
544
        store.save_grant(hub, "oxyagent_g").unwrap();
545
        assert_eq!(store.grant(hub).unwrap().as_deref(), Some("oxyagent_g"));
546
        let e = store.get(hub).unwrap().unwrap();
547
        assert_eq!(e.token.as_deref(), Some("oxyhub_t"));
548
        assert_eq!(e.account.as_deref(), Some("andy"));
549
        // A grant alone is an entry too.
550
        store
551
            .save_grant("https://elsewhere.example", "oxyagent_h")
552
            .unwrap();
553
        assert!(store.get("https://elsewhere.example").unwrap().is_some());
c9635448 Andy McCall ↶ 554
        // The grant is the credential a remote there is reached with;
555
        // beside a hub token, the hub token is.
556
        assert_eq!(
557
            store.lookup("https://elsewhere.example/a/b").0.as_deref(),
558
            Some("oxyagent_h")
559
        );
560
        assert_eq!(
561
            store.lookup("https://oxygenhub.io/a/b").0.as_deref(),
562
            Some("oxyhub_t")
563
        );
c895bc52 Andy McCall ↶ 564
        #[cfg(unix)]
565
        {
566
            use std::os::unix::fs::PermissionsExt;
567
            let mode = std::fs::metadata(store.path())
568
                .unwrap()
569
                .permissions()
570
                .mode();
571
            assert_eq!(mode & 0o077, 0, "owner only");
572
        }
573
    }
ff1f62fe Andy McCall ↶ 574
575
    #[test]
576
    fn hubs_are_scheme_host_and_port() {
577
        assert_eq!(
578
            hub_of("https://OxygenHub.io/doomsdayone/metalgear").as_deref(),
579
            Some("https://oxygenhub.io")
580
        );
581
        assert_eq!(
582
            hub_of("http://127.0.0.1:7300/a/b").as_deref(),
583
            Some("http://127.0.0.1:7300")
584
        );
585
        assert_eq!(
586
            hub_of("https://user:[email protected]/x").as_deref(),
587
            Some("https://hub.example")
588
        );
589
        assert_eq!(hub_of("/srv/repo"), None);
590
        assert_eq!(hub_of("file:///srv/repo"), None);
591
    }
592
593
    #[test]
594
    fn tokens_go_over_https_or_to_this_machine() {
595
        assert!(token_allowed("https://oxygenhub.io/a/b"));
596
        assert!(token_allowed("http://127.0.0.1:7300/a/b"));
597
        assert!(token_allowed("http://localhost/a"));
598
        assert!(token_allowed("http://[::1]:8080/a"));
599
        assert!(!token_allowed("http://oxygenhub.io/a/b"));
600
        assert!(!token_allowed("http://10.0.0.1/a"));
601
        assert!(!token_allowed("http://127.0.0.1.evil.example/a"));
602
    }
603
604
    #[test]
605
    fn save_get_and_remove_round_trip_privately() {
606
        let dir = tempfile::tempdir().unwrap();
607
        let store = Credentials::at(dir.path());
608
        assert_eq!(store.get("https://hub.example").unwrap(), None);
609
        let stored = store
610
            .save("https://hub.example", "tok\"en", Some("andy"), None)
611
            .unwrap();
612
        assert_eq!(stored, Stored::File(store.path()));
613
        store
614
            .save(
615
                "http://127.0.0.1:7300",
616
                "local",
617
                None,
618
                Some(Path::new("/ca.pem")),
619
            )
620
            .unwrap();
621
        let e = store.get("https://hub.example").unwrap().unwrap();
622
        assert_eq!(e.token.as_deref(), Some("tok\"en"));
623
        assert_eq!(e.account.as_deref(), Some("andy"));
624
        assert!(!store.too_open());
625
        assert_eq!(
626
            store.lookup("https://hub.example/o/r"),
627
            (Some("tok\"en".into()), None)
628
        );
629
        // Another host, scheme or port gets nothing.
630
        assert_eq!(store.lookup("https://other.example/o/r"), (None, None));
631
        assert_eq!(store.lookup("http://hub.example/o/r"), (None, None));
632
        assert_eq!(store.lookup("https://hub.example:8443/o/r"), (None, None));
633
        let gone = store.remove("https://hub.example").unwrap().unwrap();
634
        assert_eq!(gone.token.as_deref(), Some("tok\"en"));
635
        assert_eq!(store.lookup("https://hub.example/o/r"), (None, None));
636
        assert_eq!(store.entries().unwrap().len(), 1);
637
    }
638
639
    #[cfg(unix)]
640
    #[test]
641
    fn a_file_others_can_read_is_ignored() {
642
        use std::os::unix::fs::PermissionsExt;
643
        let dir = tempfile::tempdir().unwrap();
644
        let store = Credentials::at(dir.path());
645
        store.save("https://open.example", "t", None, None).unwrap();
646
        let mode = std::fs::metadata(store.path())
647
            .unwrap()
648
            .permissions()
649
            .mode();
650
        assert_eq!(mode & 0o777, 0o600);
651
        std::fs::set_permissions(store.path(), std::fs::Permissions::from_mode(0o644)).unwrap();
652
        assert!(store.too_open());
653
        assert_eq!(store.lookup("https://open.example/o/r"), (None, None));
654
    }
655
656
    #[cfg(unix)]
657
    #[test]
658
    fn a_helper_keeps_the_token_out_of_the_file() {
659
        let dir = tempfile::tempdir().unwrap();
660
        let vault = dir.path().join("vault");
661
        // A helper that keeps one password in a file, as a keyring would.
662
        let helper = format!(
663
            "!f() {{ case $1 in get) [ -f {v} ] && echo password=$(cat {v});; store) sed -n 's/^password=//p' > {v};; erase) rm -f {v};; esac; }}; f",
664
            v = vault.display()
665
        );
666
        std::fs::write(
667
            dir.path().join("config.toml"),
668
            format!("auth.helper = \"{helper}\"\n"),
669
        )
670
        .unwrap();
671
        let store = Credentials::at(dir.path());
672
        assert!(store.helper().is_some());
673
        let stored = store
674
            .save("https://hub.example", "secret", Some("andy"), None)
675
            .unwrap();
676
        assert!(matches!(stored, Stored::Helper(_)));
677
        let text = std::fs::read_to_string(store.path()).unwrap();
678
        assert!(!text.contains("secret"), "{text}");
679
        assert_eq!(
680
            store
681
                .get("https://hub.example")
682
                .unwrap()
683
                .unwrap()
684
                .token
685
                .as_deref(),
686
            Some("secret")
687
        );
688
        store.remove("https://hub.example").unwrap();
689
        assert!(!vault.exists());
690
    }
691
}