Reproducible Builds and Immutable Artifacts
Suppose an incident review asks two questions about a service that failed last Tuesday. Which exact bytes were running? And if you build the same commit today, do you get those bytes back? On many teams the honest answers are “the thing tagged 1.4.0, probably” and “something close.” Both answers hide a lot. A tag can be moved. A dependency can release a new version between two builds of the same commit. A build script can embed the time it ran. A configuration value can be baked into the package, so the “same” build is really a different one for each environment.
This post is about making those two questions answerable. After reading it you should be able to explain the difference between declaring dependencies and locking them, find the inputs that make two builds of the same source differ, describe what provenance records and what it does not prove, choose how to keep a released artifact immutable, decide which settings belong inside an artifact and which outside, and write tests that check those boundaries. Several claims are checked with a small Python package built and installed locally, and the results are reported together with the environment and input that produced them.
This post assumes the previous one, Infrastructure as Code: State, Drift, and Safe Changes. It assumes you know that declared intent and recorded state can differ, that a plan or a hash lets you check what will be applied, that secrets leak through the files tools write, and that one version of code is promoted across environments with environment-specific inputs. Here the thing being promoted is the build output of an application.
The local package behind the examples
The experiments use a tiny Python service package and a build script written for this post. They need no network, no cloud account, and no container runtime.
- Environment. Python 3.12 and pip on macOS, standard library only, plus OpenSSL for one optional step. Installation runs with
--no-index, so pip never contacts a package index. Docker was not used, because no container daemon was available while writing; the container material is explained from the OCI specification and from a toy model. - Input. A directory with a
srcsubdirectory holding the five files below. The service reads its settings from environment variables. - Observed result. The build commands in each section produced wheel files whose SHA-256 values were equal or different as described. Absolute hash values depend on the exact bytes and on the zlib version, so what matters is whether two runs on the same machine are equal, not the digits themselves.
src/orders_service/__init__.py:
__version__ = "1.0.0"
src/orders_service/config.py:
import os
class ConfigError(Exception):
pass
def load():
"""Read deployment settings from the environment and fail fast."""
try:
cfg = {
"db_host": os.environ["ORDERS_DB_HOST"],
"db_port": int(os.environ.get("ORDERS_DB_PORT", "5432")),
"max_items": int(os.environ.get("ORDERS_MAX_ITEMS", "50")),
}
except KeyError as e:
raise ConfigError(f"missing required setting {e.args[0]}") from None
except ValueError as e:
raise ConfigError(f"invalid number: {e}") from None
if not (1 <= cfg["db_port"] <= 65535):
raise ConfigError("ORDERS_DB_PORT out of range")
if cfg["max_items"] < 1:
raise ConfigError("ORDERS_MAX_ITEMS must be >= 1")
return cfg
src/orders_service/main.py:
from . import config
def describe():
cfg = config.load()
return f"orders-service talking to {cfg['db_host']}:{cfg['db_port']} (max {cfg['max_items']} items)"
if __name__ == "__main__":
print(describe())
src/orders_service-1.0.0.dist-info/METADATA:
Metadata-Version: 2.1
Name: orders-service
Version: 1.0.0
Summary: Example service used to demonstrate reproducible packaging
src/orders_service-1.0.0.dist-info/WHEEL:
Wheel-Version: 1.0
Generator: hand-assembled
Root-Is-Purelib: true
Tag: py3-none-any
The build script assembles a wheel, which is Python’s built distribution archive format, using only the standard library. Without --deterministic it behaves the way many ad hoc scripts do: it takes file times from disk and can embed the current time. With --deterministic it removes those inputs. It writes a RECORD manifest of file hashes and sizes following the wheel convention; the result was not validated against the packaging specification, and a successful pip install is the only evidence that pip accepted it. The script is build_wheel.py.
import argparse, base64, datetime, hashlib, os, sys, time, zipfile
ap = argparse.ArgumentParser()
ap.add_argument("--src", default="src")
ap.add_argument("--out", required=True)
ap.add_argument("--stamp", action="store_true", help="embed the current time in the package")
ap.add_argument("--deterministic", action="store_true")
args = ap.parse_args()
files = []
for root, dirs, names in os.walk(args.src):
if args.deterministic:
dirs.sort(); names.sort()
for n in names:
p = os.path.join(root, n)
files.append((os.path.relpath(p, args.src), p))
stamp = None
if args.stamp:
stamp = f"BUILT_AT = {datetime.datetime.now().isoformat()!r}\n".encode()
sde = os.environ.get("SOURCE_DATE_EPOCH")
def zip_time(path):
mtime = os.path.getmtime(path)
if args.deterministic:
if sde is None:
sys.exit("deterministic mode requires SOURCE_DATE_EPOCH")
mtime = int(sde) # one fixed value for every entry
return time.gmtime(max(mtime, 315532800))[:6] # UTC, and ZIP cannot go below 1980
entries = []
for rel, p in files:
with open(p, "rb") as f:
entries.append((rel.replace(os.sep, "/"), f.read(), zip_time(p)))
if stamp:
entries.append(("orders_service/_build_info.py", stamp, time.localtime()[:6]))
record_lines = []
for name, data, _ in entries:
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
record_lines.append(f"{name},sha256={digest},{len(data)}")
record_lines.append("orders_service-1.0.0.dist-info/RECORD,,")
record = ("\n".join(record_lines) + "\n").encode()
entries.append(("orders_service-1.0.0.dist-info/RECORD", record, entries[0][2]))
os.makedirs(args.out, exist_ok=True)
path = os.path.join(args.out, "orders_service-1.0.0-py3-none-any.whl")
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
for name, data, dt in entries:
zi = zipfile.ZipInfo(name, date_time=dt)
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = 0o644 << 16
z.writestr(zi, data)
with open(path, "rb") as f:
print(hashlib.sha256(f.read()).hexdigest()[:16], path)
Dependency locking
Declaring is not resolving
A project declares what it needs, usually as ranges: any version of a library in some interval. Resolution turns those ranges into specific versions, including the libraries that your libraries need, which are called transitive dependencies. The declaration is stable and the resolution is not, because the answer depends on what exists in the package index at the time you ask. A dependency lock file records one resolution so that it can be reviewed and reused.
A short worked example makes the difference concrete. A toy resolver with invented packages, shown after the table, traces it. Package web-lib version 2.1.0 requires codec in the range at least 1.0 and below 2.0. On Monday the index has codec 1.4.0 and 1.5.0. On Friday it also has 1.6.0.
| Action | Result |
|---|---|
Resolve web-lib on Monday, write the lock | web-lib 2.1.0, codec 1.5.0, each with a recorded content hash |
| Resolve again on Friday without the lock | web-lib 2.1.0, codec 1.6.0; the same declaration gave a different build |
| Install on Friday from the Monday lock | web-lib 2.1.0, codec 1.5.0; the new release is ignored |
Install from the lock after someone re-uploads different bytes as codec 1.5.0 | Rejected: the recorded hash does not match the content |
The core of the toy resolver is small. It picks the highest version that satisfies each range, records a hash of each chosen package’s content in the lock, and checks that hash when installing from the lock. The index contents and package names are invented, and the table above is the output of this logic over the Monday and Friday indexes.
def ver(s):
return tuple(int(x) for x in s.split("."))
def h(content):
return "sha256:" + hashlib.sha256(content.encode()).hexdigest()[:12]
def satisfies(v, spec):
if spec == "*":
return True
lo, hi = spec.split(",")
return ver(v) >= ver(lo.lstrip(">=")) and ver(v) < ver(hi.lstrip("<"))
def resolve(index, requirements):
chosen, todo = {}, list(requirements.items())
while todo:
name, spec = todo.pop()
cands = [v for v in index[name] if satisfies(v, spec)]
best = max(cands, key=ver)
chosen[name] = best
todo += list(index[name][best]["deps"].items())
return chosen
def lock(index, chosen):
return {n: {"version": v, "hash": h(index[n][v]["content"])} for n, v in chosen.items()}
def install_from_lock(index, lockfile):
for n, rec in lockfile.items():
got = h(index[n][rec["version"]]["content"])
if got != rec["hash"]:
return f"FAIL {n} {rec['version']}: expected {rec['hash']}, got {got}"
return "ok " + ", ".join(f"{n}=={r['version']}" for n, r in lockfile.items())
Nothing was wrong with codec 1.6.0 in this example. The point is that the declaration allows it, so an unlocked build can change without anyone changing the code, and a later failure then has no corresponding commit.
What real tools enforce
Pip’s hash-checking mode implements the last row of that table. The pip documentation says it uses local hashes embedded in a requirements file to protect against remote tampering and network problems, and that it is all or nothing: giving a hash for any requirement turns it on for all. It imposes three conditions: every requirement must carry a hash, every dependency must be listed, and requirements must be pinned with == or a URL or path.
The check works offline. A wheel built deterministically, as the next section explains, was placed in a directory named wheelhouse and hashed with pip hash. The requirements file pins the version and the hash:
orders-service==1.0.0 \
--hash=sha256:<hash printed by pip hash>
Installing into a virtual environment with --no-index --find-links wheelhouse --require-hashes -r req.txt made pip process the local wheel and end with Successfully installed orders-service-1.0.0. Putting a different build of the same version into another directory and repeating the install in a fresh environment made pip refuse with ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE and print the expected and actual SHA-256 values. In that run the second wheel was an earlier non-deterministic build of the same source, which is a realistic way for “the same version” to have different bytes.
The uv tool takes the lock file approach. Its documentation says uv lock resolves dependencies into a lock file, uv sync installs from it, --locked makes a command fail instead of updating an out-of-date lock, and --frozen uses the existing lock without checking whether it matches the project. The practical rule for continuous integration is to use the strict form, so a stale lock fails the build and is fixed by a person, not silently refreshed.
What a lock does not do
- It does not cover everything. The pip documentation says a wheelhouse of compiled packages is typically specific to an operating system and architecture, so it is not necessarily portable across machines. A lock for one platform may not be valid for another unless the tool produces a universal resolution, which the
uvdocumentation says its lock file does. - It does not choose the right versions. A lock freezes whatever was resolved, including a vulnerable version. Updating is a deliberate act with a review of the changed dependency graph and a re-run of tests. The lock makes updates visible; it does not make them safe.
- It does not protect the choice of source. Pip’s documentation says that with several package locations there is no priority among them, and that the best match, by version number, is selected. It warns that using
--extra-index-urlto find private packages is unsafe, because an attacker can publish a package with the same name to the public index and have it chosen. This is dependency confusion. A hash-checked lock prevents a substitution after the lock was made; it cannot help if the first resolution already picked the attacker’s package. Restrict internal names to an index you control, or use only one index. - It does not cover the build tools. Build backends and compilers are inputs too, and a source build runs their code. The lock file helps most when installation uses prebuilt, hash-verified wheels.
The wider topic, which includes who may introduce a new dependency, how you find out about a vulnerable one, and what installation steps may execute, is software supply chain security. Locking is one control within it, and a hash is only as trustworthy as the place it came from.
Builds and provenance
What makes two builds differ
A build is reproducible when the same source, build environment, and build instructions let any party recreate bit-by-bit identical copies of all specified artifacts. That is the definition on the Reproducible Builds project’s site, which adds that the relevant environment attributes typically include dependency versions, build flags, and environment variables such as the locale, and recommends minimizing them. The expected artifacts include executables, packages, and filesystem images, not build logs. Verification is a bit-by-bit comparison, usually through a cryptographic hash. The entry on reproducible builds lists the usual causes of differences: time, machine settings, paths, ordering, and deliberate variation such as randomness.
Several of these show up in the sandbox. The following is the experiment matrix that was run. Each pair of commands builds the same source twice.
# A: same source, files touched between builds, no fixed time
python3 build_wheel.py --out out/a
touch src/orders_service/*.py
python3 build_wheel.py --out out/b
# B: a build timestamp embedded in the package
python3 build_wheel.py --out out/c --stamp
python3 build_wheel.py --out out/d --stamp
# C: deterministic mode, fixed SOURCE_DATE_EPOCH, files touched between builds
export SOURCE_DATE_EPOCH=1700000000
python3 build_wheel.py --out out/e --deterministic
touch src/orders_service/*.py
python3 build_wheel.py --out out/f --deterministic
Results: the hashes of a and b differed, because the zip entries carry each file’s modification time and touch changed it. Because ZIP stores times at two-second resolution, the new time has to differ from the old one by more than that, and a touch within the same two-second window leaves the hash unchanged. The hashes of c and d differed, because the embedded time changed (the two runs were separated by a couple of seconds). The hashes of e and f were equal, even though the files were touched between them. Building from a copy of the src directory at a different path with the same arguments also gave an equal hash, because no path is recorded in the archive.
Two findings came from the experiment itself, and they are more instructive than the happy path.
First, the first version of the script converted the clamped time with the machine’s local time zone. Building the same source with TZ=UTC and with TZ=Asia/Seoul produced different hashes, because the zip entry stores a time of day and the conversion depended on the zone. Switching to UTC made them equal. Time zone and locale are exactly the “machine settings” the project warns about, and this difference surfaced only when the build ran under two settings. The script above is the corrected version.
Second, ZIP timestamps have a resolution of two seconds. With a fixed SOURCE_DATE_EPOCH of 1700000000, using 1700000001 instead produced the same hash, and using 1700000100 produced a different one. That is not a bug, but it means a small change to the epoch can be invisible in the archive, which matters when you try to detect which input changed.
The script sorts file names. Directory listing order is determined by the filesystem. On this machine’s filesystem a listing did not vary with the order in which three files were created, so an ordering difference could not be demonstrated; sorting is still the safe choice, because another filesystem may behave differently.
The Reproducible Builds project’s SOURCE_DATE_EPOCH convention is the standard answer to the time problem. Its documentation describes a variable holding the number of seconds since the Unix epoch, set by the distribution or build system, which tools should consume instead of the current time. It advises tools to use it as an upper bound for timestamps of generated files, not to replace every timestamp, and to fall back to normal behavior if it is unset. The script simply sets every entry to the value, which is a simplification that suits a package of source files. In practice the value is often derived from the last commit’s timestamp, so it is a function of the source.
Verifying reproducibility, and what it proves
Reproducibility is verified by rebuilding. A second builder, on a different machine and ideally run by a different party, builds the same commit with the same inputs and compares hashes. Agreement is evidence that the published artifact corresponds to the claimed source and instructions. Disagreement is a finding to investigate.
What it does not prove is just as important. Matching output does not show the software is correct. It does not remove trust in the source, the toolchain, or the rebuilding environment: a compromised compiler can reproduce the same malicious bytes every time. The build provenance entry makes the same point. Reproducible builds reduce reliance on a single builder. They do not make the input trustworthy.
Provenance
Provenance is a record of how an artifact was produced: who built it, from what source, with which parameters. It answers a different question than reproducibility. Reproducibility lets you verify a build by redoing it. Provenance lets you check a build against expectations without redoing it.
SLSA, the Supply-chain Levels for Software Artifacts framework, defines a build track with levels. Summarized from the specification: Build L0 has no guarantees. At Build L1 the producer’s build platform generates provenance describing how the artifact was built, which helps against mistakes but, because provenance can be forged easily at this level, offers little against tampering. At Build L2 the hosted build platform generates and signs the provenance, so the record cannot be altered after the build without detection. At Build L3 the platform adds isolation, so builds cannot influence each other and user-defined build steps cannot reach the signing secrets, which addresses tampering during the build. The specification focuses on the build track, and other supply chain risks are outside it.
The provenance format has a standard shape. An in-toto Statement has a fixed _type, a subject listing artifacts by digest, a predicateType, and a predicate. SLSA’s provenance predicate has type https://slsa.dev/provenance/v1. Its buildDefinition holds a buildType, externalParameters (inputs under outside control, which a verifier must check), optional internalParameters, and resolvedDependencies such as the source commit. Its runDetails holds the builder.id, which the specification calls the sole determiner of the SLSA Build level, and metadata such as an invocation ID. A statement is wrapped in a DSSE envelope: a payload, a payload type, and signatures, where the signature is computed over a pre-authentication encoding that combines the payload type and the payload with their lengths, not over the raw payload alone.
To see what verification does, a statement was built and signed locally with a throwaway ed25519 key and checked five ways. This is an explanatory experiment with a simplified predicate and placeholder builder and repository names. It is not a SLSA-conformant build. A reduced statement looks like this:
{
"_type": "https://in-toto.io/Statement/v1",
"subject": [{"name": "orders_service-1.0.0-py3-none-any.whl",
"digest": {"sha256": "<artifact sha256>"}}],
"predicateType": "https://slsa.dev/provenance/v1",
"predicate": {
"buildDefinition": {
"buildType": "https://builder.example/types/python-wheel/v1",
"externalParameters": {"source": "https://git.example/org/orders-service",
"ref": "refs/heads/main"},
"resolvedDependencies": [{"uri": "git+https://git.example/org/orders-service",
"digest": {"gitCommit": "<commit>"}}]
},
"runDetails": {"builder": {"id": "https://builder.example/ci/v1"},
"metadata": {"invocationId": "run-0001"}}
}
}
The verifier checked, in order: the signature over the encoded payload, that the subject digest matches the artifact in hand, that the builder is the trusted one, that the source repository is the expected one, and that no unrecognized external parameters exist. The SLSA verification guidance lists the builder identity, canonical source repository, build type, and external parameters as expectations to check, and says verifiers should reject unrecognized external parameters. The signing input and the check function are below. The signature covers the pre-authentication encoding, and the checks run in the order just described.
def pae(ptype: str, body: bytes) -> bytes:
t = ptype.encode()
return b"DSSEv1 " + str(len(t)).encode() + b" " + t + b" " + str(len(body)).encode() + b" " + body
def check(artifact_path, envelope, pub, expect_builder, expect_repo):
body = base64.b64decode(envelope["payload"])
sig = base64.b64decode(envelope["signatures"][0]["sig"])
if not verify(pae(envelope["payloadType"], body), sig, pub):
return "REJECT: signature does not verify"
st = json.loads(body)
digest = hashlib.sha256(open(artifact_path, "rb").read()).hexdigest()
if st["subject"][0]["digest"]["sha256"] != digest:
return "REJECT: artifact digest is not the one the statement describes"
pred = st["predicate"]
if pred["runDetails"]["builder"]["id"] != expect_builder:
return f"REJECT: builder {pred['runDetails']['builder']['id']} is not trusted"
ext = pred["buildDefinition"]["externalParameters"]
if ext.get("source") != expect_repo:
return f"REJECT: built from {ext.get('source')}, expected {expect_repo}"
extra = set(ext) - {"source", "ref"}
if extra:
return f"REJECT: unrecognized external parameters {sorted(extra)}"
return "ACCEPT"
The five cases and their outcomes:
| Case | Outcome | Which check caught it |
|---|---|---|
| Genuine artifact and statement | Accepted | All checks pass |
| Artifact modified after signing | Rejected | Subject digest differs from the artifact |
| Statement edited after signing | Rejected | Signature does not verify |
| Statement signed by a different key | Rejected | Signature does not verify against the trusted key |
| Valid signature from the trusted key, but built from a different repository | Rejected | Source repository differs from the expectation |
The last case is the one to remember. A valid signature shows that the trusted builder made the statement. It does not show that the statement describes something you want to run. The expectations are what turn a signature into a decision, and they must be stored and enforced where the producer cannot change them. The SLSA guidance describes ways to form expectations, such as trusting the first version seen, letting the producer define them, or letting the source repository define them, and each has a different trust assumption.
Provenance also has limits that the build model in the SLSA specification states: the steps within the build environment are controlled by the tenant, so if the source repository is compromised, the platform will accurately attest to running the attacker’s steps. Provenance makes an intrusion traceable and a forged artifact rejectable. It does not review the code. And a record that nobody verifies prevents nothing, so the decision to deploy has to include the verification step.
Immutable artifacts
Tags move, digests do not
An artifact is immutable when the identifier you use to refer to it can only ever refer to the same bytes. A version label like 1.4.0 is a name that someone can assign to different content. A content hash cannot, because it is computed from the content.
Container images show the distinction. The OCI image specification defines an image manifest that lists a configuration object and an ordered list of filesystem layers, with the base layer at index 0, each referenced through a descriptor that carries a media type, a size, and a digest. A digest has the form algorithm:encoded, and the specification requires implementations to support SHA-256, written as 64 lowercase hexadecimal characters. A client can check that retrieved content matches its digest and expected size. The manifest has no tag in it; the specification notes that tags are outside the manifest format. A tag is a separate, movable pointer that a registry keeps from a name to a manifest digest. An image index groups manifests for different platforms, so a name may resolve to different manifests on different architectures.
Docker’s documentation states the consequence: tags can be reassigned, and pulling by digest pins an image to a specific version. It also states the cost: pinning means Docker will not pull updated versions of the image, which may include security updates. So an immutable reference moves the update decision from “whenever the tag moves” to “whenever you choose,” and you need a process for choosing. The glossary entry on image tags and digests describes the same distinction, and the entry on container images explains the manifest, layer, and index structure in more detail.
Docker was not used, so the behavior is shown with a toy registry that stores blobs and manifests under their SHA-256 digests and keeps tags in a separate table. It is a model of the idea, not the OCI distribution protocol. Its core is below.
class Registry:
def __init__(self, immutable_tags=False):
self.blobs, self.tags, self.immutable = {}, {}, immutable_tags
def put_blob(self, data: bytes) -> dict:
d = digest(data); self.blobs[d] = data
return {"mediaType": "application/octet-stream", "digest": d, "size": len(data)}
def put_manifest(self, config: dict, layers: list, tag: str) -> str:
manifest = {"schemaVersion": 2, "config": config, "layers": layers}
raw = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()
d = digest(raw); self.blobs[d] = raw
if tag in self.tags and self.immutable:
raise ValueError(f"tag {tag!r} already exists (immutable tags)")
self.tags[tag] = d
return d
def pull(self, ref: str) -> str:
d = ref.split("@", 1)[1] if "@" in ref else self.tags[ref]
raw = self.blobs[d]
assert digest(raw) == d, "content does not match its digest" # what a client verifies
return d
In the model, a build was pushed under the tag orders:1.4.0, then a different build was pushed under the same tag, once with mutable tags and once with immutable tags.
| Step | Mutable tags | Immutable tags |
|---|---|---|
Push build 1 as orders:1.4.0 | Tag points to digest A | Tag points to digest A |
| Pull by tag | Digest A | Digest A |
Push build 2 as orders:1.4.0 | Succeeds; the tag now points to digest B | Rejected: tag already exists |
| Pull by tag again | Digest B | Digest A |
| Pull by digest A | Digest A | Digest A |
Mutable tags change what a name means without changing any reference that used the name. This is a practical hazard: a deployment, a rollback, and a reproduction of an incident can all pull “the same tag” and run different code. Registries can enforce immutability. Amazon ECR’s documentation describes a repository setting under which pushing an image with an existing tag fails with ImageTagAlreadyExistsException; it applies to all tags in the repository, with optional exclusion filters for tags you want to remain mutable. Other registries have their own settings, so check what yours enforces.
Promote a digest
The rule that follows is to build once, record the digest the registry reports after the push, and deploy that digest to every environment. Do not rebuild for production, and do not deploy by tag. The record of what ran is then a list of digests with timestamps, which is exactly what the incident review in the opening needed.
The same rule works for a Python wheel: the hash of the file replaces the digest, and the lock file or release record stores it. Whatever the format, the release record should hold: the source commit, the lock file, the builder identity, the artifact’s digest, a pointer to its provenance, and the configuration version applied in each environment. That is the minimum for answering both of the opening questions. See environment promotion for the pattern of moving one artifact through environments and the differences that promotion alone does not remove.
Immutability does not mean the artifact is good. A digest identifies content. It does not establish who published it, whether it contains vulnerabilities, or that its behavior will be the same against different data. Treat the digest as the answer to “which bytes,” and use provenance, scanning, and tests for the other questions. A build artifact is useful as a promotion unit when it carries its own identity and does not contain what differs between environments, which is the next topic.
Configuration boundaries and tests
What belongs inside
The Twelve-Factor App methodology defines an application’s config as everything likely to vary between deploys and says it should be strictly separated from code, since config varies substantially across deploys and code does not. It offers a litmus test: could the codebase be made open source at any moment without compromising any credentials? It advocates environment variables for config, because they are easy to change between deployments without code changes and unlikely to be committed by accident. It also criticizes grouping config into named environments such as development, staging, and production as something that does not scale cleanly, preferring independent, granular variables.
Applied to artifacts, the rule gives a division.
| Belongs in the artifact | Stays outside it |
|---|---|
| Code and static assets | Hostnames, endpoints, connection strings |
| Dependencies, bundled or declared against a lock | Credentials and keys |
| Defaults that are safe in every environment | Limits and thresholds that differ by environment |
| Its own version and a link to its source | Feature flag state per environment |
| A schema for the settings it expects | The values of those settings |
Two qualifications keep this honest. An environment variable is a delivery mechanism for configuration and not a vault: a value injected that way is visible to child processes and can appear in diagnostic output, so credentials need the lifecycle handling described under secrets management, with the environment as only the last step. And the Twelve-Factor criticism of named environment groups is a design argument, not a law; many teams keep per-environment files in version control, and the useful test is whether the artifact stays identical while only the inputs vary.
Validate configuration at startup
Separating configuration moves a class of errors from build time to start time: the artifact is the same, and the setting is missing or wrong. The remedy is to check the contract when the process starts. Configuration validation means checking that supplied settings satisfy an explicit contract before code relies on them: required keys present, types correct, values in range, and related settings consistent. The sample service’s loader does this. It requires ORDERS_DB_HOST, parses the port and limit as integers, and rejects a port outside the valid range and a non-positive limit, each with a message that names the setting.
Fail fast has an operational reason. A service that starts with a missing setting and fails on the first request fails later, under load, with a less obvious message. A service that refuses to start fails during deployment, where a health check or a canary catches it. Validation establishes that the values meet declared constraints. It does not establish that a threshold is the right business choice, and it cannot tell that a syntactically valid hostname points at the wrong environment, so validate destination identity separately where a mistake would be costly.
Tests at the artifact boundary
A unit test of the source tree does not check the artifact. Packaging can omit a file, include one that should not be there, or change behavior through a different import path. The tests that matter for this post run against the built and installed artifact: the deterministic wheel installed into a fresh virtual environment, as in the dependency section. The tests are in test_artifact.py.
import hashlib, os, re, subprocess, unittest, zipfile
WHEEL = os.environ["WHEEL"] # path to the wheel under test
PY = os.environ["PYBIN"] # interpreter of a venv that has the wheel installed
def sha256_file(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
def run(env_extra):
env = {"PATH": os.environ["PATH"], **env_extra}
return subprocess.run([PY, "-m", "orders_service.main"], env=env,
capture_output=True, text=True)
class ConfigBoundary(unittest.TestCase):
def test_missing_required_setting_fails_fast(self):
r = run({})
self.assertNotEqual(r.returncode, 0)
self.assertIn("ORDERS_DB_HOST", r.stderr)
def test_same_artifact_different_environment(self):
before = sha256_file(WHEEL)
staging = run({"ORDERS_DB_HOST": "db.staging.example"})
prod = run({"ORDERS_DB_HOST": "db.prod.example", "ORDERS_MAX_ITEMS": "100"})
self.assertEqual(before, sha256_file(WHEEL)) # the artifact did not change
self.assertIn("db.staging.example", staging.stdout)
self.assertIn("max 100", prod.stdout) # behavior differs by configuration only
class ArtifactContents(unittest.TestCase):
ENV_VALUE = re.compile(r"\b[\w-]+\.(staging|prod|dev)\.[\w.]+")
def test_no_environment_specific_values_inside_wheel(self):
with zipfile.ZipFile(WHEEL) as z:
for name in z.namelist():
text = z.read(name).decode("utf-8", "replace")
self.assertIsNone(self.ENV_VALUE.search(text), f"environment value in {name}")
if __name__ == "__main__":
unittest.main(verbosity=2)
The file reads the wheel’s path from WHEEL and the virtual environment’s Python from PYBIN. The run reported Ran 3 tests and OK. The three tests check different things. The first checks that a missing required setting stops the process with a message that names it. The second runs one artifact twice with different environments and checks that the artifact’s hash is unchanged and the behavior differs only through configuration, which is the promotion claim made testable. The third scans every file in the wheel for a pattern that looks like an environment-specific hostname.
A test that passes is weak evidence until it has been seen to fail. To check the third test, a line such as DB = "db.prod.example" was appended to a copy of __init__.py, the wheel was rebuilt from the copy, and the contents test was run against it. The result was FAILED (failures=1), with a message naming the file where the environment value was found. The failure message read environment value in orders_service/__init__.py.
The scan’s limits are real. It looks for one pattern, so it would miss a hostname written differently, an IP address, or a credential with no recognizable shape. A secret scanner with broader rules belongs in the pipeline, and a leaked secret still requires rotation, not just removal. The point of the test is to protect a specific boundary rule with a specific check, and to make the rule fail loudly when a developer breaks it.
Putting the controls together
The controls in this post form a chain, and the chain is only as strong as its weakest link. This sequence shows what each step contributes and what it leaves open.
- Lock dependencies and install with hash checking. The build’s inputs are fixed and reviewable. It does not choose safe versions or protect the first resolution from a confused index.
- Build in a controlled environment with fixed time and sorted inputs. The output depends on source and instructions. It needs verification by an independent rebuild to be more than a claim.
- Produce provenance from the build platform, and verify it against stored expectations before deployment. A deployment can be traced to a builder and a source. It cannot show the source was benign.
- Publish to a registry with immutable tags, and record the digest. A name always refers to the same bytes. It does not decide when to update.
- Keep configuration outside the artifact, validate it at start, and test the boundary on the built artifact. The same bytes run in every environment. It cannot show that a chosen threshold is right.
- Promote the digest through environments and keep the release record. The two questions in the opening can be answered later.
These controls fail in recognizable ways, and each failure corresponds to a missing link above.
| Failure | Link that was missing | Observable symptom |
|---|---|---|
| A rebuild of an old commit behaves differently | Lock or deterministic build | Different hash from the recorded one; behavior change with no commit |
| Production runs a different image than staging tested | Digest promotion, immutable tags | Tag resolves to different digests over time |
| A malicious package named like an internal one is installed | Single trusted index, hash-checked lock from a clean first resolution | Unexpected package source in the lock diff |
| A forged artifact is deployed | Provenance verification with stored expectations | Artifact digest has no matching, trusted statement |
| A staging hostname reaches production | Configuration boundary test | Environment value found inside the artifact |
| A service starts with a bad setting and fails under load | Startup validation | Failures on first request instead of at deployment |
| Security fix never arrives for a pinned base image | A process for updating pinned digests | Old digest still deployed after a fix is available |
Limits apply to everything above. The experiments ran locally with a pure-Python package and a hand-written build script, and the results show mechanisms, not how a production build system behaves; compiled extensions, multi-stage container builds, and large dependency trees add further sources of variation that were not tested. Docker and container builds were not run, so the container discussion rests on the OCI specification, Docker’s documentation, and a toy registry model. The provenance experiment used a simplified predicate and throwaway keys and does not demonstrate SLSA conformance. The wheel the script produced was accepted by pip in the local run, but it was not validated against the packaging specification. Tool behavior and documentation change between versions, so confirm details for the versions you use.
References
- Reproducible Builds: Definition
- Reproducible Builds: SOURCE_DATE_EPOCH
- SLSA v1.1 specification: Build track levels
- SLSA v1.1 specification: Provenance
- SLSA v1.1 specification: Verifying artifacts
- in-toto attestation framework: Statement v1
- DSSE: Protocol and envelope
- Open Container Initiative Image Specification: Content descriptors
- Open Container Initiative Image Specification: Image manifest
- Docker Docs: docker image pull
- Amazon ECR User Guide: Preventing image tags from being overwritten
- pip documentation: Secure installs
- pip documentation: Repeatable installs
- pip documentation: pip install
- uv documentation: Locking and syncing
- The Twelve-Factor App: Config
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
