Skip to main content
Systems Engineering

Mitigating Remote Cache Poisoning in CI/CD

Advanced architecture for stopping remote cache poisoning in distributed Bazel and CI/CD pipelines using tiered namespacing and signed provenance.

KBY Technologies12 min read
Mitigating Remote Cache Poisoning in CI/CD

A shared remote build cache is the single highest-leverage optimisation in a monorepo CI pipeline, collapsing multi-hour Bazel or Gradle builds into sub-minute incremental runs. It is also, by default, an unauthenticated write path into every trusted build that consumes it. When fork-based pull request runners and protected branch runners share the same action cache (AC) and content-addressable store (CAS), you have built a supply-chain vector disguised as a performance feature. This is remote cache poisoning: an attacker-controlled job or a non-hermetic build action stores an output under a legitimate action key, and that poisoned artifact is silently served to your main branch’s release build.

This is not a theoretical concern. Bazel, Gradle, Turborepo and Pants all implement remote caching using a two-part lookup: an action key derived from the command line, inputs, and environment, mapped to a digest of the output blob. If the derivation of that action key omits sufficient context — toolchain version, absolute paths, environment variables, or trust tier — two semantically different actions can resolve to the same key and share one cached result. The deliberate attack is simpler: action keys are computed from inputs that sit in the repository, so any client holding write access to the action cache can upload a result of its choosing under the key a trusted build will later request. The cache server cannot tell that the result did not come from running that action, so the fix is to restrict who can write.

#Architectural Breakdown: Why Shared Caches Fail Trust Boundaries

The core design flaw is treating the remote cache as a single trust domain when your CI topology has at least two: untrusted (fork PRs, external contributors, unreviewed branches) and trusted (protected branches, release tags, post-merge pipelines). Common configurations — Bazel’s --remote_cache, which uploads local results by default, Gradle’s build-cache block once remote push is enabled (it is off by default), Turborepo’s remote cache API — grant read and write access to every runner using the same bearer token or service account, regardless of which side of that boundary the job originated from.

Combine that with non-hermetic actions — genrules that shell out to date, embed absolute workspace paths, or read ambient environment variables not declared in the action’s input set — and you get a build that produces different outputs for the same nominal inputs. If a malicious PR job holds write credentials and uploads its own result under the key of a legitimate action from main, and the cache accepts the write, subsequent trusted builds will pull the attacker’s blob out of cache instead of rebuilding from source. No code review catches this because the malicious diff never lands in the trusted branch — it only ever touches the cache.

The correct architectural response is tiered cache segmentation combined with action hermeticity enforcement and cryptographic provenance verification on cache reads. This mirrors zero-trust architectural patterns applied at the network layer, but relocated to the build graph: never trust a cache write without verifying who produced it and under what conditions.

#
Trust Tiers and Instance Namespacing

Bazel supports --remote_instance_name, which cache servers that implement it use to namespace the AC and CAS server-side. This is the cheapest lever available: route untrusted PR runners to an isolated instance name, with credentials the cache server authorises for that quarantined namespace only and never for writes to the trusted instance. Trusted post-merge builds read exclusively from the trusted instance and populate it themselves — never from PR-tier output.

remote cache poisoning
1# .bazelrc — trusted (protected branch) profile
2build:trusted --remote_cache=grpcs://cache.internal.kby:443
3build:trusted --remote_instance_name=main-trusted
4build:trusted --remote_upload_local_results=true
5build:trusted --remote_cache_async
6build:trusted --incompatible_strict_action_env
7
8# .bazelrc — untrusted (same-repository pull request) profile; fork PRs run without the remote cache
9build:pr --remote_cache=grpcs://cache.internal.kby:443
10build:pr --remote_instance_name=pr-quarantine
11build:pr --remote_upload_local_results=true
12build:pr --incompatible_strict_action_env

The PR profile never names the trusted instance: it reads and writes only pr-quarantine, so PR builds get incremental reuse from earlier PR builds but never consume entries seeded by trusted builds. Client flags are not a security boundary, so the cache server must enforce this by authorising the PR credential for pr-quarantine alone. If you would rather let PR builds reuse trusted outputs, point them at main-trusted with --remote_upload_local_results=false and a credential the server treats as read-only. (--noremote_accept_cached, by contrast, disables all cache reads for a build.)

#Implementation Logic: Closing the Remote Cache Poisoning Window

Segmentation alone reduces blast radius but does not eliminate remote cache poisoning within a single trust tier — a compromised or misconfigured trusted runner can still poison the trusted namespace. The full mitigation stack requires five sequential controls:

  • Hermeticity enforcement — sandbox every action (--sandbox_default_allow_network=false), strip ambient environment variables, and pin toolchains by digest, not by tag.
  • Action key salting — make the pinned toolchain digest part of every action’s inputs so that environment drift cannot collide with a prior key.
  • Credential scoping via OIDC — issue short-lived, branch-scoped tokens rather than long-lived static service account keys for cache access.
  • Provenance attestation — sign cache writes with in-toto/SLSA metadata and verify signatures on read, not just on ingest.
  • Reproducibility spot-checks — periodically rebuild a sample of cached actions from scratch and diff output hashes against the cached digest.

#
Step 1 — OIDC-Scoped Cache Credentials in CI

Static bearer tokens for remote cache access are a major remote cache poisoning risk, because a leaked token from a fork-executed workflow grants indefinite write access to the trusted namespace. Replace them with short-lived OIDC-issued tokens scoped per branch protection state.

1# .github/workflows/ci.yml
2jobs:
3  build:
4    runs-on: ubuntu-22.04
5    permissions:
6      id-token: write
7      contents: read
8    steps:
9      - uses: actions/checkout@v4
10      - name: Select cache tier
11        id: tier
12        env:
13          IS_FORK: ${{ github.event.pull_request.head.repo.fork }}
14        run: |
15          if [ "$IS_FORK" = "true" ]; then
16            echo "config=nocache" >> "$GITHUB_OUTPUT"
17          elif [ "$GITHUB_EVENT_NAME" = "push" ] && [ "$GITHUB_REF" = "refs/heads/main" ]; then
18            echo "config=trusted" >> "$GITHUB_OUTPUT"
19          else
20            echo "config=pr" >> "$GITHUB_OUTPUT"
21          fi
22      - name: Bazel build with scoped cache credential
23        if: steps.tier.outputs.config != 'nocache'
24        env:
25          CONFIG: ${{ steps.tier.outputs.config }}
26        run: |
27          OIDC=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
28            "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=kby-remote-cache" | jq -r .value)
29          # kby-cache-auth is illustrative internal tooling: substitute your cache's token exchange
30          CACHE_TOKEN=$(kby-cache-auth exchange --oidc-token "$OIDC" --role "cache-$CONFIG" --ttl 900)
31          echo "::add-mask::$CACHE_TOKEN"
32          bazel build //... --config="$CONFIG" --remote_header="Authorization=Bearer $CACHE_TOKEN"
33      - name: Bazel build (fork, no remote cache)
34        if: steps.tier.outputs.config == 'nocache'
35        run: bazel build //...

Fork pull request workflows cannot be granted id-token: write unless an admin enables sending write tokens to workflows from pull requests, so the tier step routes fork builds to the last step, which runs without the remote cache. Event values reach the shell through env rather than ${{ }} interpolation, and the token stays in a shell variable instead of a file in the workspace, but any code the build executes can still read the credential it runs with, so the server-side scope of each role is the real boundary. The 900-second TTL is deliberate: it bounds the exploitation window if a token is exfiltrated mid-build to roughly the length of a single CI job, rather than the lifetime of a static secret rotated quarterly.

#
Step 2 — Provenance Verification on Cache Read

Namespacing prevents cross-tier writes but does nothing against a compromised trusted runner poisoning its own tier. The remaining control is cryptographic: every cache write is accompanied by an in-toto attestation referencing the Bazel Remote Execution API action digest, signed by the CI runner’s workload identity. Reads verify the signature before the blob is trusted for reuse.

Mitigating Remote Cache Poisoning in CI/CD architecture diagram 2
1#!/usr/bin/env bash
2# verify-cache-entry.sh — invoked by the remote cache proxy on read
3ACTION_DIGEST="$1"
4# kby-cache-cli is illustrative internal tooling, not a published tool
5ATTESTATION=$(kby-cache-cli fetch-attestation --digest "$ACTION_DIGEST")
6
7cosign verify-blob \
8  --key /etc/kby/cache-signing.pub \
9  --signature <(echo "$ATTESTATION" | jq -r .signature) \
10  <(echo "$ATTESTATION" | jq -r .payload) || {
11    echo "REJECT: provenance verification failed for digest ${ACTION_DIGEST}" >&2
12    exit 1
13  }
14
15echo "ACCEPT: verified provenance for digest ${ACTION_DIGEST}"

This adds some latency per cache hit for the signature check (measure it in your environment), which is usually small against the multi-second cost of a cache miss rebuild, but it converts an implicit trust decision into an auditable one — every accepted cache entry now has a signed chain of custody back to a specific runner and workflow run ID.

#Failure Modes and Edge Cases

Segmentation and signing close the primary remote cache poisoning vector, but several edge cases remain and must be handled explicitly rather than assumed away:

  • Weak hash collisions in legacy CAS backends. The Remote Execution API still allows SHA-1 as a digest function, so check which one your cache backend uses. SHA-1 is collision-broken (practical chosen-prefix collisions have been demonstrated), so it should not be used for content addressing where an attacker can supply content, even though preimage attacks against it remain impractical. Any cache backend accepting client-supplied digests without server-side recomputation is vulnerable regardless of hash strength.
  • TOCTOU between AC lookup and CAS fetch. A race condition exists where the action cache lookup succeeds against a legitimate digest, but the subsequent CAS blob fetch is served from a different, since-overwritten object if the backend permits digest reuse after garbage collection. Mitigate by configuring the CAS as strictly immutable — write-once, no overwrite — and rejecting any write where the digest already exists but the byte content differs.
  • Non-hermetic actions that pass CI but fail locally. Genrules invoking date, reading $HOSTNAME, or resolving DNS during the build will produce different outputs per invocation while presenting an identical declared input set, meaning the action key is stable but the output is not. This is the most common root cause of accidental (non-malicious) remote cache poisoning and should be caught by CI-level reproducibility checks, not code review.
  • Federated caches across multiple CI providers. Organisations running GitHub Actions, self-hosted GitLab runners, and Jenkins agents against one shared cache backend multiply the number of distinct trust boundaries that must be independently namespaced and credentialed. A single shared static token across providers reintroduces the original flaw at a larger scale.
  • Cache invalidation on toolchain rollback. Rolling back a compiler or SDK version without bumping the toolchain digest used in action key salting will cause the build to silently reuse artifacts compiled under the newer toolchain, producing a binary that does not match the declared build configuration — a correctness failure that masquerades as a successful, fast build.

#Scaling and Security Trade-offs

Every mitigation against remote cache poisoning imposes a measurable cost against raw cache hit-rate and build latency. These trade-offs should be tuned explicitly per environment rather than applied uniformly. The figures below are illustrative, not benchmarks; measure them on your own cache:

  • Single shared cache — highest hit-rate (typically 85–95% on stable monorepos), lowest infrastructure cost, but zero isolation between trust tiers; unsuitable for any repository accepting external contributions.
  • Tiered instance namespacing — hit-rate drops for PR builds (cold quarantine namespace, ~40–60% on first run per branch) but trusted-branch hit-rate is unaffected; infrastructure cost roughly doubles due to duplicate storage of common base-layer artifacts across namespaces unless a read-through shared base layer is implemented.
  • Provenance signing on every write — adds 20–40ms per action server-side and requires key management infrastructure (HSM or KMS-backed signing keys), but is the only control that defends against a compromised trusted runner rather than just an untrusted one.
  • SHA-256 vs BLAKE3 for content addressing — BLAKE3 is much faster than SHA-256 in its authors’ benchmarks and is a Remote Execution API digest function, but every client and cache server in the path must support it.
  • Aggressive TTL and eviction policies — shrinking the poisoning exploitation window by reducing entry lifetime (e.g., 24 hours instead of 30 days) directly reduces cache hit-rate and increases rebuild frequency, trading CI wall-clock time for a smaller attack surface.
  • OIDC token exchange overhead — replacing static credentials adds approximately 50–150ms per job for the token exchange round trip, a cost that is trivial against build durations measured in minutes but becomes noticeable in high-frequency, short-lived CI matrix jobs.

None of these controls are optional in isolation for a monorepo accepting external contributions at scale — instance segmentation without provenance verification still permits a compromised trusted runner to poison its own tier indefinitely, and provenance verification without hermeticity enforcement merely signs non-reproducible garbage with a valid signature. The full stack — segmentation, hermeticity, scoped credentials, and signed provenance — is the minimum viable architecture for a remote build cache that cannot be turned into a supply-chain weapon against your own release pipeline.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01Bazel Remote Execution APIbazel.build

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on Mitigating Remote Cache Poisoning in CI/CD. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.