fakecloud-core 0.41.1

Core service traits and dispatch for FakeCloud
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
//! Shared container-to-host networking resolution for service runtimes
//! that spawn sibling containers (Lambda, ECS, RDS, ElastiCache).
//!
//! Captures the issue #1539 fix shape in one place so the four runtimes
//! that shell out to `docker`/`podman` can't drift apart again:
//!
//! - **podman** ships `host.containers.internal` as a built-in container
//!   DNS entry on every platform and must NOT receive
//!   `--add-host host.docker.internal:host-gateway` — rootless podman's
//!   gvproxy leaves the magic alias empty and the `create` fails with
//!   "host containers internal IP address is empty".
//! - **bare docker on Linux** has no `host-gateway` magic; the bridge
//!   gateway IP has to be resolved from the daemon and injected explicitly.
//! - **Docker Desktop on Mac/Windows** resolves the `host-gateway` magic
//!   value to the host's IP.
//! - when fakecloud itself runs in a container (`FAKECLOUD_IN_CONTAINER=1`,
//!   baked into the published image), the sibling containers it spawns
//!   publish their ports on the *host's* daemon — reachable from inside
//!   fakecloud's container as `host.docker.internal:<port>`, not
//!   `127.0.0.1:<port>`.

/// Actionable remediation appended to every error raised when a container
/// runtime (Docker/Podman) is required for an operation but none is
/// available. Kept in one place so RDS, Lambda, ECS, and the server startup
/// banner all surface the same fix steps and can't drift apart.
pub const CONTAINER_RUNTIME_HINT: &str = "Install and start Docker or Podman, or set FAKECLOUD_CONTAINER_CLI to your container CLI path.";

/// Auto-detect an available container CLI. Honors `FAKECLOUD_CONTAINER_CLI`
/// as an explicit override (returns `None` if the override doesn't work),
/// otherwise prefers `docker` then `podman`. Returns `None` when neither
/// is usable.
pub fn detect_container_cli() -> Option<String> {
    if let Ok(cli) = std::env::var("FAKECLOUD_CONTAINER_CLI") {
        return if cli_available(&cli) { Some(cli) } else { None };
    }
    if cli_available("docker") {
        Some("docker".to_string())
    } else if cli_available("podman") {
        Some("podman".to_string())
    } else {
        None
    }
}

/// How long to wait for `<cli> info` before giving up and treating the
/// runtime as unavailable. A healthy daemon answers in well under a second;
/// an unreachable or wedged daemon (stale `DOCKER_HOST`, Docker Desktop mid
/// start, a broken socket) can leave the CLI blocked on connect *forever*,
/// which would hang fakecloud startup and the test harness. Bounding the
/// probe turns "daemon wedged" into "no runtime detected" instead of a hang.
pub const CLI_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Process-global memo of `<cli> info` results, keyed by CLI name/path.
///
/// Container-runtime liveness is fixed for the life of a process, but every
/// service runtime (Lambda, ECS, RDS, ElastiCache, EC2, MQ, MSK, ...) probes
/// it independently at startup — a dozen-plus `detect_container_cli()` calls.
/// Without a memo each probe re-runs `docker info`; when the daemon is wedged
/// (see [`CLI_PROBE_TIMEOUT`]) those probes are serial 10s hangs that stack
/// into minutes, wedging server startup and the conformance `*_probe` tests.
/// Caching the first answer collapses that to a single probe.
static CLI_AVAILABLE_CACHE: std::sync::OnceLock<
    std::sync::Mutex<std::collections::HashMap<String, bool>>,
> = std::sync::OnceLock::new();

/// True when the CLI responds to `<cli> info` with success within
/// [`CLI_PROBE_TIMEOUT`] — the same liveness probe every runtime used before
/// this module existed, but bounded so an unreachable daemon can't hang the
/// caller indefinitely (the CLI blocks on connect with no timeout of its own),
/// and memoized per process so a dozen runtimes probing at startup don't each
/// pay that bound.
pub fn cli_available(cli: &str) -> bool {
    let cache =
        CLI_AVAILABLE_CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
    if let Some(&cached) = cache.lock().unwrap().get(cli) {
        return cached;
    }
    let result = probe_cli(cli);
    cache.lock().unwrap().insert(cli.to_string(), result);
    result
}

/// Run the bounded `<cli> info` liveness probe once (uncached).
fn probe_cli(cli: &str) -> bool {
    let child = std::process::Command::new(cli)
        .arg("info")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn();
    let Ok(mut child) = child else {
        return false;
    };
    let deadline = std::time::Instant::now() + CLI_PROBE_TIMEOUT;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => return status.success(),
            Ok(None) => {}
            Err(_) => return false,
        }
        if std::time::Instant::now() >= deadline {
            // Daemon is wedged: kill the blocked probe and report unavailable.
            let _ = child.kill();
            let _ = child.wait();
            return false;
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
}

/// True when `cli` is podman or a podman-compatible binary. Matches on the
/// filename component so absolute paths (`/opt/homebrew/bin/podman`) and
/// wrappers (`podman-remote`) both register as podman. Docker Desktop's
/// compatibility CLI is named `docker`, so this check is safe.
pub fn is_podman_binary(cli: &str) -> bool {
    std::path::Path::new(cli)
        .file_name()
        .and_then(|n| n.to_str())
        .map(|n| n.contains("podman"))
        .unwrap_or(false)
}

/// Detect the Docker bridge gateway IP on Linux. Returns `None` if
/// detection fails (caller falls back to the conventional `172.17.0.1`).
pub fn detect_bridge_gateway(cli: &str) -> Option<String> {
    let output = std::process::Command::new(cli)
        .args([
            "network",
            "inspect",
            "bridge",
            "--format",
            "{{range .IPAM.Config}}{{.Gateway}}{{end}}",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let gateway = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if gateway.is_empty() || !gateway.contains('.') {
        return None;
    }
    Some(gateway)
}

/// Resolved container-to-host networking for a given CLI. Built once at
/// runtime construction and reused for every container spawn.
#[derive(Debug, Clone)]
pub struct HostNetworking {
    /// DNS name a spawned container uses to reach fakecloud on the host.
    /// `host.containers.internal` for podman, `host.docker.internal` for
    /// docker.
    pub host_alias: String,
    /// `<alias>:<value>` argument for `--add-host`, injected into every
    /// container `create`/`run`. `None` when the runtime provides the
    /// alias natively (podman).
    pub add_host_arg: Option<String>,
    /// Address fakecloud uses to reach the *sibling* containers it just
    /// spawned (readiness probes + advertised endpoints). `127.0.0.1`
    /// when fakecloud runs on the host; `host.docker.internal` when
    /// fakecloud is itself containerized (`FAKECLOUD_IN_CONTAINER=1`).
    pub sibling_host: String,
}

impl HostNetworking {
    /// Resolve networking for `cli`, reading `FAKECLOUD_IN_CONTAINER` from
    /// the process environment.
    pub fn detect(cli: &str) -> Self {
        let (host_alias, add_host_arg) = resolve_host_alias(cli);
        let sibling_host =
            resolve_sibling_host(&host_alias, std::env::var("FAKECLOUD_IN_CONTAINER").ok());
        Self {
            host_alias,
            add_host_arg,
            sibling_host,
        }
    }

    /// Convenience: append the `--add-host <alias>:<value>` flag pair to a
    /// growing argv vector when this runtime needs an explicit mapping.
    /// No-op for podman.
    pub fn push_add_host_args(&self, argv: &mut Vec<String>) {
        if let Some(arg) = &self.add_host_arg {
            argv.push("--add-host".to_string());
            argv.push(arg.clone());
        }
    }
}

/// Compute the `(host_alias, add_host_arg)` pair for a CLI. Pure except
/// for the bridge-gateway daemon probe on Linux docker, so the macOS /
/// podman branches are unit-testable without a daemon.
pub fn resolve_host_alias(cli: &str) -> (String, Option<String>) {
    if is_podman_binary(cli) {
        // Podman provides `host.containers.internal` natively on every
        // supported platform; injecting `host-gateway` on macOS fails
        // because rootless podman's gvproxy doesn't expose the magic alias.
        ("host.containers.internal".to_string(), None)
    } else if cfg!(target_os = "linux") {
        // Bare docker on Linux: resolve the bridge gateway IP and add an
        // explicit alias. `host.docker.internal:host-gateway` only works
        // on Docker Desktop; native Linux docker has no such magic.
        let ip = detect_bridge_gateway(cli).unwrap_or_else(|| "172.17.0.1".to_string());
        (
            "host.docker.internal".to_string(),
            Some(format!("host.docker.internal:{ip}")),
        )
    } else {
        // Docker Desktop on Mac/Windows: `host-gateway` is the magic alias
        // that resolves to the host's IP.
        (
            "host.docker.internal".to_string(),
            Some("host.docker.internal:host-gateway".to_string()),
        )
    }
}

/// Decide what address fakecloud uses to reach the sibling containers it
/// just spawned. Pure helper so the env-var parsing can be tested without
/// touching the process's real environment.
///
/// - `Some("1")` / `Some("true")` (case-insensitive) -> fakecloud is in a
///   container; the siblings publish their ports on the host's daemon and
///   are reachable at the same host alias the spawned containers use to
///   reach fakecloud — `host.docker.internal` under docker,
///   `host.containers.internal` under podman. Hardcoding
///   `host.docker.internal` here broke podman, whose gvproxy network only
///   resolves `host.containers.internal` (issue #1539 follow-up).
/// - anything else, including `None` -> fakecloud runs on the host,
///   siblings live on `127.0.0.1:<port>`.
pub fn resolve_sibling_host(host_alias: &str, env_value: Option<String>) -> String {
    let in_container = env_value
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    if in_container {
        host_alias.to_string()
    } else {
        "127.0.0.1".to_string()
    }
}

/// Hostnames fakecloud's bundled ECR/OCI registry can be addressed by from a
/// sibling container, each at `server_port`.
///
/// A container-spawning service rewrites the image pull URI to the runtime's
/// sibling host -- `host.docker.internal` under Docker, `host.containers.internal`
/// under podman -- or leaves it `127.0.0.1` when fakecloud runs on the host. The
/// registry enforces auth, and the Docker/Podman CLI only attaches the
/// `Authorization` header for hosts present in `config.json`, so the isolated
/// pull config must list *every* alias or the pull gets a 401. The map
/// previously omitted the podman alias, so image-based Lambda/ECS pulls failed
/// under podman-in-a-container (bug-audit 2026-06-20, 0.B2). Authorize all of
/// them with the same credential; centralized here so the two builders can't
/// drift again.
pub fn registry_auth_hosts(server_port: u16) -> Vec<String> {
    [
        "127.0.0.1",
        "host.docker.internal",
        "host.containers.internal",
    ]
    .iter()
    .map(|host| format!("{host}:{server_port}"))
    .collect()
}

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

    #[test]
    fn cli_available_false_for_missing_binary() {
        // A binary that doesn't exist fails to spawn -> unavailable, fast.
        assert!(!cli_available("definitely-not-a-real-cli-binary-xyz-123"));
    }

    #[cfg(unix)]
    #[test]
    fn cli_available_bounds_a_hanging_probe() {
        // A CLI whose `info` invocation blocks forever (like `docker info`
        // against an unreachable daemon) must not hang the caller: the probe
        // is killed at CLI_PROBE_TIMEOUT and reported unavailable. Regression
        // test for the local-conformance-probe hang.
        use std::io::Write;
        use std::os::unix::fs::PermissionsExt;

        let dir = std::env::temp_dir().join(format!("fc-clitest-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let script = dir.join("hangcli");
        std::fs::write(&script, "#!/bin/sh\nsleep 600\n").unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::io::stdout().flush().ok();

        let start = std::time::Instant::now();
        let available = cli_available(script.to_str().unwrap());
        let elapsed = start.elapsed();

        std::fs::remove_dir_all(&dir).ok();
        assert!(!available, "a hanging probe must report unavailable");
        assert!(
            elapsed < CLI_PROBE_TIMEOUT + std::time::Duration::from_secs(5),
            "probe took {elapsed:?}, expected it bounded near {CLI_PROBE_TIMEOUT:?}"
        );
    }

    #[test]
    fn is_podman_binary_matches_bare_name() {
        assert!(is_podman_binary("podman"));
        assert!(is_podman_binary("podman-remote"));
    }

    #[test]
    fn registry_auth_hosts_includes_podman_alias() {
        // The podman sibling alias (host.containers.internal) must be authorized
        // or image-based Lambda/ECS pulls 401 under podman-in-a-container (0.B2).
        let hosts = registry_auth_hosts(4566);
        assert!(hosts.contains(&"127.0.0.1:4566".to_string()));
        assert!(hosts.contains(&"host.docker.internal:4566".to_string()));
        assert!(
            hosts.contains(&"host.containers.internal:4566".to_string()),
            "podman sibling alias must be authorized: {hosts:?}"
        );
    }

    #[test]
    fn is_podman_binary_matches_absolute_path() {
        assert!(is_podman_binary("/opt/homebrew/bin/podman"));
        assert!(is_podman_binary("/usr/local/bin/podman-remote"));
    }

    #[test]
    fn is_podman_binary_rejects_docker() {
        assert!(!is_podman_binary("docker"));
        assert!(!is_podman_binary("/usr/local/bin/docker"));
        assert!(!is_podman_binary("docker-credential-helper"));
    }

    #[test]
    fn resolve_host_alias_podman_has_no_add_host() {
        let (alias, add_host) = resolve_host_alias("podman");
        assert_eq!(alias, "host.containers.internal");
        assert_eq!(add_host, None);
        let (alias, add_host) = resolve_host_alias("/opt/homebrew/bin/podman");
        assert_eq!(alias, "host.containers.internal");
        assert_eq!(add_host, None);
    }

    #[test]
    fn resolve_host_alias_docker_emits_add_host() {
        let (alias, add_host) = resolve_host_alias("docker");
        assert_eq!(alias, "host.docker.internal");
        // On macOS this is host-gateway; on Linux it's a bridge IP. Either
        // way docker must get an explicit --add-host.
        assert!(add_host.is_some());
        assert!(add_host.unwrap().starts_with("host.docker.internal:"));
    }

    #[test]
    fn resolve_sibling_host_defaults_to_loopback() {
        assert_eq!(
            resolve_sibling_host("host.docker.internal", None),
            "127.0.0.1"
        );
        assert_eq!(
            resolve_sibling_host("host.docker.internal", Some(String::new())),
            "127.0.0.1"
        );
        assert_eq!(
            resolve_sibling_host("host.docker.internal", Some("0".to_string())),
            "127.0.0.1"
        );
        assert_eq!(
            resolve_sibling_host("host.containers.internal", Some("false".to_string())),
            "127.0.0.1"
        );
    }

    #[test]
    fn resolve_sibling_host_uses_host_alias_when_in_container() {
        // Docker: siblings reachable at host.docker.internal.
        assert_eq!(
            resolve_sibling_host("host.docker.internal", Some("1".to_string())),
            "host.docker.internal"
        );
        assert_eq!(
            resolve_sibling_host("host.docker.internal", Some("true".to_string())),
            "host.docker.internal"
        );
        assert_eq!(
            resolve_sibling_host("host.docker.internal", Some("TRUE".to_string())),
            "host.docker.internal"
        );
        // Podman: must use host.containers.internal, NOT host.docker.internal
        // (issue #1539 follow-up — gvproxy only resolves the containers alias).
        assert_eq!(
            resolve_sibling_host("host.containers.internal", Some("1".to_string())),
            "host.containers.internal"
        );
    }

    #[test]
    fn detect_wires_sibling_host_to_podman_alias_in_container() {
        // Full path: a podman binary in a container must advertise siblings
        // at host.containers.internal. resolve_host_alias drives host_alias,
        // which resolve_sibling_host then reuses.
        let (alias, add_host) = resolve_host_alias("podman");
        assert_eq!(alias, "host.containers.internal");
        assert_eq!(add_host, None);
        assert_eq!(
            resolve_sibling_host(&alias, Some("1".to_string())),
            "host.containers.internal"
        );
    }

    #[test]
    fn push_add_host_args_noop_for_podman() {
        let net = HostNetworking {
            host_alias: "host.containers.internal".to_string(),
            add_host_arg: None,
            sibling_host: "127.0.0.1".to_string(),
        };
        let mut argv = vec!["create".to_string()];
        net.push_add_host_args(&mut argv);
        assert_eq!(argv, vec!["create".to_string()]);
    }

    #[test]
    fn push_add_host_args_emits_for_docker() {
        let net = HostNetworking {
            host_alias: "host.docker.internal".to_string(),
            add_host_arg: Some("host.docker.internal:host-gateway".to_string()),
            sibling_host: "127.0.0.1".to_string(),
        };
        let mut argv = vec!["create".to_string()];
        net.push_add_host_args(&mut argv);
        assert_eq!(
            argv,
            vec![
                "create".to_string(),
                "--add-host".to_string(),
                "host.docker.internal:host-gateway".to_string(),
            ]
        );
    }
}