Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 12: GitLab CI und Jenkins

Ziel: GitLab-Jobs melden sich per id_tokens bei OpenBao an, und Jenkins holt Secrets per AppRole mit gewrappter Secret-ID. · Dauer: ca. 90 min · Voraussetzung: Tag 10

Briefing

  • GitLab stellt JWTs nur aus, wenn der Job sie per id_tokens: mit eigener aud anfordert. Issuer ist die URL der GitLab-Instanz.
  • Wichtige Claims: project_id, project_path, namespace_path, ref, ref_type, ref_protected, environment, environment_protected.
  • Zwei Wege im Job: secrets: mit vault: (Premium/Ultimate, Runner holt das Secret) oder bao im Job-Image (jede Edition, volle Kontrolle).
  • Jenkins ohne OIDC: AppRole aus Tag 10. Der Controller ist Trusted Orchestrator und reicht nur ein Wrapping-Token an den Agenten.
GitLab-Job ── id_tokens (aud) ──▶ auth/jwt-gitlab/login role=shop-deploy
Jenkins ── issuer-Token ──▶ secret-id (gewrappt)
                            └──▶ Agent: unwrap ──▶ approle/login

Drill 1: GitLab-Issuer per Discovery

Für deine Instanz trägst du deren URL ein. Die Discovery liefert die Schlüssel von /oauth/discovery/keys. Zum Ausprobieren nimmst du gitlab.com in einem Wegwerf-Mount:

mkdir -p ~/secrets-lab/tag12 && cd ~/secrets-lab/tag12
export BAO_ADDR=http://127.0.0.1:8200 BAO_TOKEN=root
curl -s https://gitlab.com/.well-known/openid-configuration | jq '{issuer, jwks_uri}'
bao auth enable -path=jwt-gitlab-com jwt >/dev/null
bao write auth/jwt-gitlab-com/config oidc_discovery_url=https://gitlab.com \
  bound_issuer=https://gitlab.com
bao read -field=status auth/jwt-gitlab-com/config; echo
bao auth disable jwt-gitlab-com

Erwartet:

{
  "issuer": "https://gitlab.com",
  "jwks_uri": "https://gitlab.com/oauth/discovery/keys"
}
Success! Data written to: auth/jwt-gitlab-com/config
valid
Success! Disabled the auth method (if it existed) at: jwt-gitlab-com/

Für eine eigene Instanz sieht das so aus (Muster, nicht ausführen):

bao write auth/jwt-gitlab/config \
  oidc_discovery_url=https://gitlab.example.com \
  bound_issuer=https://gitlab.example.com
# alternativ ohne Discovery:
# bao write auth/jwt-gitlab/config \
#   jwks_url=https://gitlab.example.com/oauth/discovery/keys \
#   bound_issuer=https://gitlab.example.com

Tipp: Hat die Instanz ein internes Zertifikat, gehört die CA in oidc_discovery_ca_pem bzw. jwks_ca_pem, nicht in einen Skip-Verify-Schalter.

Fortschritt speichern? Kostenlos registrieren

Drill 2: GitLab-Claims im Lab nachbauen

Ein GitLab-JWT für einen Deploy-Job auf geschütztem main mit geschütztem Environment. Die Werte stammen aus der GitLab-Doku; boolesche Claims sind dort Strings.

cp ../tag10/{mint-jwt.sh,ci-issuer.key,ci-issuer.pub} .
cat > gitlab-claims.json <<'EOF'
{
  "iss": "https://gitlab.lab.example", "aud": "https://openbao.lab.example",
  "sub": "project_path:acme/shop:ref_type:branch:ref:main",
  "namespace_id": "7", "namespace_path": "acme",
  "project_id": "42", "project_path": "acme/shop",
  "user_login": "zachmann", "pipeline_id": "1234", "pipeline_source": "push",
  "job_id": "5678", "ref": "main", "ref_type": "branch", "ref_path": "refs/heads/main",
  "ref_protected": "true", "environment": "production",
  "environment_protected": "true", "deployment_tier": "production",
  "runner_environment": "self-hosted"
}
EOF
export BASE=gitlab-claims.json
claims() { jq -R 'split(".")[1] | gsub("-";"+") | gsub("_";"/")
  | @base64d | fromjson'; }
./mint-jwt.sh | claims | jq '{iss, sub, ref, ref_protected, environment}'

Erwartet:

{
  "iss": "https://gitlab.lab.example",
  "sub": "project_path:acme/shop:ref_type:branch:ref:main",
  "ref": "main",
  "ref_protected": "true",
  "environment": "production"
}

Achte auf die Unterschiede zu GitHub: ref ist hier nur main, der volle Pfad steht in ref_path. Der Default-sub ist project_path:<gruppe>/<projekt>:ref_type:<typ>:ref:<ref>.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Mount jwt-gitlab/ und Rolle shop-deploy

bao auth enable -path=jwt-gitlab jwt
bao write auth/jwt-gitlab/config [email protected] \
  bound_issuer=https://gitlab.lab.example
bao write auth/jwt-gitlab/role/shop-deploy - <<'EOF'
{
  "role_type": "jwt",
  "user_claim": "user_login",
  "bound_audiences": ["https://openbao.lab.example"],
  "bound_claims": {
    "project_id": "42",
    "ref_protected": "true",
    "environment": "production",
    "environment_protected": "true"
  },
  "claim_mappings": {"project_path": "project_path", "pipeline_id": "pipeline_id",
                     "ref": "ref"},
  "token_policies": ["ci-deploy"],
  "token_ttl": "5m",
  "token_explicit_max_ttl": "10m"
}
EOF
BAO_TOKEN= bao write auth/jwt-gitlab/login role=shop-deploy jwt="$(./mint-jwt.sh)"

Erwartet:

Success! Enabled jwt auth method at: jwt-gitlab/
Success! Data written to: auth/jwt-gitlab/config
Success! Data written to: auth/jwt-gitlab/role/shop-deploy
Key                        Value
---                        -----
token                      s.aQo7Yf5suEYOmKh7QQ3SaF8q
token_accessor             8F8MBOirhVnYLHzhtKQ0lev9
token_duration             5m
token_renewable            true
token_policies             ["ci-deploy" "default"]
identity_policies          []
policies                   ["ci-deploy" "default"]
token_meta_pipeline_id     1234
token_meta_project_path    acme/shop
token_meta_ref             main
token_meta_role            shop-deploy

Negativtests: ungeschützter Branch, falsches Environment, fremdes Projekt.

for a in ref_protected=false environment=staging project_id=43; do
  echo "== $a"
  BAO_TOKEN= bao write auth/jwt-gitlab/login role=shop-deploy \
    jwt="$(./mint-jwt.sh $a)" 2>&1 | tail -1
done

Erwartet:

== ref_protected=false
* error validating claims: claim "ref_protected" does not match any associated bound
claim values
== environment=staging
* error validating claims: claim "environment" does not match any associated bound
claim values
== project_id=43
* error validating claims: claim "project_id" does not match any associated bound
claim values

Warum project_id statt project_path? Pfade werden frei, wenn ein Projekt umzieht, und könnten neu vergeben werden. Ohne Projekt- oder Namespace-Bindung käme jedes Projekt der Instanz in die Rolle.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Variante A – secrets: mit vault: (Premium)

Der Runner holt das Secret vor dem Skript. Konfiguration über CI/CD-Variablen im Projekt (nicht ausgeführt, gegen GitLab-Doku geprüft):

cat > gitlab-ci-premium.yml <<'EOF'
variables:
  VAULT_SERVER_URL: https://openbao.example.com
  VAULT_AUTH_PATH: jwt-gitlab      # Default wäre "jwt"
  VAULT_AUTH_ROLE: shop-deploy

deploy:
  stage: deploy
  environment: production
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  id_tokens:
    OPENBAO_ID_TOKEN:
      aud: https://openbao.lab.example   # = bound_audiences der Rolle (Drill 3)
  secrets:
    REGISTRY_PASSWORD:
      vault: ci/deploy/registry_password@secret   # KV v2: secret/data/ci/deploy
      token: $OPENBAO_ID_TOKEN
    KUBE_TOKEN:
      vault:
        engine:
          name: kv-v2
          path: secret
        path: ci/deploy
        field: kubeconfig_token
      file: false
      token: $OPENBAO_ID_TOKEN
  script:
    - docker login registry.example.com -u ci --password-stdin < "$REGISTRY_PASSWORD"
EOF

Die aud muss exakt zu bound_audiences der Rolle shop-deploy passen, hier der Lab-Wert. https://openbao.example.com steht nur als Platzhalter für deine OpenBao-Adresse. In Produktion wählst du beide passend (Enterprise-Notiz).

Ohne file: false ist $REGISTRY_PASSWORD ein Dateipfad, deshalb < "$REGISTRY_PASSWORD". Das ist die sicherere Voreinstellung: Der Wert taucht nicht in der Prozessumgebung auf.

Achtung: GitLab dokumentiert die Integration für HashiCorp Vault. Der Runner spricht die Vault-HTTP-API, gegen OpenBao ist das im Lab nicht live getestet. Prüfe es in deiner Umgebung, bevor du dich darauf verlässt.

Fortschritt speichern? Kostenlos registrieren

Drill 5: Variante B – bao im Job-Image

Funktioniert in jeder Edition. Das offizielle Image hat einen Server-Entrypoint, also entrypoint: [""]. jq und curl sind nicht drin, bao reicht.

cat > .gitlab-ci.yml <<'EOF'
deploy:
  stage: deploy
  image:
    name: quay.io/openbao/openbao:2.7.1
    entrypoint: [""]
  environment: production
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  id_tokens:
    OPENBAO_ID_TOKEN:
      aud: https://openbao.lab.example   # = bound_audiences der Rolle (Drill 3)
  variables:
    BAO_ADDR: https://openbao.example.com
  script:
    - ./ci/bao-secrets.sh
EOF
mkdir -p ci
cat > ci/bao-secrets.sh <<'EOF'
#!/bin/sh
# GitLab-Job: ID-Token bei OpenBao einlösen, Secret als Datei ablegen, Token widerrufen
set -eu
BAO_TOKEN=$(bao write -field=token auth/jwt-gitlab/login \
  role=shop-deploy jwt="$OPENBAO_ID_TOKEN")
export BAO_TOKEN
umask 077
bao kv get -field=registry_password secret/ci/deploy > "${TMPDIR:-/tmp}/registry-pw"
echo "✔ Secret als Datei abgelegt"
bao token revoke -self >/dev/null && echo "✔ OpenBao-Token widerrufen"
EOF
chmod +x ci/bao-secrets.sh

Das Skript probierst du lokal mit einem geminteten GitLab-JWT aus:

mkdir -p job-tmp
env -u BAO_TOKEN TMPDIR=$PWD/job-tmp OPENBAO_ID_TOKEN="$(./mint-jwt.sh)" \
  ./ci/bao-secrets.sh
ls -l job-tmp | awk 'NR>1 {print $1, $NF}'; cat job-tmp/registry-pw; echo

Erwartet:

✔ Secret als Datei abgelegt
✔ OpenBao-Token widerrufen
-rw------- registry-pw
lab-reg-pw

GitLab maskiert nur Variablen, die als „masked” definiert sind. Werte, die das Skript selbst holt, kennt GitLab nicht. Deshalb Datei statt echo und nie set -x.

Fortschritt speichern? Kostenlos registrieren

Drill 6: Jenkins mit AppRole und Wrapping

Der Jenkins-Controller hält zwei Credentials: die Role-ID und einen kurzlebigen Orchestrator-Token mit Policy approle-issuer (Tag 10). Der Agent bekommt pro Build nur eine gewrappte, einmalige Secret-ID.

cat > ci/bao-login.sh <<'EOF'
#!/usr/bin/env bash
# Jenkins-Agent: Secret-ID gewrappt holen, auspacken, per AppRole anmelden.
# Erwartet ROLE_ID und ISSUER_TOKEN (aus withCredentials). Wird per "source" geladen.
set -euo pipefail
WRAP=$(BAO_TOKEN=$ISSUER_TOKEN bao write -wrap-ttl=60s -field=wrapping_token \
  -f auth/approle/role/jenkins-deploy/secret-id)
path=$(BAO_TOKEN=$ISSUER_TOKEN bao write -field=creation_path sys/wrapping/lookup \
  token="$WRAP")
[ "$path" = auth/approle/role/jenkins-deploy/secret-id ] \
  || { echo "✘ unerwarteter creation_path: $path" >&2; exit 1; }
SECRET_ID=$(BAO_TOKEN=$WRAP bao unwrap -field=secret_id)
BAO_TOKEN=$(BAO_TOKEN= bao write -field=token auth/approle/login \
  role_id="$ROLE_ID" secret_id="$SECRET_ID")
export BAO_TOKEN
unset SECRET_ID WRAP
EOF
export ROLE_ID=$(bao read -field=role_id auth/approle/role/jenkins-deploy/role-id)
export ISSUER_TOKEN=$(bao token create -policy=approle-issuer -ttl=1h -field=token)
( source ci/bao-login.sh
  bao token lookup -format=json | jq -c '.data | {meta, policies, ttl}'
  bao kv get -field=registry_password secret/ci/deploy; echo
  bao token revoke -self )

Erwartet:

{"meta":{"role_name":"jenkins-deploy"},"policies":["ci-deploy","default"],"ttl":599}
lab-reg-pw
Success! Revoked token (if it existed)

Das passende Jenkinsfile (nicht ausgeführt). Einfache Anführungszeichen im sh-Schritt, damit Groovy keine Secrets interpoliert:

pipeline {
  agent { label 'linux' }
  environment {
    BAO_ADDR = 'https://openbao.example.com'
  }
  stages {
    stage('Deploy') {
      steps {
        withCredentials([
          string(credentialsId: 'openbao-role-id', variable: 'ROLE_ID'),
          string(credentialsId: 'openbao-issuer-token', variable: 'ISSUER_TOKEN')
        ]) {
          sh '''#!/bin/bash
            set +x
            source ci/bao-login.sh
            bao kv get -field=registry_password secret/ci/deploy \
              | docker login registry.example.com -u ci --password-stdin
            bao token revoke -self
          '''
        }
      }
    }
  }
}

Achtung: Jenkins führt sh sonst mit /bin/sh aus. Für source und pipefail muss #!/bin/bash direkt hinter den Anführungszeichen stehen, ohne Zeilenumbruch.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Alternative – HashiCorp-Vault-Plugin

Das Jenkins-Plugin hashicorp-vault-plugin erledigt Login und Lesen selbst. Credential vom Typ „Vault App Role Credential” mit Role-ID, Secret-ID und Pfad approle (nicht ausgeführt, gegen Plugin-README geprüft):

def secrets = [
  [path: 'secret/ci/deploy', engineVersion: 2, secretValues: [
    [envVar: 'REGISTRY_PASSWORD', vaultKey: 'registry_password']]]
]
def configuration = [vaultUrl: 'https://openbao.example.com',
                     vaultCredentialId: 'openbao-approle',
                     engineVersion: 2]
node('linux') {
  withVault([configuration: configuration, vaultSecrets: secrets]) {
    sh '''echo "$REGISTRY_PASSWORD" \
      | docker login registry.example.com -u ci --password-stdin'''
  }
}

Das Plugin spricht die Vault-HTTP-API und sollte daher mit OpenBao funktionieren; im Lab ist es nicht getestet. Nachteil: Die Secret-ID liegt dauerhaft im Credential-Store, Wrapping und Einmal-Nutzung entfallen. Setze dann mindestens secret_id_ttl, secret_id_bound_cidrs und rotiere per Job.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

cat > check.sh <<'EOF'
#!/usr/bin/env bash
cd ~/secrets-lab/tag12
export BAO_ADDR="${BAO_ADDR:-http://127.0.0.1:8200}" BASE=gitlab-claims.json
gl() { BAO_TOKEN= bao write -field=token auth/jwt-gitlab/login role=shop-deploy \
  jwt="$(./mint-jwt.sh "$@")" >/dev/null 2>&1; }
gl && echo "✔ GitLab-Deploy-Job kommt rein" || echo "✘ GitLab-Login"
gl ref_protected=false && echo "✘ ungeschützter Branch kommt rein" \
  || echo "✔ ungeschützter Branch abgewiesen"
gl aud=https://gitlab.lab.example && echo "✘ falsche aud akzeptiert" \
  || echo "✔ falsche aud abgewiesen"
export ROLE_ID=$(BAO_TOKEN=root bao read -field=role_id \
  auth/approle/role/jenkins-deploy/role-id)
export ISSUER_TOKEN=$(BAO_TOKEN=root bao token create -policy=approle-issuer \
  -ttl=5m -field=token)
( source ci/bao-login.sh && bao kv get -field=registry_password secret/ci/deploy \
  | grep -q lab-reg-pw ) && echo "✔ Jenkins-AppRole-Flow" || echo "✘ AppRole-Flow"
EOF
bash check.sh

Erwartet:

✔ GitLab-Deploy-Job kommt rein
✔ ungeschützter Branch abgewiesen
✔ falsche aud abgewiesen
✔ Jenkins-AppRole-Flow

Challenge

Releases entstehen aus geschützten Tags v* ohne Environment. Lege eine Rolle shop-release an, die nur geschützte Tags von Projekt 42 akzeptiert.

Hinweis: bound_claims_type=glob und ref_type=tag; der Claim environment fehlt bei solchen Jobs, binde ihn also nicht.

Lösung

export BAO_TOKEN=root
bao write auth/jwt-gitlab/role/shop-release - <<'EOF'
{
  "role_type": "jwt", "user_claim": "user_login",
  "bound_audiences": ["https://openbao.lab.example"],
  "bound_claims_type": "glob",
  "bound_claims": {"project_id": "42", "ref_type": "tag", "ref": "v*",
                   "ref_protected": "true"},
  "token_policies": ["ci-deploy"], "token_ttl": "5m"
}
EOF
TAG="ref_type=tag ref=v1.4.0 environment= environment_protected="
for extra in "" "ref_protected=false" "ref_type=branch ref=v-test"; do
  printf '%-30s ' "${extra:-geschützter Tag}"
  BAO_TOKEN= bao write -field=token_policies auth/jwt-gitlab/login role=shop-release \
    jwt="$(./mint-jwt.sh $TAG $extra)" 2>&1 | tail -1; echo
done

Erwartet:

geschützter Tag               [ci-deploy default]
ref_protected=false            * error validating claims: claim "ref_protected" does
not match any associated bound claim values
ref_type=branch ref=v-test     * error validating claims: claim "ref_type" does not
match any associated bound claim values

Fortschritt speichern? Kostenlos registrieren

Enterprise-Notiz

  • aud pro Ziel eindeutig wählen (Produktion z. B. https://openbao.example.com, in id_tokens und bound_audiences gleich) und pro Job nur die id_tokens anfordern, die er braucht.
  • Immer project_id/namespace_id binden; wird ein Projektpfad wiederverwendet, blockiert GitLab die Ausgabe, bis du ci_id_token_sub_claim_components mit project_id anpasst. Rollen mit bound_subject dann nachziehen.
  • Produktions-Deploys nur über geschützte Branches/Tags und geschützte Environments; beides als Claim binden, nicht nur in .gitlab-ci.yml per rules:.
  • Jenkins: Orchestrator-Token periodisch und eng (approle-issuer), Agents in festen Netzen mit secret_id_bound_cidrs/token_bound_cidrs; mittelfristig auf OIDC umsteigen.
  • Runner-Images mit bao pinnen (Digest) und selbst scannen; Self-hosted Runner per runner_environment unterscheiden.