Operator notes

Scan OCI images for secrets without a daemon.

layerleak reads manifests, image config, build history, and decompressed filesystem layers directly from a registry or from a local OCI layout or docker save archive. It is read-only, verifies every blob against its OCI digest, reports incomplete coverage instead of hiding it, and keeps actionable findings separate from likely test fixtures and placeholders. Values are always redacted in its output.

This copy documents the 3.0.0 line on the github.com/brumbelow/layerleak/v3 module path. The changelog and OpenAPI version are frozen at 3.0.0 so an accepted release candidate can be promoted from the same source commit; a release command shown here works once that tag is published. Upgrading from v1.0.0 or a v2.x container install? Read the upgrade guide first.

Install signed release archive · go install …/v3
Build from source Go 1.27.1+
Persistence PostgreSQL 16.13+
Default exposure redacted findings
01

Quickstart

Download a release archive

Every release attaches prebuilt CLI archives, so no Go toolchain is needed: layerleak_<version>_<os>_<arch>.tar.gz for linux and darwin on amd64 and arm64, and layerleak_<version>_windows_amd64.zip. The layerleak_<version>_checksums.txt file is signed keylessly by the release workflow and every archive carries a build-provenance attestation. Verify before you run:

version=v3.0.0
archive="layerleak_${version}_linux_amd64.tar.gz"
checksums="layerleak_${version}_checksums.txt"
base="https://github.com/brumbelow/layerleak/releases/download/${version}"
curl --fail --location --proto '=https' --tlsv1.2 --remote-name-all \
  "${base}/${archive}" "${base}/${checksums}" "${base}/${checksums}.sigstore.json"

sha256sum --check --ignore-missing "${checksums}"
cosign verify-blob \
  --bundle "${checksums}.sigstore.json" \
  --certificate-identity 'https://github.com/Brumbelow/layerleak/.github/workflows/container-release.yml@refs/heads/main' \
  --certificate-oidc-issuer 'https://token.actions.githubusercontent.com' \
  "${checksums}"
gh attestation verify "${archive}" --repo Brumbelow/layerleak \
  --signer-workflow Brumbelow/layerleak/.github/workflows/container-release.yml \
  --source-ref refs/heads/main --deny-self-hosted-runners

tar -xzf "${archive}" layerleak
./layerleak version

layerleak version prints the version, commit, build time, Go version, and platform (--format json for the same as JSON); layerleak --version prints the first line only.

GitHub Action

The repository root is a composite action that downloads the archive for the runner, verifies its checksum, the checksums file's cosign bundle, and the archive attestation, then runs layerleak scan with --no-artifacts. Pin it to a release tag; the matching archive is downloaded from that release.

name: Image secrets
on: { push: { branches: [main] } }
permissions: { contents: read, security-events: write }
jobs:
  layerleak:
    runs-on: ubuntu-24.04
    steps:
      - id: scan
        uses: brumbelow/layerleak@v3.0.0
        with: { image: "ghcr.io/${{ github.repository }}:${{ github.sha }}", fail-on: none }
      - uses: github/codeql-action/upload-sarif@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
        if: ${{ always() && steps.scan.outputs.sarif-file != '' }}
        with: { sarif_file: "${{ steps.scan.outputs.sarif-file }}" }

Inputs are image (required), version, format (default sarif), fail-on (default low), allow-partial, platform, output-file, and extra-args; outputs are exit-code, result-file, sarif-file, and version. The step fails exactly when the CLI exits non-zero. See the README action reference for every input.

Go install or source build

go install github.com/brumbelow/layerleak/v3@latest
layerleak version
layerleak scan library/nginx:1.29 --format json
git clone https://github.com/brumbelow/layerleak.git
cd layerleak
go build -o layerleak .
./layerleak scan alpine:3.20 --platform linux/amd64

Building needs Go 1.27.1 or newer, and GOBIN or GOPATH/bin must be on PATH after go install. Pin a release with @v3.0.0 instead of @latest. The module path is github.com/brumbelow/layerleak/v3; the root path without /v3 stays at v1.0.0 forever, so always include the suffix. The binary is still named layerleak. Module-installed binaries report the resolved module version; checkout builds report a VCS-derived development version, or dev without VCS information. The CLI runs on Linux, macOS, and Windows on amd64 and arm64; the API image supports linux/amd64 and linux/arm64.

02

Scan model

layerleak resolves images on Docker Hub, GHCR, Quay, GCR, MCR, Amazon ECR Public, and other OCI-compatible registries, and reads local image layouts and archives. It does not need a Docker daemon and does not check whether a detected credential is live.

Single image

A bare repository scans its latest tag. Use a tag or digest for an immutable target.

layerleak scan ubuntu
layerleak scan alpine@sha256:<digest>
layerleak scan ghcr.io/homebrew/core/hello:latest

Repository sweep

--all-tags explicitly enumerates the public tags of a bare repository, resolves each to a digest, and scans each distinct digest once.

layerleak scan mongo --all-tags \
  --max-repository-tags 500 \
  --max-repository-targets 200

Local image

Images that were never pushed are read from the filesystem. The CLI only: the HTTP API rejects these references.

layerleak scan oci:./build/image:1.2
layerleak scan oci-archive:app.tar:app:1.2
layerleak scan docker-archive:save.tar:app:1.2

Private registry

The password or token is read from standard input; there is no --password flag.

printf '%s' "$REGISTRY_TOKEN" | layerleak scan \
  ghcr.io/org/private-app:1.2 \
  --username robot --password-stdin

Platforms

Without --platform, every linux manifest of a multi-platform index (and every manifest that names no operating system) is scanned. Manifests for other operating systems are not downloaded and are reported as platform_skipped diagnostics. Index entries that are not image manifests are never scanned and are reported as manifest_skipped: BuildKit attestation manifests (annotated vnd.docker.reference.type: attestation-manifest), manifests that declare an artifactType such as application/vnd.in-toto+json, unknown/unknown platform entries, nested indexes, and descriptors of any other media type. Skipped entries do not fail the scan.

--platform os[/arch[/variant]] selects platforms explicitly; omitted parts match anything and variants are normalised like containerd, so --platform linux selects every Linux manifest and linux/arm64/v8 equals linux/arm64. With a selector, non-matching entries are left out without a diagnostic, and a single-manifest image whose config does not match fails with platform_not_found. A selected manifest whose layers are foreign or non-distributable (Windows base layers) or use an unknown media type is reported as manifest_unsupported: that platform fails, the others still run, and the result is partial.

Local inputs

ReferenceSource
oci:<dir>[:<tag>][@<digest>]An OCI image layout directory (oci-layout, index.json, blobs/), as written by buildx --output type=oci, skopeo copy ... oci:, or crane pull --format oci.
oci-archive:<file.tar>[:<tag>][@<digest>]The same layout inside a tar archive (buildx --output type=oci,dest=..., skopeo copy ... oci-archive:).
docker-archive:<file.tar>[:<repo>[:<tag>]][@<digest>]A docker save archive (manifest.json, config and layer tars, optional repositories).

The path is absolute or relative to the working directory and ends at the first colon (a Windows drive letter stays in the path). The tag is the org.opencontainers.image.ref.name annotation (for oci: and oci-archive:) or the docker save RepoTags name, and an image name matches in any spelling that normalises to it. A source holding several images needs a tag or @<digest>; --all-tags enumerates the tags the source holds. The source string becomes the repository (oci:/srv/images/app) and the stored registry is local. Every blob is verified against its descriptor digest and size, archives are indexed in memory and never extracted, links inside archives are never followed, and registry credentials are refused for a local source (exit 1).

Private registries and egress

--username <name> --password-stdin supplies a credential for one scan; both flags are required together and exactly one trailing newline is removed from standard input. Without the flags, the CLI applies the LAYERLEAK_REGISTRY_USERNAME/LAYERLEAK_REGISTRY_PASSWORD pair to the registry of the reference on the command line. The API applies that pair only when LAYERLEAK_REGISTRY_BASE_URL pins the registry endpoint, so a caller can never make the server send the operator's credential to a registry the caller names. LAYERLEAK_DOCKER_CONFIG names a Docker config.json whose auths entries supply credentials by registry host in both; credential helpers are not invoked and ~/.docker/config.json is never read implicitly. A credential is bound to the one registry host it was given for, is sent only over https, and never appears in logs, output, scan records, or the database. A 401 or 403 exits 1 with authentication to <registry host> failed.

HTTPS_PROXY, HTTP_PROXY, and NO_PROXY are honoured. When a proxy is selected for a request, the registry hostname is sent as the CONNECT target and local DNS resolution and IP pinning are skipped, because the proxy is the egress control; the https-only rule and the private-host allowlists still apply. Hosts matched by NO_PROXY are connected directly with address pinning. LAYERLEAK_REGISTRY_BASE_URL is not a proxy setting: it replaces the registry endpoint for every scan (a pull-through mirror or an alternate registry). Private, loopback, link-local, and other non-public destinations are blocked unless their exact host[:port] is listed in LAYERLEAK_ALLOWED_PRIVATE_REGISTRY_HOSTS or LAYERLEAK_ALLOWED_PRIVATE_AUTH_HOSTS; allowlisting a host is also what permits plain http:// to it.

What is scanned

  • Filesystem. Regular files in the final filesystem (file_final) and earlier versions of files that a later layer deleted or overwrote (file_deleted_layer), reconstructed layer by layer with whiteouts. Files with a UTF-16 byte-order mark or shape are transcoded to UTF-8 first. Binary files are excluded; files over LAYERLEAK_MAX_FILE_BYTES are skipped with a files_skipped_oversize diagnostic and coverage becomes partial.
  • Nested archives. A zip, jar, war, wheel, egg, gzip, or tar file inside a layer is expanded one level in memory and its entries are reported under outer/path!inner/path. An archive inside a nested archive is never opened; anything beyond a bound is a nested_archive_skipped diagnostic and coverage stays complete.
  • Image metadata. Config environment variables (env), labels (label), build history commands, comments, and authors (history), and other config fields such as the command, entrypoint, user, and working directory (config).
  • Unreadable sensitive files. A binary or oversize file whose path marks a private key, keystore, password database, credential store, or GPG keyring is reported by path alone under the sensitive_file_* identifiers, with an empty redacted_value and context_snippet and zero offsets.
  • Placeholders. Matches that look like test fixtures, examples, or placeholders (test and example paths, placeholder markers, known dummy values, example hosts, well-known default credentials) are reported as suppressed findings with disposition example and a disposition_reason, and do not count as actionable.

Detection uses a compiled, read-only catalog of 161 detector identifiers; there is no rule file or custom-rule syntax. layerleak detectors list prints each identifier with its confidence tier, matching strategy, and description (--format json for JSON), and the same data is published as the detector catalog.

Repository sweeps accept --tag-page-size, --max-repository-tags, and --max-repository-targets, which override the matching environment variables for one command. --max-repository-tags and --max-repository-targets accept 0 to disable the cap; --tag-page-size must be greater than zero.

03

Configuration

Every setting is an environment variable with a safe default; no process reads a .env file itself. .env.example in the repository lists them with their defaults and the README configuration tables are the reference; the tables below carry the same rows. Durations use Go syntax (30s, 10m, 1h). Booleans accept 1, true, yes, on and 0, false, no, off. Rows marked must be positive reject 0; every other MAX_* bound accepts 0 to disable it. Exceeding a scan bound never truncates silently: the scan becomes partial or failed and a diagnostic names the bound. Two bounds are informational instead: the nested-archive bounds add a nested_archive_skipped diagnostic and the raw-value bound adds a raw_retention_truncated diagnostic, and coverage stays complete for both.

Core and registry
VariableDefaultPurpose
LAYERLEAK_LOG_LEVELinfodebug, info, warn, or error (case-insensitive); any other spelling is rejected.
LAYERLEAK_LOG_FORMATjsonLog record encoding on stderr for the CLI and the API: json (one object per line, safe for log shippers) or text (key=value records for a terminal); case-insensitive, anything else is rejected. The CLI flag --log-format overrides it for one scan.
LAYERLEAK_FINDINGS_DIR./findingsCLI only. Directory for scan records (one JSON file per scan); relative values resolve against the working directory. --output-dir overrides it, --no-artifacts skips it.
LAYERLEAK_PERSIST_RAW_SECRETS0Boolean. Unsafe opt-in for raw values and snippets.
LAYERLEAK_HTTP_TIMEOUT30sPer-attempt deadline for manifest, config, tag, and auth requests and for the response headers of blob requests; also bounds dial and TLS handshake.
LAYERLEAK_BLOB_TIMEOUT10mLayer blob transfer deadline.
LAYERLEAK_SCAN_TIMEOUT30mEnd-to-end CLI scan deadline.
LAYERLEAK_REGISTRY_REQUEST_ATTEMPTS2Attempts including the first request; retries back off exponentially (jittered, at most 5s) or honour Retry-After (at most 30s); must be positive.
LAYERLEAK_REGISTRY_MAX_REDIRECTS3Redirect cap; each destination is revalidated; must be positive.
LAYERLEAK_MAX_AUTH_RESPONSE_BYTES1048576Maximum registry token response size; must be positive.
LAYERLEAK_ALLOWED_PRIVATE_REGISTRY_HOSTSemptyComma-separated exact private registry host[:port] allowlist.
LAYERLEAK_ALLOWED_PRIVATE_AUTH_HOSTSemptyComma-separated exact private auth host[:port] allowlist.
LAYERLEAK_REGISTRY_BASE_URLemptyRegistry endpoint override for a pull-through mirror or alternate registry; validated at startup. Use HTTPS_PROXY for forward proxies.
LAYERLEAK_REGISTRY_AUTH_URLemptyToken endpoint override matching the registry override; validated at startup.
LAYERLEAK_REGISTRY_USERNAMEemptyRegistry username; requires LAYERLEAK_REGISTRY_PASSWORD. The CLI applies the pair to the registry of the scanned reference when --username is not given; the API applies it only to the registry pinned by LAYERLEAK_REGISTRY_BASE_URL, never to a registry a caller names. Sent only to that one host, over https.
LAYERLEAK_REGISTRY_PASSWORDemptyPassword or access token paired with LAYERLEAK_REGISTRY_USERNAME; never logged, persisted, or sent to any other host.
LAYERLEAK_DOCKER_CONFIGemptyPath to a Docker config.json whose auths entries supply credentials by registry host (auth or username/password fields; Docker Hub aliases resolve). Credential helpers are not invoked. Must be a regular file; blank skips Docker configuration.
Resource bounds
VariableDefaultPurpose
LAYERLEAK_MAX_FILE_BYTES1048576Maximum decompressed bytes buffered for one file; must be positive. Larger files are not scanned: they are reported with a files_skipped_oversize diagnostic and coverage becomes partial.
LAYERLEAK_MAX_LAYER_BYTES536870912Maximum decompressed stream bytes for one layer.
LAYERLEAK_MAX_LAYER_ENTRIES50000Maximum tar entries for one layer.
LAYERLEAK_MAX_IMAGE_LAYERS512Maximum layers selected for one image.
LAYERLEAK_MAX_IMAGE_MANIFESTS64Maximum platform manifests selected from one image index.
LAYERLEAK_MAX_IMAGE_LAYER_BYTES4294967296Aggregate advertised compressed and expanded layer bytes.
LAYERLEAK_MAX_IMAGE_ARTIFACTS250000Aggregate tar entry count across all selected layers, including directories, links, whiteouts, and device nodes.
LAYERLEAK_MAX_RETAINED_BYTES1073741824Bytes retained while reconstructing final state.
LAYERLEAK_MAX_NESTED_ARCHIVE_BYTES67108864Per archive stored in a layer (zip/jar/war/whl/egg, gzip, tar): the largest archive buffered for one-level expansion and the most decompressed bytes read out of it. Entries are scanned under outer/path!inner/path; expansion is charged to its own copy of the layer and image byte and entry budgets, tracked separately from the layer stream, so one layer can process up to twice its configured byte budget. Anything beyond a bound is skipped and reported with a nested_archive_skipped diagnostic while coverage stays complete. 0 disables nested archive expansion entirely.
LAYERLEAK_MAX_NESTED_ARCHIVE_ENTRIES10000Maximum entries examined per nested archive; the rest are skipped and reported. 0 disables this bound (the layer and image entry budgets still apply).
LAYERLEAK_MAX_LAYER_CACHE_BYTES0Memory for the per-sweep layer cache used by --all-tags: a layer whose files held no findings is remembered by digest (entry metadata only, never file content) so tags sharing it do not fetch and replay it again. Results are identical with and without the cache; it trades memory for time and registry traffic. Layers with findings, nested archives, or a hardlink whose target is not a file of the same layer (another layer's file, a directory or a missing path) are always re-fetched, and a layer whose entry list alone would exceed the cache size is not recorded. The budget is a conservative estimate of heap use. 0 (the default) disables the cache.
LAYERLEAK_MAX_MANIFEST_BYTES8388608Maximum manifest response size.
LAYERLEAK_MAX_CONFIG_BYTES8388608Maximum image config response size.
LAYERLEAK_MAX_TAG_RESPONSE_BYTES8388608Maximum tag-list response page size.
LAYERLEAK_MAX_FINDINGS_PER_SCAN10000Maximum findings retained for one scan.
LAYERLEAK_MAX_RAW_FINDING_BYTES67108864Maximum raw value and context bytes retained when raw-secret persistence is enabled. Once reached, detection continues with raw retention disabled, coverage stays complete, and a raw_retention_truncated diagnostic reports how many findings were recorded without raw values.
LAYERLEAK_TAG_PAGE_SIZE100Registry tag-list page size; must be positive.
LAYERLEAK_MAX_REPOSITORY_TAGS1000Maximum tags enumerated by --all-tags.
LAYERLEAK_MAX_REPOSITORY_TARGETS250Maximum distinct targets scanned by --all-tags.
API and PostgreSQL
VariableDefaultPurpose
LAYERLEAK_API_ADDR127.0.0.1:8080API listen address as host:port (the host may be empty, a hostname, or an IP); validated at startup; image default is 0.0.0.0:8080.
LAYERLEAK_API_MAX_REQUEST_BYTES16384Maximum JSON request body; must be positive.
LAYERLEAK_API_SCAN_TIMEOUT30mDeadline for an API scan.
LAYERLEAK_API_MAX_CONCURRENT_SCANS1In-process scan concurrency; must be positive.
LAYERLEAK_API_READ_HEADER_TIMEOUT5sHTTP header deadline.
LAYERLEAK_API_READ_TIMEOUT15sHTTP request read deadline.
LAYERLEAK_API_RESPONSE_WRITE_TIMEOUT30sNon-scan response write deadline.
LAYERLEAK_API_IDLE_TIMEOUT60sKeep-alive idle timeout.
LAYERLEAK_API_SHUTDOWN_TIMEOUT30sHow long shutdown waits for in-flight handlers after the drain window; must be positive.
LAYERLEAK_API_PRESTOP_DELAY0sDrain window after SIGTERM/SIGINT: /readyz answers 503 not_ready and new scans are refused with 503 server_shutting_down while in-flight requests keep running; when it elapses, in-flight scans are cancelled with 503 server_shutting_down. May be 0s. Keep LAYERLEAK_API_STOP_GRACE_PERIOD above this plus LAYERLEAK_API_SHUTDOWN_TIMEOUT.
LAYERLEAK_API_READINESS_TIMEOUT2sDatabase readiness query deadline.
LAYERLEAK_API_READINESS_CACHE_TTL5sHow long a /readyz result (success or failure) is reused before the ping and schema-contract validation run again; concurrent probes share one check. 0s validates on every probe.
LAYERLEAK_API_BEARER_TOKENSemptyOpt-in authentication: comma-separated bearer tokens, each at least 32 printable ASCII characters. When set, every /api/ request needs Authorization: Bearer <token> (401 unauthorized otherwise); /health, /livez and /readyz stay open. Tokens are kept only as SHA-256 digests and compared in constant time. Mutually exclusive with LAYERLEAK_API_BEARER_TOKENS_FILE.
LAYERLEAK_API_BEARER_TOKENS_FILEemptyPath of a file with one bearer token per line (blank lines ignored, at most 64 KiB), read once at startup; the same rules as LAYERLEAK_API_BEARER_TOKENS apply. Use it to mount tokens as a secret instead of an environment variable.
LAYERLEAK_API_METRICS_ADDRemptyOptional host:port for a second listener that serves Prometheus text-format metrics at GET /metrics (request counts and durations by route pattern, scan outcomes and error codes, in-flight scans, process start time). Empty disables it; it must differ from LAYERLEAK_API_ADDR, because metrics are never served on the API port. Bind it to a private interface: the endpoint is unauthenticated.
LAYERLEAK_DATABASE_URLemptyPostgreSQL connection URL. The password may be left out of the URL and supplied through PGPASSWORD or PGPASSFILE; the driver fills any field the URL omits from the standard PG* variables.
LAYERLEAK_DATABASE_MAX_OPEN_CONNS10Open connection cap; must be positive.
LAYERLEAK_DATABASE_MAX_IDLE_CONNS5Idle connection cap.
LAYERLEAK_DATABASE_CONN_MAX_LIFETIME30mConnection lifetime.
LAYERLEAK_DATABASE_CONN_MAX_IDLE_TIME5mIdle connection lifetime.
LAYERLEAK_DATABASE_QUERY_TIMEOUT10sRead and readiness query deadline.
LAYERLEAK_DATABASE_WRITE_TIMEOUT2mTransactional persistence deadline.
Compose only (read by docker-compose.yml, never by the binaries)
VariableDefaultPurpose
LAYERLEAK_IMAGEghcr.io/brumbelow/layerleak:latestImage used by the api, migrate, and purge-raw-secrets services.
LAYERLEAK_API_HOST127.0.0.1Host interface the API port is published on.
LAYERLEAK_API_PORT8080Host port published for the API.
LAYERLEAK_DB_NAMElayerleakDatabase created by the db service.
LAYERLEAK_DB_USERlayerleakRole created by the db service.
LAYERLEAK_DB_PASSWORDrequiredPassword for that role. .env.example ships it empty and Compose refuses to start until it is set.
LAYERLEAK_API_STOP_GRACE_PERIOD35sHow long Compose waits for the API to drain before killing it; keep it above LAYERLEAK_API_SHUTDOWN_TIMEOUT.

layerleak-migrate-up and layerleak-purge-raw-secrets read four more variables of their own; they are listed under Postgres.

04

Results

--format summary (the default) prints counts, a per-target table, and the first 50 actionable findings; --format json prints the stable result (result_schema_version 2, described by schemas/result-v2.schema.json); --format sarif prints a SARIF 2.1.0 log. --output <file> writes the formatted output to a file created with mode 0600 instead of stdout (- is stdout). Every result has a top-level status (completed, partial, or failed), a coverage object, per-target, per-platform, and per-tag status, and diagnostics. --format json prints the result for failed scans too, so automation can read the diagnostics. The silent paths are cancellation and failures before any result exists (invalid input, an unreadable local source, or an error opening the store): those print only the error on stderr and exit 1.

Exit codes

CodeMeaning
0Complete scan with no blocking findings, or an accepted (--allow-partial) usable partial scan with none.
1Invalid input, operational failure (registry, network, authentication), persistence failure, or cancellation (LAYERLEAK_SCAN_TIMEOUT, SIGINT, SIGTERM).
2One or more actionable findings at or above --fail-on. Findings take precedence over incomplete coverage.
3The scan finished with usable but incomplete coverage and --allow-partial was not given.

--fail-on low|medium|high|none sets the lowest confidence of an actionable finding that produces exit code 2: low (the default) is every actionable finding and none reports without failing. --allow-partial accepts usable incomplete coverage (exit 0 or 2 instead of 3) without hiding the missing coverage. Scripts that retry on 1 should treat 3 as "investigate coverage". A second SIGINT or SIGTERM terminates the process immediately.

One scan record per scan

Every scan that produced a result, whether completed, partial, or failed, writes exactly one scan record, <dir>/<utc-timestamp>-<reference-token>-<random>.json, unless --no-artifacts is given. <dir> is --output-dir, otherwise LAYERLEAK_FINDINGS_DIR (a relative value resolves against the working directory), otherwise ./findings under the working directory; the CLI does not look for a surrounding go.mod. The full path is printed quoted on stderr (Scan record: "…"). The record (record_schema_version 2, described by schemas/scan-record-v2.schema.json) holds the same redacted result as --format json, every finding with its source_location (actionable first, then suppressed), the persistence outcome (disabled, saved with scan_run_id, or failed with storage_unavailable), and created_at. There is no separate findings file.

A missing directory is created with mode 0700; an existing directory is never chmod-ed, a symbolic link in its place is refused, and the CLI warns once when an existing directory is readable by other users. Records are written 0600 and never overwrite an existing file. If the record cannot be written, the scan still prints its result and exits 1. --no-db ignores LAYERLEAK_DATABASE_URL for one run; a database-save failure exits 1, records storage_unavailable, and still prints the result.

Finding fields

detector_name confidence disposition disposition_reason source_type manifest_digest platform file_path layer_digest key line_number redacted_value fingerprint context_snippet match_start match_end present_in_final_image

Actionable findings are listed under findings and counted in total_findings and unique_fingerprints; suppressed ones are listed under suppressed_findings and counted in suppressed_findings_count. The scan record adds source_location to each finding. fingerprint is the SHA-256 of the raw value, stable across installs; for a path-only sensitive_file_* finding it is derived from the layer digest and path. The occurrence counters and first/last-seen times belong to the HTTP API, which aggregates stored history.

Redaction

Raw secret values and raw context snippets are never written locally: stdout, the scan record, JSON, and SARIF are always redacted, even with LAYERLEAK_PERSIST_RAW_SECRETS=1. A redacted_value under 12 characters is masked completely (********); a longer value shows its first three characters followed by the same fixed eight-character mask (ghp********), so neither the length nor the tail is disclosed, and a multi-line value becomes [REDACTED MULTILINE]. In context_snippet every copy of the matched value is replaced with [REDACTED]. Raw persistence exists only in PostgreSQL with LAYERLEAK_PERSIST_RAW_SECRETS=1, and the API and scan history stay redacted even then.

Baselines

A baseline file accepts reviewed findings by fingerprint so a rotated secret left in an old layer does not fail every run. Nothing is read implicitly; pass the file with --baseline.

layerleak scan ghcr.io/org/app:1.2 --format json --output result.json --fail-on none
layerleak baseline create --from result.json --reason "rotated 2026-09-01; old layer only"
layerleak scan ghcr.io/org/app:1.2 --baseline layerleak-baseline.json

baseline create reads a result or a scan record and writes one entry (fingerprint, detector, reason) per actionable finding to layerleak-baseline.json with mode 0600, never overwriting without --force and never writing values, paths, or snippets. Entries may carry an RFC 3339 expires. A matched finding is reported with disposition: baselined among suppressed_findings and never produces exit code 2. This is a per-caller view applied by the CLI: stdout, the scan record, SARIF, and the exit code see it, while the database and therefore the HTTP API keep the scanner's disposition. A malformed baseline exits 1 before the scan starts.

SARIF

--format sarif writes one SARIF 2.1.0 run per scan: every default detector under tool.driver.rules, a result per finding with level from its confidence, a layerleak/fingerprint/v1 partial fingerprint, the image reference as the IMAGE URI base, and a suppressions entry on suppressed and baselined findings. Only redacted values are written.

layerleak scan ghcr.io/org/app:1.2 --format sarif --output layerleak.sarif --fail-on none --no-artifacts
05

Postgres persistence

The API and persistent CLI mode need PostgreSQL 16.13 or newer. Migrations are explicit: the API never creates or upgrades schema, refuses to start unless the installed schema is exactly version 0004, and /readyz re-checks the database and schema afterwards. From a checkout, against a local database:

export LAYERLEAK_DATABASE_URL='postgres://layerleak@127.0.0.1:5432/layerleak?sslmode=disable'
export PGPASSWORD='<password>'
export LAYERLEAK_MIGRATIONS_DIR="$PWD/migrations"
go run ./cmd/migrate --status
go run ./cmd/migrate

Without flags the command applies every pending migration and a rerun is a no-op. --status prints the ledger (each shipped migration with its state, applied time, and SHA-256, then current and expected) and exits 0 when the database is current, 2 when migrations are pending or a legacy schema is waiting to be adopted, and 1 on any error such as checksum drift. --dry-run lists what a run would adopt and apply and changes nothing; --version prints the build version. The command holds an advisory lock (its wait bounded by LAYERLEAK_MIGRATION_TIMEOUT) with bounded per-migration lock waits, records checksums in a migration ledger, runs one transaction per migration, and refuses drift, gaps, dirty state, or a partial legacy schema. There is no down command.

Read by layerleak-migrate-up
VariableDefaultPurpose
LAYERLEAK_MIGRATIONS_DIR/app/migrationsDirectory holding the shipped migrations/*.sql; from a checkout use $PWD/migrations.
LAYERLEAK_MIGRATION_TIMEOUT30mOverall deadline for one run of the command; 0 disables it.
LAYERLEAK_MIGRATION_LOCK_TIMEOUT15slock_timeout for table locks inside each migration transaction, retried up to three times; the advisory-lock wait is bounded only by LAYERLEAK_MIGRATION_TIMEOUT.

The published image contains the same command. For a database that is not on the same host, mount the CA that signed the server certificate and use sslmode=verify-full, the only mode that both encrypts the connection and verifies the server's identity:

export LAYERLEAK_DATABASE_URL='postgres://<user>@<host>:5432/layerleak?sslmode=verify-full&sslrootcert=/etc/layerleak/postgres-ca.pem'
docker run --rm \
  -v /path/to/postgres-ca.pem:/etc/layerleak/postgres-ca.pem:ro \
  -e LAYERLEAK_DATABASE_URL -e PGPASSWORD \
  --entrypoint /usr/local/bin/layerleak-migrate-up \
  ghcr.io/brumbelow/layerleak:v3.0.0 --status

Current state is deduplicated by (manifest_digest, fingerprint) in findings, with one row per place a value was seen in finding_occurrences. Append-only scan history lives in scan_runs as a redacted snapshot of the public result, regardless of LAYERLEAK_PERSIST_RAW_SECRETS.

Purging raw values First set LAYERLEAK_PERSIST_RAW_SECRETS=0 on every API and CLI database writer and restart or stop them. layerleak-purge-raw-secrets --dry-run reports how many raw values and snippets would be cleared; --confirm clears only findings.value and finding_occurrences.raw_snippet in id-range batches of --batch-size rows (default 5000), one transaction per batch, and keeps redacted findings and history. Committed batches stay purged if a later one fails, so a failed run can be rerun. Raw material lingers in dead tuples until vacuum and in WAL archives, replicas, and backups taken before the purge.
Read by layerleak-purge-raw-secrets
VariableDefaultPurpose
LAYERLEAK_PURGE_TIMEOUT30mOverall deadline for one run of layerleak-purge-raw-secrets; 0 disables it. Each batch is separately bounded by LAYERLEAK_DATABASE_WRITE_TIMEOUT.
06

HTTP API

The API binary (layerleak-api in the image, cmd/api in the source) is JSON-only and PostgreSQL-backed: it requires LAYERLEAK_DATABASE_URL and never reads scan records. It listens on plain HTTP; deploy it on a private network behind TLS termination and an authenticating gateway that also rate-limits.

  • GET/health
  • GET/livez
  • GET/readyz
  • POST/api/v1/scans
  • GET/api/v1/scans/{id}
  • GET/api/v1/repositories
  • GET/api/v1/repositories/{repository}/scans
  • GET/api/v1/repositories/{repository}/findings
  • GET/api/v1/findings/{id}

/health and /livez report process liveness and the build version without querying PostgreSQL. /readyz requires a database ping and schema version 0004, reuses its answer for LAYERLEAK_API_READINESS_CACHE_TTL, and answers 503 not_ready while the process drains.

POST /api/v1/scans is synchronous and accepts reference, optional platform, and optional all_tags; unknown fields are rejected. A bare reference means latest unless all_tags is true. Local sources (oci:, oci-archive:, docker-archive:) are rejected with 400 invalid_request. The response carries scan_run_id and the redacted result; unlike the CLI, its error fields read scan step failed and diagnostic messages are fixed text chosen by diagnostic code. Incomplete work returns 422 scan_incomplete or scan_limit_exceeded, and a scan that finished but could not be persisted returns 503 storage_unavailable with the result and without a scan_run_id. Scans beyond LAYERLEAK_API_MAX_CONCURRENT_SCANS get 429 scan_capacity_exceeded.

curl --fail-with-body \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer $API_TOKEN" \
  -d '{"reference":"alpine:3.20","platform":"linux/amd64"}' \
  http://127.0.0.1:8080/api/v1/scans

List endpoints accept limit (default 50, clamped to 200) and offset, and every list response returns next_cursor: an opaque keyset position when the page was full, or "" when the listing is exhausted. Pass it back as cursor so deep pages cost the same as the first; a cursor is tied to one endpoint and cannot be combined with a non-zero offset. Repository endpoints accept registry as host or host:port (default docker.io), the {repository} segment accepts a literal / or %2F, and the finding list accepts disposition=actionable|suppressed|all (default actionable).

Stored finding fields

id manifest_digest fingerprint redacted_value detectors occurrence_count actionable_occurrence_count suppressed_occurrence_count first_seen_at last_seen_at

GET /api/v1/findings/{id} adds the redacted occurrences history. These aggregates come from the database and are not part of the CLI result.

Bearer tokens are opt-in Authentication is off by default. Setting LAYERLEAK_API_BEARER_TOKENS (comma-separated) or LAYERLEAK_API_BEARER_TOKENS_FILE (one per line) requires Authorization: Bearer <token> on every /api/ path; a missing or unknown token answers 401 unauthorized with WWW-Authenticate. /health, /livez, and /readyz stay open. Tokens are at least 32 characters, held only as SHA-256 digests, compared in constant time, and never logged, and the API warns at startup when it listens on a non-loopback address without tokens. This is defence in depth, not authorization: there are no users, roles, or tenants, so keep TLS termination and your gateway.

LAYERLEAK_API_METRICS_ADDR adds a second listener that serves Prometheus text-format metrics at GET /metrics: requests by route pattern and status class, request durations, scans by outcome and error code, in-flight scans, process start time, and build info. Labels never carry paths, references, or request bodies. It must differ from LAYERLEAK_API_ADDR and is unauthenticated, so bind it to a private interface. The API logs one record per request (JSON by default, key=value with LAYERLEAK_LOG_FORMAT=text; method, route pattern, status, bytes, duration, request id, remote address) and never the path, query, or body.

On SIGTERM or SIGINT the API drains: for LAYERLEAK_API_PRESTOP_DELAY /readyz answers 503 and new scans are refused with 503 server_shutting_down while in-flight requests continue; then in-flight scans are cancelled with 503 server_shutting_down and the server stops within LAYERLEAK_API_SHUTDOWN_TIMEOUT, exiting 0.

Status codes

Errors use {"error": {"code", "message", "request_id"}} with fixed, neutral messages; every response carries X-Request-ID, Cache-Control: no-store, and X-Content-Type-Options: nosniff, and the API never redirects.

StatuscodeWhereBody
200every endpointthe documented response
400invalid_requestevery endpointerror envelope
401unauthorizedevery /api/ path when LAYERLEAK_API_BEARER_TOKENS is set; WWW-Authenticate: Bearer realm="layerleak"error envelope
404not_foundreads, unknown pathserror envelope
404image_not_foundPOST /api/v1/scansenvelope, plus result when available
405method_not_allowedevery endpoint; Allow names the accepted methoderror envelope
408scan_canceledPOST /api/v1/scans; the client closed the connection before the scan finishederror envelope
413request_too_largePOST /api/v1/scanserror envelope
415unsupported_media_typePOST /api/v1/scanserror envelope
422scan_incompletePOST /api/v1/scansenvelope, plus result and scan_run_id when persisted
422scan_limit_exceededPOST /api/v1/scans; the error object adds limit_kind and limitenvelope, plus result and scan_run_id when persisted
429scan_capacity_exceededPOST /api/v1/scans; Retry-After: 5error envelope
500internal_errorevery endpointerror envelope
502scan_failedPOST /api/v1/scans; transport errors, registry 5xx and timeouts inside the scanenvelope, plus result when available
502registry_unauthorizedPOST /api/v1/scans; the registry or its token endpoint answered 401/403envelope, plus result when available
503storage_unavailablereads: a database query failed; POST /api/v1/scans: the scan finished but could not be persistedreads: envelope; scans: envelope plus result
503registry_rate_limitedPOST /api/v1/scans; the registry answered 429 after bounded retries; Retry-After: 60envelope, plus result when available
503server_shutting_downPOST /api/v1/scans while draining, and any request the drain cancellederror envelope
503not_readyGET /readyzerror envelope
504scan_timeoutPOST /api/v1/scans; LAYERLEAK_API_SCAN_TIMEOUT expiredenvelope, plus result when available

Open the versioned OpenAPI 3.1 specification.

07

Container & Compose

The published image supports linux/amd64 and linux/arm64. It is shell-free, runs as UID/GID 10001, works with a read-only root filesystem, and contains CA roots, the migrations, and four static binaries: layerleak-api (the default entrypoint, listening on 0.0.0.0:8080), layerleak-migrate-up, layerleak-purge-raw-secrets, and layerleak-healthcheck, which probes /readyz with a two-second deadline. It does not contain the layerleak CLI. Pin it by release tag or, better, by the image.index_digest in the release's release-manifest.json (ghcr.io/brumbelow/layerleak@sha256:<digest>) instead of :latest.

docker pull ghcr.io/brumbelow/layerleak:v3.0.0
docker run --rm \
  -p 8080:8080 \
  -v /path/to/postgres-ca.pem:/etc/layerleak/postgres-ca.pem:ro \
  -e LAYERLEAK_DATABASE_URL='postgres://<user>:<password>@<host>:5432/layerleak?sslmode=verify-full&sslrootcert=/etc/layerleak/postgres-ca.pem' \
  --read-only --tmpfs /tmp:mode=1777 \
  --cap-drop ALL --security-opt no-new-privileges \
  ghcr.io/brumbelow/layerleak:v3.0.0

Keep sslmode=verify-full with the mounted CA for any database that is not on the same host. Omitting sslmode is not a safe shortcut: the driver's implicit require encrypts without verifying the server certificate. Use sslmode=disable only for a database reachable solely over a private network, as the Compose file does for its db service. A password embedded in a URL must be percent-encoded; PGPASSWORD may hold any characters.

docker-compose.yml runs db (PostgreSQL 16.15 pinned by multi-platform digest), migrate, and api; purge-raw-secrets is in the tools profile. One command starts the stack: api waits for the database to be healthy and for migrate to finish, so a fresh volume becomes ready without a manual migration step. Set the required password and pin the image in .env first; the example ships the password empty and LAYERLEAK_IMAGE at :latest.

cp .env.example .env
# In .env: set LAYERLEAK_DB_PASSWORD and pin
# LAYERLEAK_IMAGE=ghcr.io/brumbelow/layerleak:v3.0.0
docker compose config
docker compose up -d
docker compose ps
curl --fail http://127.0.0.1:8080/readyz

The API runs read-only with every capability dropped, a 256 MiB /tmp tmpfs, a 2 GiB memory limit, and a 256-process limit (mem_limit and pids_limit; mirror them under deploy.resources.limits for a Swarm stack, and raise the memory limit with any MAX_*_BYTES bound you lift). The database keeps only the five capabilities its entrypoint needs, and the one-shot migrate and purge commands run read-only on a 64 MiB tmpfs. The host port binds to 127.0.0.1 by default; change LAYERLEAK_API_HOST only when an authenticated network edge is ready. The api service has a 35-second stop_grace_period (LAYERLEAK_API_STOP_GRACE_PERIOD); whatever runs the container must allow more than LAYERLEAK_API_SHUTDOWN_TIMEOUT, otherwise an in-flight scan is killed before it is persisted. Dockge and Komodo deploy the same file.

docker compose --profile tools run --rm purge-raw-secrets --dry-run
docker compose --profile tools run --rm purge-raw-secrets --confirm
08

Browser demo

The demo replays a real layerleak scan of a synthetic OCI image layout: a multi-platform index whose linux/amd64 image hides fabricated secrets in its environment, a label, the build history, a final file, a deleted file, a nested jar, an unreadable SSH key, and a test fixture. A repository test builds the layout, runs the CLI, and regenerates the fixture from its progress lines, summary, and scan record, and fails if the committed copy drifts. The tables are the Postgres rows that result would produce, with raw-value columns empty. Nothing runs in your browser and nothing is sent anywhere.

layerleak scan oci:payments-api:1.4.2 --progress plain --no-db

Open the demo replay