pelagos 0.1.1

Fast Linux container runtime — OCI-compatible, namespaces, cgroups v2, seccomp, networking, image management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Registry authentication provider.
//!
//! Resolution order:
//! 1. CLI flags (`username` + `password`)
//! 2. Environment variables (`REMORA_REGISTRY_USER` + `REMORA_REGISTRY_PASS`)
//! 3. `~/.docker/config.json`:
//!    a. `credHelpers[registry]` — per-registry credential helper
//!    b. `credsStore` — global credential helper
//!    c. `auths[registry].auth` — static base64-encoded `user:pass`
//! 4. `RegistryAuth::Anonymous`
//!
//! Credential helpers follow the Docker credential helper protocol:
//! - Binary: `docker-credential-<helper>` on PATH
//! - `get`: registry hostname → stdin; JSON `{"Username":"…","Secret":"…"}` ← stdout
//! - `store`: JSON `{"ServerURL":"…","Username":"…","Secret":"…"}` → stdin
//! - `erase`: registry hostname → stdin

use oci_client::secrets::RegistryAuth;

/// Resolve the best available auth for `registry`.
///
/// `registry` is the bare hostname, e.g. `"ghcr.io"`, `"docker.io"`.
pub fn resolve_auth(
    registry: &str,
    username: Option<&str>,
    password: Option<&str>,
) -> RegistryAuth {
    // 1. CLI flags take priority.
    if let (Some(u), Some(p)) = (username, password) {
        return RegistryAuth::Basic(u.to_string(), p.to_string());
    }

    // 2. Environment variables.
    let env_user = std::env::var("REMORA_REGISTRY_USER").ok();
    let env_pass = std::env::var("REMORA_REGISTRY_PASS").ok();
    if let (Some(u), Some(p)) = (env_user.as_deref(), env_pass.as_deref()) {
        if !u.is_empty() && !p.is_empty() {
            return RegistryAuth::Basic(u.to_string(), p.to_string());
        }
    }

    // 3. ~/.docker/config.json
    if let Some((u, p)) = parse_docker_config(registry) {
        return RegistryAuth::Basic(u, p);
    }

    RegistryAuth::Anonymous
}

/// Parse `~/.docker/config.json` and return `(username, password)` for `registry`.
///
/// Checks `credHelpers`, then `credsStore`, then `auths` (static base64).
pub fn parse_docker_config(registry: &str) -> Option<(String, String)> {
    let config_path = docker_config_path()?;
    let data = std::fs::read_to_string(config_path).ok()?;
    let value: serde_json::Value = serde_json::from_str(&data).ok()?;

    // 1. Per-registry or global credential helper.
    if let Some(helper) = find_credential_helper(&value, registry) {
        if let Some(creds) = call_credential_helper(&helper, registry) {
            return Some(creds);
        }
    }

    // 2. Static base64 credentials.
    let auths = value.get("auths")?.as_object()?;
    for key in registry_keys(registry) {
        if let Some(entry) = auths.get(&key) {
            if let Some(auth_b64) = entry.get("auth").and_then(|v| v.as_str()) {
                if let Some((u, p)) = decode_auth(auth_b64) {
                    return Some((u, p));
                }
            }
        }
    }
    None
}

/// Find the credential helper name for `registry` from a parsed config.json.
///
/// Checks `credHelpers[registry]` (per-registry) first, then `credsStore` (global).
/// Returns the bare helper name (e.g. `"ecr-login"`), not the full binary name.
pub(crate) fn find_credential_helper(config: &serde_json::Value, registry: &str) -> Option<String> {
    // Per-registry helpers take priority.
    for key in registry_keys(registry) {
        if let Some(helper) = config
            .get("credHelpers")
            .and_then(|h| h.get(&key))
            .and_then(|v| v.as_str())
        {
            return Some(helper.to_string());
        }
    }
    // Global fallback.
    config
        .get("credsStore")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
}

/// Invoke `docker-credential-<helper> get` and return `(username, secret)`.
///
/// Writes the registry hostname to the helper's stdin, reads JSON from stdout.
/// Returns `None` if the helper binary is not found or returns an error.
pub(crate) fn call_credential_helper(helper: &str, registry: &str) -> Option<(String, String)> {
    use std::io::Write as _;
    use std::process::{Command, Stdio};

    let binary = format!("docker-credential-{}", helper);
    let mut child = Command::new(&binary)
        .arg("get")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;

    // Write registry hostname (bare, without scheme) to stdin.
    let bare = registry
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_end_matches('/');
    child.stdin.take()?.write_all(bare.as_bytes()).ok()?;

    let output = child.wait_with_output().ok()?;
    if !output.status.success() {
        return None;
    }

    let json: serde_json::Value = serde_json::from_slice(&output.stdout).ok()?;
    let username = json.get("Username").and_then(|v| v.as_str())?.to_string();
    let secret = json.get("Secret").and_then(|v| v.as_str())?.to_string();
    Some((username, secret))
}

/// Invoke `docker-credential-<helper> store` to persist credentials.
fn store_via_helper(helper: &str, registry: &str, username: &str, password: &str) -> bool {
    use std::io::Write as _;
    use std::process::{Command, Stdio};

    let binary = format!("docker-credential-{}", helper);
    let payload = serde_json::json!({
        "ServerURL": registry,
        "Username": username,
        "Secret": password,
    });
    let Ok(mut child) = Command::new(&binary)
        .arg("store")
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(payload.to_string().as_bytes());
    }
    child.wait().map(|s| s.success()).unwrap_or(false)
}

/// Invoke `docker-credential-<helper> erase` to remove credentials.
fn erase_via_helper(helper: &str, registry: &str) -> bool {
    use std::io::Write as _;
    use std::process::{Command, Stdio};

    let binary = format!("docker-credential-{}", helper);
    let bare = registry
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_end_matches('/');
    let Ok(mut child) = Command::new(&binary)
        .arg("erase")
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    if let Some(mut stdin) = child.stdin.take() {
        let _ = stdin.write_all(bare.as_bytes());
    }
    child.wait().map(|s| s.success()).unwrap_or(false)
}

/// Write (or update) credentials for `registry`.
///
/// If a credential helper is configured for the registry (`credHelpers` or
/// `credsStore`), delegates to `docker-credential-<helper> store`.
/// Otherwise writes a static base64 entry into `~/.docker/config.json`.
pub fn write_docker_config(registry: &str, username: &str, password: &str) -> std::io::Result<()> {
    // Check for a configured helper first.
    if let Some(helper) = config_credential_helper(registry) {
        if store_via_helper(&helper, registry, username, password) {
            return Ok(());
        }
        // Helper available but failed — fall through to static storage.
        log::warn!(
            "credential helper '{}' store failed; falling back to config.json",
            helper
        );
    }

    let config_path = docker_config_path().ok_or_else(|| {
        std::io::Error::other("cannot determine HOME directory for docker config")
    })?;

    let mut value: serde_json::Value = if config_path.exists() {
        let data = std::fs::read_to_string(&config_path)?;
        serde_json::from_str(&data).unwrap_or(serde_json::json!({}))
    } else {
        serde_json::json!({})
    };

    if !value.get("auths").map(|v| v.is_object()).unwrap_or(false) {
        value["auths"] = serde_json::json!({});
    }

    let auth_b64 = base64_encode(format!("{}:{}", username, password).as_bytes());
    value["auths"][registry] = serde_json::json!({ "auth": auth_b64 });

    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let json =
        serde_json::to_string_pretty(&value).map_err(|e| std::io::Error::other(e.to_string()))?;
    std::fs::write(&config_path, json)
}

/// Remove credentials for `registry`.
///
/// If a credential helper is configured, delegates to `docker-credential-<helper> erase`.
/// Otherwise removes the `auths` entry from `~/.docker/config.json`.
pub fn remove_docker_config(registry: &str) -> std::io::Result<()> {
    // Check for a configured helper first.
    if let Some(helper) = config_credential_helper(registry) {
        if erase_via_helper(&helper, registry) {
            return Ok(());
        }
        log::warn!(
            "credential helper '{}' erase failed; falling back to config.json removal",
            helper
        );
    }

    let config_path = docker_config_path().ok_or_else(|| {
        std::io::Error::other("cannot determine HOME directory for docker config")
    })?;

    if !config_path.exists() {
        return Err(std::io::Error::other(format!(
            "not logged in to {}",
            registry
        )));
    }

    let data = std::fs::read_to_string(&config_path)?;
    let mut value: serde_json::Value =
        serde_json::from_str(&data).map_err(|e| std::io::Error::other(e.to_string()))?;

    let removed = if let Some(auths) = value.get_mut("auths").and_then(|v| v.as_object_mut()) {
        let mut removed = false;
        for key in registry_keys(registry) {
            if auths.remove(&key).is_some() {
                removed = true;
            }
        }
        removed
    } else {
        false
    };

    if !removed {
        return Err(std::io::Error::other(format!(
            "not logged in to {}",
            registry
        )));
    }

    let json =
        serde_json::to_string_pretty(&value).map_err(|e| std::io::Error::other(e.to_string()))?;
    std::fs::write(&config_path, json)
}

/// Return the credential helper name for `registry` from the live config, if any.
fn config_credential_helper(registry: &str) -> Option<String> {
    let config_path = docker_config_path()?;
    let data = std::fs::read_to_string(config_path).ok()?;
    let value: serde_json::Value = serde_json::from_str(&data).ok()?;
    find_credential_helper(&value, registry)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn docker_config_path() -> Option<std::path::PathBuf> {
    let home = std::env::var("HOME").ok()?;
    Some(
        std::path::PathBuf::from(home)
            .join(".docker")
            .join("config.json"),
    )
}

/// Return candidate registry keys for `~/.docker/config.json` lookup.
///
/// Docker uses different canonical forms depending on history:
/// - `docker.io` → also try `"https://index.docker.io/v1/"`
/// - All others → exact hostname plus `"https://<host>/"` variant
fn registry_keys(registry: &str) -> Vec<String> {
    let bare = registry
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_end_matches('/');
    // docker.io and index.docker.io are the same registry.  oci-client's
    // resolve_registry() maps "docker.io" → "index.docker.io", but users
    // naturally run `remora image login docker.io`, so we need to search
    // both forms regardless of which one was presented.
    match bare {
        "docker.io" | "index.docker.io" => vec![
            "docker.io".to_string(),
            "index.docker.io".to_string(),
            "https://index.docker.io/v1/".to_string(),
        ],
        _ => vec![bare.to_string(), format!("https://{}/", bare)],
    }
}

/// Decode a base64-encoded `"user:password"` string.
fn decode_auth(b64: &str) -> Option<(String, String)> {
    let decoded = base64_decode(b64.trim())?;
    let s = String::from_utf8(decoded).ok()?;
    let (u, p) = s.split_once(':')?;
    Some((u.to_string(), p.to_string()))
}

pub(crate) fn base64_encode(data: &[u8]) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char);
        out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char);
        out.push(if chunk.len() > 1 {
            ALPHABET[((n >> 6) & 0x3f) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            ALPHABET[(n & 0x3f) as usize] as char
        } else {
            '='
        });
    }
    out
}

fn base64_decode(b64: &str) -> Option<Vec<u8>> {
    fn char_to_val(c: u8) -> Option<u8> {
        match c {
            b'A'..=b'Z' => Some(c - b'A'),
            b'a'..=b'z' => Some(c - b'a' + 26),
            b'0'..=b'9' => Some(c - b'0' + 52),
            b'+' => Some(62),
            b'/' => Some(63),
            b'=' => Some(0),
            _ => None,
        }
    }
    let clean: Vec<u8> = b64.bytes().filter(|&b| !b" \t\r\n".contains(&b)).collect();
    if clean.len() % 4 != 0 {
        return None;
    }
    let mut out = Vec::with_capacity(clean.len() / 4 * 3);
    for chunk in clean.chunks(4) {
        let v0 = char_to_val(chunk[0])?;
        let v1 = char_to_val(chunk[1])?;
        let v2 = char_to_val(chunk[2])?;
        let v3 = char_to_val(chunk[3])?;
        let n = ((v0 as u32) << 18) | ((v1 as u32) << 12) | ((v2 as u32) << 6) | (v3 as u32);
        out.push((n >> 16) as u8);
        if chunk[2] != b'=' {
            out.push((n >> 8) as u8);
        }
        if chunk[3] != b'=' {
            out.push(n as u8);
        }
    }
    Some(out)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_base64_roundtrip() {
        let data = b"user:password123";
        let encoded = base64_encode(data);
        let decoded = base64_decode(&encoded).expect("decode");
        assert_eq!(decoded, data);
    }

    #[test]
    fn test_decode_auth_basic() {
        let b64 = base64_encode(b"user:pass");
        let (u, p) = decode_auth(&b64).expect("decode_auth");
        assert_eq!(u, "user");
        assert_eq!(p, "pass");
    }

    #[test]
    fn test_decode_auth_password_with_colon() {
        // Password contains ':', should split on first colon only.
        let b64 = base64_encode(b"user:pa:ss");
        let (u, p) = decode_auth(&b64).expect("decode_auth");
        assert_eq!(u, "user");
        assert_eq!(p, "pa:ss");
    }

    #[test]
    fn test_parse_docker_config_synthetic() {
        let tmp = tempfile::tempdir().expect("tmpdir");
        let docker_dir = tmp.path().join(".docker");
        std::fs::create_dir_all(&docker_dir).unwrap();
        let auth_b64 = base64_encode(b"myuser:mypass");
        let config = serde_json::json!({
            "auths": { "ghcr.io": { "auth": auth_b64 } }
        });
        std::fs::write(
            docker_dir.join("config.json"),
            serde_json::to_string(&config).unwrap(),
        )
        .unwrap();

        // Temporarily override HOME.
        let old_home = std::env::var("HOME").ok();
        std::env::set_var("HOME", tmp.path());
        let result = parse_docker_config("ghcr.io");
        if let Some(h) = old_home {
            std::env::set_var("HOME", h);
        } else {
            std::env::remove_var("HOME");
        }

        let (u, p) = result.expect("should find creds");
        assert_eq!(u, "myuser");
        assert_eq!(p, "mypass");
    }

    #[test]
    fn test_resolve_auth_env() {
        std::env::set_var("REMORA_REGISTRY_USER", "envuser");
        std::env::set_var("REMORA_REGISTRY_PASS", "envpass");
        let auth = resolve_auth("example.com", None, None);
        std::env::remove_var("REMORA_REGISTRY_USER");
        std::env::remove_var("REMORA_REGISTRY_PASS");
        match auth {
            RegistryAuth::Basic(u, p) => {
                assert_eq!(u, "envuser");
                assert_eq!(p, "envpass");
            }
            other => panic!("expected Basic, got {:?}", other),
        }
    }

    #[test]
    fn test_resolve_auth_cli_priority() {
        std::env::set_var("REMORA_REGISTRY_USER", "envuser");
        std::env::set_var("REMORA_REGISTRY_PASS", "envpass");
        let auth = resolve_auth("example.com", Some("cliuser"), Some("clipass"));
        std::env::remove_var("REMORA_REGISTRY_USER");
        std::env::remove_var("REMORA_REGISTRY_PASS");
        match auth {
            RegistryAuth::Basic(u, p) => {
                assert_eq!(u, "cliuser");
                assert_eq!(p, "clipass");
            }
            other => panic!("expected Basic, got {:?}", other),
        }
    }

    #[test]
    fn test_resolve_auth_anonymous() {
        std::env::remove_var("REMORA_REGISTRY_USER");
        std::env::remove_var("REMORA_REGISTRY_PASS");
        let tmp = tempfile::tempdir().unwrap();
        let old_home = std::env::var("HOME").ok();
        std::env::set_var("HOME", tmp.path());
        let auth = resolve_auth("nobody.example", None, None);
        if let Some(h) = old_home {
            std::env::set_var("HOME", h);
        } else {
            std::env::remove_var("HOME");
        }
        assert!(
            matches!(auth, RegistryAuth::Anonymous),
            "expected Anonymous"
        );
    }

    /// Verify `find_credential_helper` returns the per-registry helper when present.
    #[test]
    fn test_find_credential_helper_per_registry() {
        let config = serde_json::json!({
            "credHelpers": {
                "ghcr.io": "gh",
                "123.dkr.ecr.us-east-1.amazonaws.com": "ecr-login"
            },
            "credsStore": "desktop"
        });
        assert_eq!(
            find_credential_helper(&config, "ghcr.io"),
            Some("gh".to_string())
        );
        assert_eq!(
            find_credential_helper(&config, "123.dkr.ecr.us-east-1.amazonaws.com"),
            Some("ecr-login".to_string())
        );
    }

    /// Verify `find_credential_helper` falls back to `credsStore` when no per-registry entry.
    #[test]
    fn test_find_credential_helper_global_fallback() {
        let config = serde_json::json!({ "credsStore": "desktop" });
        assert_eq!(
            find_credential_helper(&config, "ghcr.io"),
            Some("desktop".to_string())
        );
    }

    /// Verify `find_credential_helper` returns None when neither key is present.
    #[test]
    fn test_find_credential_helper_none() {
        let config = serde_json::json!({ "auths": {} });
        assert_eq!(find_credential_helper(&config, "ghcr.io"), None);
    }

    /// Verify `call_credential_helper` parses the JSON output of a fake helper.
    ///
    /// Writes a small shell script that emits the expected JSON on stdout,
    /// adds the temp dir to PATH, then calls the helper.
    #[test]
    fn test_call_credential_helper_get() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let helper_path = tmp.path().join("docker-credential-fake-remora-test");
        std::fs::write(
            &helper_path,
            "#!/bin/sh\necho '{\"Username\":\"testuser\",\"Secret\":\"testpass\"}'\n",
        )
        .unwrap();
        // Make executable.
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(&helper_path, std::fs::Permissions::from_mode(0o755)).unwrap();

        // Prepend tmp dir to PATH so our fake binary is found.
        let original_path = std::env::var("PATH").unwrap_or_default();
        let new_path = format!("{}:{}", tmp.path().display(), original_path);
        std::env::set_var("PATH", &new_path);

        let result = call_credential_helper("fake-remora-test", "ghcr.io");

        std::env::set_var("PATH", original_path);

        let (u, p) = result.expect("helper should return creds");
        assert_eq!(u, "testuser");
        assert_eq!(p, "testpass");
    }

    /// Verify that `parse_docker_config` uses a configured helper over static auths.
    #[test]
    fn test_parse_docker_config_uses_helper() {
        let tmp = tempfile::tempdir().expect("tempdir");

        // Write fake helper binary.
        let helper_path = tmp.path().join("docker-credential-fake-remora-test2");
        std::fs::write(
            &helper_path,
            "#!/bin/sh\necho '{\"Username\":\"helperuser\",\"Secret\":\"helperpass\"}'\n",
        )
        .unwrap();
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(&helper_path, std::fs::Permissions::from_mode(0o755)).unwrap();

        // Write config.json that uses the helper for ghcr.io but also has a
        // static auths entry — helper must win.
        let docker_dir = tmp.path().join(".docker");
        std::fs::create_dir_all(&docker_dir).unwrap();
        let static_auth = base64_encode(b"staticuser:staticpass");
        let config = serde_json::json!({
            "credHelpers": { "ghcr.io": "fake-remora-test2" },
            "auths": { "ghcr.io": { "auth": static_auth } }
        });
        std::fs::write(
            docker_dir.join("config.json"),
            serde_json::to_string(&config).unwrap(),
        )
        .unwrap();

        let original_home = std::env::var("HOME").ok();
        let original_path = std::env::var("PATH").unwrap_or_default();
        std::env::set_var("HOME", tmp.path());
        std::env::set_var(
            "PATH",
            format!("{}:{}", tmp.path().display(), original_path),
        );

        let result = parse_docker_config("ghcr.io");

        if let Some(h) = original_home {
            std::env::set_var("HOME", h);
        } else {
            std::env::remove_var("HOME");
        }
        std::env::set_var("PATH", original_path);

        let (u, p) = result.expect("should find creds via helper");
        assert_eq!(u, "helperuser");
        assert_eq!(p, "helperpass");
    }

    #[test]
    fn test_registry_keys_docker_io() {
        let keys = registry_keys("docker.io");
        assert!(keys.contains(&"docker.io".to_string()));
        assert!(keys.contains(&"https://index.docker.io/v1/".to_string()));
    }

    #[test]
    fn test_registry_keys_other() {
        let keys = registry_keys("ghcr.io");
        assert!(keys.contains(&"ghcr.io".to_string()));
        // Exact hostname variant
        assert_eq!(keys[0], "ghcr.io");
    }
}