alien-core 3.3.26

Deploy software into your customers' cloud accounts and keep it fully managed
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
//! What a sandbox image must carry for the agent to serve, and the Dockerfile text carrying it.
//!
//! Two kinds of image exist and neither is built the way the other is. AWS renders one per
//! deployment onto a customer-supplied base image; GCP builds static images in CI. Nothing at build
//! time reads the other side, and a value that disagrees is invisible until a session fails: an
//! agent listening on a port no caller dials, or an exec into a uid the image never created.
//!
//! So the values live here once and both kinds render the block that carries them from this
//! module. The GCP Dockerfiles are committed as generated text because the release workflow builds
//! them with `docker build`, which cannot call a Rust function.

/// Path the agent binary is installed at inside every sandbox image.
///
/// An image that installs one path and entrypoints another exits before it serves, and the
/// session times out on connect.
pub const AGENT_PATH: &str = "/usr/local/bin/alien-sandbox-agent";

/// Port the agent serves unless the platform pins another.
///
/// Defined once because two independent copies are a runtime-only failure: the image build places
/// the agent on one port and the client dials the other, and nothing catches it until a sandbox
/// hangs. AWS scopes its endpoint token to an explicit port set, so this cannot be discovered.
pub const AGENT_PORT: u16 = 8971;

/// Mode of the agent binary, owned by `0:0` so the exec uid cannot rewrite its supervisor.
pub const AGENT_MODE: u32 = 0o755;

/// Name of the exec identity's passwd and group entries.
pub const EXEC_USER: &str = "sandbox";

/// Mode of the session root, which the exec uid owns.
pub const SESSION_ROOT_MODE: u32 = 0o700;

/// `RUST_LOG` for a GCP image, which the agent needs set before it logs anything.
pub const GCP_AGENT_LOG_FILTER: &str = "info";

/// How an image ends, and the isolation that ending permits.
///
/// One value rather than two, because `ALIEN_SANDBOX_ISOLATION` and the trailing `USER` describe
/// the same decision from opposite sides: an image that asks for `uid-split` under a non-root
/// `USER` has no privilege left to drop with, and every exec in it fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Isolation {
    /// The agent starts as root and drops to the exec uid before every spawn, so a command can
    /// never rewrite its own supervisor. The image declares no `USER`.
    UidSplit,
    /// The agent starts as the exec uid and supervises commands under it, which is all a runtime
    /// that refuses a root image can offer. The image ends `USER <uid>:<uid>`.
    Platform,
}

impl Isolation {
    /// The `ALIEN_SANDBOX_ISOLATION` value the agent parses.
    pub fn env_value(self) -> &'static str {
        match self {
            Self::UidSplit => "uid-split",
            Self::Platform => "platform",
        }
    }
}

/// How the agent decides a caller may be served.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Authorization {
    /// The connection is the proof. The agent serves an uncapabilitied request only from a socket
    /// peer it cannot trace back to the exec uid, which keeps the supervised command out.
    Transport,
    /// The caller presents a signed token, which is what a network anything can reach requires.
    Capability,
}

impl Authorization {
    /// The `ALIEN_SANDBOX_AUTHORIZATION` value the agent parses.
    pub fn env_value(self) -> &'static str {
        match self {
            Self::Transport => "transport",
            Self::Capability => "capability",
        }
    }
}

/// The values an image must carry for the agent to run in it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SandboxImage {
    /// Uid and gid the supervised command runs as.
    pub exec_uid: u32,
    /// Directory a session's files live under, and the only place `exec_uid` may write.
    pub session_root: &'static str,
    /// Port the agent serves, both its own protocol and any lifecycle hooks.
    pub port: u16,
    pub authorization: Authorization,
    pub isolation: Isolation,
}

impl SandboxImage {
    /// Gid the supervised command runs as, always equal to the exec uid.
    pub fn exec_gid(&self) -> u32 {
        self.exec_uid
    }

    /// The agent's configuration contract as `(name, value)` pairs, in the order the `ENV` block
    /// lists them.
    pub fn contract_env_vars(&self) -> [(&'static str, String); 6] {
        [
            ("ALIEN_SANDBOX_ROOT", self.session_root.to_string()),
            ("ALIEN_SANDBOX_PORT", self.port.to_string()),
            (
                "ALIEN_SANDBOX_AUTHORIZATION",
                self.authorization.env_value().to_string(),
            ),
            ("ALIEN_SANDBOX_EXEC_UID", self.exec_uid.to_string()),
            ("ALIEN_SANDBOX_EXEC_GID", self.exec_gid().to_string()),
            (
                "ALIEN_SANDBOX_ISOLATION",
                self.isolation.env_value().to_string(),
            ),
        ]
    }

    /// The `uid:gid` the image runs as, or `None` when it declares no user and starts as root.
    /// Why the gid is explicit is in the `USER` comment [`entrypoint`] renders.
    pub fn user(&self) -> Option<String> {
        match self.isolation {
            Isolation::UidSplit => None,
            Isolation::Platform => Some(format!("{}:{}", self.exec_uid, self.exec_gid())),
        }
    }

    /// The port the image exposes, as an OCI `ExposedPorts` key.
    pub fn exposed_port(&self) -> String {
        format!("{}/tcp", self.port)
    }

    /// The exec identity's `/etc/passwd` line, without a trailing newline.
    pub fn passwd_entry(&self) -> String {
        format!(
            "{EXEC_USER}:x:{uid}:{gid}::{root}:/sbin/nologin",
            uid = self.exec_uid,
            gid = self.exec_gid(),
            root = self.session_root,
        )
    }

    /// The exec identity's `/etc/group` line, without a trailing newline.
    pub fn group_entry(&self) -> String {
        format!("{EXEC_USER}:x:{gid}:", gid = self.exec_gid())
    }
}

/// The Lambda MicroVM image, rendered per deployment onto a customer base image.
///
/// The agent runs as root so it can drop to [`SandboxImage::exec_uid`] before every spawn; inside
/// a MicroVM that is contained by hardware virtualisation, which is the tenant boundary. A
/// shared-kernel backend must give the agent `CAP_SETUID` instead of root.
pub const AWS_MICROVM: SandboxImage = SandboxImage {
    exec_uid: 60000,
    session_root: "/sandbox",
    port: AGENT_PORT,
    authorization: Authorization::Transport,
    isolation: Isolation::UidSplit,
};

/// The GCP Agent Platform image, built once in CI and run with nothing layered on top.
///
/// 1000 is the conventional first non-root uid, chosen over the 60000 [`AWS_MICROVM`] uses because
/// that value was never tried against Agent Platform. One uid covers the agent and the commands it
/// supervises: Agent Platform refuses an image that requires root, so there is no second uid to
/// drop to.
///
/// Agent Platform is only known to serve 8080, on the image and on the declared template port
/// alike, and whether it honours a declared port or assumes 8080 has never been established.
/// 8080 is right under either answer; any other number is right under only one.
pub const GCP_AGENT_PLATFORM: SandboxImage = SandboxImage {
    exec_uid: 1000,
    session_root: "/sandbox",
    port: 8080,
    authorization: Authorization::Transport,
    isolation: Isolation::Platform,
};

/// Every variable a GCP Agent Platform image sets: the contract, then `RUST_LOG`.
pub fn gcp_agent_platform_env() -> Vec<(&'static str, String)> {
    let mut env = GCP_AGENT_PLATFORM.contract_env_vars().to_vec();
    env.push(("RUST_LOG", GCP_AGENT_LOG_FILTER.to_string()));
    env
}

/// The `RUN` step creating the exec identity and the session root it owns.
pub fn identity_setup(image: &SandboxImage) -> String {
    format!(
        r#"RUN printf '{passwd}\n' >> /etc/passwd \
 && printf '{group}\n' >> /etc/group \
 && mkdir -p {root} \
 && chown {uid}:{gid} {root} \
 && chmod {SESSION_ROOT_MODE:04o} {root}"#,
        passwd = image.passwd_entry(),
        group = image.group_entry(),
        root = image.session_root,
        uid = image.exec_uid,
        gid = image.exec_gid(),
    )
}

/// The `ENV` block carrying the agent's configuration contract.
pub fn contract_env(image: &SandboxImage) -> String {
    let vars: Vec<String> = image
        .contract_env_vars()
        .iter()
        .map(|(name, value)| format!("{name}={value}"))
        .collect();
    format!("ENV {}", vars.join(" \\\n    "))
}

/// `EXPOSE`, the image's ending, and the `ENTRYPOINT`.
pub fn entrypoint(image: &SandboxImage) -> String {
    let ending = match image.user() {
        None => String::new(),
        Some(user) => format!(
            "# Explicit gid so a runtime that does not read /etc/passwd cannot start the agent in \
             group 0, which\n# makes the exec drop a privilege crossing whose setgroups needs a \
             CAP_SETGID this image lacks, so\n# every exec fails.\nUSER {user}\n"
        ),
    };
    format!(
        "EXPOSE {port}\n{ending}ENTRYPOINT [\"{AGENT_PATH}\"]",
        port = image.exposed_port()
    )
}

/// Path of the committed minimal wolfi GCP Dockerfile, relative to the repository root.
#[cfg(test)]
const GCP_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-agent";

/// Path of the committed default GCP sandbox Dockerfile, relative to the repository root.
#[cfg(test)]
const GCP_DEFAULT_DOCKERFILE: &str = "docker/Dockerfile.alien-sandbox-gcp";

/// Set to regenerate the committed GCP Dockerfiles instead of comparing against them.
#[cfg(test)]
const GCP_DOCKERFILE_UPDATE: &str = "UPDATE_SANDBOX_AGENT_DOCKERFILE";

/// Renders [`GCP_DOCKERFILE`], the minimal wolfi image.
#[cfg(test)]
fn gcp_agent_platform_dockerfile() -> String {
    gcp_dockerfile(
        "Multi-arch build for the alien-sandbox-agent Docker image",
        "docker.io/chainguard/wolfi-base:latest",
        "# git is for the sandboxed command, not the agent, and pulls 24 transitive packages. That cost
# lands here because this image is the sandbox, with no customer base image underneath to carry it.
RUN apk add --no-cache git",
    )
}

/// Renders [`GCP_DEFAULT_DOCKERFILE`], the published default GCP sandbox image: the agent on
/// `buildpack-deps`, a full Ubuntu build toolchain.
#[cfg(test)]
fn gcp_default_sandbox_dockerfile() -> String {
    assert_eq!(
        GCP_AGENT_PLATFORM.exec_uid, 1000,
        "the userdel below exists only because Ubuntu's own user holds the exec uid"
    );
    gcp_dockerfile(
        "Multi-arch build for the default GCP sandbox image: buildpack-deps plus the agent",
        "docker.io/library/buildpack-deps:26.04",
        "# Ubuntu ships `ubuntu` at uid 1000. Appending a second entry for that uid leaves `id` and every
# tool resolving it to `ubuntu`, so the exec user would not be `sandbox`.
RUN userdel --remove ubuntu",
    )
}

/// Renders a GCP Dockerfile onto `base`, with `base_setup` run as root before the agent lands.
///
/// Everything outside the shared block is here because it is true of the GCP images alone: the
/// `binary-selector` stage, which exists because the release workflow builds one manifest for two
/// architectures from binaries cross-compiled outside Docker; and `RUST_LOG`, which the agent's own
/// `EnvFilter` needs before it will emit anything.
#[cfg(test)]
fn gcp_dockerfile(title: &str, base: &str, base_setup: &str) -> String {
    let image = &GCP_AGENT_PLATFORM;
    format!(
        r#"# Generated by `cargo test -p alien-core --lib sandbox_image`. Do not edit by hand.
# Regenerate with {GCP_DOCKERFILE_UPDATE}=1 in front of that command.
#
# {title}
# Run directly as the GCP Agent Platform sandbox; nothing layers on top of it

FROM docker.io/chainguard/wolfi-base:latest AS binary-selector

COPY target/aarch64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-aarch64
COPY target/x86_64-unknown-linux-musl/release/alien-sandbox-agent /tmp/alien-sandbox-agent-x86_64

ARG TARGETARCH
RUN case "$TARGETARCH" in \
       amd64)  cp /tmp/alien-sandbox-agent-x86_64 /tmp/alien-sandbox-agent ;; \
       arm64)  cp /tmp/alien-sandbox-agent-aarch64 /tmp/alien-sandbox-agent ;; \
       *)      echo "unsupported TARGETARCH '$TARGETARCH'" >&2; exit 1 ;; \
    esac

FROM {base}

{base_setup}

# Root-owned and unwritable by uid {exec_uid}: the supervised command runs under that uid and must not
# be able to rewrite its own supervisor.
COPY --from=binary-selector --chown=0:0 --chmod={AGENT_MODE:04o} \
     /tmp/alien-sandbox-agent {AGENT_PATH}

# Numeric ids and a plain append rather than adduser, which differs across base distributions.
# Linux runs a process under a uid with no passwd entry, but tooling inside the sandbox reads one.
{identity}

# The template carries no env, so the contract lives here, and none of it is optional. transport
# serves an uncapabilitied request only from a socket `peer::transport_may_serve` cannot trace
# back to the exec uid, and the agent refuses the mode where /proc/net/tcp is unreadable.
{env}

# The release build resolves tracing-subscriber once across every package it names, and five of
# them ask for env-filter, so the agent's fmt::init() has an EnvFilter under it. Unset, that
# filter discards the startup warning saying this image serves requests without a capability.
ENV RUST_LOG={GCP_AGENT_LOG_FILTER}

{entrypoint}
"#,
        exec_uid = image.exec_uid,
        identity = identity_setup(image),
        env = contract_env(image),
        entrypoint = entrypoint(image),
    )
}

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

    fn committed_path(relative: &str) -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .join(relative)
    }

    /// Where two texts first part, in terms a reader can act on. `assert_eq!` on a whole
    /// Dockerfile prints two escaped blobs and says nothing about which line moved.
    fn first_difference(committed: &str, rendered: &str) -> String {
        for (index, (left, right)) in committed.lines().zip(rendered.lines()).enumerate() {
            if left != right {
                let line = index + 1;
                return format!("line {line}: committed {left:?}, contract renders {right:?}");
            }
        }
        format!(
            "committed has {} lines, the contract renders {}",
            committed.lines().count(),
            rendered.lines().count()
        )
    }

    /// The whole file, not chosen properties. A mutation this comparison cannot see is one that
    /// leaves the bytes alone, and there is no such mutation.
    #[test]
    fn the_committed_gcp_dockerfiles_are_what_the_contract_renders() {
        for (file, rendered) in [
            (GCP_DOCKERFILE, gcp_agent_platform_dockerfile()),
            (GCP_DEFAULT_DOCKERFILE, gcp_default_sandbox_dockerfile()),
        ] {
            let path = committed_path(file);

            if std::env::var_os(GCP_DOCKERFILE_UPDATE).is_some() {
                std::fs::write(&path, &rendered)
                    .unwrap_or_else(|error| panic!("{} must be writable: {error}", path.display()));
                continue;
            }

            let committed = std::fs::read_to_string(&path)
                .unwrap_or_else(|error| panic!("{} must be readable: {error}", path.display()));
            assert!(
                committed == rendered,
                "{file} has drifted from the contract it is rendered from.\n\
                 {}\n\
                 Regenerate it: {GCP_DOCKERFILE_UPDATE}=1 cargo test -p alien-core --lib sandbox_image",
                first_difference(&committed, &rendered)
            );
        }
    }

    /// An image built without a Dockerfile carries what the CI images carry, so the env the
    /// accessor hands out is read back from the committed file rather than restated.
    #[test]
    fn the_gcp_env_accessor_is_every_env_the_committed_dockerfile_sets() {
        let committed = std::fs::read_to_string(committed_path(GCP_DEFAULT_DOCKERFILE)).unwrap();
        let mut set = Vec::new();
        let mut in_env = false;
        for line in committed.lines() {
            let line = line.trim();
            let rest = match line.strip_prefix("ENV ") {
                Some(rest) => rest,
                None if in_env => line,
                None => continue,
            };
            in_env = rest.ends_with('\\');
            for pair in rest.trim_end_matches('\\').split_whitespace() {
                let (name, value) = pair.split_once('=').expect("ENV name=value");
                set.push((name.to_string(), value.to_string()));
            }
        }
        let accessor: Vec<(String, String)> = gcp_agent_platform_env()
            .into_iter()
            .map(|(name, value)| (name.to_string(), value))
            .collect();
        assert_eq!(accessor, set);
    }

    /// Every consumer derives these, so nothing else compares them against a number. The
    /// setup emitters tell the agent which uid to drop to; if that stops matching the uid the
    /// image creates, the sandbox starts and every exec fails.
    #[test]
    fn the_two_images_carry_the_identities_their_stacks_were_built_against() {
        assert_eq!(AWS_MICROVM.port, 8971);
        assert_eq!(AWS_MICROVM.exec_uid, 60000);
        assert_eq!(AWS_MICROVM.session_root, "/sandbox");
        assert_eq!(GCP_AGENT_PLATFORM.port, 8080);
        assert_eq!(GCP_AGENT_PLATFORM.exec_uid, 1000);
        assert_eq!(GCP_AGENT_PLATFORM.session_root, "/sandbox");
        for image in [&AWS_MICROVM, &GCP_AGENT_PLATFORM] {
            assert_ne!(image.exec_uid, 0, "the exec uid must never be root");
        }
    }

    /// The ending an image declares and the isolation it claims come off one value, so they
    /// cannot disagree. The AWS half is rendered at run time and reaches no committed file, which
    /// is why the whole-file comparison above covers only the GCP side of it.
    #[test]
    fn the_ending_an_image_declares_follows_its_isolation() {
        assert!(!entrypoint(&AWS_MICROVM).contains("USER "));
        assert!(contract_env(&AWS_MICROVM).contains("ALIEN_SANDBOX_ISOLATION=uid-split"));
        assert!(entrypoint(&GCP_AGENT_PLATFORM).contains("\nUSER 1000:1000\n"));
        assert!(contract_env(&GCP_AGENT_PLATFORM).contains("ALIEN_SANDBOX_ISOLATION=platform"));
    }
}