We are going to design a system for hermetic builds with a focus on cache correctness, which includes:
- Hashing: to uniquely identify build inputs and outputs.
- Sandboxing: to isolate builds and ensure they are reproducible.
- Poisoning defenses: to prevent or detect the use of untrusted or tampered inputs.
- Metrics: to measure and improve the hermeticity and correctness of the build.
Let's break down each component.
-
Hashing:
- We need to hash all build inputs (source files, configuration files, environment variables, toolchain versions, etc.) to create a content-addressable key.
- We also hash the build output (artifacts) to verify that the same inputs produce the same output.
-
Sandboxing:
- The build must run in an isolated environment (e.g., using containers, chroot, or other OS-level isolation) to prevent access to non-declared inputs.
- The sandbox should have a known, fixed environment (e.g., fixed current working directory, fixed environment variables, no network access by default, etc.).
-
Poisoning defenses:
- This includes ensuring that the build does not use any non-hermetic inputs (like the current time, random numbers, or system state).
- We can use techniques like:
a. Static analysis of build scripts to detect non-hermetic operations.
b. Runtime monitoring (seccomp, ptrace, etc.) to block system calls that would break hermeticity.
c. Providing deterministic substitutes for non-hermetic operations (e.g., a fixed time, a deterministic random number generator).
-
Metrics:
- We need to collect metrics on:
a. Cache hits and misses (to see if hermeticity is working and caching is effective).
b. Build times (to ensure that hermetic builds are not significantly slower).
c. Number of non-hermetic operations detected or blocked.
d. The size of the sandbox environment (how many files are made available) to ensure minimalism.
Implementation plan:
Step 1: Define the hash of the build.
- The build key (or cache key) is a hash of:
* The source tree (all files that are part of the build, including build scripts and configuration).
* The toolchain (exact versions of compilers, linkers, etc. and their configuration).
* The build environment (variables that affect the build, e.g., CFLAGS, but only those that are explicitly declared as affecting the build).
* The sandbox configuration (to ensure that the same sandbox is used for the same build key).
We can use a hash function (like SHA-256) and combine the hashes of these components.
Step 2: Sandbox setup.
- Before running the build, set up a sandbox that contains:
* The source files (from the hash above) mounted at a fixed path.
* The toolchain (pre-determined, and we assume it is hermetic itself).
* A minimal set of system files (e.g., /etc/passwd, /etc/group, but static and fixed).
- The sandbox should not have access to the host's network, and should have a fixed current working directory.
Step 3: Poisoning defenses.
- In the sandbox, we can set environment variables to fixed values (e.g., SOURCE_DATE_EPOCH for deterministic timestamps).
- We can use a patched toolchain that is built to be hermetic (or configure the existing one to be deterministic).
- We can use seccomp to filter system calls that might break hermeticity (e.g., gettimeofday, clock_gettime, etc.) and instead provide a fixed time.
- We can also intercept random number generation (e.g., by preloading a library that overrides /dev/urandom with a deterministic stream).
Step 4: Build execution and caching.
- Run the build inside the sandbox.
- After the build, hash the output artifacts (the files that are declared as build outputs).
- Compare the hash of the output with any existing cache entry (using the build key as the cache key). If the hash matches, we can use the cached output. Otherwise, store the new output and its hash.
Step 5: Metrics collection.
- Log every build attempt: whether it was a cache hit or miss, the time taken, and any non-hermetic operations that were blocked.
- Also, log the size of the sandbox (number of files, total size) to ensure we are not including unnecessary files.
Step 6: Verification.
- Periodically, we should rebuild the same build key in a fresh sandbox and compare the output hash to ensure that the build is truly hermetic.
However, note that building a fully hermetic build system is very challenging. We might have to accept some non-hermetic aspects and then try to mitigate them.
Let's design a simple prototype for a single build (e.g., a C program compiled with gcc).
Example:
Build key = hash(
hash(all source files in the src directory and the build script),
hash(toolchain info: gcc version, configured with ...),
hash(build environment variables: e.g., CFLAGS, but only the ones we consider),
hash(sandbox config: which system files are included, etc.)
)
Sandbox:
We use a container (Docker) or a chroot with:
- The source tree (from the hash above) mounted at /src.
- The toolchain installed in the container (or mounted from the host, but then we must hash the toolchain binaries).
- A fixed /etc/passwd and /etc/group (with a fixed user and group for the build).
- No network.
Poisoning defenses:
Set SOURCE_DATE_EPOCH to a fixed value (e.g., 0).
Use a seccomp profile that blocks gettimeofday, clock_gettime, and other non-hermetic syscalls? But note that some builds might need time. Instead, we can intercept these calls and return a fixed time.
For random numbers, we can mount a tmpfs with a pre-seeded /dev/urandom (or use a library that overrides rand()).
Build command:
In the sandbox, run the build script (e.g., make) with the current working directory set to /src.
After build, collect the output files (e.g., the binary) and compute their hash.
Then, check the cache: if the build key exists and the output hash matches, we have a cache hit. Otherwise, cache the output.
Metrics:
Record the build key, whether it was a hit or miss, the time, and any seccomp violations (if we log them).
However, note that the above example is for a C build. For other languages, we might need different toolchains and different non-hermetic operations.
Let's generalize:
We need a build system that can:
- Define what the inputs are (this is the job of the build definition, e.g., a BUILD file in Bazel).
- Define what the outputs are.
- Define the command to run (and the environment).
Then, the hermetic build system will:
- Compute the hash of the inputs (recursively, if the inputs are directories).
- Set up a sandbox with exactly those inputs and the toolchain.
- Run the command in the sandbox with the specified environment.
- Collect the outputs and hash them.
The cache key is the hash of the inputs, the command, and the environment (and the toolchain, which is part of the environment).
But note: the command itself might be non-hermetic if it uses the current time or random numbers. So we must either:
- Modify the command (or the toolchain) to be hermetic, or
- Intercept the non-hermetic operations.
This is where poisoning defenses come in.
Alternatively, we can require that the build command is written in a way that is hermetic (e.g., by using deterministic builds flags). But that is not always possible.
Therefore, we might need to have a set of known non-hermetic operations and provide deterministic replacements for them.
Example for C:
- Use -frandom-seed for gcc to make the output deterministic.
- Use -Wl,--build-id=none to avoid build-id which might include a timestamp.
- Use SOURCE_DATE_EPOCH for the timestamp in the binary (if the binary format supports it).
But note: even with these, there might be other non-hermeticities (like the order of files in the archive, or the path names).
So, we might need to have a per-language strategy.
Given the complexity, we might design a system that:
-
Has a pluggable layer for each language/toolchain to define:
- How to make the toolchain hermetic (e.g., flags to pass).
- What non-hermetic operations to watch for and how to replace them.
-
The core system provides:
- Sandboxing (with seccomp, namespaces, etc.)
- A way to inject deterministic versions of non-hermetic operations (e.g., by preloading a library that overrides gettimeofday, or by mounting a fixed /dev/urandom).
-
The build definition (e.g., a rule) must declare:
- The source files.
- The toolchain (or the toolchain is implicit in the rule).
- The command to run.
- The environment variables that affect the build.
Then, the core system computes the hash of:
- The source files (by their content).
- The toolchain (by its version and its own hash? or by the files in the toolchain?).
- The command (the exact string, but note that the command might be a script that we also hash?).
- The environment variables (only the ones that are declared as affecting the build?).
But note: the command might be a script that is also a source file? Then it's already included in the source files.
So, we can say:
Build key = hash(
hash(all source files and build scripts),
hash(toolchain: the set of binaries and their hashes, or a version string that is known to be hermetic),
hash(environment variables that are declared as affecting the build),
hash(sandbox configuration: which system files are included, etc.)
)
However, the toolchain might be too big to hash every time. We can precompute the hash of the toolchain and use that as a fixed value.
Steps for a build:
- The build system (e.g., Bazel) receives a build request for a target.
- It collects all the dependencies (source files, generated files, etc.) and the toolchain.
- It computes the build key.
- It checks the cache: if there is an entry for that build key and the output hash matches (the output hash is stored in the cache), then it returns the cached output.
- Otherwise, it sets up a sandbox with:
- The source files (from the computed set) mounted at a fixed path.
- The toolchain (from the toolchain repository) mounted at a fixed path.
- A minimal set of system files (from a known, fixed set).
- Environment variables set to the declared ones (and possibly some fixed ones like SOURCE_DATE_EPOCH).
- It runs the command (from the build rule) in the sandbox.
- It collects the output files (declared in the rule) and computes their hash.
- It stores the output in the cache (if the build succeeded) and returns the output.
For poisoning defenses:
- During the build, if the sandbox detects a non-hermetic operation (via seccomp or other means), it can either block it (and provide a deterministic value) or log it and let the build continue (but then the build is not hermetic and we should not cache it).
So, we might want to:
- If any non-hermetic operation is detected, mark the build as non-hermetic and do not cache the output (or cache it but with a note that it is non-hermetic, and maybe not reuse it for other builds?).
But note: we want to enforce hermeticity, so we might want to fail the build if a non-hermetic operation is detected.
Alternatively, we can have a mode that allows non-hermetic operations (for debugging) but then we don't cache.
Given the goal of hermetic builds, we should:
- By default, fail the build if a non-hermetic operation is detected.
- Have a way to whitelist certain operations (if we know they are safe) or to provide replacements.
This is a very complex system.
Given the scope, let's outline a minimal viable product for a specific language (C) and a specific build system (make).
We'll assume:
- The build is driven by a Makefile.
- The Makefile is written to be hermetic (or we patch it to be hermetic).
Steps for C:
Toolchain: we use a Docker image that has a hermetic toolchain (e.g., with deterministic flags set).
The build system (our wrapper) will:
1. Compute the hash of the source tree (including the Makefile and all source files).
2. Check the cache.
3. If not in cache, run the build in a Docker container with:
- The source tree mounted.
- The toolchain (from the Docker image).
- Environment:
SOURCE_DATE_EPOCH=0
TZ=UTC
- Seccomp profile that blocks gettimeofday, clock_gettime, etc. (but note: some builds might need time? Then we must intercept and return a fixed time. We can use a seccomp that allows the syscall but returns a fixed value? Or we can use a preloaded library that overrides the libc functions?).
4. After build, collect the output (the binary) and compute its hash.
5. Store in cache.
But note: the Makefile might have non-hermetisms, like using `$(shell date)` or `$(shell fortune)`. We must catch these.
We can:
- Run the Makefile in a dry-run mode to see what commands it runs, and then check those commands for non-hermetic operations? But that is complex.
Alternatively, we can run the build in the sandbox and monitor the syscalls. If we see a non-hermetic syscall (like gettimeofday) that we haven't allowed, we fail.
For C builds, we can set:
- The compiler flags: -frandom-seed=0, -Wl,--build-id=none, and maybe others.
But the Makefile might not use these flags. So we must either:
a) Patch the Makefile to add these flags, or
b) Set environment variables that the Makefile uses (like CFLAGS) and hope that the Makefile uses them.
This is why hermetic builds are hard.
Given the complexity, we might need to have a per-project configuration that specifies:
- The toolchain (and its hermetic flags).
- The environment variables that affect the build.
- The list of non-hermetic operations that are allowed (and how to replace them).
Alternatively, we can have a standard way for the build system (like Bazel) to declare these.
Since we are designing a system, let's assume we are building on top of an existing build system that already has some hermeticity (like Bazel).
In Bazel, we have:
- Starlark rules that declare their inputs and outputs.
- The execution platform (toolchain) is declared.
- The sandboxing is built-in.
So, we can extend Bazel with:
- A way to compute a hash of the entire build (including the toolchain and the platform) and use that as the cache key.
- Additional poisoning defenses (like seccomp profiles, deterministic random, etc.) that are automatically applied.
But Bazel already does some of this.
Given the open-ended question, we can design a system that:
- Uses content-addressable storage for the build inputs and outputs.
- Runs builds in a sandbox that provides a minimal, fixed environment.
- Uses a combination of static analysis (of the build scripts) and runtime monitoring (seccomp) to enforce hermeticity.
- Collects metrics on cache efficiency and hermeticity violations.
We'll break down the design into modules:
Module 1: Content Addrissing and Hashing
- Compute a hash of the entire source tree (including build scripts and configuration) by walking the tree and hashing each file (by content and path). We can use a Merkle tree for efficiency.
- Compute a hash of the toolchain: we can precompute the hash of the toolchain (by hashing all the binaries in the toolchain) and store it as a fixed value. Alternatively, we can require that the toolchain is identified by a hash (e.g., the toolchain is stored in a content-addressable store and we refer to it by its hash).
- The build key is then: hash( source_tree_hash, toolchain_hash, environment_hash, sandbox_config_hash )
Module 2: Sandbox
- We use a container runtime (Docker, podman, etc.) or a chroot with:
* The source tree (from the source_tree_hash) mounted at a fixed path.
* The toolchain (from the toolchain_hash) mounted at a fixed path.
* A fixed set of system files (from a known base image or a predefined set).
- We set the current working directory to the source tree mount point.
- We set environment variables to the declared ones (and some fixed ones for hermeticity, like SOURCE_DATE_EPOCH=0).
Module 3: Poisoning Defenses
- We use a seccomp profile that blocks:
* gettimeofday, clock_gettime (and return a fixed time, e.g., 0)
* getrandom, /dev/urandom (and return a fixed stream of zeros? or a fixed stream from a seed)
* network syscalls (if not allowed)
* any other syscall that might break hermeticity (like reading from /proc, etc.)
- We can also use a preloaded library that overrides libc functions that are non-hermetic (like time(), rand(), etc.) to return deterministic values.
Module 4: Build Execution and Caching
- Run the build command (from the build rule) in the sandbox.
- If the build fails, do not cache.
- If the build succeeds, collect the output files (declared in the rule) and compute a hash of the entire output set (e.g., hash of the concatenation of all output files? or a Merkle tree of the output directory?).
- Store the output in a content-addressable store, keyed by the build key.
Module 5: Metrics
- Log for each build:
* Build key (or a hash of it, to avoid logging large strings)
* Whether it was a cache hit or miss.
* The time taken (in the sandbox).
* Any seccomp violations (if we log them, we can count how many non-hermetic operations were attempted).
* The size of the output (and the number of files).
- We can also log the size of the sandbox (number of files and total size of the source tree and toolchain).
Step 6: Verification
- Periodically, we can rebuild the same build key in a fresh sandbox and compare the output hash. If they differ, we have a non-hermetic build.
However, note that the build might be non-hermetic because of:
- The order of files in an archive (if the toolchain does not sort).
- The current time (if not overridden).
- The random seed (if not fixed).
- The user name or host name (if included in the build).
- The path of the source tree (if absolute paths are embedded).
So, we must also:
- Ensure that the toolchain is built to be hermetic (or use a hermetic toolchain).
- Ensure that the build script (Makefile, etc.) does not use absolute paths or host-specific information.
This is why hermetic builds are hard and often require a lot of work.
Given the complexity, we might start with a simpler system that only works for a specific language and a specific set of build rules, and then generalize.
Let's design for C with Make, and assume we have a Makefile that is written to be hermetic (or we patch it to be hermetic).
We'll create a wrapper around make that:
- Computes the hash of the source tree (excluding any build outputs, i.e., only the inputs).
- Sets up a sandbox (using Docker) with:
* The source tree (except any files that are generated by the build? but then the Makefile might generate files and then use them. So we must include the generated files as inputs? That's the challenge of hermetic builds: we must know all inputs. In a Makefile, we might have generated sources. So we must run the generate step in the sandbox too. So the entire build must be in the sandbox, and we must capture all inputs that are read during the build. This is where we need to monitor the filesystem access. That's even harder.
Alternatively, we require that the build rule declares all inputs (including generated ones) and then we only provide those. But then we must generate them first? That's a chicken and egg problem.
So, for a general build system, we need:
- A way to declare all inputs (including generated ones) before the build. This is what Bazel does with its Starlark rules: they declare the inputs and outputs.
Therefore, we assume that the build system we are extending already has a way to declare the inputs and outputs.
In our design, we require:
- The build rule (or the build system) must provide:
* A list of all input files (source and generated) that are read by the build.
* A list of all output files (the artifacts).
* The command to run (and the environment).
Then, we can:
- Hash the input files (by their content and path) to get the source_tree_hash.
- Hash the toolchain (by its content, or by a version string that we trust to be hermetic).
- Hash the environment variables (the ones that are declared as affecting the build).
- Hash the sandbox configuration (which system files we include, etc.).
- Then, set up the sandbox with exactly the input files (and the toolchain) and run the command.
- After the build, we check that the output files are exactly the declared ones (and that no extra files were created? or we allow extra files but we only cache the declared ones?).
- Then, we hash the output files (the declared ones) and store them.
But note: the build might read additional files that are not declared (like from /usr/include). That would break hermeticity. So we must:
- In the sandbox, only provide the declared input files and the toolchain (and a minimal set of system headers, etc.). But then the build might fail because it expects system headers.
- So we must also provide the system headers? But then the system headers become part of the toolchain? Or we consider the toolchain to include the system headers? This is system-dependent.
Given the complexity, we might have to accept that the sandbox must include a minimal system (like a root filesystem) for the build to run. But then we must hash that system too? Otherwise, the same build on two different systems (with different system headers) might produce different outputs.
So, the toolchain must include the system headers? Or we must fix the system?
In practice, hermetic builds often use a toolchain that is built for a specific target and includes the necessary system headers (like a sysroot). So the toolchain includes the sysroot.
Therefore, we assume:
- The toolchain is a self-contained directory that includes the compiler and the sysroot (for C, the C library and headers).
Then, in the sandbox, we mount:
- The toolchain at /toolchain (and set the appropriate environment variables, like `SYSROOT=/toolchain/sysroot`).
- The source tree at /src.
And the build command is run with the appropriate flags (like --sysroot=/toolchain/sysroot).
Then, the only inputs are the source tree and the toolchain.
So, the build key is:
hash( source_tree_hash, toolchain_hash, environment_hash, sandbox_config_hash )
And the sandbox config hash is for the minimal system files (like /etc/passwd, /etc/group) that we provide. We can fix these to be the same for all builds? Then we don't need to include them in the hash? But if we change them, we might break the build. So we should fix them and then not include them in the hash? Or include them in the hash to detect changes?
We can have a fixed set of system files (from a known base image) and then we don't need to hash them because they are fixed. But then if we update the base image, we must change the hash? Actually, we want the build to be hermetic, so we must fix the system files. So we can:
- Use a fixed base image (with fixed system files) and then the hash of the base image is part of the toolchain? Or we consider the base image as part of the toolchain?
Alternatively, we can define the sandbox configuration as part of the toolchain? That is, the toolchain includes the base image? Then the toolchain hash would include the base image.
But note: the toolchain might be just the compiler and the sysroot, and the base image might be separate.
Given the complexity, let's simplify:
We define a "build environment" that includes:
- The toolchain (compiler, linker, etc.) and the sysroot.
- The base system files (like /etc/passwd, /etc/group, and maybe a minimal /dev).
We then hash the entire build environment (toolchain + base system) and that becomes part of the build key.
Then, the sandbox is created by:
- Using a container image that is built from the build environment (so the build environment is the root filesystem of the container?).
- Then we mount the source tree at /src.
So, the container image is the build environment. We can build the container image from the toolchain and the base system files, and then hash the container image (by its layers? or by the files in it?).
This is getting very heavy.
Given the time, we might have to accept that building a fully hermetic build system is a research problem and we can only do it for specific cases.
Since the question is about design, we can outline the ideal system and then note the challenges.
Let's summarize the design:
Components:
-
Build Key Computation:
- The build key is a hash of:
a) The set of input files (with their content and relative paths) -> source_tree_hash.
b) The toolchain (the entire set of files that are part of the toolchain, including the sysroot and the base system) -> toolchain_hash.
c) The environment variables that are declared as affecting the build -> env_hash.
d) The sandbox configuration (which is fixed by the build system, but if we change it, it should change the key) -> sandbox_config_hash.
We can compute the source_tree_hash by:
For each input file, compute its hash (e.g., SHA256) and then combine them in a deterministic order (e.g., sorted by path) using a Merkle tree.
Similarly for the toolchain.
-
Sandbox:
- We use a container (with the toolchain as the root filesystem) and mount the source tree at a fixed path (e.g., /src).
- We set the working directory to /src.
- We set the environment variables to the declared ones (and some fixed ones for hermeticity, like SOURCE_DATE_EPOCH=0, TZ=UTC, etc.).
-
Poisoning Defenses:
- We use a seccomp profile that blocks non-hermetic syscalls (or returns fixed values for them). We can have a default profile that blocks:
- gettimeofday, clock_gettime -> return 0.
- getrandom, /dev/urandom -> return a fixed stream (e.g., all zeros, or a fixed seed).
- network syscalls (if not allowed by the build rule).
- reading from /proc, /sys (except for allowed ones?).
- We also set the environment variables to fixed values (like SOURCE_DATE_EPOCH) to override the time.
-
Build Execution and Caching:
- Run the build command (from the build rule) in the sandbox.
- If the build fails, do not cache.
- If the build succeeds, collect the declared output files and compute a hash of the entire set (again, a Merkle tree of the output files, by their content and relative path).
- Store the output in a content-addressable store, keyed by the build key.
-
Metrics:
- For each build attempt, log:
- timestamp
- build key (or a hash of it)
- whether it was a cache hit or miss
- the time taken (in seconds)
- the number of seccomp violations (if any)
- the size of the input (source tree and toolchain) and the output (in bytes and number of files)
-
Verification:
- Periodically, for a random sample of build keys, rebuild them in a fresh sandbox and compare the output hash. If they differ, investigate.
Challenges:
- The toolchain must be hermetic. If the toolchain itself uses non-hermetic operations (like the current time in the compiler), then we must fix that too. This might require building a hermetic toolchain (with the same defenses).
- The build rule must declare all inputs and outputs. If it misses an input, the build might break when the input changes.
- The sandbox must be minimal and fixed. If we include too many files (like the entire host's /usr) then we are not hermetic because the host's /usr might change.
- We must fix the base system (the container image) and never change it. Or if we change it, we must change the toolchain_hash (so we get a new build key).
- The build might have non-hermetic operations that we haven't thought of (e.g., reading the hostname, the username, the current user ID, etc.). We must block these or fix them.
- The build might generate outputs that are not deterministic (e.g., due to parallelism, or due to hash randomization in the compiler). We must fix these in the toolchain (e.g., by using -frandom-seed for gcc).
- The build might use the current working directory path in the output (e.g., in debug info). We must ensure that the build is run in a fixed path (like /src) and that the toolchain does not embed the absolute path? Or we must use a toolchain that strips absolute paths.
Given these challenges, we might need to have a way to:
- Statically analyze the build command (and the toolchain) to detect non-hermetic operations.
- Have a database of known non-hermetic operations for each toolchain and how to fix them.
This is a huge undertaking.
Therefore, a practical approach might be:
Start with a build system that is known to be hermetic (like Bazel) and then add:
- A way to hash the entire toolchain (including the sysroot) and the source tree.
- A sandbox that is more minimal (maybe using a custom base image that only has the toolchain and a few system files).
- Seccomp and environment fixes for common non-hermetic operations (time, random).
- Metrics collection.
And then gradually tighten the sandbox and add more defenses as we find non-hermeticities.
Given the above, we can write a high-level design document for a system that extends an existing build system (like Bazel) with:
- A new cache implementation that uses content-addressable storage and the build key as described.
- A new sandbox implementation that uses a custom container image (with the toolchain and a minimal base) and applies seccomp and environment fixes.
- Metrics collection.
But note: Bazel already has a content-addressable cache and sandboxing. So we are proposing to:
- Change the cache key to include the hash of the toolchain (and the base system) and the sandbox config.
- Change the sandbox to use a fixed base image (and then the toolchain is part of that base image? or we mount the toolchain?).
In Bazel, the toolchain is already part of the execution platform, so we can hash the entire execution platform (including the sysroot and the base image) and include that in the cache key.
Then, we also need to apply the poisoning defenses (seccomp, environment) in the sandbox.
So, the design for a Bazel extension:
- We define a new execution platform that includes:
* The toolchain (with a fixed sysroot).
* A base image that is fixed (with a fixed set of system files).
* A seccomp profile that is fixed.
* A set of environment variables that are fixed (or set by the rule).
- The cache key for an action is then:
hash( action inputs (including the toolchain files), action command, action environment, execution platform (which includes the base image and seccomp profile) )
- But note: the execution platform might be the same for many actions, so we can precompute its hash.
- Then, when running an action, we set up the sandbox with:
* The input files (from the action's inputs).
* The toolchain (from the execution platform) mounted at a fixed path.
* The base system (from the execution platform) as the root filesystem? Or we use the base image as the container image and then mount the toolchain and the source tree?
- Actually, in Bazel, the sandbox is already chroot-like. We can change the sandbox to use a container that has the base image, and then mount the toolchain and the source tree.
- Then, we set the environment variables (from the action and from the execution platform) and run the command.
- We also apply the seccomp profile.
- We collect metrics per action.
This is a more concrete design.
Given the time, I'll stop here and note that this is a very complex system and the above is a high-level design.
Let me know if you have any specific questions about a particular aspect.
Excellent topic. Hermetic builds are fundamental to reproducible, secure, and cache-efficient software delivery. Let's break this down systematically.
1. Core Principle: Hermeticity
A build is hermetic if its output depends solely on its declared inputs (source files, dependencies, toolchain, flags) and nothing else from the build environment (host OS, network, time, filesystem state, etc.).
2. Hashing: The Foundation of Content-Addressability
What to Hash
| Component | Why Hash It? | Implementation |
|---|
| Source Files | Detect any code change | SHA-256/Merkle tree of all source files |
| Build Config | Flags, env vars affect output | Hash of canonicalized command line & env |
| Toolchain | Compiler/linker versions matter | Hash of compiler binaries + sysroot |
| External Dependencies | Third-party libs/artifacts | Hash of dependency contents (not just version) |
| Build Scripts | Makefiles, CMake, build.rs | Hash of entire script tree |
| Sandbox Manifest | Isolation boundary definition | Hash of sandbox configuration |
Cache Key Composition
cache_key = HASH(
sources_merkle_hash,
toolchain_hash,
config_hash,
platform_hash, # OS/arch variants
sandbox_policy_hash
)
Best Practice: Use content-addressable storage (CAS) where outputs are stored under hash(output) and retrieved by cache_key.
3. Sandboxing: Enforcing Isolation
Techniques (From Strict to Permissive)
| Method | Security | Overhead | Use Case |
|---|
| Kernel Namespaces + cgroups (Docker/LXC) | High | Medium | General purpose |
| chroot + user ns | Medium | Low | Simpler isolation |
| 容器镜像沙盒 (Bazel gaye-ji) | Very High | Medium | Reproducible builds |
| Emulated VM (Firecracker) | Maximum | High | Highest security needs |
| No sandbox | None | None | Trusted environments only |
Sandbox Manifest Must Include:
- Read-write mounts: Only declared outputs + temp dirs
- Read-only mounts: Sources, toolchain, sysroot
- White/blacklisted syscalls via seccomp-bpf
- Network: Typically disabled or emulated
- Time: Fixed via
SOURCE_DATE_EPOCH or intercept
- User/GID: Fixed to non-root (e.g.,
nobody)
4. Poisoning Defenses: Detecting/Mitigating Non-Hermeticity
Static Analysis (Pre-build)
- Scan build scripts for non-hermetic patterns:
# Anti-patterns to detect:
`date` `hostname` `random` `/dev/urandom` `pwd`
`find . -type f` (unordered)
`ls` (parsed output)
`git rev-parse` (if not pinned)
- Toolchain flags enforcement:
# GCC/Clang:
-frandom-seed=<fixed>
-Wl,--build-id=none
-fno-ident
# Rust:
-C link-arg=-Wl,--build-id=none
Runtime Monitoring (During Build)
- Seccomp-bpf filters to block:
gettimeofday, clock_gettime → return SOURCE_DATE_EPOCH
getrandom, /dev/urandom → return deterministic stream
socket, connect, bind → block (unless explicitly allowed)
- Filesystem audit (fanotify/inotify) to log any file access outside declared inputs.
- LD_PRELOAD interceptors for libc time/rand functions:
// Example interceptor for time()
time_t time(time_t *t) {
static time_t fake_time = 1609459200; // 2021-01-01 00:00:00 UTC
if (t) *t = fake_time;
return fake_time;
}
Post-build Verification
- Re-run in fresh sandbox: Rebuild same
cache_key → must get identical output hash.
- Diff sandbox logs: Compare file access traces between builds.
- Output hash mismatch detection: If same inputs produce different output → poisoning alert.
5. Metrics & Monitoring
Cache Efficiency Metrics
| Metric | Formula | Target |
|---|
| Cache Hit Rate | hits / (hits + misses) | >90% for CI |
| Cache Invalidation Rate | keys_missing / total_keys | <5% |
| Sandbox Setup Time | sandbox_start → first_syscall | <100ms |
| Build Time Variance | stddev(time) across same key | ≈0ms (hermetic) |
Hermeticity Quality Metrics
| Metric | Measurement | Alert Threshold |
|---|
| Syscall Blocker Hits | Count of blocked non-hermetic syscalls | >0 (unless expected) |
| Undeclared Input Access | Files read outside declared inputs | >0 |
| Output Hash Consistency | SHA256(output) variance across 3 rebuilds | 0 |
| Time Source Calls | Calls to time()/gettimeofday not returning SOURCE_DATE_EPOCH | 0 |
| Random Source Calls | Calls to rand()/random() not from deterministic source | 0 |
Operational Dashboards
- Cache efficiency by target/team
- Hermeticity violation trends (by project, build system)
- Sandbox resource usage (memory, CPU, disk I/O)
- Toolchain version drift (compiler updates breaking hermeticity)
6. Practical Implementation Blueprint
For Bazel/Buck/Bazel-like:
# BUILD.bazel
cc_binary(
name = "myapp",
srcs = ["main.cc"],
deps = [...],
# Declare all implicit inputs:
data = [...], # config files, scripts
# Hermeticity enforcement:
features = ["-parse_headers"], # force explicit deps
# Sandbox policy:
sandbox = True,
sandbox_config = ":sandbox_policy",
)
For Generic Make/NPM/Maven:
# Wrapper script (hermetic-build.sh)
#!/bin/bash
CACHE_KEY=$(compute_key sources/ toolchain/ Makefile CFLAGS)
if cache_has $CACHE_KEY; then
restore_from_cache $CACHE_KEY
exit 0
fi
# Run in sandbox
sandbox_exec --mount=src:/src \
--mount=toolchain:/toolchain \
--read-only=/toolchain \
--cap-drop=ALL \
--seccomp=hermetic.json \
--env=SOURCE_DATE_EPOCH=1704067200 \
bash -c "cd /src && make"
# Verify outputs
for out in $(declare_outputs); do
if ! cmp -s $out /cache/$CACHE_KEY/$(basename $out); then
echo "Non-hermetic output detected!"
exit 1
fi
done
store_in_cache $CACHE_KEY outputs/
Poisoning Defense Stack
# hermetic-policy.yaml
seccomp:
- syscall: gettimeofday
action: return_value
value: 0 # SOURCE_DATE_EPOCH derived
- syscall: getrandom
action: trace_log # Alert but allow (debug mode)
# action: kill (production)
env_whitelist:
- SOURCE_DATE_EPOCH
- TZ=UTC
- LC_ALL=C
fs_whitelist:
- /src/** # source tree
- /toolchain/** # compiler
- /dev/null
- /etc/passwd # read-only
7. Common Pitfalls & Mitigations
| Issue | Symptom | Fix |
|---|
| Timestamp embedding | Build ID changes every build | -Wl,--build-id=none + SOURCE_DATE_EPOCH |
| File ordering | Archive (.a) order varies | -Wl,--no-check-sort or deterministic archiver |
| Hostname leakage | uname -n in debug info | -fdebug-prefix-map=$(PWD)=. |
| Parallel build race | Different output on N-core vs 1-core | make -j1 or proper dependencies |
| Unordered hash traversal | Different file traversal order | `find -type f -print0 |
| Toolchain non-hermeticity | Compiler embeds build path | Rebuild toolchain with --with-build-sysroot |
8. Advanced: Cryptographic Supply Chain Integration
Source → [Sign] → Build (hermetic) → [Sign Output] → Deploy
↑ ↑
Provenance Attestation
- SLSA (Supply-chain Levels for Software Artifacts) framework compliance.
- Build provenance: Include
cache_key, sandbox config, and toolchain hashes in attestation.
- Rebuildability: Anyone with inputs + toolchain hash can reproduce exact binary.
- Verification:
attestation.verify(cache_key == rebuilt_key)
9. Tooling Ecosystem
| Tool | Hermeticity Features |
|---|
| Bazel | Built-in sandboxing, remote cache, SkyLark rules |
| Nix | Purely functional, content-addressed store |
| BUCK | Similar to Bazel, Facebook internal |
| reproducible-builds.org | Standards, diffoscope, fixes |
| gitian | Deterministic builds (used by Bitcoin) |
| trades | Experimental cargo/poetry wrapper |
10. Checklist for Hermetic Build Implementation
Key Insight
Hermeticity isn't binary—it's a spectrum. Start with:
- Basic hashing + sandboxing
- Time/random fixes
- Metrics + alerts
- Supply chain attestation
The most impactful wins are usually:
- Fixing timestamp embedding
- Enforcing declared dependencies only
- Pinning toolchain with sysroot
Would you like to dive deeper into any specific area (e.g., seccomp filter design, cache invalidation strategies, or integration with a specific build system)?