DevOps & CI/CD Bug Report

GitLab protected CI/CD variables empty in merge request pipelines

A preview deploy job got empty credentials in merge request pipelines while the same job worked on main. Protected variables are only exposed to protected refs; we fixed it with environment-scoped, non-protected preview credentials and kept production secrets protected.

Ryan Pham Ryan Pham @ryan_bugs · November 29, 2026 · 8 min read · 0 Views
637-gitlab-protected-variables-missing-in-mr-pipelines

We added a "deploy preview" job to our GitLab pipeline so every merge request got a temporary environment. On main the job had deployed fine for months. In the first merge request pipeline it failed in under a second:

$ ./scripts/deploy.sh preview
deploy.sh: KUBE_TOKEN is empty; refusing to continue
ERROR: Job failed: exit code 1

The variable existed. We could see KUBE_TOKEN under Settings, CI/CD, Variables, with the value set and the "Protected" and "Masked" checkboxes ticked. A teammate retried the job twice and then ran the pipeline manually on the feature branch from the Pipelines page: same empty value.

Reproducing it

  1. Define a project variable KUBE_TOKEN, flag it Protected.

  2. Leave main as the only protected branch.

  3. Add a job that prints whether the variable is set:

check-token:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  script:
    - 'if [ -n "$KUBE_TOKEN" ]; then echo "token present"; else echo "token missing"; fi'
    - echo "ref=$CI_COMMIT_REF_NAME protected=$CI_COMMIT_REF_PROTECTED source=$CI_PIPELINE_SOURCE"
  1. Open a merge request from feature/preview. Output:

token missing
ref=feature/preview protected=false source=merge_request_event

On main the same job prints token present and protected=true.

What we ruled out

  • Masking hiding the value. A masked variable is replaced with [MASKED] in logs, but it is still set in the environment. Our script tested emptiness, not the printed value, so masking was not the cause.

  • Variable defined at the wrong level. We checked group variables too; a project variable with the same key overrides a group one, and there was only one definition.

  • Environment scope. The variable's scope was * (all environments), so it was not filtered by the job's environment:.

  • Typo in the key. Keys are case-sensitive. We copied the key from the settings page into the script to be sure.

Root cause

The variable was marked Protected, and GitLab only passes protected variables to pipelines that run on protected branches or protected tags. CI_COMMIT_REF_PROTECTED=false in the output proved the merge request pipeline ran for the unprotected source branch feature/preview. The job never received the variable at all, by design. Production had worked only because deploys ran from main.

What is happening under the hood

When GitLab creates a job, it builds the variable set from instance, group, project and pipeline sources, then filters it. Two filters matter here:

  1. Protected filter. If the pipeline's ref is not protected, every variable flagged Protected is dropped. For merge request pipelines, GitLab treats the pipeline as protected only when both the source and target branches are protected. A feature branch into main is therefore unprotected.

  2. Environment scope filter. If a variable has an environment scope other than *, it is passed only to jobs whose environment:name matches that scope (wildcards such as review/* are supported).

There is no error when a variable is filtered out. The job simply runs without it, which is why the failure shows up as a confusing downstream symptom: an empty token, an auth error from a cloud CLI, or a script deploying with defaults.

Masking is a third, unrelated switch. It controls log output only. GitLab enforces format requirements before it lets you mask a value (single line, minimum length of 8 characters, and a limited character set that depends on your GitLab version). A value that fails those rules cannot be saved as masked; it does not get silently unmasked.

Environment

Component

Version / value

GitLab

GitLab.com (SaaS), Premium tier

Runner

GitLab-hosted saas-linux-small-amd64

Pipeline types

Branch pipelines on main, merge request pipelines on feature branches

Protected branches

main only

Variable

KUBE_TOKEN, project level, Protected + Masked, scope *

Minimal reproduction

variables:
  # nothing here; KUBE_TOKEN comes from project settings (Protected)

deploy-preview:
  stage: deploy
  environment:
    name: review/$CI_MERGE_REQUEST_IID
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  script:
    - test -n "$KUBE_TOKEN" || { echo "KUBE_TOKEN is empty"; exit 1; }
    - ./scripts/deploy.sh preview

Who is affected

Any GitLab project (SaaS or self-managed) where a job that needs a protected variable runs in:

  • merge request pipelines from unprotected source branches;

  • branch pipelines on unprotected branches;

  • pipelines for merge requests from forks, which run in the fork's context by default.

Projects that deploy only from protected branches never see it, which is why it often appears the first time someone adds review apps.

The fix

Unprotecting the production token would have "fixed" the job and also handed cluster-admin access to every branch, including branches anyone with Developer role can push. Instead we split credentials by environment.

1. Keep production credentials protected and scoped. KUBE_TOKEN became two variables with the same key and different environment scopes:

Key

Value

Protected

Masked

Environment scope

KUBE_TOKEN

prod deployer token

yes

yes

production

KUBE_TOKEN

preview namespace token

no

yes

review/*

GitLab allows the same key with different scopes; the job gets the one whose scope matches its environment.

2. Limit the preview token's power. The preview token belongs to a Kubernetes service account that can only manage resources in review-* namespaces. If a branch leaks it, the blast radius is preview environments.

3. Make every deploy job declare its environment.

 deploy-preview:
   stage: deploy
+  environment:
+    name: review/$CI_MERGE_REQUEST_IID
+    on_stop: stop-preview
   rules:
     - if: $CI_PIPELINE_SOURCE == "merge_request_event"
   script:
     - test -n "$KUBE_TOKEN" || { echo "KUBE_TOKEN is empty"; exit 1; }
     - ./scripts/deploy.sh preview

 deploy-prod:
   stage: deploy
+  environment:
+    name: production
   rules:
     - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
   script:
     - ./scripts/deploy.sh production

4. Fail fast with a clear message. Every script that needs a secret checks it at the top and names the likely cause:

require_var() {
  if [ -z "${!1:-}" ]; then
    echo "$1 is empty. ref=$CI_COMMIT_REF_NAME protected=$CI_COMMIT_REF_PROTECTED env=${CI_ENVIRONMENT_NAME:-none}" >&2
    echo "Protected variables are only available on protected refs; check environment scope." >&2
    exit 1
  fi
}
require_var KUBE_TOKEN

Alternatives and trade-offs

  • Protect the feature branches with a wildcard such as release/*. Works for release branches, but protecting every feature branch defeats the purpose of protection.

  • Run the deploy only after merge. Simplest and safest; you lose per-MR previews.

  • Short-lived cloud credentials via id_tokens. Instead of a stored token, the job requests an OIDC token and the cloud or Vault decides access from claims such as ref_protected and environment. This removes the stored secret entirely and is where we are heading for production.

  • Protected environments. On Premium, a protected production environment restricts who can deploy to it, which adds a human gate on top of the variable filter.

How to test the fix

Run the check job on three refs and compare:

# from a feature branch MR pipeline
token present (preview)  env=review/42  protected=false

# from main
token present (prod)     env=production protected=true

We printed a non-secret fingerprint of each token (first 6 characters of its SHA-256) to prove which one each job received:

printf '%s' "$KUBE_TOKEN" | sha256sum | cut -c1-6

Confirming in production

After the change we watched the next ten merge requests. Every preview deploy succeeded, and the Kubernetes audit log showed only the preview service account acting in review-* namespaces. Production deploys from main continued to use the production service account. A deliberate test, adding environment: production to a job in a feature branch, received no KUBE_TOKEN at all, which is the behaviour we want.

Regression guard

  • A CI lint script fails the pipeline if any job that references KUBE_TOKEN lacks an environment: block.

  • A scheduled job lists project variables through the API and alerts if any variable with "prod" in its key is not protected.

curl --silent --header "PRIVATE-TOKEN: $AUDIT_TOKEN" \
  "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/variables" \
  | jq -r '.[] | select((.key|test("PROD";"i")) and .protected==false) | .key'

Security implications

The bug itself was protective: GitLab correctly withheld a production credential from an unprotected branch. The dangerous fix is the obvious one, unticking Protected. Anyone who can push a branch can edit .gitlab-ci.yml in that branch and print or exfiltrate any variable the pipeline receives; masking does not stop a script from sending the value elsewhere. Keep high-privilege secrets protected, give unprotected pipelines low-privilege, scoped credentials, and prefer OIDC so there is nothing stored to steal.

Prevention checklist

  • Mark every production credential Protected and give it an environment scope.

  • Create separate, low-privilege credentials for review and preview environments.

  • Declare environment: on every deploy job.

  • Check required variables at the top of scripts with a message naming protection and scope.

  • Audit variables periodically through the API.

References

Add a label

#gitlab-ci #secrets #merge-requests #ci-variables #protected-branches
Written by
Ryan Pham @ryan_bugs

I build and run the platforms other engineers ship on: CI/CD pipelines, Kubernetes clusters, GPU inference services, LLM features in production, and the cloud bills that come with all of it. I have also spent years writing and operating automated trading systems, where a rounding bug or a missed websocket message is not a log line but a position you did not intend to hold. Each post here starts from a real failure: the alert, the exact error, what we ruled out, the root cause, and how we proved the fix. Same path every time: Investigate, Explain, Fix, Verify. No hype, no price predictions, just engineering.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.