Jenkins Hour 6: Enterprise Security and Governance in Practice

From “it runs” to “safe for 20 teams to use”: authentication, authorization, SSO, credentials, Script Security, plugin governance, controller isolation, audit and supply chain
Jenkins LTS 2.580.2Java 21 / 25matrix-auth 3.3 · role-strategy 928.xScript Security 1436.xVerified against jenkins.io security advisories · 2026-11
Overall learning goals
  • Explain the three pillars of the Jenkins security model: Security Realm (authentication: who you are),Authorization Strategy (authorization: what you can do), and CSRF crumb (preventing your browser from being “borrowed” by other sites), as well as why API tokens do not need a crumb.
  • Design RBAC for multiple teams: compare Matrix Authorization (global + project/folder matrix, three inheritance strategies) and Role-based Strategy (global / item regex / agent roles), and map the groups of SSO (Microsoft Entra ID, generic OIDC,SAML) groups to permissions, and know why SECURITY-3935 (Entra groups authorized by display name) is dangerous.
  • Manage credentials: scopes (SYSTEM / GLOBAL), credential domains (domain),folder-level credentials; use HashiCorp Vault,Azure Key Vault,AWS Secrets Manager plugins keep secrets in external systems.
  • Understand Script Security: how the Groovy sandbox intercepts each method call,RejectedAccessException how calls enter the “In-process Script Approval” queue, the difference between Approve / Deny / “Approve assuming permissions check”, and why to turn on forceSandbox.
  • Build plugin governance: read security advisories (2026-09-02, 2026-09-16, 2026-10-28), vulnerability and deprecation warnings in the Update Center,plugins.txt pin versions and --latest=false, plugin admission and retirement processes.
  • Implement controller isolation: built-in node 0 executor, Agent → Controller access control (always on since 2.326), and Authorize Project so builds run as the user.
  • Put audit and supply chain into practice: Audit Trail, Job Config History, SBOMs and signatures for build images, and finish the whole governance architecture review with one review checklist.

1-hour time allocation table

#TimeModuleCore contentAnimations / interactionLab (~/jenkinslab Compose environment)
0Before classPrep: multi-team sample environmentAdd ~/jenkinslab security plugins, Compose secrets, JCasC directory; create the team-a / team-b folders and the alice / bob / carol usersSecurity baseline self-assessment (10 items)compose.override.yaml + casc/
100–06Security model: authentication, authorization and CSRFSecurity Realm, Authorization Strategy, ACL decisions, crumb, API tokens (including the expiry time from 2.555.1), Overall/ManageCore animation: authorization decision for one request (authentication → matrix/roles → folder inheritance)whoAmI, POST without a crumb is rejected, API token calls
206–13SSO and RBACEntra ID / OIDC / SAML, group claim mapping, escape hatch; three matrix inheritance strategies vs role regex; folder delegationStep-by-step demo of the OIDC authorization code login flowFolder matrix + role-strategy comparison
313–21Credential management: credential domains, Vault and external secretsScopes, credential domains, folder credentials, CredentialsProvider lookup order, Vault AppRole, Key Vault and Secrets Manager tag conventions, log maskingCredential lookup resolver: from job to external providersFolder credentials + Vault dev server + withVault
421–28Script Security, sandbox and Groovy approvalGroovy sandbox, allowlist/denylist, signature approval, whole-script SHA512 approval, ACL-aware methods, forceSandbox, Script ConsoleCore animation: sandbox interception → approval queue → administrator decision → rerunTrigger RejectedAccessException and make the correct approval decision
528–35Plugin security: vulnerability advisories and plugin governanceAdvisory structure, Update Center warnings, deprecated/unmaintained plugins, pinned versions, admission checklist, upgrade cadencePlugin inventory scan and remediation simulatorjenkins-plugin-cli lists warnings and available updates
635–42controller and agent isolationbuilt-in node 0 executor, Agent → Controller access control, build identity (Authorize Project), Job Restrictions, and the security trade-offs of agents themselves“Where builds run and what they can reach” simulatornumExecutors: 0 + label constraints + build identity verification
742–50Audit, compliance and supply chain securityAudit Trail, Job Config History, change auditing for configuration as code; plugin and image pinning, SBOM, signing, provenanceSupply chain pipeline from commit to signed imageAudit Trail logs + syft SBOM + cosign signing
850–60Integrated governance architecture reviewReview checklist, common failure modes, incident responseInteractive review scoring + troubleshooting treeRun a governance review on jenkinslab
—After classCheat sheet · Capstone labMulti-team RBAC + folder credentials + Vault + forceSandbox + 0 executor + audit + pinned plugin imageFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / configurationLab
Principles of authentication, authorization and CSRF✓✓·····✓/whoAmI/api/json,/crumbIssuer/api/jsonm1
API tokens and scripted clients✓✓····✓✓curl -u user:token,security.apiTokenm1
SSO (Entra ID / OIDC / SAML)·✓··✓··✓securityRealm: oic / azure / samlm2 (configuration review)
Multi-team RBAC and folder inheritance✓✓✓··✓·✓projectMatrix,roleBased,authorizationMatrixsetup, m2
Credential scopes, folder credentials and external secrets··✓·✓✓·✓withCredentials,withVault,azureKeyVaultm3
Script Security and approval···✓✓·✓✓security.scriptApproval.forceSandboxm4
Plugin vulnerabilities and governance·✓·✓✓·✓✓jenkins-plugin-cli --view-all-security-warningsm5
controller isolation and build identity··✓··✓·✓numExecutors: 0,queueItemAuthenticatorm6
Audit and supply chain····✓·✓✓audit-trail,syft,cosignm7

Excluded from this lesson (and where to learn them)

TopicWhy it is not in this lessonWhere to learn it
Basic credential types,credentials() and withCredentials basic syntaxCovered in Lesson 1; this lesson only covers scopes, folders and external secretsHour 1
CPS execution model, trusted vs. untrusted Shared LibrariesLesson 2 covers the mechanism; this lesson only covers its impact on Script SecurityHour 2
Azure managed identity / AWS IRSA and other “no long-lived keys” cloud setupsLessons 3 and 4 already configure these step by stepLesson 3 · Lesson 4
Full usage of JCasC, Job DSL and the Kubernetes pluginLesson 5 already covers this; this lesson writes security configuration directly in JCasCHour 5
Deep troubleshooting: performance, stuck queues, thread dumpsCovered systematically in Lesson 7Hour 7
Container image hardening, Pod Security, NetworkPolicyBelongs to container / cluster-level securityDocker 8 hours · Kubernetes 8 hours
Permission models of GitHub Actions / Azure PipelinesDifferent platforms; you can read them side by sideGitHub 8 hours · Azure DevOps 8 hours

How to use this courseware

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · audio · video. For the security lesson, read the “common misconceptions” in “Principles” first, then do the labs, and finally read the “production cases”.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress; it is saved in this browser (it is cleared on refresh if local storage is blocked).
Chinese audio
The “Audio” page reads the narration aloud with the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the narration can still be read or passed to a TTS tool.
Version notes This lesson is based on Jenkins LTS 2.580.2 (released 2026-10-28, tested on JDK 21 / 25); weekly is currently 2.590. Recent changes directly relevant to this lesson have been checked against jenkins.io: 2.555.1 requires Java 21+,enables the Overall/Manage permission by default,API tokens can have an expiry time, crumb no longer includes the client IP (the “Enable proxy compatibility” option was removed); 2.541.1 core can configure Content-Security-Policy; 2.326 Agent → Controller access control can no longer be turned off. 2.580.2 fixes 15 core vulnerabilities from the 2026-10-28 advisory (XStream deserialization RCE, a setup-wizard race that creates an admin, etc.),LTS versions below 2.580.2 should be upgraded as soon as possible. Plugin versions are listed in the source page.
Connection to previous lessons This lesson's labs reuse the Docker Compose environment from Lessons 1 and 2 ~/jenkinslab (service jenkins / agent1 / gitea, administrator admin, credentials gitea-myapp,registry-creds, sample app myapp). Lesson 5 already moved configuration to JCasC; this lesson also writes the security configuration as JCasC files, and the same YAML can go into the kind cluster lab as a Helm release jenkins of controller.JCasC.configScripts.

Module 0 · Prep: multi-team sample environment (complete before class)

Add security plugins to ~/jenkinslab, store passwords with Compose secrets, and define 2 team folders and 4 users with JCasC
Before class ≈ 15 minutesjenkins/jenkins:2.580.2-jdk21No cloud costs
Prerequisites
  • CompletedLesson 1of ~/jenkinslab: compose.yaml contains jenkins (127.0.0.1:8080 / 50000, volume jenkins_home),agent1 (inbound agent, label linux docker, 2 executors),gitea (127.0.0.1:3000, user lab, repository lab/myapp), credentials gitea-myapp, Job myapp, admin API token in ~/jenkinslab/.secrets/jenkins-token. Lesson 1 already set the built-in node to 0 executors; this lesson uses JCasC to make that setting permanent. The Lesson 1 and 2 myapp,myapp-multibranch stay unchanged; this lesson creates team-a/myapp,team-b/myapp — two demo Jobs. The Helm instance on the Lesson 5 kind cluster (namespace jenkins, port forwarding 8081) can use the same JCasC, but this lesson's labs use the Compose instance (8080) as the reference.
  • CompletedLesson 5: understand the JCasC CASC_JENKINS_CONFIG,${...} variables and the Job DSL jobs: section.
  • This machine has docker compose (v2),curl,jq. All labs are done locally,with no cloud costs; Entra ID / Key Vault / Secrets Manager only appear in the “production cases” and the configuration reviews.
  • Security risk warning: This lesson replaces Jenkins' security realm with a local user database managed by JCasC,admin 's password will be changed to the value in .secrets/admin_pw . Back up first: docker run --rm -v jenkinslab_jenkins_home:/h -v "$PWD":/b alpine tar czf /b/jenkins_home-before-part6.tgz -C /h . (the volume name follows docker volume ls ), and users' API tokens are stored in JENKINS_HOME/users/ , after switching they usually remain valid; if .secrets/admin_token returns 401, regenerate it with the new password using the method on the m1 “Commands” page.

Step 1: Confirm the baseline version

cd ~/jenkinslab
docker compose ps --format 'table {{.Service}}\t{{.Image}}\t{{.Status}}'
curl -sI http://127.0.0.1:8080/login | grep -i '^x-jenkins:'
SERVICE   IMAGE                                   STATUS
agent1    jenkins/inbound-agent:latest-jdk21      Up 2 hours
gitea     gitea/gitea:(Lesson 1 version)              Up 2 hours
jenkins   jenkins/jenkins:2.580.2-jdk21       Up 2 hours
X-Jenkins: 2.580.2

If X-Jenkins is below 2.580.2: change the image in compose.yaml to jenkins/jenkins:2.580.2-jdk21 , then docker compose pull jenkins && docker compose up -d jenkins. Versions 2.580.1 and earlier are affected by several high-severity vulnerabilities in the 2026-10-28 advisory (for example SECURITY-4122: a race in the setup wizard can create an admin account). Use the image tags of agent1 / gitea from your actual Lesson 1 values.

Step 2: Install the plugins used in this lesson (pinned versions)

First install the plugins into the reference directory bundled with the image /usr/share/jenkins/ref/plugins, then restart (not rebuild) the container; the startup script copies missing plugins into JENKINS_HOME/plugins (in the volume, so they survive even if the container is rebuilt later). In production, do this step in a custom image (covered in m7).

docker compose exec jenkins jenkins-plugin-cli --latest=false --plugins \
  configuration-as-code:2147.v8a_8d38668c72 \
  job-dsl \
  matrix-auth:3.3 \
  role-strategy:928.vc60b_edb_fea_e1 \
  cloudbees-folder:6.1107.v31f8955765c8 \
  script-security:1436.v1082791135e4 \
  credentials:1514.vb_01eb_014e7d4 \
  credentials-binding:728.v902a_273b_8947 \
  hashicorp-vault-plugin:384.vda_86ec66c537 \
  audit-trail:472.vb_51e5934ec50 \
  authorize-project:534.v2f208c45e11c \
  jobConfigHistory:1380.v762185b_9a_793
docker compose restart jenkins
sleep 40; curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/login
Done
200

job-dsl If no version is written, the latest version is used —this is only done in labs; in production, every line in plugins.txt must include a version. --latest=false Let dependencies use the lowest satisfying version instead of quietly pulling the latest (the plugin manager tool's default --latest=true, in which case dependencies may still be upgraded even if you pinned a version).

Step 3: Compose secrets and the JCasC directory

By default, JCasC resolves the content of /run/secrets/<name> file as ${name}, which works directly with Compose secrets: passwords do not go into environment variables and do not appear in docker inspect .

mkdir -p ~/jenkinslab/{casc,.secrets}
cd ~/jenkinslab
for u in admin alice bob carol; do
  [ -s .secrets/${u}_pw ] || openssl rand -base64 18 | tr -d '\n' > .secrets/${u}_pw
done
chmod 600 .secrets/*; grep -qx '.secrets/' .gitignore 2>/dev/null || echo '.secrets/' >> .gitignore
# Lesson 1 already stored admin's API token in .secrets/jenkins-token; this lesson keeps it as admin_token
[ -s .secrets/admin_token ] || cp .secrets/jenkins-token .secrets/admin_token 2>/dev/null || true
cat > compose.override.yaml <<'EOF'
# Compose merges automatically with compose.yaml (environment / volumes / secrets of the same-named service are appended)
services:
  jenkins:
    environment:
      CASC_JENKINS_CONFIG: /var/jenkins_home/casc_configs
    volumes:
      - ./casc:/var/jenkins_home/casc_configs:ro
    secrets: [admin_pw, alice_pw, bob_pw, carol_pw]
secrets:
  admin_pw: { file: ./.secrets/admin_pw }
  alice_pw: { file: ./.secrets/alice_pw }
  bob_pw:   { file: ./.secrets/bob_pw }
  carol_pw: { file: ./.secrets/carol_pw }
EOF

Step 4: Security baseline JCasC (all modules in this lesson build on it)

jenkins:
  systemMessage: "jenkinslab · Lesson 6 security baseline (managed by JCasC; do not edit in the UI)"
  numExecutors: 0                 # m6: built-in node does not run builds
  disableRememberMe: true
  markupFormatter: plainText      # description fields do not render HTML, which prevents stored XSS
  securityRealm:
    local:
      allowsSignup: false
      users:
        - id: admin
          password: "${admin_pw}"
        - id: alice               # team-a developer
          password: "${alice_pw}"
        - id: bob                 # team-b developer
          password: "${bob_pw}"
        - id: carol               # auditor: read-only
          password: "${carol_pw}"
  authorizationStrategy:
    projectMatrix:                # global matrix + allow authorizations to be added on folders/Jobs
      entries:
        - user:
            name: admin
            permissions: [Overall/Administer]
        - group:
            name: authenticated
            permissions: [Overall/Read]
        - user:
            name: carol
            permissions: [Job/Read, View/Read]
security:
  apiToken:
    creationOfLegacyTokenEnabled: false
    tokenGenerationOnCreationEnabled: false
    usageStatisticsEnabled: true
  scriptApproval:
    forceSandbox: false           # m4 lab: change to true (force sandbox)
jobs:
  - script: >
      ['team-a': 'alice', 'team-b': 'bob'].each { team, dev ->
        folder(team) {
          description(team + ' Pipeline, only ' + dev + ' and administrators can build')
          properties {
            authorizationMatrix {
              inheritanceStrategy { inheriting() }
              entries {
                user {
                  name(dev)
                  permissions(['Job/Read', 'Job/Build', 'Job/Cancel', 'Job/Configure',
                               'Job/Create', 'Job/Workspace', 'Run/Replay', 'Credentials/View'])
                }
              }
            }
          }
        }
        pipelineJob(team + '/myapp') {   // Don't use "${team}": JCasC would resolve ${...} as its own variable first (escape it as ^${...})
          definition {
            cpsScm {
              scm { git { remote { url('http://gitea:3000/lab/myapp.git'); credentials('gitea-myapp') }; branch('*/main') } }
              scriptPath('Jenkinsfile')
            }
          }
        }
      }
cd ~/jenkinslab
docker compose up -d jenkins          # recreates the container because the override changed
sleep 45
docker compose logs jenkins 2>&1 | grep -iE 'casc|ConfigurationAsCode|SEVERE' | tail -5
curl -s -u "admin:$(cat .secrets/admin_pw)" http://127.0.0.1:8080/whoAmI/api/json | jq '{name, authenticated, authorities}'
{
  "name": "admin",
  "authenticated": true,
  "authorities": [
    "authenticated"
  ]
}
What if you get locked out? JCasC authorization mistakes can remove everyone's permissions (including admin's). Recovery: fix casc/*.yaml then docker compose restart jenkins; if that doesn't work, temporarily disable security following the official docs (edit $JENKINS_HOME/config.xml , change <useSecurity> to false and restart — at this point anyone can access it (restore it immediately after the fix). This lesson binds its ports only to 127.0.0.1, which reduces this risk.

Relationship to the Gitea credentials:gitea-myapp is still in the system-level Global store created in Lesson 1; m3 will move it to team-a a folder store, to demonstrate team isolation.

Warm-up: answer from memory (30 seconds)

Where does the Groovy code of a Pipeline run? sh Where do the steps run?

Groovy (code interpreted by CPS) runs in the controller's JVM ; sh/bat steps like sh go through the Remoting channel and execute on agent (Lesson 2). This is exactly why Script Security must exist: a Jenkinsfile is “controller code” that anyone with Job/Configure or repository write permission can change.

Who does a build run as by default?

By default, it runs as SYSTEM identity (full permissions), unless Authorize Project is installed and a policy such as “run as the triggering user” is configured. This affects which credentials a build can use and which downstream Jobs it can trigger (m6).

Security baseline self-assessment (10 items)

Tick which items your production Jenkins already achieves items (saved in this browser). Come back and tick them again after you finish this lesson.

Environment self-check list

Module 1 · Security model: authentication, authorization and CSRF

00:00 – 06:00 · Every request must answer three questions: Who are you? Did you initiate this request yourself? Do you have this permission on this object?
6 minJenkins core 2.580.22.555.1: API tokens expire, Overall/Manage enabled by default★★★★★
Learning goals
  • Distinguish Security Realm (authentication, which produces the username + group authorities) from Authorization Strategy (authorization, which produces the ACL for each object).
  • Understand the permission hierarchy: Overall/Administer ⊃ Overall/Manage ⊃ Overall/SystemRead ⊃ Overall/Read; Job/Read implies Job/Discover; without Discover, the response is 404, and with Discover but without Read, it returns 403.
  • Explain what the CSRF crumb contains (username + web session ID + instance salt), why API token requests are exempt from the crumb, and why 2.555.1 removed the IP option.
  • Choose the correct authentication method for scripted clients: username + API token (expiry can be set), rather than password + crumb + cookie.
Prerequisites: Lesson 1's controller / agent / executor, and Lesson 1's “Credentials and security basics”. Importance:★★★★★

What: three independent mechanisms

MechanismQuestion it answersPluggable extension pointCommon implementations
Security RealmWho you are and which groups you belong tohudson.security.SecurityRealmJenkins built-in user database, LDAP, Microsoft Entra ID, OpenID Connect, SAML, GitHub OAuth
Authorization Strategywhich permissions you have on an object (root, folder, Job, agent, view)hudson.security.AuthorizationStrategy → ACLMatrix (global / project), Role-based, Logged-in users can do anything, Folder-based
CSRF protectionwhether this modification request was intentionally sent by your own browserhudson.security.csrf.CrumbIssuerDefault Crumb Issuer, Strict Crumb Issuer plugin

They are independent: switching to Entra ID login does not change the authorization matrix, and changing authorization does not affect who can log in. Production incidents often come from “only half configured”. For example, after adding SSO but keeping “Logged-in users can do anything”, every employee in the company becomes a Jenkins administrator (since weekly 2.586 the core shows an administrator warning for this kind of authorization strategy).

Permission hierarchy and “implied” relationships

PermissionMeaningKey point
Overall/AdministerEverything, including Script Console and plugin installation= can run arbitrary code on the controller. There is no “half administrator”.
Overall/ManageSome global configuration, cannot execute arbitrary codeJEP-223,enabled by default since 2.555.1; suited to platform operations rather than security administrators
Overall/SystemReadRead-only view of global configurationOptional permission, requires a system property jenkins.security.SystemReadPermission=true or the Extended Read Permission plugin; suited to the auditor + JCasC scenario
Overall/ReadCan see Jenkins itselfAlmost no other permission is useful without it
Job/Discover → Job/ReadKnows the Job exists → can view the JobRead implies Discover. Neither: 404 (hides existence); only Discover: 403 or redirect to login
Job/ConfigureModify Job configurationIn a Pipeline, equivalent to “rewriting Groovy that runs on the controller”; subject to the sandbox (m4). Implied Run/Replay-related abilities must be evaluated separately.
Credentials/ViewSee credential metadata in the UICannot see plaintext secrets; using credentials depends on build identity and scope (m3)

Why: why three layers

  • Authentication is outsourced: the enterprise identity system (Entra ID / Okta / Keycloak) handles MFA, offboarding disablement and conditional access; Jenkins only consumes the result.
  • Authorization is built in: only Jenkins knows what “team-a/myapp” is as an object, so object-level authorization must be done inside Jenkins.
  • CSRF is independent: even if you are logged in and have permission, a malicious site can still make your browser send a POST with your cookie; the crumb proves the request came from a page Jenkins rendered itself.

How: what happens inside the controller for one request

  1. Jetty → Servlet filter chain: establish identity from the session cookie,Authorization: Basic header (API token or password) Authentication; with nothing provided, it is anonymous.
  2. Security Realm Provides the username and authorities (such as authenticated, SSO groups).
  3. CrumbFilter: POST requests need a valid crumb; requests authenticated with an API token are exempt.
  4. Stapler routing to the object (/job/team-a/job/myapp/build → Folder → WorkflowJob → doBuild).
  5. Permission check: job.checkPermission(Item.BUILD) → AuthorizationStrategy.getACL(job) → matrix/role calculation → allow or throw AccessDeniedException3 (“alice is missing the Job/Build permission”).

Composition of the CSRF crumb (since 2.555.1)

Default Crumb Issuer hashes username + web session ID + unique instance salt. Since 2.555.1 the client IP is no longer included (this is equivalent to the old “Enable proxy compatibility” always being checked), because the session ID provides stronger binding. Consequence: when a script calls the API with “username + password”, it must first request /crumbIssuer/api/json and save the Set-Cookie, and subsequent requests must carry both the crumb and the cookie; it is recommended to switch to API tokens instead, API token requests do not need a crumb.

API token

  • On /me/security generate; shown only once; Jenkins stores only the hash. Since 2.555.1 you can set an expiry time (the header menu shows a badge for tokens that are about to expire).
  • “Legacy tokens” (one per user, viewable again) should be disabled: security.apiToken.creationOfLegacyTokenEnabled: false.
  • Under SSO (OIDC/SAML/Entra) Jenkins does not know user passwords,so scripted clients can only use API tokens.

When: choosing an authorization strategy

StrategySuitable forNot suitable for
Anyone can do anythingNeverAll environments (including the “intranet”)
Logged-in users can do anythingPersonal labsAny instance connected to company SSO
Matrix-based security (global)Single team, few usersNeed to isolate Jobs by team
Project-based MatrixMultiple teams + folder delegation; configuration follows the objectHundreds of teams need a unified template (consider Role-based)
Role-based StrategyDozens to hundreds of teams with consistent naming conventions (regex matching)Inconsistent folder naming; teams need self-service authorization
Folder-based Strategy (folder-auth)—Current version has unfixed security warnings (m2, m5)
Common misconceptions① “Jenkins is on the intranet, so it doesn't need CSRF / authorization”: the official guidance is to keep CSRF protection even on a fully trusted private network, because a phishing page on the intranet can equally make your browser send a POST. ② “Giving Overall/Manage makes it safe”: Manage cannot execute arbitrary code, but it can change many global settings (for example, which credentials certain features use to connect to external systems), so it is still a high-privilege permission. ③ “Forbidding viewing a Job returns 403”: without Discover, Jenkins returns 404 on purpose, to hide whether the object exists. ④ “API tokens also need a crumb”: they do not; crumbs are needed for session- or password-based requests.

Architecture diagram: security checkpoints after a request enters the controller

Browsersession cookie + crumb Script / CLIBasic user:API-token Malicious web pageBorrows cookie, no crumb ① Authentication filtersession / BasicHeaderAPI token / password→ AuthenticationSecurityRealm providesusername + authoritiesno credentials = anonymous ② CrumbFilterChecks POST onlyhash(user, session ID, salt)API token requests exemptfailure → 403No valid crumb ... ③ Stapler routing/job/team-a/job/myapp/build → doBuildgetItem() step by stepno Discover → 404 ④ Permission checkcheckPermission(Item.BUILD)AuthorizationStrategy.getACL(job)global ∪ folder ∪ Job(per inheritance strategy)denied → AccessDeniedException3 Authentication (Realm) and authorization (Strategy) are two plugin extension points that can be replaced independently; CSRF only blocks “state-changing” requests
Figure 1-1: each request passes in turn through authentication → CSRF → routing → object-level permission check

Permission calculation: inheritance from root → folder → Job

Global matrix (Jenkins root)admin: Overall/Administerauthenticated: Overall/Readcarol: Job/Read, View/Read Folder team-a (inheriting)alice: Job/Read, Build, Cancel,Configure, Create, Workspace,Run/Replay, Credentials/View Job team-a/myapp(no extra authorization)Effective permissions = root ∪ team-a ∪ this Job Three inheritance strategies (inheritanceStrategy of matrix-auth) inheriting (default): this level's authorizations + global + all parent folders inheritingGlobal: this level + global, skipping parent folders nonInheriting: only this level's authorizations; the only exception is Overall/Administer Note: anyone with Job/Configure can change this level's matrix and grant themselves permissions
Figure 1-2: effective permissions are the result of merging up the object tree; the inheritance strategy decides at which level the merge happens

Core animation: authorization decision for one request

Choose “who”, “what action” and “authorization strategy”, then step through: authentication → CSRF → Overall/Read → merge the ACL along the object tree (matrix/roles/folder inheritance) → final HTTP result. The log area shows the matching Jenkins internal classes and methods, as well as the response the client actually sees.

RequestJetty AuthenticationSecurityRealm CSRFCrumbFilter Overall/ReadJenkins root ACL Object ACLroot → folder → Job Result—
Choose a combination, then click “Play” or “Next”.
$ waiting for request…

Suggested order: alice builds (200) → bob reads team-a (404) → carol builds (403: can see but not run) → malicious page (crumb rejected) → alice builds with API token (no crumb needed) → switch to nonInheriting and watch carol lose visibility → alice opens Script Console (403).

Core commands and endpoints

Command / endpointPurposeKey parameters / notes
GET /whoAmI/api/jsonCheck what Jenkins thinks you are and which authorities you haveFirst step when troubleshooting SSO group mapping
GET /crumbIssuer/api/jsonGet a crumb for a session- or password-authenticated scriptMust save and send back Set-Cookie (the crumb is bound to the session ID)
POST /me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewTokenGenerate an API token for the current usernewTokenName; the returned value is shown only once
curl -u user:TOKEN -X POST …/buildTrigger a build with an API tokenno crumb needed; returns 201 + Location pointing to the queue item
java -jar jenkins-cli.jar -s URL -auth user:TOKEN who-am-iCLI authentication self-checkThe CLI uses HTTP/WebSocket and is subject to the same authorization
GET /manage/configureSecurity/Security configuration in the UIWhen managed by JCasC, only verify it read-only
J=http://127.0.0.1:8080; cd ~/jenkinslab
# 1) Who am I
curl -s -u "alice:$(cat .secrets/alice_pw)" $J/whoAmI/api/json | jq '{name,authenticated,authorities}'
# 2) Generate an API token with password + crumb + session cookie (only needed once)
CRUMB=$(curl -s -c /tmp/cj -u "alice:$(cat .secrets/alice_pw)" $J/crumbIssuer/api/json | jq -r '.crumbRequestField+":"+.crumb')
curl -s -b /tmp/cj -u "alice:$(cat .secrets/alice_pw)" -H "$CRUMB" -X POST \
  "$J/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken" \
  --data 'newTokenName=lab-m1' | jq -r '.data.tokenValue' > .secrets/alice_token
wc -c secrets/alice_token
{
  "name": "alice",
  "authenticated": true,
  "authorities": [
    "authenticated"
  ]
}
34 secrets/alice_token
# 3) Trigger a build with the API token: no crumb needed
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -u "alice:$(cat .secrets/alice_token)" \
  -X POST $J/job/team-a/job/myapp/build
# 4) The same POST with password but no crumb: rejected by CSRF
curl -s -o /dev/null -w '%{http_code}\n' -u "alice:$(cat .secrets/alice_pw)" -X POST $J/job/team-a/job/myapp/build
# 5) bob views team-a: for him this Job does not exist
curl -s -o /dev/null -w '%{http_code}\n' -u "bob:$(cat .secrets/bob_pw)" $J/job/team-a/job/myapp/api/json
201 http://127.0.0.1:8080/queue/item/12/
403
404

How to verify: The response body of step 4 contains “No valid crumb was included in the request”. Common mistakes: Fetching the crumb without saving the cookie (the crumb is bound to the session, so it becomes invalid when the session changes); putting the token in shell history (in the lab, read it from a file). Production use: Create a separate service account and an API token with an expiry time for each automation client, so it is traceable in the Audit Trail.

# 6) CLI self-check (download jenkins-cli.jar from this instance so the versions match)
curl -s -O $J/jnlpJars/jenkins-cli.jar
java -jar jenkins-cli.jar -s $J -auth "alice:$(cat .secrets/alice_token)" who-am-i
Authenticated as: alice
Authorities:
  authenticated

Lab 1: verify authentication, CSRF and object-level authorization (about 6 min)

Confirm the baseline is in effect: anonymous access is redirected to log in,/signup is unavailable.
J=http://127.0.0.1:8080
curl -s -o /dev/null -w 'manage: %{http_code}\n' $J/manage/
curl -s -o /dev/null -w 'signup: %{http_code}\n' $J/signup
manage: 403
signup: 404

/signup The exact status code after registration is disabled may vary by version (any 4xx means registration is unavailable; use what you actually see). The key point is that the login page no longer has a “create account” entry.

Generate an API token for alice (see step 2 on the “Commands” page), then open alice → Security in the UI and confirm that the token name lab-m1 appears; in 2.555.1+ you can see and set the expiry time.
Permission matrix test for four subjects:
cd ~/jenkinslab; J=http://127.0.0.1:8080
for u in alice bob carol admin; do
  for path in job/team-a/job/myapp/api/json job/team-b/job/myapp/api/json manage/; do
    code=$(curl -s -o /dev/null -w '%{http_code}' -u "$u:$(cat .secrets/${u}_pw)" "$J/$path")
    printf '%-6s %-34s %s\n' "$u" "$path" "$code"
  done
done
alice  job/team-a/job/myapp/api/json      200
alice  job/team-b/job/myapp/api/json      404
alice  manage/                            403
bob    job/team-a/job/myapp/api/json      404
bob    job/team-b/job/myapp/api/json      200
bob    manage/                            403
carol  job/team-a/job/myapp/api/json      200
carol  job/team-b/job/myapp/api/json      200
carol  manage/                            403
admin  job/team-a/job/myapp/api/json      200
admin  job/team-b/job/myapp/api/json      200
admin  manage/                            200
carol can only view, not build:
curl -s -u "carol:$(cat .secrets/carol_pw)" -c /tmp/cc $J/crumbIssuer/api/json | jq -r '.crumbRequestField+":"+.crumb' > /tmp/crumb
curl -s -b /tmp/cc -u "carol:$(cat .secrets/carol_pw)" -H "$(cat /tmp/crumb)" -X POST $J/job/team-a/job/myapp/build | grep -o 'carol is missing[^<]*'
carol is missing the Job/Build permission
Revoke the token (a good habit at the end of a lab): in the UI, go to alice → Security → delete lab-m1, then run step 3 on the “Commands” page; it should return 401.

Cleanup: Delete /tmp/cj /tmp/cc /tmp/crumb; .secrets/alice_token later modules will still use it, so you can keep it (it is already in .gitignore). Risk: Localhost 127.0.0.1 only.

Case 1: after SSO integration, everyone becomes an administrator

Problem: A company moved Jenkins from LDAP to Entra ID. During the migration, to “get logins working first”, it chose Logged-in users can do anything. Three months later a security scan found that 4,000 employees could open the Script Console. Fix: Change the authorization strategy to Project Matrix: globally grant only authenticated Overall/Read, and grant administration to one Entra security group (by object ID); delegate team permissions to folders. Configuration: See the azureAdMatrix/projectMatrix in m2. Limitations: On cut-over day, have a “break-glass” administrator ready (a local account or the OIDC escape hatch) to avoid locking yourself out.

Case 2: after upgrading to 2.555.1, the deployment script gets 403

Problem: A release script calls Jenkins with “username + password + crumb” but never saves the cookie. It used to work by luck because proxy compatibility was enabled; after the upgrade the crumb is bound to the session, and every call returned 403. Fix: Switch to a service account + API token (set a 90-day expiry and rotate it in the key management system). Limitations: An API token inherits all permissions of its account, so the service account should be granted only the folder permissions it needs.

Case 3: the platform team needs to change global configuration but should not be able to execute code

Problem: Platform operations needs to maintain tool installations and global environment variables, but the security team does not want to add Administer. Fix: Grant Overall/Manage (enabled by default since 2.555.1) + Overall/SystemRead; Script Console and plugin installation remain available only to the security administrators group. Limitations: Some plugin configuration pages still require Administer; Manage can change “which credentials a feature uses”, so it still needs auditing (m7).

HTTP ERROR 403 No valid crumb was included in the request

Cause: A session- or password-authenticated POST was sent without a crumb, or the crumb does not match the current session (the script did not save the cookie, or a reverse proxy dropped the Jenkins-Crumb header or cookie).

curl -s -c /tmp/cj -u "alice:$(cat ~/jenkinslab/.secrets/alice_pw)" http://127.0.0.1:8080/crumbIssuer/api/json | jq .
grep -i jsessionid /tmp/cj | cut -f6

Fix: Switch to an API token (preferred); or save the cookie and send both the cookie and the crumb on later requests. Check whether the reverse proxy allows underscores / custom headers. Do not disable CSRF with a system property.

carol is missing the Job/Build permission

Cause: Authentication succeeded, but the object ACL does not contain that permission.

# Administrator queries a user's permissions on an object in the Script Console
def u = hudson.model.User.getById('carol', false).impersonate2()
def job = jenkins.model.Jenkins.get().getItemByFullName('team-a/myapp')
println job.getACL().hasPermission2(u, hudson.model.Item.BUILD)

Fix: Grant it on the folder (not globally); confirm the inheritance strategy is not cutting off authorization from parent levels.

Accessing an existing Job returns 404 Not Found

Cause: The user has neither Job/Read nor Job/Discover, so Jenkins hides its existence on purpose. The folder itself may also be invisible (Read is needed on every folder level).

Fix: Confirm the Job path as an administrator; check the user's permissions on each folder level; for scenarios where the user should know a Job exists but not see it, grant Job/Discover separately.

401 Unauthorized: Invalid password/token for user: alice

Cause: The token was revoked or expired (2.555.1+), a line break was copied with it, or the password was mistakenly used in an SSO scenario.

tr -d '\n' < ~/jenkinslab/.secrets/alice_token | wc -c   # normal length is 34

Fix: Regenerate the token and set a reasonable expiry time; on SSO instances, scripts can only use API tokens.

Command-line questions
1. Write one command that uses bob's API token to query his authorities in Jenkins.
curl -s -u "bob:$BOB_TOKEN" http://127.0.0.1:8080/whoAmI/api/json | jq .authorities
2. An old script that can only use a password needs to trigger a build. Write the correct way to obtain and use the crumb.
CRUMB=$(curl -s -c cj -u "u:$PW" $J/crumbIssuer/api/json | jq -r '.crumbRequestField+":"+.crumb')
curl -s -b cj -u "u:$PW" -H "$CRUMB" -X POST $J/job/team-a/job/myapp/build

The key is to -c save -b , then send back the cookie.

Scenario analysis
An audit finds that a developer has Job/Configure on team-a but no extra global permissions. He claims “I can only change my own Job, so the impact is limited.” How do you assess this?

① Under Project Matrix, anyone with Job/Configure can change that Job's authorization matrix and add any permission on that Job to himself (or others). ② A Pipeline's Groovy runs on the controller; although it is subject to the sandbox, sandbox-bypass vulnerabilities (such as the six high-severity Script Security issues of 2026-09-16) turn “changing the Jenkinsfile” into “arbitrary code execution on the controller”. ③ Builds run as SYSTEM by default and may use global-scope credentials. Conclusion: Job/Configure is a high-privilege permission; keep Script Security up to date, configure build identity (m6), and keep credentials at folder level (m3).

Verified videos

▶
Common Pitfalls in Jenkins Security and How to Avoid Them
CloudBeesTV · English · title and channel verified with YouTube oEmbed (2026-11-16) · duration per the page
Purpose: a supplement to this module's “common misconceptions”, to see the most common misconfigurations in real environments.
▶
Jenkins Security Best Practices | Jenkins User Management | Jenkins Advanced
Bribe By Bytes · English · verified with oEmbed (2026-11-16)
Purpose: UI walkthrough (users, authorization, CSRF settings pages). Note that the Jenkins version in the video may be older than 2.555.1, and the crumb IP option has been removed.

Official documentation

Video storyboard (this courseware cannot generate videos or MP3 directly, so storyboards and narration scripts are provided)

Shot 1 · 0:00–0:20
Visual: Three doors in a row: “Who are you”, “Did you send this yourself”, “Are you allowed to do this”.
Narration: Jenkins handles every request by passing through three doors in turn: authentication, the CSRF check and authorization.
Shot 2 · 0:20–0:50
Visual: Three request lines (browser, script, malicious web page) enter the controller; the script line carries an API token and goes straight past the CSRF door.
Narration: The browser relies on the session and crumb, the script relies on the API token; a malicious web page can borrow the cookie but cannot get the crumb, so it is stopped at the second door.
Shot 3 · 0:50–1:30
Visual: Object tree: root, team-a folder, myapp; permissions flow down like water, and when switched to nonInheriting, the water is cut off by a gate.
Narration: Effective permissions are the result of merging up the object tree. The inheritance strategy decides at which level the merge happens; someone without Discover permission sees a 404.
Quiz ≥ 70% marks it automatically

Module 2 · SSO and RBAC: Entra ID / OIDC / SAML and folder permissions

06:00 – 13:00 · Hand identity to the enterprise IdP and delegate permissions to folders by team; authorization trusts only immutable group IDs
7 minoic-auth 4.737.x · saml 4.623.x · azure-ad 723.xSECURITY-3935 / 4065 (2026-09-02)★★★★★
Learning goals
  • Compare the Microsoft Entra ID plugin, the generic OpenID Connect plugin and the SAML plugin in terms of protocol, group mapping, maintenance status and known risks.
  • Understand where the OIDC authorization code flow lands in Jenkins: /securityRealm/commenceLogin → IdP → /securityRealm/finishLogin → groups → authorities.
  • Use Project Matrix folder authorization or Role-based Strategy item regex to implement multi-team isolation; master the three inheritance strategies and permission templates.
  • Prepare “break-glass” access (OIDC escape hatch or a local emergency account), and know how to recover when SSO fails.
Prerequisites: m1; basic OAuth 2.0 / OIDC terminology. Importance:★★★★★

What: three SSO plugins

Microsoft Entra ID (azure-ad)OpenID Connect (oic-auth)SAML (saml)
ProtocolOIDC + Microsoft GraphOIDC (any IdP: Entra, Okta, Keycloak, Google…)SAML 2.0 (ADFS, Entra, Okta, Keycloak…)
Current version (2026-11)723.v212c114e2fb_f (2026-10-21)4.737.vb_3d1a_0e7cf0b_ (2026-11-16)4.623.v7875d61cd9f5 (2026-08-25)
Where groups come fromgroups claim of the ID token (object IDs) + optional Graph querygroupsFieldName (JMESPath) takes values from the ID token or userinfogroupsAttributeName assertion attributes
Authorization works withbuilt-in azureAdMatrix (can search by display name, store by object ID); can also be combined with matrix / role-strategymatrix-auth / role-strategymatrix-auth / role-strategy
Secretsclient secret / certificate / Workload Identity (federated credential, no secret)client secret (PKCE recommended)SP signing/encryption keystore (optional)
Maintenance notesCommunity-maintained; the README states that Microsoft has not supported it since 2024-02-29Actively maintained by the communityCommunity-maintained
Recent advisoriesSECURITY-3935: groups can also be matched by display name, which leads to privilege escalation; from 711.x only by object ID— (no unfixed warnings as of 2026-11)SECURITY-4065: IdP metadata can be overwritten without permission, allowing login as any user; fixed in 4.623.x

RBAC: three authorization plugins

Matrix Authorization (matrix-auth 3.3)Role-based Strategy (role-strategy 928.x)Folder-based (folder-auth)
Where authorization is writtenGlobally + on the properties of each folder/Job/agent (follows the object)Centralized in one place: global roles, item roles (regex), agent rolesDefined centrally, assigned by folder
Multi-teamone matrix per team folder; can be generated with Job DSL / JCasCone item role team-a(/.*)? covers the entire folder treesimilar approach
Inheritanceinheriting / inheritingGlobal / nonInheritingNo inheritance concept: the permission is granted wherever the regex matchesFolder inheritance
DelegationAnyone with Job/Configure can change this object's matrix (the risk is here too)Permissions such as “Role Based Strategy/ItemRoles” can delegate role management—
StatusActive (3.3 released 2026-07)Active (released 2026-10)Latest release 2024-11 (217.vd5b_18537403e); the Update Center shows that the current version is still affected by SECURITY-3062 (2025-01-22, “Disabled permissions can be granted”) with no fix——should not be adopted

Role-based regex details (from the plugin README)

  • Regex matching Full full item name, case-sensitive; (?i) case-insensitive.
  • To grant both the folder itself and the Jobs inside it, use team-a($|/.*) or team-a(/.*)?; if you only write team-a/.* , users cannot see the folder itself.
  • When granting Job/Create, also grant Job/Configure and Job/Read; only names matching the regex can be created.
  • Permission templates let hundreds of team roles share the same set of permissions.

Why: why SSO + group authorization

A local user database cannot enforce MFA, cannot be disabled through the HR offboarding process, and cannot be audited uniformly. After SSO,authorization should reference only groups (team changes are handled in the IdP), and it should reference only immutable group identifiers: SECURITY-3935 shows that Entra group display names are neither unique nor immutable, and any tenant member can by default create a group with the same name. Authorizing by display name therefore lets anyone grant themselves permissions.

How: where OIDC login lands in Jenkins

  1. User visits /login → /securityRealm/commenceLogin → 302 to the IdP's authorization endpoint (with state,nonce; when PKCE is enabled, also with code_challenge).
  2. The IdP completes MFA / conditional access → 302 back to /securityRealm/finishLogin?code=…&state=… (this is the Redirect URI that must be registered in the IdP).
  3. Jenkins exchanges the code (+ client secret / PKCE verifier) for an ID token → verifies the signature (JWKS),iss,aud,exp,nonce.
  4. Uses userNameField to get the username,groupsFieldName to get the groups → establishes the session; the groups become the authorities used by the authorization strategy.

When: how to choose

  • If the company uses only Entra ID and needs to search groups by name in the UI → Entra ID plugin (be sure to upgrade to 711.x+, which authorizes groups by object ID).
  • Multiple IdPs or Keycloak/Okta → generic OIDC plugin (enable PKCE, configure an escape hatch).
  • IdP only offers SAML (legacy ADFS) → SAML plugin (upgrade to 4.623.x+).
  • < 10 teams with a clear folder structure → Project Matrix; many teams with consistent naming → Role-based.
Common misconceptions① “Going live with SSO makes it secure”: SSO only solves authentication; the authorization strategy must still move away from “logged in means administrator”. ② “Configuring by group display name is more intuitive”: display names can be forged (SECURITY-3935), so use only object IDs; the displayName (objectId) shown in the UI is only for readability. ③ “SSO users can call the API with a password”: Jenkins does not know the SSO password, so scripts must use an API token. ④ “nonInheriting keeps administrators out”: Overall/Administer can never be removed.

Architecture diagram: IdP group → Jenkins authorities → folder authorization

Enterprise IdP (Entra ID) group jenkins-adminsobjectId 7f3c…a1 group team-a-devobjectId 2b9e…44 group auditorsobjectId c05d…19 MFA · conditional access · offboarding disablement Security RealmVerify ID tokenuserNameFieldgroupsFieldNameauthorities = group object IDs Authorization Strategy Global: 7f3c…a1 → Administer · authenticated → Overall/Read Folder team-a: 2b9e…44 → Job/Build, Configure, Replay… Global: c05d…19 → Overall/SystemRead + Job/Read or Role-based: item role pattern "team-a(/.*)?"
Figure 2-1: authorization references only immutable group object IDs; membership changes are made only in the IdP

Flowchart: OIDC authorization code login

Browser Jenkins IdP GET /securityRealm/commenceLogin 302 → /authorize?state&nonce&code_challenge Login + MFA 302 → /securityRealm/finishLogin?code&state POST /token (code + secret / verifier) id_token (JWT, containing groups) Jenkins: verify signature (JWKS), iss/aud/exp/nonce → session + authorities
Figure 2-2: the Redirect URI must be ${JENKINS_URL}/securityRealm/finishLogin, and a wrong Jenkins URL is the number one cause of login failure

Step-by-step demo of OIDC / SAML login and group mapping

Choose an IdP plugin and a “fault injection”, then step through the real HTTP round trips between browser, Jenkins and IdP, and the authorities that finally enter the authorization strategy.

Browser
Jenkins controller
IdP
Authorization strategy
Choose a plugin to start.
$ waiting for login…

JCasC configuration snippet (choose one as securityRealm)

ConfigurationPurposeKey fields / notes
securityRealm.oicGeneric OIDCserverConfiguration.wellKnown,clientId/clientSecret,groupsFieldName,properties: [pkce, escapeHatch]
securityRealm.azureEntra IDclientid,tenant,clientsecret or credentialtype: WorkloadIdentity
securityRealm.samlSAML 2.0idpMetadataConfiguration.url,usernameAttributeName,groupsAttributeName
authorizationStrategy.roleBasedrole-based authorizationroles.global/items/agents,pattern,permissionTemplates
authorizationStrategy.azureAdMatrixEntra matrixentries look like name: "team-a-dev (2b9e…)"
jenkins:
  securityRealm:
    oic:
      serverConfiguration:
        wellKnown:
          wellKnownOpenIDConfigurationUrl: "https://login.example.com/realms/corp/.well-known/openid-configuration"
      clientId: "jenkins"
      clientSecret: "${oidc_client_secret}"     # /run/secrets/oidc_client_secret
      userNameField: "preferred_username"
      groupsFieldName: "groups"
      fullNameFieldName: "name"
      emailFieldName: "email"
      logoutFromOpenidProvider: true
      properties:
        - "pkce"
        - escapeHatch:
            username: "breakglass"
            secret: "${oidc_breakglass_pw}"
            group: "jenkins-admins"
jenkins:
  securityRealm:
    azure:
      clientid: "00000000-1111-2222-3333-444444444444"
      tenant: "contoso.onmicrosoft.com"
      credentialtype: "WorkloadIdentity"        # no client secret; requires AZURE_FEDERATED_TOKEN_FILE
      cacheduration: 3600
      fromrequest: true
  authorizationStrategy:
    azureAdMatrix:
      entries:
        - group:
            name: "jenkins-admins (7f3c0000-0000-0000-0000-0000000000a1)"
            permissions: [Overall/Administer]
        - group:
            name: authenticated
            permissions: [Overall/Read]
jenkins:
  securityRealm:
    saml:
      idpMetadataConfiguration:
        url: "https://adfs.example.com/FederationMetadata/2007-06/FederationMetadata.xml"
        period: 1440                            # minutes; periodically refresh IdP metadata
      usernameAttributeName: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"
      groupsAttributeName: "http://schemas.xmlsoap.org/claims/Group"
      displayNameAttributeName: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
      maximumAuthenticationLifetime: 28800
      binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"

How to verify: After logging in, visit /whoAmI/api/json,authorities the groups should appear (for OIDC, group names or IDs depending on the IdP claim; for Entra, object IDs). Common mistakes: The Jenkins URL (Manage Jenkins → System) does not match the Redirect URI registered in the IdP; in Entra, groupMembershipClaims is not set to SecurityGroup; too many user groups (when Entra exceeds the limit, the token only carries an “overage” marker and a Graph query is needed). Production use: Keep the SSO configuration in JCasC, with secrets in /run/secrets or a Kubernetes Secret, so changes can be reviewed and rolled back.

# OIDC debugging: view the endpoints the IdP advertises and the supported algorithms
curl -s https://login.example.com/realms/corp/.well-known/openid-configuration \
  | jq '{issuer, authorization_endpoint, token_endpoint, jwks_uri, code_challenge_methods_supported}'
# Decode the payload of an ID token (inspect the claims only; the signature is not verified)
cut -d. -f2 <<<"$ID_TOKEN" | tr '_-' '/+' | base64 -d 2>/dev/null | jq '{iss,aud,preferred_username,groups}'

Lab 2: same requirements, Project Matrix vs Role-based (about 7 min)

Record the result of the current setup (Project Matrix + folder authorization): rerun the loop from step 3 of the m1 lab and save it as /tmp/matrix.txt.
cd ~/jenkinslab; J=http://127.0.0.1:8080
check(){ for u in alice bob carol; do for p in job/team-a/job/myapp/api/json job/team-b/job/myapp/api/json; do
  printf '%-6s %-32s %s\n' $u $p $(curl -s -o /dev/null -w '%{http_code}' -u "$u:$(cat .secrets/${u}_pw)" $J/$p); done; done; }
check | tee /tmp/matrix.txt
Write the equivalent Role-based configuration (a new file overrides authorizationStrategy; JCasC merges files in filename order, so a later file would conflict on the same key; therefore we temporarily replace the authorization section in 10-security.yaml):
jenkins:
  authorizationStrategy:
    roleBased:
      permissionTemplates:
        - name: "team-dev"
          permissions: ["Job/Read", "Job/Build", "Job/Cancel", "Job/Configure", "Job/Create",
                        "Job/Workspace", "Run/Replay", "Credentials/View"]
      roles:
        global:
          - name: "admin"
            permissions: ["Overall/Administer"]
            entries: [{ user: "admin" }]
          - name: "reader"
            permissions: ["Overall/Read"]
            entries: [{ group: "authenticated" }]
          - name: "auditor"
            permissions: ["Overall/Read", "Job/Read", "View/Read"]
            entries: [{ user: "carol" }]
        items:
          - name: "team-a-dev"
            pattern: "team-a(/.*)?"
            templateName: "team-dev"
            entries: [{ user: "alice" }]
          - name: "team-b-dev"
            pattern: "team-b(/.*)?"
            templateName: "team-dev"
            entries: [{ user: "bob" }]
cp casc/10-security.yaml /tmp/10-security.bak
# delete the authorizationStrategy section in 10-security.yaml (up to before security:)
python3 - <<'EOF'
import re,pathlib
p=pathlib.Path('casc/10-security.yaml'); t=p.read_text()
t=re.sub(r'\n  authorizationStrategy:\n(?:    .*\n|      .*\n)+', '\n', t)
p.write_text(t)
EOF
grep -c authorizationStrategy casc/10-security.yaml   # expect 0
docker compose restart jenkins && sleep 45
check | tee /tmp/roles.txt; diff /tmp/matrix.txt /tmp/roles.txt && echo "the two strategies give the same result"
0
alice  job/team-a/job/myapp/api/json    200
alice  job/team-b/job/myapp/api/json    404
bob    job/team-a/job/myapp/api/json    404
bob    job/team-b/job/myapp/api/json    200
carol  job/team-a/job/myapp/api/json    200
carol  job/team-b/job/myapp/api/json    200
the two strategies give the same result

Note: after switching to roleBased, the folder's authorizationMatrix property no longer takes effect (only one authorization strategy can be active); Job DSL still writes that property when it runs again, but it is ignored.

Experience the regex trap: change team-a-dev's pattern to team-a/.*, after restarting, alice accessing /job/team-a/ returns 404, but directly accessing /job/team-a/job/myapp/ also returns 404, because without seeing the parent folder the child object cannot be routed. Change it back to team-a(/.*)?.
Experience nonInheriting: restore the matrix configuration, and in 20-teams.yaml change team-a's inheriting() to nonInheriting(); after restarting, carol gets 404 for team-a (the global Job/Read no longer inherits downward), while admin can still access it.
rm casc/15-authz-roles.yaml; cp /tmp/10-security.bak casc/10-security.yaml
sed -i 's/inheriting() }/nonInheriting() }/' casc/20-teams.yaml
docker compose restart jenkins && sleep 45 && check | grep carol
carol  job/team-a/job/myapp/api/json    404
carol  job/team-b/job/myapp/api/json    404

Both folders are generated by the same Job DSL block, so both become nonInheriting. This is the amplifying effect of configuration as code. After the lab, change it back to inheriting() and restart.

(optional, not run in this lesson's environment) Connect Keycloak OIDC: add Keycloak to Compose (in start-dev mode), create the realm corp, the client jenkins (Redirect URI http://127.0.0.1:8080/securityRealm/finishLogin), the group mapper groups, then use the 30-sso-oidc.yaml on the “Commands” page. Be sure to verify login first with the escape hatch account, then remove the local user database.

Cleanup: Confirm that casc/ has only 10-security.yaml and 20-teams.yaml, and that 20-teams.yaml is inheriting(), then restart Jenkins.

Case 1: Entra group display name collision (SECURITY-3935)

Problem: The authorization matrix contains an entry Jenkins-Admins (display name); Entra allows members to create security groups by default, so an attacker can create a same-named group and add themselves, which grants admin rights in 710.x and earlier versions. Fix: Upgrade azure-ad to 711.x+ (current 723.x); export JCasC and check that all group entries include object IDs; in Entra, restrict users from creating security groups. Limitations: After the upgrade, authorizations that depend on display names will stop working; you can temporarily restore them with -Dcom.microsoft.jenkins.azuread.ObjId2FullSidMap.enableDisplayNameAuthorization=true — this is an unsafe transitional measure and must have a deadline.

Case 2: SAML IdP metadata overwritten (SECURITY-4065)

Problem: In SAML plugin 4.618.x and earlier, a constructor with @DataBoundConstructor writes the IdP metadata file; an attacker who can submit certain forms could replace it with their own IdP and log in as any user. Fix: Upgrade to 4.623.x; pin idpMetadataConfiguration.url in JCasC and refresh it periodically; monitor $JENKINS_HOME/saml-idp-metadata.xml for changes (Audit Trail + file integrity monitoring). Limitations: Plugin upgrades require regression testing of the login flow; have break-glass accounts ready.

Case 3: authorization maintenance for 120 teams

Problem: One folder per team; manually maintaining the matrix led to permission drift. Fix: Adopt Role-based: unify the naming <bu>-<team>, one permission template team-dev, generate item roles from the CMDB with JCasC (pattern ^bu1-payments(/.*)?$, with groups as Entra object IDs); the platform team only has the “Role Based Strategy/ItemRoles” delegation permission. Limitations: A wrong regex will match another team's items, so unit-test the generated YAML in CI (list the existing items each pattern matches).

Error after OIDC login: Invalid state / Redirect URI mismatch (AADSTS50011)

Cause: The Jenkins URL in Manage Jenkins → System does not match the access address or the Redirect URI registered in the IdP (http/https, port, reverse-proxy path); or the session cookie is lost during the IdP round trip (SameSite, multiple controller replicas).

curl -s -u "admin:$TOKEN" "$J/manage/configure" -o /dev/null -w '%{http_code}\n'
docker compose exec jenkins grep -A1 jenkinsUrl /var/jenkins_home/jenkins.model.JenkinsLocationConfiguration.xml

Fix: Unify the Jenkins URL; register ${JENKINS_URL}/securityRealm/finishLogin in the IdP; make the reverse proxy pass X-Forwarded-Proto/Host.

Login succeeds, but whoAmI's authorities only include authenticated

Cause: The token has no groups claim (groupMembershipClaims not configured in Entra; no groups mapper in Keycloak; groupsFieldName JMESPath is wrong).

Fix: Decode the ID token (see the “Commands” page) to confirm the claim name; fix the mapper; when Entra has too many groups, enable Graph permission queries.

After switching the security realm, nobody can log in (locked out)

Cause: IdP configuration is wrong or unreachable, and there is no local emergency account.

Fix: Log in with the escape hatch account in the OIDC plugin; otherwise correct JCasC and restart; as a last resort, temporarily disable security following the official docs (<useSecurity>false) and fix it immediately. Prevention: Verify SSO changes first on a staging instance; keep break-glass accounts and rehearse them periodically.

Role-based: the user has an item role but cannot see the folder

Cause: The pattern was written as team-a/.*, which does not match the folder itself; or the case does not match.

Fix: Change it to team-a(/.*)? or (?i)team-a($|/.*); hover over the matched items on the Manage Roles page to check.

Command-line questions
1. Write the Role-based item role so that the Entra group (object ID 2b9e…44) can build payments the folder and all its child items.
items:
  - name: "payments-dev"
    pattern: "payments(/.*)?"
    permissions: ["Job/Read", "Job/Build", "Job/Cancel"]
    entries: [{ group: "2b9e0000-0000-0000-0000-000000000044" }]
Scenario analysis
The company is switching from LDAP to Entra ID, with the change on Friday evening. List your change and rollback plan.

① Verify on a staging instance first: Redirect URI, groups claim, whoAmI output; ② change all authorization entries to group object IDs and review them in JCasC; ③ keep break-glass access: a local emergency administrator (or OIDC escape hatch), with the password in the vault; ④ the change is a JCasC file replacement, and rollback means restoring the old files and restarting; ⑤ notify all API clients to switch to API tokens; ⑥ after the change, check the login events in the Audit Trail and the 403 ratio.

Verified videos

▶
Jenkins Tutorial For Beginners - Using the Role-Based Authorization Strategy + Manage Roles
CodeBind · English · verified with oEmbed (2026-11-16)
Purpose: UI walkthrough of Role-based Strategy (Manage Roles / Assign Roles).
▶
DevOps: Jenkins Matrix-Based Security | ACL for Users
DevOps - Free Tutorials · English · verified with oEmbed (2026-11-16)
Purpose: demonstration of the matrix authorization interface.
▶
How to Secure Jenkins with Keycloak OIDC Integration
Middleware Technologies · English · verified with oEmbed (2026-11-16)
Purpose: reference for the optional Keycloak OIDC lab; the plugin interface may differ slightly from 4.737.x.

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: An employee enters the password and MFA on the IdP login page; Jenkins only receives a “stamped business card” (the ID token).
Narration: SSO hands authentication to the enterprise identity system; Jenkins only verifies the signature and validity period on the card.
Shot 2 · 0:30–1:00
Visual: Two group cards both named “Jenkins-Admins” with different object IDs, circled in red.
Narration: Group display names can collide; object IDs cannot. Authorization trusts only object IDs, which is the lesson of advisory 3935.
Shot 3 · 1:00–1:40
Visual: On the left, one matrix per folder; on the right, one regex covering a whole subtree.
Narration: With few teams, use folder matrices; with many teams, use roles plus regex. Both can produce the same result; the difference is who maintains them.
Quiz ≥ 70% marks it automatically

Module 3 · Credential management: credential domains, Vault and external secrets

13:00 – 21:00 · Credentials should be as close as possible to the Job that uses them; secrets are best never to enter Jenkins at all
8 mincredentials 1514.x · hashicorp-vault 384.xazure-keyvault 381.x · aws-secrets-manager 2.227.x★★★★★
Learning goals
  • Distinguish credential store (system / folder / user),scope (SYSTEM / GLOBAL),credential domain (domain: grouped by hostname / URI), and know which one is the boundary of team isolation.
  • Explain CredentialsProvider lookup order: nearest folder → parent folder → system store (GLOBAL only) → external providers, and how build identity affects the result.
  • Use HashiCorp Vault (AppRole + withVault), Azure Key Vault (credentials provider + tag type), AWS Secrets Manager (tag jenkins:credentials:type,jenkins:credentials:folder) to keep secrets outside Jenkins.
  • Avoiding log leakage: the limits of credential masking, Groovy string interpolation warnings,set -x and encoded output.
Prerequisites: Lesson 1 credentials basics (gitea-myapp,registry-creds); managed identity and IRSA from Lessons 3 and 4. Importance:★★★★★

What: stores, scopes, credential domains

ConceptValuesPurposeIs it a security boundary?
StoreSystem (Jenkins root), Folder, UserDetermines which Jobs can see it: a folder store is visible only to that folder and its childrenYes— this is how multi-team isolation works
ScopeSYSTEM, GLOBAL (user stores have a separate USER scope)SYSTEM is only for Jenkins itself (e.g., connecting agents, SSO client secret),builds cannot use it; GLOBAL can be used by buildsYes: setting a system credential to SYSTEM
Credential domainGlobal domain (_) + custom (hostname, URI scheme rules)Grouping and matching: plugins can list only the credentials in matching domains for a given target URLNo— it is only an organizational method and does not stop a Job from using it by ID
PermissionsCredentials/View, Create, Update, Delete, ManageDomains; optional UseOwn / UseItemControls who can manage credentials in the UI; use of credentials is decided by build identityPartial

How: one withCredentials lookup process

  1. Pipeline steps call build identity (default SYSTEM; the triggering user after Authorize Project is configured, etc.) CredentialsProvider.findCredentialById(id, type, run).
  2. Ask each CredentialsProvider: the folder provider searches upward from the folder that contains the Job level by level; the system provider returns only GLOBAL scope credentials; external providers (Azure Key Vault, AWS Secrets Manager, Kubernetes Credentials Provider…) return results by their own rules.
  3. Once found, the binding plugin (credentials-binding) writes it to temporary environment variables or files and registers the secret value with the log masker; the temporary files are deleted when the block ends.
  4. If not found, it reports Could not find credentials entry with ID '…'— for “another team's credentials”, this is exactly the expected behavior.

Two modes for external secrets

ModePluginWhen the secret enters JenkinsCharacteristics
Credentials provider (Credentials Provider)Azure Key Vault, AWS Secrets Manager Credentials Provider, Kubernetes Credentials ProviderRead by ID when needed; metadata is cached (the Key Vault documentation states 10 minutes)Read-only; Jobs still use the normal credentials('id'), transparent to existing Pipelines; the credential type is determined by tags
Build wrapper / stepHashiCorp Vault (withVault), Azure Key Vault (withAzureKeyvault)Read on entering the block, injected as environment variablesJenkins stores only the “credentials for accessing external systems” (AppRole, managed identity); paths and keys are written in the Jenkinsfile

Key conventions for the three external systems (verified 2026-11)

  • HashiCorp Vault plugin 384.x: officially recommends AppRole for machine authentication; credential types include Vault Token, AppRole, GitHub Token, AWS IAM, GCP, etc.; withVault(configuration: [...], vaultSecrets: [[path:, engineVersion:, secretValues: [[envVar:, vaultKey:]]]]); it can be configured globally in JCasC under unclassified.hashicorpVault.configuration (global setting) vaultUrl.
  • Azure Key Vault plugin 381.x: authentication can use a service principal or managed identity (user- or system-assigned); when used as a credentials provider, secrets default to Secret text, and the tag type=username/secretFile/sshUserPrivateKey/certificate/githubApp changes the type. The README notes that the same JCasC file cannot both configure the provider and resolve credentials from it.
  • AWS Secrets Manager Credentials Provider 2.227.x: read-only; IAM requires secretsmanager:ListSecrets and GetSecretValue; tag jenkins:credentials:type (string / usernamePassword / sshUserPrivateKey / certificate / file / githubApp),jenkins:credentials:folder can restrict secrets to a specified folder; tags are non-secret metadata (visible to ListSecrets), so SSH passphrases must not be stored in tags.

Why: why credentials should be “pushed down” and “externalized”

Credentials stored in the system store with GLOBAL scope,anyone who can modify any Job can use in a build (and send outside). Pushing them down to a folder shrinks the exposure to one team; externalizing to Vault / Key Vault means there is no plaintext on Jenkins disks or in backups (even if $JENKINS_HOME/secrets/master.key and credentials.xml are stolen together, the attacker only gets short-term credentials for external systems), and you gain rotation and auditing from the external system.

When

  • Team-specific deployment keys and repository tokens → folder store + GLOBAL scope.
  • Used only by Jenkins itself (agent SSH key, SSO client secret, Vault AppRole management credentials) → SYSTEM scope.
  • In the cloud → prefer no long-lived keys (managed identity / workload identity from Lesson 3, IRSA / Pod Identity from Lesson 4); when a secret is required, put it in Key Vault / Secrets Manager.
  • Multi-cloud, dynamic database credentials, short-lived tokens → Vault.
Common misconceptions① “Credential domains isolate teams”: no. A domain is only a classification, and a Job can still use credentials outside the global domain by ID; isolation comes from folder stores and scopes. ② “Log masking guarantees no leaks”: masking only matches the original text; base64, character-by-character output and writing to artifacts can all get around it, and anyone who can change the Jenkinsfile can do this on purpose. ③ “Credentials/View can see plaintext”: it only shows metadata; but “can use” and “can see” are different things, and anyone who can change a Job can “use” the credential in a build and send it out. ④ “SYSTEM scope is more advanced, so builds can use it too”: exactly the opposite; SYSTEM scope is invisible to builds (SECURITY-3729 is the case where resolveScm steps wrongly gave builds SYSTEM credentials; fixed in Pipeline: Multibranch 842.x).

Architecture diagram: credential stores and providers

Jenkins controller System store (Jenkins root)SYSTEM: agent1-ssh, oidc-client (invisible to builds)GLOBAL: registry-creds (visible to all Jobs) team-a storegitea-myappvault-team-a team-b storegitea-teamb(invisible to team-a) Disk: credentials.xml + secrets/master.key encrypted External credential providers (read-only) Azure Key Vaulttag type=username …Managed identity / service principal AWS Secrets Managerjenkins:credentials:typejenkins:credentials:folder Kubernetes Secretstag jenkins.io/credentials-type Read at build time HashiCorp VaultAppRole → short-lived tokenwithVault { … } Azure Key VaultwithAzureKeyvault { … } Jenkins only stores the “access credentials”The secret itself never touches disk
Figure 3-1: the isolation boundary is “store + scope”; external providers keep the secret itself in a dedicated key management system

Data flow: the path of withVault within one build

Look up vault-team-ateam-a folder store AppRole loginrole_id + secret_id Vault issues tokenpolicy myapp-read · 15m Read secret/myappKV v2 · data/myapp Inject env + maskInvalid as soon as the block ends The Vault audit log records every read (who, when, which path); revoking the AppRole secret_id cuts off that team's access
Figure 3-2: in Vault mode, a leaked Jenkins backup only exposes a revocable AppRole with restricted policies

Credential lookup resolver

Select a Job, a credential ID and a build identity, and observe step by step CredentialsProvider the order in which each store and external provider is queried, where scope or folder boundaries filter results, and what finally appears in the log.

Job's folder
Parent folder
System store
External providers
Bind + mask
Choose to start.
$ withCredentials(...)

Core commands and API

Command / endpointPurposeNotes
POST /job/<folder>/credentials/store/folder/domain/_/createCredentialsCreate a credential in the global domain of a folder storethe request body is the credential XML,Content-Type: application/xml
POST /manage/credentials/store/system/domain/_/createCredentialsCreate in the system storerequires Credentials/Create (usually administrators only)
GET …/store/folder/domain/_/api/json?tree=credentials[id,description]List credential metadatadoes not return secrets
withCredentials([string(credentialsId:, variable:)])Bind as environment variablesin sh use single quotes '$VAR', do not use Groovy interpolation
withVault(configuration:, vaultSecrets:)Read a secret from VaultengineVersion: 2 corresponds to KV v2
az keyvault secret set --tags type=username username=…Prepare credentials for the Key Vault providerthe tag determines the credential type in Jenkins
aws secretsmanager create-secret --tags Key=jenkins:credentials:type,Value=stringPrepare credentials for the Secrets Manager providercan add jenkins:credentials:folder
# Create a Secret text in the team-a folder store (alice has Job/Configure, but creating credentials needs Credentials/Create, so use admin here)
J=http://127.0.0.1:8080; cd ~/jenkinslab
cat > /tmp/cred.xml <<'EOF'
<org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>
  <scope>GLOBAL</scope>
  <id>team-a-only</id>
  <description>sample token only for team-a</description>
  <secret>lab-token-aaaa-1111</secret>
</org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl>
EOF
ADMIN_TOKEN=$(cat .secrets/admin_token 2>/dev/null)   # if not generated, generate it for admin using the m1 method
curl -s -o /dev/null -w '%{http_code}\n' -u "admin:$ADMIN_TOKEN" -H 'Content-Type: application/xml' \
  --data-binary @/tmp/cred.xml "$J/job/team-a/credentials/store/folder/domain/_/createCredentials"
curl -s -u "admin:$ADMIN_TOKEN" "$J/job/team-a/credentials/store/folder/domain/_/api/json?tree=credentials[id,description]" | jq -c .credentials
200
[{"description":"sample token only for team-a","id":"team-a-only"}]
withCredentials([string(credentialsId: 'team-a-only', variable: 'TOKEN')]) {
  sh 'curl -sf -H "Authorization: Bearer $TOKEN" http://gitea:3000/api/v1/version'   // ✓ single quotes: expanded by the shell
  sh "echo ${TOKEN}"                                                             // ✗ Groovy interpolation: the secret enters the step parameters
}
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
		 Affected argument(s) used the following variable(s): [TOKEN]
		 See https://jenkins.io/redirect/groovy-string-interpolation for details.
+ echo ****

Why interpolation is unsafe: Groovy first concatenates the secret into the command string; the command string is saved as a step parameter in the build record and also appears in the agent's process list. With single quotes, Groovy passes only the literal $TOKEN, which the shell on the agent expands from environment variables.

Lab 3: folder credential isolation + Vault AppRole (about 8 min)

Generate an API token for admin (same as m1, replacing alice with admin, and save it as .secrets/admin_token), then use the commands on the “Commands” page to create it in team-a team-a-only.
Prepare a small function to create a Pipeline Job (uses the API token, no crumb needed):
mkjob(){ # usage: mkjob user token-file folder name Groovy-script-file
  local esc; esc=$(sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' "$5")
  printf '<flow-definition><definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition"><script>%s</script><sandbox>true</sandbox></definition></flow-definition>' "$esc" > /tmp/job.xml
  curl -s -o /dev/null -w "create $3/$4: %{http_code}\n" -u "$1:$(cat $2)" -H 'Content-Type: application/xml' \
    --data-binary @/tmp/job.xml "http://127.0.0.1:8080/job/$3/createItem?name=$4"
}
cat > /tmp/cred-demo.groovy <<'EOF'
pipeline {
  agent { label 'linux' }
  stages { stage('use') { steps {
    withCredentials([string(credentialsId: 'team-a-only', variable: 'TOKEN')]) {
      sh 'echo "token length: ${#TOKEN}"; echo "$TOKEN"'
    }
  } } }
}
EOF
mkjob alice .secrets/alice_token team-a cred-demo /tmp/cred-demo.groovy
# bob needs his own token (generate it to .secrets/bob_token using the m1 method)
mkjob bob .secrets/bob_token team-b cred-demo /tmp/cred-demo.groovy
create team-a/cred-demo: 200
create team-b/cred-demo: 200
Build each one separately and compare the logs:
for t in a b; do u=$([ $t = a ] && echo alice || echo bob)
  curl -s -X POST -u "$u:$(cat .secrets/${u}_token)" "$J/job/team-$t/job/cred-demo/build"; done
sleep 25
for t in a b; do u=$([ $t = a ] && echo alice || echo bob); echo "== team-$t"
  curl -s -u "$u:$(cat .secrets/${u}_token)" "$J/job/team-$t/job/cred-demo/lastBuild/consoleText" | grep -E 'token length|\*\*\*\*|Could not find|Finished'; done
== team-a
token length: 19
****
Finished: SUCCESS
== team-b
ERROR: Could not find credentials entry with ID 'team-a-only'
Finished: FAILURE
Start a Vault dev server (lab only; data is in memory):
docker network ls --format '{{.Name}}' | grep jenkinslab     # usually jenkinslab_default
docker run -d --name vault --network jenkinslab_default -p 127.0.0.1:8200:8200 --cap-add=IPC_LOCK \
  -e VAULT_DEV_ROOT_TOKEN_ID=root -e VAULT_DEV_LISTEN_ADDRESS=0.0.0.0:8200 hashicorp/vault:2.2.2
V="docker exec -i -e VAULT_ADDR=http://127.0.0.1:8200 -e VAULT_TOKEN=root vault vault"
$V kv put secret/myapp redis_password=s3cr3t-lab
$V policy write myapp-read - <<'EOF'
path "secret/data/myapp" { capabilities = ["read"] }
EOF
$V auth enable approle
$V write auth/approle/role/jenkins-team-a token_policies=myapp-read token_ttl=15m secret_id_ttl=24h
ROLE_ID=$($V read -field=role_id auth/approle/role/jenkins-team-a/role-id)
SECRET_ID=$($V write -f -field=secret_id auth/approle/role/jenkins-team-a/secret-id)
echo "role_id=$ROLE_ID"; echo "secret_id length ${#SECRET_ID}"
Success! Data written to: auth/approle/role/jenkins-team-a
role_id=5c0e8f1e-3b0a-...-9d2f
secret_id length 36
Store the AppRole in the team-a folder and run withVault:
cat > /tmp/vault-cred.xml <<EOF
<com.datapipe.jenkins.vault.credentials.VaultAppRoleCredential>
  <scope>GLOBAL</scope><id>vault-team-a</id><description>Vault AppRole for team-a</description>
  <roleId>$ROLE_ID</roleId><secretId>$SECRET_ID</secretId><path>approle</path>
</com.datapipe.jenkins.vault.credentials.VaultAppRoleCredential>
EOF
curl -s -o /dev/null -w '%{http_code}\n' -u "admin:$(cat .secrets/admin_token)" -H 'Content-Type: application/xml' \
  --data-binary @/tmp/vault-cred.xml "$J/job/team-a/credentials/store/folder/domain/_/createCredentials"
rm /tmp/vault-cred.xml; unset SECRET_ID
cat > /tmp/vault-demo.groovy <<'EOF'
pipeline {
  agent { label 'linux' }
  stages { stage('vault') { steps {
    withVault(configuration: [vaultUrl: 'http://vault:8200', vaultCredentialId: 'vault-team-a', engineVersion: 2],
              vaultSecrets: [[path: 'secret/myapp', secretValues: [[envVar: 'REDIS_PASSWORD', vaultKey: 'redis_password']]]]) {
      sh 'echo "got redis password, length ${#REDIS_PASSWORD}"; echo "$REDIS_PASSWORD"'
    }
  } } }
}
EOF
mkjob alice .secrets/alice_token team-a vault-demo /tmp/vault-demo.groovy
curl -s -X POST -u "alice:$(cat .secrets/alice_token)" "$J/job/team-a/job/vault-demo/build"; sleep 25
curl -s -u "alice:$(cat .secrets/alice_token)" "$J/job/team-a/job/vault-demo/lastBuild/consoleText" | grep -E 'got redis|\*\*\*\*|Finished'
200
got redis password, length 10
****
Finished: SUCCESS

Revoke on the Vault side: $V write auth/approle/role/jenkins-team-a/secret-id-accessor/destroy secret_id_accessor=… or delete the role directly; the next build should fail (403 permission denied).

Cleanup:docker rm -f vault; delete the Job team-a/vault-demo,team-*/cred-demo (in the UI or with POST …/doDelete); delete /tmp/*.groovy /tmp/job.xml /tmp/cred.xml. Risk: Vault dev mode does not encrypt storage and has a fixed root token; for local lab use only.

Case 1: Jenkins on Azure reads Key Vault with a managed identity

Problem: 40 teams and 600 credentials are all in the GLOBAL system store, so backup leaks are a big risk and rotation is difficult. Fix: The controller runs on AKS (workload identity from Lesson 3) or on a VM with a managed identity; install the Azure Key Vault plugin as a credentials provider,-Djenkins.azure-keyvault.url=https://kv-jenkins-prod.vault.azure.net + -Djenkins.azure-keyvault.uami.enabled=true; in Key Vault, use tags type to define the type; Key Vault RBAC grants the Jenkins identity only “Key Vault Secrets User”. Configuration:az keyvault secret set --vault-name kv-jenkins-prod --name gitea-myapp --value "$PAT" --tags type=username username=ci-bot. Limitations: The provider is read-only and the credential ID equals the secret name; metadata is cached for 10 minutes; one Key Vault is visible to all Jobs. Team isolation needs a separate Key Vault per team plus on-demand reads via the Vault plugin, or switching to folder credentials.

Case 2: restricting Secrets Manager secrets by folder on AWS

Problem: Jenkins on EC2 reads Secrets Manager through an instance role, but all teams can use all secrets. Fix: The AWS Secrets Manager Credentials Provider reads the jenkins:credentials:folder tag, and payments/* limits the secret to the payments folder; IAM policies restrict access with tag conditions GetSecretValue; CloudTrail audits the reads. Limitations: Tags are non-secret metadata; secrets without a folder tag are visible to all Jobs (backward-compatible behavior), so tagging must be enforced in the onboarding process.

Case 3: Vault dynamic credentials replace long-lived database passwords

Problem: Integration tests use a shared database administrator password, which a departed employee had copied. Fix: The Vault database secrets engine issues a database account valid for 30 minutes for each build; Jenkins holds only one AppRole per team (secret_id rotated every 24 hours, refreshed by a platform Job). Limitations: Vault becomes a hard dependency of builds and needs high availability; the AppRole secret_id is still a secret in Jenkins, so store it in a folder store and restrict the CIDR (secret_id_bound_cidrs).

ERROR: Could not find credentials entry with ID 'gitea-myapp'

Cause: The credential is in another folder; it is SYSTEM scope; the ID has the wrong case; the external provider is not ready (Key Vault cache not refreshed, IAM missing ListSecrets); after Authorize Project is configured, the triggering user lacks permission to use the credential.

curl -s -u "admin:$T" "$J/job/team-a/credentials/store/folder/domain/_/api/json?tree=credentials[id]" | jq -c .
curl -s -u "admin:$T" "$J/manage/credentials/store/system/domain/_/api/json?tree=credentials[id,typeName]" | jq -c .

Fix: Put the credential in the Job's folder or a parent folder; set credentials that builds need to GLOBAL in the system store; refresh the Key Vault cache on the system configuration page.

Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.

Cause: A credential variable is referenced inside a double-quoted GString.

Fix: Change to single quotes sh 'cmd "$TOKEN"'; when mixing with ordinary variables, use withEnv to also put ordinary values into environment variables.

Vault: Exception while executing Vault request / permission denied

Cause: KV engine version mismatch (v2 requires engineVersion: 2, and the policy path must be written as secret/data/…); AppRole secret_id expired; the controller/agent cannot resolve vault hostname.

docker exec -e VAULT_ADDR=http://127.0.0.1:8200 -e VAULT_TOKEN=root vault vault policy read myapp-read
docker compose exec jenkins getent hosts vault

Fix: Correct the policy and engineVersion; confirm the request path in the Vault audit log.

Secret appears in the build log without being masked as ****

Cause: The output is a transformed value (base64, URL-encoded, split characters), or the secret came from a non-credential source (parameters, file contents).

Fix: Rotate the secret immediately; delete the corresponding build records; review the Jenkinsfile change history of this Job (Job Config History / Git commits); push the credential down to a folder to reduce the number of people who can “use” it.

Command-line questions
1. In AWS Secrets Manager, create a username/password credential that only the team-a folder can use.
aws secretsmanager create-secret --region ca-central-1 --name 'team-a-registry' --secret-string "$PW" \
  --tags 'Key=jenkins:credentials:type,Value=usernamePassword' 'Key=jenkins:credentials:username,Value=ci-bot' \
         'Key=jenkins:credentials:folder,Value=team-a'
2. Write a withVault snippet that reads from the KV v2 secret/myapp path redis_password.
withVault(configuration: [vaultUrl: 'http://vault:8200', vaultCredentialId: 'vault-team-a', engineVersion: 2],
          vaultSecrets: [[path: 'secret/myapp', secretValues: [[envVar: 'REDIS_PASSWORD', vaultKey: 'redis_password']]]]) {
  sh 'test -n "$REDIS_PASSWORD"'
}
Scenario analysis
The security team requires that “no production secrets be exposed if the Jenkins backup leaks”. Design your credential architecture.

① Production deployments use identities without long-lived keys (managed identity / workload identity / IRSA), so no cloud keys are stored in Jenkins; ② other secrets go into Vault / Key Vault, and Jenkins stores only one AppRole per team (folder store, short TTL, CIDR binding) or uses managed identity to access Key Vault; ③ the Jenkins system store keeps only agent connection credentials with SYSTEM scope; ④ backups are encrypted and kept apart from secrets/master.key ; ⑤ regular drills: assume credentials.xml + master.key leak, and be able to revoke all AppRoles within 1 hour.

Verified videos

▶
The Correct Way to Handle Credentials in a Jenkins Pipeline
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: withCredentials, single quotes vs. interpolation.
▶
How To Define Credentials at a Folder Level in Jenkins
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: UI operations for folder credentials, corresponding to lab steps 1–3.
▶
How to Integrate HashiCorp Vault With Jenkins
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: Vault plugin configuration; the plugin version may be older, so follow the 384.x documentation.

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: A string of keys is distributed from the “system vault” into each team's small drawer (folder store).
Narration: The boundary of team isolation is the storage location and scope, not the credential domain.
Shot 2 · 0:30–1:10
Visual: The build shows its AppRole to Vault and gets a pass that automatically expires after 15 minutes.
Narration: Jenkins holds only a key that can be revoked at any time; the real secrets stay in Vault.
Shot 3 · 1:10–1:40
Visual: Asterisks in the log; next to them, a base64-encoded string is not hidden.
Narration: Masking only recognizes the original text. Anyone who can change the Jenkinsfile can use the credential, so keep the group that can use it as small as possible.
Quiz ≥ 70% marks it automatically

Module 4 · Script Security, sandbox and Groovy approval

21:00 – 28:00 · A Jenkinsfile is “code written by someone else that runs in the controller JVM”; the sandbox intercepts every method call, and approval is the administrator's signature
7 minscript-security 1436.v1082791135e42026-09-16: 6 high-severity sandbox bypasses (fixed in 1422.x)★★★★★
Learning goals
  • Explain the real mechanism of the Groovy sandbox: AST transformation → every call passes through GroovyInterceptor → allowlist / denylist decision → RejectedAccessException.
  • Read signature formats (method / staticMethod / new / field), and distinguish “method signature approval” from “whole-script (SHA512 hash) approval”.
  • Use Approve / Deny / Approve assuming permissions check correctly, and recognize dangerous signatures that must be denied (such as Jenkins getInstance,RunWrapper getRawBuild,new java.io.File).
  • Understand trusted and untrusted Shared Libraries, Script Console, Run/Replay and forceSandbox and their place in governance.
Prerequisites: Lesson 2 CPS execution model (Groovy runs on the controller). Importance:★★★★★

What: two mechanisms

Groovy sandbox (Sandbox)Script approval (Script Approval)
For whomscripts with “Use Groovy Sandbox” checked: all Pipelines do this by defaultscripts not using the sandbox (whole-script approval), and individual signatures outside the sandbox allowlist
Granularityeach method call, constructor and field accesswhole script: by content hash (default SHA512: prefix); signature: by method class method parameter types
Who decidesallowlist (built-in + approved) and denylistOverall/Administer, in Manage Jenkins → In-process Script Approval
ScopeAll sandboxed scripts are treated the same; even Pipelines written by administrators are subject to the same restrictionsEffective globally: one approval, and the same script/signature is available to all Jobs and all plugins

How: how the sandbox intercepts calls

  1. When the CPS compiles a Jenkinsfile,SandboxTransformer rewrites the AST: a.b(c) becomes Checker.checkedCall(a, "b", c), constructors, properties and array access work the same way.
  2. At runtime SandboxInterceptor (GroovyInterceptor implementation) resolves the most general declared signature from the receiver's real type, and asks Whitelist: the built-in generic-whitelist, plugin-contributed allowlists, and administrator-approved signatures. “Dangerous” signatures on the denylist show a red warning on the approval page.
  3. Not allowed → throw RejectedAccessException, with a message like Scripts not permitted to use new java.io.File java.lang.String, and at the same time ScriptApproval.accessRejected adds the signature to the pending approval queue, and the build fails.
  4. After an administrator approves it, the signature is added to approvedSignatures (stored in $JENKINS_HOME/scriptApproval.xml), then rerun the build to pass.

Pipeline steps (sh,readFile,withCredentials…) do not need approval themselves: they are APIs provided by plugins that perform their own permission checks. What needs approval is direct calls to Java/Groovy/Jenkins internal objects.

The three approval buttons

ButtonEffectWhen to use
ApproveThe signature enters the allowlist and applies to all sandboxed scriptsPure functions and read-only methods that do not involve permissions, such as method java.lang.String toUpperCase
DenyRemoves it from pending (does not add it to the allowlist)File system, reflection,Jenkins.instance,getRawBuild, network, processes
Approve assuming permissions checkCalls are allowed, but only when the script runs as a real user; still rejected when running as SYSTEMMethods that perform ACL checks themselves, for example ItemGroup getItems (filtered by Job/Read)

Four easily overlooked things

  • Scripts saved by administrators are no longer auto-approved: older versions automatically approved scripts saved by administrators; this was disabled to prevent social-engineering attacks (README).
  • Global Shared Libraries are trusted: Global Pipeline Libraries configured in Manage Jenkins → System do not run in the sandbox; folder-level libraries do run in the sandbox. Write access to a global library repository ≈ administrator.
  • Script Console (/manage/script) = arbitrary code execution on the controller; only Overall/Administer can use it, and all use should be audited (the Audit Trail records Groovy use).
  • forceSandbox (“Force the use of the sandbox globally in the system”): in high-security environments, only sandboxed scripts are allowed, and the approval page stops creating new pending items; JCasC key security.scriptApproval.forceSandbox. In the source code it applies only to users who lack Overall/Administer and, when running outside the sandbox, reports Running scripts out of the sandbox is not allowed in the system.

Why: the sandbox must be kept up to date

The sandbox is “isolating untrusted code within the same JVM”, which is inherently hard. The 2026-09-16 advisory fixed 8 high-severity Script Security issues at once (6 sandbox bypasses + 1 classpath approval bypass + 1 TOCTOU race condition in the Update Center). For example, interface cast proxies did not check the proxied method (SECURITY-3929), and operations on null receivers were not intercepted (SECURITY-3931), affecting 1415.x and earlier, fixed in 1422.x; the current version is 1436.x. Anyone who can edit a Pipeline can use a sandbox bypass to execute arbitrary code on the controller, so Script Security is the top-priority tier for plugin updates (m5).

When

  • Logic that needs “privileges” (reading/writing Jenkins objects, calling internal APIs) → put it in a trusted global Shared Library, published after code review rather than by approving signatures.
  • When a team asks to approve a signature → first ask “can this be done with existing steps or plugins?”; when approval is unavoidable, record it in the JCasC approvedSignatures, with review traces.
  • Job DSL / Groovy system scripts → managed by the platform team in JCasC, not given to ordinary teams.
Common misconceptions① “Approval only affects this one Job”: approvals are global. ② “Pipelines written by administrators are not restricted by the sandbox”: the sandbox treats everyone the same; only scripts with the sandbox unchecked (which requires whole-script approval) or trusted libraries are exempt. ③ “Approving Jenkins getInstance only to read a Job name” gives access to the Jenkins singleton, which means access to every object, including credentials and system configuration. ④ “Disabling the sandbox and approving scripts is less work”: every script change needs re-approval, and approvers find it hard to see parameter-injection risks.

Architecture diagram: sandbox decision chain

Jenkinsfilenew File(p).text"x".toUpperCase() CPS compileSandboxTransformercall → Checker.checked* SandboxInterceptorresolved to the most general signaturenew java.io.File String Whitelist (ProxyWhitelist)① generic-whitelist (built-in)② plugin-contributed allowlist③ approvedSignatures (administrator)④ ACL allowlist (assuming permissions) allowcontinue execution denyRejectedAccessException In-process Script Approvalpending signature queueApprove / Deny /Approve assuming perms accessRejected() enqueues Denylist (dangerous signatures):Jenkins getInstance · getRawBuildapproval page shows a red warning
Figure 4-1: the sandbox decides on every call; rejected signatures enter the approval queue, and the build itself fails

Trust boundary: which Groovy is outside the sandbox

Outside the sandbox (equivalent to administrator capability) · Script Console (/manage/script, Overall/Administer) · Global Shared Library (Global Pipeline Libraries) · non-sandboxed scripts approved as a whole (by SHA512 hash) · Job DSL scripts in JCasC, init.groovy.d → write access = administrator privileges; must be code-reviewed Inside the sandbox (untrusted) · all Jenkinsfiles (Declarative / Scripted) · scripts modified via Run/Replay · folder-level Shared Libraries · Groovy plugin scripts with the sandbox checked (email-ext, etc.) → security = Script Security version + allowlist quality
Figure 4-2: every point outside the sandbox is a “privileged code entry” and should be countable and controllable

Core animation: sandbox interception → approval queue → administrator decision → rerun

Select a line of Jenkinsfile code, then step through the CPS transformation, the signature resolved by the interceptor, the allowlist decision and entry into the approval queue. At the “administrator decision” step, choose a button to see the consequences of approve/deny and the recommended practice.

CPS compile
Interceptor
Allowlist decision
Approval queue
Administrator decision
Rerun result
Choose code to start.
$ build #1 starts…

Core configuration and queries

Config / commandPurposeNotes
security.scriptApproval.approvedSignaturesManage approved signatures as codeJCasC key; review trail is kept; after a restart the YAML is authoritative
security.scriptApproval.forceSandboxForce sandboxPrevents new pending items from being created
security.scriptApproval.approvedScriptHashesWhole-script approval (hash)SHA512 by default; avoid if possible
ScriptApproval.get().pendingSignaturesList pending approvals in the Script Consolerequires Administer
$JENKINS_HOME/scriptApproval.xmlPersistence file for approval stateBackup and audit object
security:
  scriptApproval:
    forceSandbox: true
    approvedSignatures:
      # Every entry needs a review record (ticket number):
      - "method java.net.URI getHost"              # SEC-1234: parse the artifact repository hostname
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval
def sa = ScriptApproval.get()
println "pending signatures: " + sa.pendingSignatures*.signature
println "approved: " + sa.approvedSignatures.toList()
println "dangerous approved: " + sa.dangerousApprovedSignatures.toList()
println "forceSandbox: " + sa.forceSandbox
pending signatures: [new java.io.File java.lang.String]
approved: [method java.net.URI getHost]
dangerous approved: []
forceSandbox: true

How to verify:dangerousApprovedSignatures Must be empty. A non-empty result means someone approved a denylisted signature, which should be reviewed immediately. Common mistakes: An approval made in the UI is overwritten after a JCasC restart (the YAML is authoritative), or the reverse: UI-only approvals remain that were never put into code. Production use: Export the approval state weekly and check for differences (m7 audit).

# Trigger the script console from the command line (also requires Administer, and is recorded by the Audit Trail)
curl -s -u "admin:$(cat ~/jenkinslab/.secrets/admin_token)" \
  --data-urlencode 'script=println org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().forceSandbox' \
  http://127.0.0.1:8080/manage/scriptText

Lab 4: trigger a sandbox rejection and make the correct approval decision (about 7 min)

alice writes a Pipeline that “wants to read a controller file” (using the mkjob function from m3):
cat > /tmp/sandbox-demo.groovy <<'EOF'
pipeline {
  agent { label 'linux' }
  stages { stage('probe') { steps { script {
    echo 'MYAPP'.toLowerCase()                                   // on the allowlist
    def k = new File('/var/jenkins_home/secrets/master.key').text // will be intercepted
    echo "len=${k.length()}"
  } } } }
}
EOF
mkjob alice .secrets/alice_token team-a sandbox-demo /tmp/sandbox-demo.groovy
curl -s -X POST -u "alice:$(cat .secrets/alice_token)" "$J/job/team-a/job/sandbox-demo/build"; sleep 20
curl -s -u "alice:$(cat .secrets/alice_token)" "$J/job/team-a/job/sandbox-demo/lastBuild/consoleText" | grep -E 'myapp|Scripts not permitted|Finished'
myapp
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.File java.lang.String
Finished: FAILURE

Note: even if the sandbox lets it through, this Groovy still runs on controller the controller script {} (the block is not on an agent), which is exactly why it is dangerous.

Administrator reviews the pending approval and denies it: admin opens Manage Jenkins → In-process Script Approval, sees new java.io.File java.lang.String, and clicks Deny; or runs the query script from the “Commands” page in the Script Console to confirm the queue contents.
Provide an alternative: read workspace files with readFile step (runs on the agent, subject to permission constraints):
steps { script { def df = readFile 'Dockerfile'; echo "lines=${df.readLines().size()}" } }
Enable forceSandbox: change casc/10-security.yaml in forceSandbox: false to true, restart Jenkins, then try to create a Job that does not use the sandbox:
sed -i 's/forceSandbox: false.*/forceSandbox: true/' casc/10-security.yaml
docker compose restart jenkins && sleep 45
sed -e 's#<sandbox>true#<sandbox>false#' /tmp/job.xml > /tmp/job-nosb.xml
curl -s -o /dev/null -w '%{http_code}\n' -u "alice:$(cat .secrets/alice_token)" -H 'Content-Type: application/xml' \
  --data-binary @/tmp/job-nosb.xml "$J/job/team-a/createItem?name=nosandbox-demo"

Expected: alice is not an administrator, so forceSandbox applies to her (in the source code, isForceSandboxForCurrentUser() = forceSandbox and the current user lacks Administer). When you create or run the Job you will see Running scripts out of the sandbox is not allowed in the system (whether it is reported at save time or run time depends on the actual output); the approval page will not show new pending items. Run sandbox-demo again: it is still rejected, but new java.io.File no longer enters the pending approval queue.

Verify the approval state is clean: in the Script Console, dangerousApprovedSignatures is empty and forceSandbox is true.

Cleanup: Delete team-a/sandbox-demo,team-a/nosandbox-demo (if created); keep forceSandbox: true as the new baseline. Risk: Do not approve new java.io.File during the lab; approvals are global.

Case 1: a “temporary approval” for getRawBuild becomes a backdoor

Problem: A team asked an administrator to approve method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild so that a Pipeline could read upstream build logs. In a penetration test a year later, the tester used rawBuild to reach a Run object, then went on to other teams' builds and configuration. Fix: Revoke that signature; wrap the required capability into one function in a trusted global library (returning only the needed strings, performing permission checks internally), and publish it through code review. Limitations: Every change to a trusted library must be reviewed; write access to the library repository is managed at administrator level.

Case 2: emergency response to the Script Security sandbox bypass advisory

Problem: The 2026-09-16 advisory disclosed 6 sandbox bypasses (affecting 1415.x and earlier). Fix: Within 24 hours, upgrade script-security to 1422.x+ (custom image plugins.txt one-line change → CI builds the image → staging → production rolling update). Until the upgrade is complete, temporarily tighten: only trusted members may change Jenkinsfiles (branch protection), and pause Run/Replay authorization. Limitations: Pipeline-related plugins often need coordinated upgrades (Pipeline: Groovy Libraries also got a fix the same day); run regression tests in staging.

Case 3: 50 approval items per week, and administrators are overwhelmed

Problem: Teams are used to writing lots of Groovy logic in Jenkinsfiles. Fix: Enable forceSandbox; publish a “Pipeline authoring standard”: move logic into shell/Python scripts run on agents; put shared capabilities in trusted libraries; approvals may enter the JCasC approvedSignatures only through a ticket. Limitations: Teams need a migration period; a trusted library becomes a product of the platform team and needs versions and release notes.

RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance

Cause: The script tries to access the Jenkins singleton, which is a dangerous signature.

Fix: Do not approve it. Use existing steps instead (such as the build step to trigger downstream builds, or the allowlisted properties of currentBuild ), or wrap the minimum capability in a trusted global library.

org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedUsageException: script not yet approved for use

Cause: The current content (hash) of the non-sandboxed script was not approved; any single-character change requires re-approval.

println org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().pendingScripts*.script*.take(80)

Fix: Change the script to run in the sandbox; if privileges are really needed, move them to a trusted library or a script managed by JCasC.

Approved the signature, but the rerun still fails (same exception)

Cause: The approved signature differs from the actual one (different receiver type or parameter types); a JCasC restart overwrote the approval made in the UI; or the signature is on the denylist and blocked by the forceSandbox environment policy.

Fix: Copy the full signature from the exception; write the approval into JCasC; rerun (do not Replay the old script).

NotSerializableException appears after approving a signature

Cause: After approval the script can get Jenkins internal objects (such as Run or Item); storing them in a CPS variable fails during persistence (Lesson 2). This is usually also a sign that the signature should not have been approved.

Fix: Revoke the approval and use a step that returns simple values (String/Map), or a @NonCPS trusted library function.

Command-line questions
1. Write a Script Console script that lists all approved “dangerous” signatures.
println org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get().dangerousApprovedSignatures.toList()
2. Use JCasC to enable forced sandboxing and keep only one reviewed signature.
security:
  scriptApproval:
    forceSandbox: true
    approvedSignatures:
      - "method java.net.URI getHost"
Scenario analysis
A developer submits an approval request for method hudson.model.ItemGroup getItems, with the reason “list the Job names in the same folder for downstream triggering”. How do you handle it?

It is an ACL-aware method: when run as a real user it returns only the Jobs that user can read; when run as SYSTEM (the default build identity) it returns all Jobs. Approving it directly would let anyone who can create Jobs list the names of hidden Jobs. Choose “Approve assuming permissions check” (still rejected when running as SYSTEM) and combine it with Authorize Project so builds run as the triggering user (m6). A better approach is to call the Job directly by parameter or a conventional Job name build job: 'team-a/xxx'.

Verified videos

▶
Abusing Jenkins: Groovy Script Console
Pentester Academy TV · English · verified with oEmbed (2026-11-16)
Purpose: understand from an attacker's perspective that “Script Console = arbitrary code execution”, and why Administer cannot be delegated.
▶
How To Run a Groovy Script in Jenkins
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: the entry points of the Script Console and system Groovy.

No verified English video was found that specifically covers In-process Script Approval decisions; please use the storyboard below.

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: The Jenkinsfile is split into individual method calls, and before each call an inspector (interceptor) appears.
Narration: The sandbox rewrites every method call into “check the ticket first, then execute”; the ticket is the signature on the allowlist.
Shot 2 · 0:30–1:00
Visual: A call to new File is intercepted; a card with the signature flies into the “pending” basket, and the build turns red.
Narration: Rejected signatures enter the approval queue, and the build fails. Once approved, every Job can use that signature.
Shot 3 · 1:00–1:40
Visual: Three buttons in front of the administrator; Deny is selected, and the readFile alternative is shown.
Narration: What steps can solve, do not approve as a signature; what needs privilege goes into a trusted library, after code review.
Quiz ≥ 70% marks it automatically

Module 5 · Plugin security: vulnerability advisories and plugin governance

28:00 – 35:00 · Every plugin is code with full permissions inside the controller JVM; the fewer, newer and better maintained the plugins, the safer
7 minplugin-installation-manager-tool 2.16.0Update Center: 1568 warning records (2026-11-16)★★★★★
Learning goals
  • Understand the structure of Jenkins security advisories: SECURITY IDs, CVEs, CVSS, affected versions, fixed versions, and the “no fix available” lists.
  • Understand how the Update Center pushes advisories to each instance (warnings,deprecations,adopt-this-plugin labels, metadata signing), and the administrator warnings in Manage Jenkins.
  • Establish a plugin governance process: admission checklist, owners, pinned versions (plugins.txt + --latest=false), upgrade cadence, emergency patches, and retirement.
  • Decide what to do with plugins that have “no fix” (such as Parameterized Remote Trigger and folder-auth): remove, replace, or apply compensating controls.
Prerequisites: Lesson 1 plugin system and Update Center; Lesson 5 JCasC. Importance:★★★★★

What: where vulnerability information comes from

SourceContentHow to consume it
Security advisoriesOne page per date: affected components, each issue's SECURITY ID / CVE / CVSS, description, fixed versions, plugins with no fix availableSubscribe to the jenkinsci-advisories mailing list or RSS; create tickets from advisories
Update Center update-center.jsonwarnings (each entry has id, message, url, affected-version regex and lastVersion),deprecations, plugin labels (such as adopt-this-plugin),signatureJenkins downloads and verifies signatures daily; after matching installed plugins it shows warnings in Manage Jenkins
plugins.jenkins.ioEach plugin's version, release date, install count, dependencies, security warning history, health scoreReview these during admission
jenkins-plugin-cli--view-all-security-warnings,--available-updates,--listGate plugins.txt in CI

Quick look at recent advisories (relevant to this lesson)

DateComponentKey pointsFixes
2026-10-28Jenkins core15 issues: XStream resolves-to deserialization RCE (SECURITY-4125), collection element type check bypass, setup wizard race that can create an admin (SECURITY-4122), insufficient session expiry, Old Data Monitor injection taking over an admin, workspace browser XSS, etc.weekly 2.588 / LTS 2.580.2
2026-09-16Script Security and 13 other plugins6 sandbox / approval bypasses; Pipeline: Multibranch resolveScm can reach SYSTEM credentials (SECURITY-3729)script-security 1422.x; workflow-multibranch 842.x
2026-09-02core + 17 pluginscore deserialization → Script Console access (SECURITY-3972); SAML metadata overwrite (4065); Entra group display name privilege escalation (3935)LTS 2.568.3; saml 4.623.x; azure-ad 711.x; Parameterized Remote Trigger has no fix

Why: plugins are the largest attack surface

  • Plugins and the core run in the same JVM with no permission isolation: a small plugin with XSS or a missing permission check can become the entry point for taking over an administrator session.
  • Many plugins are in the “unmaintained” (adopt-this-plugin) state: a vulnerability found in them may never be fixed (the advisory says “no fixes are available”).
  • Transitive dependencies: installing one plugin may bring in a dozen dependencies; “we only installed 30” may really be 120.

How: the plugin governance process

  1. Admission: the requester explains the purpose and alternatives; check maintenance status (recent release, whether it is unmaintained), security warning history, install count and number of dependencies; assign an owner.
  2. Pin: plugins.txt each line carries a version; when building the image jenkins-plugin-cli --latest=false, check in CI --view-all-security-warnings the intersection of the output with plugins.txt.
  3. Cadence: follow LTS (a new baseline about every 12 weeks, with .2/.3 patches in between); batch plugin upgrades once a month; assess security advisories the same day, and ship high-severity fixes within 24–72 hours.
  4. Retirement: quarterly review of plugins that are “unused / unmaintained / have unfixed warnings”; before removal, verify in staging that no Job is affected.
  5. Deny list: for example permissive-script-security (makes the sandbox only log instead of blocking; tagged adopt-this-plugin; last released 2021),folder-auth (unfixed SECURITY-3062), and any plugin that is “convenient for disabling CSRF or the sandbox”.

When: how to handle a warning

SituationAction
A fixed version existsUpgrade (preferred), then go live after staging validation
No fix, and the plugin can be replacedMigrate to the alternative and then remove (e.g., Parameterized Remote Trigger → the target instance's API token + curl/httpRequest, or decouple through an event bus)
No fix yet, so it cannot be removed for nowcompensating controls: tighten related permissions, disable the related feature, add WAF rules; before “hiding” the warning in Manage Jenkins → Security, record the person accepting the risk and the deadline
Not affected (feature not enabled)hide the warning after recording the rationale, and re-check at the next upgrade
Common misconceptions① “LTS has no security issues”: almost every LTS patch release includes security fixes (2.580.2 is one). ② “A plugin that is not in use carries no risk”: an installed plugin, even if not configured, still loads code and HTTP endpoints. ③ “Pinned versions mean never upgrading”: pinning is for upgrading in a controlled way: each upgrade is a commit and review of plugins.txt. ④ “Automatic updates are the safest”: unreviewed automatic updates can introduce breaking changes or supply-chain risk, so they should go staging → production.

Architecture diagram: how advisories reach your Jenkins

Reporter / bounty programprivately reports SECURITY-xxxx Jenkins security teamcoordinates the maintainer's fix Advisory dayjenkins.io/security/advisoryfixed versions + no-fix listCVE assignment update-center.json (signed)warnings[]: id · url · versions.patterndeprecations · labelssignature (certificate chain verified) Your Jenkins controllerDownloads UC metadata daily → matches installed plugins with version regex → red warning in Manage JenkinsYour CI: jenkins-plugin-cli checks plugins.txt → blocks warned versions from entering images Your governance processmailing list / RSS → ticket → assess impact → upgrade or compensateGoal: fix high-severity issues in production within 24–72 hours
Figure 5-1: advisory → signed Update Center metadata → in-instance warnings + CI gate

Flowchart: plugin lifecycle

Requestpurpose · owner Admission reviewmaintenance · warnings · dependencies Pin versionplugins.txt + image Run + monitoradvisories · monthly upgrade Review / retireunused · unmaintained · no fix Upgrade = one commit changing plugins.txt
Figure 5-2: every plugin has an owner and an exit path

Plugin inventory scan and remediation simulator

Below is a “realistic” production plugin inventory (versions and warnings come from Update Center data as of 2026-11-16). Click “Scan” to match warnings one by one, then choose a remediation action for each plugin, and finally look at the risk score.

Click “Scan”.
$ jenkins-plugin-cli --plugin-file plugins.txt --view-all-security-warnings

Core commands

CommandPurposeKey parameters
jenkins-plugin-cli -f plugins.txt --latest=falseInstall by pinned versiondefault --latest=true will upgrade dependencies to the latest
jenkins-plugin-cli --view-all-security-warningsList all plugins with security warningsintersect with plugins.txt for a gate
jenkins-plugin-cli --available-updates -f plugins.txt --output txtList available upgrade versionsGenerate an upgrade PR
jenkins-plugin-cli --listinstalled / to download / effective plugin set--short-list top level only
GET /pluginManager/api/json?depth=1Plugin inventory of the running instancetree=plugins[shortName,version,hasUpdate,active]
jq '.warnings[]' update-center.actual.jsonRead Update Center warnings directlyby versions[].pattern match
# 1) Export the plugin inventory of the running instance (plugins.txt in fixed format)
J=http://127.0.0.1:8080; cd ~/jenkinslab
curl -s -u "admin:$(cat .secrets/admin_token)" "$J/pluginManager/api/json?depth=1&tree=plugins[shortName,version]" \
  | jq -r '.plugins[] | "\(.shortName):\(.version)"' | sort > plugins.txt
wc -l plugins.txt; grep -E '^(script-security|matrix-auth|role-strategy):' plugins.txt
97 plugins.txt
matrix-auth:3.3
role-strategy:928.vc60b_edb_fea_e1
script-security:1436.v1082791135e4
# 2) Check warnings and available updates in the controller container with plugin-cli (no install)
docker compose cp plugins.txt jenkins:/tmp/plugins.txt
docker compose exec jenkins jenkins-plugin-cli -f /tmp/plugins.txt --no-download --available-updates --output txt | head
docker compose exec jenkins jenkins-plugin-cli --view-all-security-warnings --no-download | grep -iE 'script-security|saml|azure-ad|folder-auth|Remote-Trigger'
folder-auth - Disabled permissions can be granted SECURITY-3062 https://www.jenkins.io/security/advisory/2025-01-22/#SECURITY-3062
Parameterized-Remote-Trigger - Tokens stored in plain text SECURITY-3800 https://www.jenkins.io/security/advisory/2026-09-02/#SECURITY-3800
script-security - Sandbox bypass vulnerability SECURITY-3929 https://www.jenkins.io/security/advisory/2026-09-16/#SECURITY-3929
...

Note:--view-all-security-warnings What is listed is all historical warnings in the Update Center; this does not mean your version is affected. To determine whether you are affected, match your version against the warning's version regex (the script below), or check the warnings in Manage Jenkins. --no-download Check only, no download (per the help output of 2.16.0).

# 3) Precise check: match plugins.txt against the Update Center version regex
curl -sL https://updates.jenkins.io/current/update-center.actual.json -o /tmp/uc.json
python3 - plugins.txt /tmp/uc.json <<'EOF'
import json,re,sys
inst=dict(l.strip().split(':',1) for l in open(sys.argv[1]) if ':' in l)
uc=json.load(open(sys.argv[2]))
for w in uc['warnings']:
    v=inst.get(w['name'])
    if v and any(re.fullmatch(x['pattern'],v) for x in w['versions']):
        print(f"AFFECTED {w['name']}:{v} {w['id']} {w['message']} {w['url']}")
EOF
(no output = no affected versions in plugins.txt)

Lab 5: build a plugin gate for jenkinslab (about 7 min)

Export the inventory and scan: run items 1) and 3) on the “Commands” page to confirm that no plugin is affected at present.
Simulate an “old version”: in a copy, change script-security to a version from before 2026-09, then run the matching script.
sed 's/^script-security:.*/script-security:1415.v9a_f9b_3a_c253d/' plugins.txt > /tmp/plugins-old.txt
python3 - /tmp/plugins-old.txt /tmp/uc.json <<'EOF' | sort | uniq -c | sort -rn | head
import json,re,sys
inst=dict(l.strip().split(':',1) for l in open(sys.argv[1]) if ':' in l)
uc=json.load(open(sys.argv[2]))
for w in uc['warnings']:
    v=inst.get(w['name'])
    if v and any(re.fullmatch(x['pattern'],v) for x in w['versions']): print(w['name'], w['message'])
EOF
      6 script-security Sandbox bypass vulnerability
      1 script-security TOCTOU race condition
      1 script-security Classpath approval bypass vulnerability
Turn it into a CI gate: save it as ~/jenkinslab/ci/plugin-gate.sh; any output fails the build (exit code 1).
#!/usr/bin/env bash
set -euo pipefail
PLUGINS=${1:-plugins.txt}
curl -fsSL https://updates.jenkins.io/current/update-center.actual.json -o /tmp/uc.json
out=$(python3 - "$PLUGINS" /tmp/uc.json <<'EOF'
import json,re,sys
inst=dict(l.strip().split(':',1) for l in open(sys.argv[1]) if ':' in l and not l.startswith('#'))
uc=json.load(open(sys.argv[2]))
deny={'permissive-script-security','folder-auth'}
for n in inst:
    if n in deny: print(f"DENYLIST {n}")
for w in uc['warnings']:
    v=inst.get(w['name'])
    if v and any(re.fullmatch(x['pattern'],v) for x in w['versions']):
        print(f"AFFECTED {w['name']}:{v} {w['id']} {w['url']}")
EOF
)
[ -z "$out" ] && { echo "plugin gate: OK"; exit 0; }
echo "$out"; exit 1
chmod +x ci/plugin-gate.sh
ci/plugin-gate.sh plugins.txt; echo "exit=$?"
ci/plugin-gate.sh /tmp/plugins-old.txt | head -3; echo "exit=${PIPESTATUS[0]}"
plugin gate: OK
exit=0
AFFECTED script-security:1415.v9a_f9b_3a_c253d SECURITY-3929 https://www.jenkins.io/security/advisory/2026-09-16/#SECURITY-3929
AFFECTED script-security:1415.v9a_f9b_3a_c253d SECURITY-3931 https://www.jenkins.io/security/advisory/2026-09-16/#SECURITY-3931
AFFECTED script-security:1415.v9a_f9b_3a_c253d SECURITY-3923 https://www.jenkins.io/security/advisory/2026-09-16/#SECURITY-3923
exit=1
Check the warnings inside the instance: admin opens Manage Jenkins and confirms that the top of the page does not show “Warnings have been published for the following currently installed components”; then open Manage Jenkins → Plugins → Installed and check whether any plugins are marked as unmaintained or deprecated.

Cleanup: Delete /tmp/plugins-old.txt /tmp/uc.json; plugins.txt and ci/plugin-gate.sh are kept for the m7 custom image build. Cost: None.

Case 1: 48 hours after the 2026-10-28 core advisory

Problem: The advisory disclosed 15 core issues; the XStream deserialization RCE needs only Overall/Read plus any account, or certain Configure permissions. Fix: T+0 assessment: all instances on 2.580.1 and earlier are affected. T+4h: upgrade staging to 2.580.2 and run smoke tests (login, SSO, Pipeline, JCasC reload). T+24h: production rolling update (change the image tag in Helm / change the tag in Compose). At the same time, check whether anyone has set the rollback system property mentioned in the advisory (such as hudson.util.XStream2.SUPPRESS_TYPE_PERMISSION). Limitations: The new XStream type allowlist may affect a few old plugins; catch ForbiddenClassException class errors in staging.

Case 2: Parameterized Remote Trigger has no fix

Problem: The advisories of 2026-08-05 and 2026-09-02 (credential ID enumeration, plaintext token storage) have no fix, yet 30 Jobs depend on it to trigger across instances. Fix: Write a trusted library function triggerRemote(url, job, tokenCredId), implemented with httpRequest + API token (folder credentials); replace in bulk with Job DSL; finally remove it from plugins.txt and add it to the gate's deny list. Limitations: During the transition, narrow the group of people with Job/Configure, and rotate all tokens that were ever saved in this plugin.

Case 3: reducing 230 plugins to 95

Problem: Legacy instances have many plugins, and upgrades often fail. Fix: Use /pluginManager/api/json + Job configuration scanning (grep config.xml for plugin class names) to find unused plugins; review quarterly; every new plugin must have an owner. Result: Upgrade time dropped from 2 days to 2 hours, and the average time to handle a security warning dropped from 3 weeks to 3 days. Limitations: Some plugins are used only in global configuration or JCasC, so scanning Job configuration misses them; combine it with a JCasC export.

Warnings have been published for the following currently installed components

Cause: A warning's version regex in the Update Center metadata matched an installed plugin.

Fix: Click the warning link to read the advisory → upgrade to the fixed version → if there is no fix, remove the plugin, or record the risk acceptance and then hide the warning (Manage Jenkins → Security → Hidden security warnings).

Jenkins fails to start after a plugin upgrade: Failed to load: ... (requires Jenkins 2.580.x or higher)

Cause: The plugin's requiredCore minimum Jenkins version is above the current core version, or a dependency was pulled --latest=true up to a version that needs a higher core.

docker compose logs jenkins 2>&1 | grep -E 'Failed to load|requires' | head

Fix: Upgrade the core first or choose a compatible plugin version; when building the image, pass --jenkins-version and --latest=false; roll back by restoring the plugins/ directory from backup.

Update site ... signature verification failed / unable to fetch Update Center data

Cause: Outbound proxy or firewall blocking, a TLS man-in-the-middle proxy rewriting content, or a self-hosted mirror that is not signed correctly.

Fix: Allow access to updates.jenkins.io; when self-hosting an Update Center mirror, use the official metadata or your own signing certificate and configure trust; do not “fix” this by disabling signature verification.

Command-line questions
1. Write the command that, when building the image, uses only the pinned versions in plugins.txt (dependencies take the minimum satisfying version).
FROM jenkins/jenkins:2.580.2-jdk21
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt --latest=false
Scenario analysis
Friday afternoon advisory: a plugin you use has a high-severity vulnerability with “no fix available”. What do you do within 2 hours?

① Read the advisory to confirm the affected feature and the required permissions (for example, whether Item/Configure is needed, and whether it can be exploited anonymously); ② inventory the Jobs that use this plugin (search config.xml / JCasC); ③ compensate immediately: tighten related permissions, disable the affected features or Jobs, and if necessary temporarily disable the plugin (Manage Jenkins → Plugins → uncheck enable, restart); ④ rotate the tokens and secrets stored in the plugin; ⑤ set a replacement plan and a removal timetable; ⑥ add it to the gate's deny list to prevent it from being reintroduced.

Verified videos

▶
Understanding Security soft-spots of Jenkins | Importance of Jenkins security advisory | OpsMx
OpsMx · English · verified with oEmbed (2026-11-16)
Purpose: the importance of security advisories and common weak points.
▶
Common Pitfalls in Jenkins Security and How to Avoid Them
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: common traps at the plugin and configuration level (shared with Module 1).

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: On the advisory page, line after line of SECURITY IDs flows into a signed update-center.json package, delivered to each Jenkins.
Narration: After an advisory is published, the Update Center carries the warnings to every instance; but the real fix depends on your upgrade process.
Shot 2 · 0:30–1:10
Visual: plugins.txt enters CI; the gate script marks the vulnerable versions in red, and the build fails.
Narration: Pin plugins in plugins.txt, so every upgrade is a reviewable commit; vulnerable versions cannot pass the gate.
Quiz ≥ 70% marks it automatically

Module 6 · controller and agent isolation, builds running on agents

35:00 – 42:00 · The controller is the “crown jewel”: builds do not run on it, agents cannot command it, and builds run as a real identity
7 minAgent → Controller access control: always on since 2.326authorize-project 534.x★★★★★
Learning goals
  • Set the built-in node's executors to 0, and understand why building on the controller is equivalent to handing JENKINS_HOME (including secrets/) to the build script's author.
  • Explain what Agent → Controller access control protects (a compromised agent cannot make the controller run arbitrary commands or read controller files), and what it does not protect (other builds on the same agent, and secrets passed to the agent).
  • Use Authorize Project so builds run as the triggering user, and experience the chained effects on Agent/Build permissions, scheduled builds and credential lookup.
  • Divide agents by trust level: labels are not a security boundary; use node permissions, Job Restrictions or a separate controller to isolate production deployment capability.
Prerequisites: Lesson 1 controller / agent / executor; Lesson 5 Kubernetes Pod agent. Importance:★★★★★

What: three layers of isolation

IsolationMechanismConfigurationWhat it blocks
Don't build on the controllerexecutors of built-in node = 0JCasC jenkins.numExecutors: 0; or the Job Restrictions plugin limits which Jobs may use built-inbuild scripts directly reading and writing JENKINS_HOME (secrets/master.key,credentials.xml, all Job configuration)
Agent → Controller access controlOn the Remoting channel, commands (Callables) and file access that an agent sends to the controller must be explicitly allowedsince 2.326 always on, cannot be turned off or customized (the older whitelisted-callables.d and filepath-filters.d rules apply only to 2.325 and earlier)A compromised agent making the controller run commands and read controller files
Build identityQueueItemAuthenticator (Authorize Project plugin)Globally: run as the triggering user / a specified user / anonymous; or allow each project to chooseRunning as SYSTEM means “anyone who can modify a Job inherits SYSTEM's capabilities” (trigger any downstream job, run on any node, use system GLOBAL credentials)

Why: who controls the build?

The official documentation lists users with Job/Configure, build script authors (pom.xml,Makefile) and code authors (test code runs during the build). All of them can influence the commands executed during the build,and all of them are at a lower trust level than Jenkins administrators. On the built-in node, the build process and the Jenkins process are the same OS user, so they can read everything.

How: Agent → Controller access control

  • The controller and agents form a “distributed process” via the Remoting channel: usually the controller sends Callable to the agent for execution (such as sh steps and file operations).
  • The reverse direction (an agent asking the controller to execute) also exists, but plugins must declare a role for each Callable (RoleChecker); commands that are undeclared, or declared as “execute only on agents”, are refused by the controller.
  • It does not protect: after the agent itself is compromised,other builds running on that agent, the credentials passed through it, or the network resources it can reach. So divide agents by trust level.

How: build identity (Authorize Project)

PolicyEffectNotes
Run as the user who triggered the buildBuild runs as the triggering userREADME: Not applicable to scheduled/polled builds; the user must be granted permissions such as Agent/Build
Run as a specific userRun as a service accountNon-administrators who specify another user must provide that user's password or API token; only administrators and that user can change the configuration
Run as anonymousNo permissions at allSuited to untrusted PR builds that only compile but do not deploy
Run as SYSTEMOnly used to override global settingsPlugins may treat SYSTEM as anonymous

After enabling, node assignment checks whether the build identity has the Agent/Build permission on that agent (if not, the build waits in the queue and shows the reason); build a step that triggers a downstream build checks Job/Build; credential lookup also runs as this identity (the actual visible scope depends on the Credentials plugin's permission settings; verify in staging).

When: how to divide agents

  • Untrusted (Fork PRs, external contributors): one-off agents (Kubernetes Pod / temporary VM), anonymous identity, no credentials, no production network.
  • Team builds: agent pools per team or per trust level; for container builds use rootless / BuildKit / Kaniko-style approaches,avoid mounting the host Docker socket.
  • Production deployment: dedicated agents, where only Jobs in specific folders may use them (node authorization matrix + build identity, or Job Restrictions), and only this agent can reach production on the network.
  • When trust levels differ greatly (for example, open-source projects vs. internal production releases) → separate controllers, rather than distinguishing them by configuration within a single controller.
Common misconceptions① “Using labels confines production deployment to dedicated agents”: the label is written in the Jenkinsfile, and the author can freely change it to the production agent's label; you need node permissions + build identity, or Job Restrictions. ② “Agent → Controller access control can be turned off to stay compatible with old plugins”: it cannot be turned off since 2.326; old plugins must be updated. ③ “It's convenient for agent1 to use Docker”: mounting the /var/run/docker.sock socket on an agent lets any build docker run -v /:/host obtain host root; this course's agent1 is exactly this trade-off and suits only local labs. ④ “With 0 executors on the controller, Pipelines no longer run on the controller”: a Pipeline's Groovy (CPS) still runs on the controller, executed by the flyweight executor; so Script Security still matters.

Architecture diagram: trust zones

controller (built-in node: 0 executors) JENKINS_HOME: secrets/master.key · credentials.xmlPipeline CPS (flyweight executor) + Script SecurityAgent → Controller access control (always on)QueueItemAuthenticator: build identity Untrusted: PR / Forkone-off Pod · anonymous identityno credentials · no production network Team build pooltriggering user identity · folder credentialsrootless image build Production deployment agentnode matrix: only the deploy service accountManaged identity · production network Remoting (controller → agent)
Figure 6-1: the controller does not build; agents are pooled by trust level; production capability exists only on dedicated agents

Data flow: identity and node checks for one build

alice triggersJob/Build ✓ QueueItemAuthenticatorbuild identity = alice select nodelabel linux → agent1 Node.canTakeDoes alice have Agent/Build? execute / blockqueue why When running as SYSTEM this step always passes. This is why labels cannot restrict production agents.
Figure 6-2: build identity makes “node permissions” actually take effect

Simulator: where builds run and what they can reach

Choose where the build runs, the build identity, and what the build script tries to do, then step through the mechanisms that actually take effect (or are missing) in Jenkins.

Scheduling
Identity / permissions
Execution environment
Remoting
Result
Choose, then start.
$ waiting for scheduling…

Core configuration and commands

Config / commandPurposeNotes
jenkins.numExecutors: 0built-in node does not run buildsPipeline CPS still runs on the controller's flyweight executor
security.queueItemAuthenticator.authenticators[].global.strategyglobal build identitytriggeringUsersAuthorizationStrategy etc.
on the node's authorizationMatrixwho can build on this agentOnly meaningful when the build identity is not SYSTEM
GET /queue/api/json?tree=items[task[name],why]Check why the queue is blockedInsufficient permissions and no matching label are both shown in “why”
GET /computer/api/json?tree=computer[displayName,numExecutors,offline]Nodes and executorsConfirm built-in is 0
security:
  queueItemAuthenticator:
    authenticators:
      - global:
          strategy: "triggeringUsersAuthorizationStrategy"
jenkins:
  authorizationStrategy:
    projectMatrix:
      entries:      # Note: the same key can be defined in only one file; when operating, merge it into 10-security.yaml
        - user: { name: admin, permissions: [Overall/Administer] }
        - group: { name: authenticated, permissions: [Overall/Read] }
        - user: { name: carol, permissions: [Job/Read, View/Read] }
        - user: { name: alice, permissions: [Agent/Build] }
        - user: { name: bob,   permissions: [Agent/Build] }
J=http://127.0.0.1:8080; T=$(cat ~/jenkinslab/.secrets/admin_token)
curl -s -u "admin:$T" "$J/computer/api/json?tree=computer[displayName,numExecutors,offline]" | jq -c '.computer[]'
curl -s -u "admin:$T" "$J/queue/api/json?tree=items[task[name],why]" | jq -c '.items[]'
{"displayName":"Built-In Node","numExecutors":0,"offline":false}
{"displayName":"agent1","numExecutors":2,"offline":false}
{"task":{"name":"myapp"},"why":"‘alice’ lacks permission to run on ‘agent1’"}

How to verify: Built-In Node is 0; when triggering-user identity is enabled but Agent/Build is not granted, the queue “why” shows insufficient permissions. Common mistakes: Scheduled builds have no “triggering user” under the triggering-user policy and appear as anonymous. You need to configure “run as a specified service account” for these Jobs. Production use: Grant the deploy agent's node matrix only to the deploy service account, and have the release Job run as that account.

# Review the Docker socket trade-off on agent1 (the choice made in Lesson 1)
docker compose exec agent1 sh -c 'ls -l /var/run/docker.sock 2>/dev/null || echo "docker.sock not mounted"'
docker compose exec agent1 id

Lab 6: controller 0 executors + build as the triggering user (about 7 min)

Verify built-in node does not take work: create a Job that deliberately specifies built-in.
cat > /tmp/builtin-probe.groovy <<'EOF'
pipeline { agent { label 'built-in' }
  stages { stage('x') { steps { sh 'ls $JENKINS_HOME/secrets' } } } }
EOF
mkjob alice .secrets/alice_token team-a builtin-probe /tmp/builtin-probe.groovy
curl -s -X POST -u "alice:$(cat .secrets/alice_token)" "$J/job/team-a/job/builtin-probe/build"; sleep 15
curl -s -u "admin:$(cat .secrets/admin_token)" "$J/queue/api/json?tree=items[id,task[name],why]" | jq -c '.items[]'
{"id":31,"task":{"name":"builtin-probe"},"why":"Waiting for next available executor on ‘Built-In Node’"}

The build will never start on the controller. Cancel it: curl -X POST -u admin:$T "$J/queue/cancelItem?id=31".

Enable “run as the triggering user”: in casc/10-security.yaml of security: add queueItemAuthenticator section (see the “Commands” page); first do not grant alice Agent/Build; after a restart, have alice trigger team-a/myapp, and observe the queue:
{"task":{"name":"myapp"},"why":"‘alice’ lacks permission to run on ‘agent1’"}
Grant node permissions: in the global matrix, add Agent/Build for alice and bob (in production, it is better to grant this to team groups in the agent node properties); after a restart, the build starts running.
Observe the difference for scheduled builds: add team-a/myapp to triggers { cron('H/5 * * * *') } (committed through the Jenkinsfile in Gitea). After 5 minutes, check whether the timer-triggered build is blocked (no triggering user → treated as anonymous, with no Agent/Build). Conclusion: scheduled or polled Jobs need “run as a specified user”.
Confirm Agent → Controller access control cannot be turned off: admin opens Manage Jenkins → Security; there is no “Agent → Controller Security” switch on the page (removed since 2.326).

Cleanup: Delete team-a/builtin-probe; if you do not want to keep the triggering-user identity policy, delete queueItemAuthenticator section and restart (later capstone labs will enable it again). Risk: Enabling build identity may cause existing Jobs to queue because of missing Agent/Build or credential permissions; rehearse in staging first in production.

Case 1: “We set 0 executors long ago”, but builds still run on the controller

Problem: A security audit found that a team's build could read JENKINS_HOME. Cause: a “local agent” process was started on the controller host, running as the same OS user as Jenkins. Fix: According to the official docs, an agent on the same machine must run as a different OS user, and have JENKINS_HOME no read/write permission and no sudo; eventually migrate to a Kubernetes Pod agent. Limitations: Same-host isolation still shares the kernel and is only a transitional measure.

Case 2: label changed to the production agent

Problem: A developer wrote agent { label 'prod-deploy' } into the Jenkinsfile on a feature branch; the build ran as SYSTEM on the production deploy agent and gained production network access. Fix: Enable Authorize Project (triggering-user identity); grant the deploy agent's node matrix only to svc-deploy; put the release Job in the release folder, configure “run as svc-deploy”, and only the release group can configure that folder. Limitations: All Jobs need their Agent/Build authorizations reviewed; some older plugins have poor compatibility with non-SYSTEM identities.

Case 3: lateral movement via the Docker socket

Problem: To make image builds convenient, all agents mounted the host's docker.sock; a test with poisoned dependencies started a privileged container during the build, and read other builds' workspaces and cached cloud credentials on the host. Fix: Switch to Kubernetes Pod agents + daemonless image builds (BuildKit rootless / Kaniko-style), and enable Pod Security Admission in the namespace restricted; change cloud credentials to workload identity (Lessons 3 and 4). Limitations: Some builds that depend on Docker-in-Docker behavior need to be reworked.

‘alice’ lacks permission to run on ‘agent1’ (the build keeps waiting in the queue)

Cause: Triggering-user identity is enabled, and the build identity does not have Agent/Build on that node.

Fix: Grant Agent/Build to the team group in the node properties or the global matrix; or configure the Job to run as a service account.

Waiting for next available executor on ‘Built-In Node’

Cause: The Job explicitly specifies the built-in label (or the old name master), while the controller executors are 0. This is the expected behavior.

Fix: Change it to an agent label; work that must happen on the controller (such as orchestration) is done by the Pipeline itself and does not need an executor.

java.lang.SecurityException: agent-to-controller call rejected (after upgrading old plugins to 2.326+)

Cause: A plugin's Remoting Callable did not declare a role, or tried to make the controller run a command, and was rejected by Agent → Controller access control.

docker compose logs jenkins 2>&1 | grep -iE 'SecurityException|agent.*controller|RoleChecker' | tail -5

Fix: Upgrade the plugin; if there is no update, replace the plugin. It cannot be allowed through configuration (custom rules were removed in 2.326).

After enabling build identity: ERROR: Could not find credentials entry with ID '…'

Cause: Credential lookup now runs as the triggering user, who does not have use permission in the context where the credential lives, or the build was triggered on a schedule (anonymous).

Fix: Put the credential in the team's folder and confirm the team members' permissions; have scheduled Jobs run as a specified service account; verify key Pipelines one by one in staging.

Command-line questions
1. Use one command to list the executor count of every node and confirm built-in is 0.
curl -s -u "admin:$T" "$J/computer/api/json?tree=computer[displayName,numExecutors]" | jq -r '.computer[] | "\(.displayName)\t\(.numExecutors)"'
Scenario analysis
The same Jenkins runs Fork PRs for open-source projects and also production releases. How would you design the isolation?

Preferably split into two controllers, since the trust levels differ too much. If they must coexist: Fork PRs use one-off Pod agents + anonymous identity + no credentials + network isolation; production releases go in a separate folder, run as a service account, and only that account has Agent/Build on the deploy agent; controller 0 executors; Script Security kept up to date with forceSandbox enabled; PR builds do not read Fork changes to the Jenkinsfile (use the Jenkinsfile from a trusted branch; see the trust settings for Multibranch in Lesson 2).

Verified videos

▶
What Is a Jenkins Agent?
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: a review of the controller / agent division of labor, as the starting point for this module's isolation design.

No verified English video specifically covering Agent → Controller access control or Authorize Project was found; please use the storyboard.

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: The controller is a vault; the number of workstations at the door drops from 2 to 0.
Narration: The vault does no work: built-in node executors are set to zero, and builds all go to agents.
Shot 2 · 0:30–1:00
Visual: A compromised agent passes a note to the vault: “help me read a file”, and the guard refuses.
Narration: Starting from 2.326, agent-to-controller access control is always on and cannot be turned off.
Shot 3 · 1:00–1:40
Visual: The build wears the triggering user's badge and is stopped at the door of the production agent.
Narration: Only when builds run as a real identity do node permissions take effect; labels are not a security boundary.
Quiz ≥ 70% marks it automatically

Module 7 · Audit, compliance and supply chain security

42:00 – 50:00 · You can call it governable only when you can answer “who changed what and when, and where build artifacts come from”
8 minaudit-trail 472.x · jobConfigHistory 1380.xsyft v1.57.2 · cosign v3.1.4★★★★☆
Learning goals
  • Use Audit Trail to record configuration changes, build triggers, login events, credential use and Groovy script use, and send the logs to a centralized system.
  • Use Job Config History + JCasC/Git to answer “who changed the configuration, when, and to what”.
  • Protect Jenkins' own supply chain: pin core image digests and plugin versions, build custom images, generate SBOMs, and sign them.
  • Protect the build artifact supply chain: generate an SBOM, scan and sign the myapp image, and verify it on the deployment side; know what Jenkins natively does not provide (SLSA provenance attestations, OIDC identities trusted by the public Sigstore Fulcio).
Prerequisites: m5 plugin pinning; image builds from the Docker course. Importance:★★★★☆

What: three levels of auditing

LevelToolWhat is recordedLimitations
Requests / eventsAudit Trail PluginRecords requests by URI regex (by default covers creating, configuring and deleting Jobs and views, starting and stopping builds, restarts, etc.); optionally records build causes, credential use, Groovy script use (such as Script Console), and login success/failure/logout; output to file, Syslog, console, ElasticsearchRecords “who did the action”, not the differences in configuration content; custom URI regexes can be bypassed (the plugin documentation has a note on bypassable patterns), so prefer the default patterns
Configuration diffJob Configuration HistorySaves an XML history each time a Job or system configuration is saved; differences can be compared and rolled backStored in JENKINS_HOME; the 2026-09-02 advisory has a fix (1380.x), so keep it updated
Declarative source of truthJCasC + Job DSL + GitGlobal security, authorization, credential references and Job definitions are all code; the PR is the approval recordUI “temporary changes” drift from code; use periodic JCasC reloads or make UI changes read-only

What: two lines of supply chain

Jenkins itself (platform supply chain)Build artifacts (application supply chain)
Pincore images by digest pinned; plugins.txt all with versions; --latest=falsedependency lock files; base image digests; Shared Libraries use version tags @Library('lib@v1.4.2')
Trusted sourceUpdate Center metadata signatures, Linux package repository GPG (new signing key used since 2.541.1 5E386EAD…ABFC68)read Jenkinsfiles only from trusted branches; signed source commits
SBOMrun syft on the custom Jenkins imagerun syft on the myapp image (SPDX / CycloneDX)
Signatures / attestationscosign sign the custom imagecosign sign the image + attach SBOM attestation; the deployment side (admission controller) verifies
ScanningImage vulnerability scanning + m5 plugin gateImage and dependency scanning, with threshold gates

Why

Compliance audits (SOC 2, ISO 27001, etc.) typically require traceable changes, separation of duties, approved production deployments, and provable artifact provenance. Jenkins is where “code becomes production”, and attackers most want to poison it here: tampering with Jenkinsfiles, introducing malicious plugins, replacing build artifacts. Auditing makes things traceable afterwards; supply-chain controls prevent them beforehand.

How: Jenkins' role in signing

  • Jenkins The core does not natively issue OIDC identity tokens, and does not include SLSA provenance generation. The community has OpenID Connect Provider plugin (oidc-provider 234.x), which can turn Jenkins into an OIDC issuer and provide ID tokens to builds as credentials (the Entra ID plugin documentation uses it for federated credentials). However, the public Sigstore Fulcio only trusts the issuers it supports, so do not assume your Jenkins can do public “keyless signing” directly.
  • Pragmatic approach: keep signing keys in KMS / Key Vault / Vault (cosign supports azurekms://,awskms://,hashivault://), invoked by a dedicated signing Job that runs as a service account; Jenkins holds only the identity that accesses KMS.
  • cosign v3's sign-blob by default writes records to the transparency log (public Rekor) according to the signing configuration; for an intranet setup, use the private infrastructure's --signing-config, and have the verifier use it accordingly --trusted-root or (not recommended) --insecure-ignore-tlog.

When

  • For any production Jenkins: Audit Trail (sent to a centralized log, retained ≥ 1 year) + JCasC/Git; Job Config History as a supplement.
  • Regulated industries: add a “deployment approval record” (input step's committer + ticket number written into the build description); SBOMs and signatures are archived with the artifact.
  • Multi-instance platform: all controllers use the same custom image (same plugins.txt); the only difference is in JCasC.
Common misconceptions① “With Audit Trail we know what configuration changed”: it records actions, not differences; for differences see Job Config History or Git. ② “Audit logs in JENKINS_HOME are enough”: administrators (or an attacker who compromised the controller) can modify them; they must be shipped in real time to append-only centralized storage. ③ “An SBOM is a security scan”: an SBOM is an inventory; scanning is a judgment based on that inventory; you need both, plus signatures to prevent tampering. ④ “Jenkins can directly use Sigstore keyless signing”: it requires a trusted OIDC issuer, and Jenkins is not one by default.

Architecture diagram: audit data flow

Jenkins controller Audit Trail: /job/…/configSubmit by alicelogin success/failure · credential use · Script Console Job Config History: XML diff build records: trigger reason, input approver JCasC source: Git commit + PR review Syslog / Fluent Bitreal-time forwarding SIEM / centralized logsappend-only · retained ≥ 1 yearAlerts: Script Console use,authorization policy changes, spikes in login failures Git (JCasC / Job DSL / plugins.txt)Changes = PR: author, reviewer, timestamp, diffPeriodically compare the “exported running configuration” with the repository to detect drift
Figure 7-1: actions (Audit Trail) + differences (Config History / Git) + centralized append-only storage

Flowchart: signed build pipeline

Committrusted branch build and testone-off agent imagebase image digest SBOMsyft Scan gateany high severity fails Signing + attestationcosign · KMS key Deployment-side verificationadmission controller Each step is written to the build record and the audit log; the signing key is used through KMS only in a dedicated signing Job
Figure 7-2: every step from commit to deployment of the artifact is verifiable

Supply chain pipeline and attack injection

Run a myapp release pipeline step by step; the corresponding audit events appear on the right at the same time. Select an “attack injection” and see at which step it is detected (or missed).

Commit / checkout
build and test
image + SBOM
scan gate
sign and push
deployment verification
pipeline log
$ waiting…
audit events
audit.log
Choose, then start.

Core configuration and commands

Config / commandPurposeNotes
unclassified.audit-trailJCasC configuration auditloggers: logFile / console / syslog / Elasticsearch; logBuildCause
docker buildx imagetools inspectget the image digestpin by digest in FROM
syft <image> -o spdx-jsongenerate SBOMalso supports cyclonedx-json
cosign sign-blob --key … --bundle …signed files (such as SBOM)v3: --bundle output verification material
cosign verify-blob --key … --bundle …verify signaturesused together with private infrastructure --trusted-root
cosign sign --key … <image@digest>sign the imagethe image must be in a registry (such as ACR/ECR from Lessons 3 and 4)
unclassified:
  audit-trail:
    logBuildCause: true
    displayUserName: false
    loggers:
      - logFile:
          log: "/var/jenkins_home/audit/audit-%g.log"
          limit: 25          # MB
          count: 10
      - console:             # also write to stdout, for collection by docker logs / Fluent Bit
          output: STD_OUT
          dateFormat: "yyyy-MM-dd HH:mm:ss.SSS"
          logPrefix: "AUDIT"
    # do not set a pattern: use the plugin's default URI patterns (custom regexes can be bypassed)
cd ~/jenkinslab
docker compose exec jenkins mkdir -p /var/jenkins_home/audit
docker compose restart jenkins && sleep 45
# trigger a few auditable actions
curl -s -X POST -u "alice:$(cat .secrets/alice_token)" http://127.0.0.1:8080/job/team-a/job/myapp/build
curl -s -o /dev/null -u "bob:wrong-password" http://127.0.0.1:8080/whoAmI/api/json
docker compose logs jenkins 2>&1 | grep AUDIT | tail -5
docker compose exec jenkins sh -c 'tail -5 /var/jenkins_home/audit/audit-0.log'
AUDIT 2026-11-16 21:04:11.204 - /job/team-a/job/myapp/build by alice from 172.18.0.1
AUDIT 2026-11-16 21:04:12.881 - login failure: bob from 172.18.0.1
AUDIT 2026-11-16 21:04:40.017 - team-a/myapp #7 Started by user alice

How to verify: Save a Job configuration, run a build, and run a Script Console script, once each, and confirm all three appear. Common mistakes: The log directory does not exist or the Jenkins user lacks write permission; a custom pattern missed the new URL form. Production use: Use Fluent Bit to collect stdout or files and send them to the SIEM, and set alerts for “Script Console use” and “authorization policy changes”.

Lab 7: audit + custom image with pinned plugins + SBOM and signing (about 8 min)

Enable Audit Trail: save the casc/50-audit.yaml, run the commands in it, and confirm the audit events appear. Then, as admin, run println 1+1 in the Script Console and confirm that the Groovy use is also recorded.
Build a Jenkins image with pinned versions (using the list exported in m5) plugins.txt:
cd ~/jenkinslab
BASE=$(docker buildx imagetools inspect jenkins/jenkins:2.580.2-jdk21 --format '{{json .Manifest.Digest}}' | tr -d '"')
echo "base digest: $BASE"
cat > Dockerfile.jenkins <<EOF
FROM jenkins/jenkins:2.580.2-jdk21@${BASE}
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt --latest=false
EOF
ci/plugin-gate.sh plugins.txt && docker build -f Dockerfile.jenkins -t jenkinslab/jenkins:2.580.2-p6 .
base digest: sha256:3c1f…e9a2
plugin gate: OK
 => exporting to image
 => naming to docker.io/jenkinslab/jenkins:2.580.2-p6
Generate SBOMs for the Jenkins image and the myapp image (syft runs in a container and reads the local Docker images; this step needs the Docker socket and belongs to the local toolchain, not to the Jenkins agent):
for img in jenkinslab/jenkins:2.580.2-p6 myapp:1.1; do
  out=$(echo "$img" | tr '/:' '__').spdx.json
  docker run --rm -v /var/run/docker.sock:/var/run/docker.sock anchore/syft:v1.57.2 "$img" -o spdx-json > "$out"
  printf '%-32s packages=%s\n' "$img" "$(jq '.packages|length' "$out")"
done
jq -r '.packages[] | select(.name=="script-security" or .name=="gunicorn") | "\(.name) \(.versionInfo)"' *.spdx.json
jenkinslab/jenkins:2.580.2-p6    packages=812
myapp:1.1                        packages=164
script-security 1436.v1082791135e4
gunicorn 23.0.0

syft will recognize .jpi/.hpi plugins as Java packages, and the plugin versions appear in the SBOM. This is the “SBOM of the Jenkins platform itself”. If myapp:1.1 is not on this machine, replace it with the image tag built in Lesson 1.

Sign and verify the SBOM with cosign (local key, lab only):
export COSIGN_PASSWORD=$(openssl rand -base64 18)
C="docker run --rm -e COSIGN_PASSWORD -v $PWD:/w -w /w gcr.io/projectsigstore/cosign:v3.1.4"
$C generate-key-pair
$C sign-blob --yes --key cosign.key --bundle myapp_1.1.spdx.bundle.json myapp_1.1.spdx.json
$C verify-blob --key cosign.pub --bundle myapp_1.1.spdx.bundle.json myapp_1.1.spdx.json
echo tampered >> myapp_1.1.spdx.json
$C verify-blob --key cosign.pub --bundle myapp_1.1.spdx.bundle.json myapp_1.1.spdx.json || echo "tampering detected"
Private key written to cosign.key
Public key written to cosign.pub
Verified OK
Error: ... invalid signature ...
tampering detected

Privacy note: cosign v3 writes signing records by default (SBOM digest and public key information) to the public transparency log Rekor. If you do not want this to be public, do not run this step, or use the private infrastructure option described in the cosign documentation --signing-config. In production, keep the keys in KMS (--key azurekms://… / awskms://… / hashivault://…).

(optional) Switch to a custom image: change compose.yaml the jenkins image in jenkinslab/jenkins:2.580.2-p6,docker compose up -d jenkins. After this, a plugin upgrade = edit plugins.txt → gate → rebuild the image.

Cleanup:rm cosign.key cosign.pub *.spdx.json *.bundle.json (or keep them safely); unset COSIGN_PASSWORD. Keep the audit configuration.

Case 1: who changed the authorization policy at dawn?

Problem: On Monday morning, team-b's Jobs were found to be buildable by everyone. Fix: Audit Trail showed 03:12 /manage/configureSecurity/configure by ops-bot; Job Config History showed config.xml in which team-b's folder matrix had been replaced. Tracing led to ops-bot's API token being written into a public script repository. Response: revoke the token, reload authorization from JCasC, and rotate the credentials that ops-bot could reach. Improvements: Set expiry times on service account tokens; send authorization changes to the SIEM as real-time alerts; limit UI changes to security configuration to break-glass scenarios.

Case 2: use an SBOM to answer “are we affected?” within 1 hour

Problem: A serious vulnerability was disclosed in a Java library, and management required immediate knowledge of which Jenkins plugins and which artifacts were affected. Fix: The SBOMs of all Jenkins images and application images are stored in the artifact repository; use jq/grype to batch-query the SBOMs, producing the list in 40 minutes; on the Jenkins side, compare against the m5 gate and the advisory. Limitations: SBOM accuracy depends on how well the generation tool recognizes the packaging format (shaded dependencies embedded in plugins may not be fully recognized).

Case 3: the deployment side accepts only signed images

Problem: Audit requires that “production clusters only run images built by the release pipeline”. Fix: The release Job runs as a service account on a dedicated signing agent,cosign sign --key azurekms://kv-sign-prod/myapp-signing <acr>/myapp@sha256:…; admission policies on AKS (Kyverno, etc.) verify signatures and the registry; Jenkins has only a managed identity with access to the Key Vault signing key (sign permission only). Limitations: A signature proves “who signed it”, not that the build process was untampered; it must be combined with trusted agents, build isolation and provenance attestations.

Audit Trail produces no output

Cause: The log path directory does not exist or has no write permission; a JCasC key name is wrong, so the configuration was not applied; the custom pattern is too narrow.

docker compose logs jenkins 2>&1 | grep -iE 'audit|casc' | tail
docker compose exec jenkins ls -ld /var/jenkins_home/audit

Fix: Create the directory and make sure it is owned by jenkins; in Manage Jenkins → System, check that the Audit Trail configuration matches the YAML; delete the custom pattern to use the default.

jenkins-plugin-cli: Plugin … depends on …, but there is an older version defined on the top level

Cause:--latest=false Under the dependency resolution, a plugin version pinned in plugins.txt is below another plugin's minimum dependency requirement.

Fix: Upgrade that dependency to the required version as indicated and write it back to plugins.txt; use --list to view the effective plugin set, then run the gate again.

cosign verify-blob: error … no matching signatures / invalid signature

Cause: The file was modified (the expected tamper detection); the wrong public key or bundle was used; or a private-infrastructure signature was verified without a trusted root being provided.

Fix: Confirm that the file digest matches the bundle; use the corresponding cosign.pub/KMS public key; private deployment configuration --trusted-root.

Command-line questions
1. Write the first line of a Dockerfile that pins the Jenkins base image by digest (assume the digest is sha256:abc…).
FROM jenkins/jenkins:2.580.2-jdk21@sha256:abc...

Write both the tag and the digest: the tag aids readability, and the digest guarantees immutability.

2. List all packages and versions whose names contain “log4j” from the SPDX SBOM.
jq -r '.packages[] | select(.name|test("log4j")) | "\(.name) \(.versionInfo)"' sbom.spdx.json
Scenario analysis
The auditor asks: “How do you prove that myapp:1.1 in production was built by the Jenkins release pipeline, and that developers did not intervene in the build process?”

What can be proven: ① image signatures (KMS key, available only to the release service account) + deployment-side verification; ② the release Job's build records (trigger user, input approver, commit SHA) and the Audit Trail; ③ the release Job configuration is managed by JCasC / Job DSL, and changes have PR records; ④ SBOMs are archived with the artifact and signed. What still needs to be added: the build runs on one-off, isolated agents; the Jenkinsfile and Shared Library come from protected branches or pinned versions; for stronger guarantees, generate and sign provenance attestations (in-toto / SLSA style). Jenkins does not include this natively, so it must be implemented in the pipeline.

Verified videos

▶
Sigstore demo with cosign
Sigstore (official channel) · English · verified with oEmbed (2026-11-16)
Purpose: a demonstration of cosign signing and verification; the video may be based on cosign v2, so follow the official documentation for v3 command parameters.
▶
What is sigstore? The future of supply chain security?
Cloud Native Skunkworks · English · verified with oEmbed (2026-11-16)
Purpose: understand transparency logs, Fulcio and the concept of keyless signing, and why Jenkins cannot directly use public keyless signing.

No verified English video specifically about the Jenkins Audit Trail plugin was found; please use the storyboard.

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: Each time a button in Jenkins is pressed, an audit record flies to a distant “append-only” vault.
Narration: Audit logs must leave Jenkins in real time and be stored somewhere even administrators cannot modify.
Shot 2 · 0:30–1:10
Visual: A packing list (SBOM) and a wax seal (signature) are attached to the image; an inspector at the deployment gate checks the seal.
Narration: The SBOM tells you what is in the image, the signature tells you who released it, and deployment-side verification keeps unsigned images out of production.
Quiz ≥ 70% marks it automatically

Module 8 · Integrated governance architecture review

50:00 – 60:00 · Use one checklist, one read-only collection script and one troubleshooting tree to turn the first 7 modules into an executable review
10 minIntegration of all modulesReview results → improvement tickets★★★★★
Learning goals
  • Review a Jenkins instance across 8 domains (version, authentication, authorization, CSRF/token, credentials, Script Security, plugins, isolation, audit/supply chain) and set priorities.
  • Use a read-only Script Console collection of facts, rather than screenshots and verbal descriptions.
  • Master the first-hour response to a security incident: contain, collect evidence, rotate, recover.
  • Use the interactive troubleshooting tree to locate “permission / login / credential / sandbox” problems.
Prerequisites: Modules 1–7. Importance:★★★★★

What: review checklist (sorted by risk)

#DomainCheck itemPass criteriaModule
1VersionCore and pluginsLTS ≥ 2.580.2; no security warnings in Manage Jenkins; plugins have a gatem5
2AuthenticationSecurity RealmSSO (Entra ID 711.x+ / OIDC / SAML 4.623.x+); local users only as break-glass accounts; registration disabledm2
3AuthorizationPolicy and number of administratorsNot “logged in means administrator”; Administer granted to one group (by object ID); team permissions in folders / item rolesm1 m2
4CSRF / tokencrumb, API tokensCSRF not disabled by a system property; legacy tokens disabled; service account tokens have expiry timesm1
5CredentialsLocation and scopeTeam credentials in folders; the system store contains only platform credentials with SYSTEM scope; production secrets are externalizedm3
6Script SecurityApproval and sandboxforceSandbox; no dangerous signatures approved; global library repository protectedm4
7Isolationexecutors, build identity, agent partitioningbuilt-in 0 executors; runs as the triggering user / service account; production agents have node authorizationm6
8Audit / supply chainlog forwarding, configuration as code, pinned imagesAudit Trail → SIEM; JCasC in Git; custom images pinned by digest, SBOM + signaturesm7

Why: why “review” rather than “configure once”

The official documentation reminds us that a Jenkins environment grows over time and its trust model must evolve with it; it should be “health-checked” regularly, to see whether security settings that were turned off for compatibility should be turned back on. A review turns “we think it's secure” into reproducible evidence and traceable tickets.

How: the four steps of a review

  1. Collect: read-only Script Console script (see “Commands”) + /pluginManager/api/json + JCasC export (/manage/configuration-as-code/export).
  2. Compare: compare item by item against the pass criteria in the table above, and record the evidence.
  3. Rate: issues that unauthenticated users can exploit, or that can lead to code execution on the controller, are P1 (such as “logged in means administrator”, a lagging Script Security, builds on the controller); credential location and missing audit are P2; compliance issues are P3.
  4. Track: turn each item into a JCasC / plugins.txt PR, and verify it closed in the next review.

When: the first hour of incident response

TimeAction
0–10 minContain: restrict access if needed (reverse proxy allows only the administrator network), pause the queue (Prepare for Shutdown), preserve the scene (do not restart immediately)
10–30 minCollect evidence: copy the Audit Trail, Job Config History,scriptApproval.xml,config.xml, the plugin list, recently modified files (find $JENKINS_HOME -newer …)
30–60 minRotate: all credentials Jenkins can reach (prefer external AppRole / cloud identity / Git tokens), all user API tokens; upgrade to the fixed version; rebuild the configuration from JCasC
Common misconceptions① “A review is just running a scanner”: scanners cannot see design problems such as “team credentials stored in the system store” or “a label impersonating the production agent”. ② “Reinstalling after an incident makes it clean”: if credentials were not rotated and the external identities referenced by JCasC were not reset, the attacker still has the keys. ③ “More administrators is safer (they back each other up)”: each extra Administer is one more person who can execute code on the controller; backup should be a break-glass procedure, not a standing permission.

Architecture diagram: target state (production-ready version of jenkinslab)

Entra ID / OIDCMFA · group object IDsbreak-glass account in the vault GitJCasC · Job DSLplugins.txt · global library controller (custom image @ digest) Authorization: projectMatrix / roleBased (folders)0 executor · forceSandboxBuild identity: triggering user / service accountCredentials: folders + Vault AppRoleAPI tokens with expiry · no legacy tokensPlugin gate · advisories fixed within 24–72hAudit Trail → stdout / files agent pools (by trust level)PR: one-off Pod · anonymousteam: rootless build · deploy: dedicated External systemsVault / Key Vault / Secrets Manager / KMSSIEM (audit) · image registry (signatures + SBOM) All configuration comes from Git; all secrets come from external systems; all actions go to the SIEM
Figure 8-1: governance target architecture

Flowchart: closed loop from review to improvement

Collect factsread-only script Compare against checklistEvidence Rate P1/P2/P3Risk acceptor PR fixJCasC / plugins.txt Verify in next reviewQuarterly
Figure 8-2: review is a cycle, not a one-off project

Interactive governance review scoring

Choose a preset instance or tick items manually; the system calculates each domain's score according to the rules of m1–m7 and gives the top 3 improvement items (P1 first).

Choose a preset or tick items, then click “Evaluate”.

Read-only fact collection script

SourceWhat is collectedNotes
Script ConsoleRealm, authorization strategy, CSRF, executors, build identity, approval status, number of administratorsRead-only; it is itself audited
/manage/configuration-as-code/exportYAML of the currently running configurationCompare with the JCasC in Git to detect drift (secrets are masked in the export)
/pluginManager/api/jsonPlugin versionsFeed into the m5 gate script
/whoAmI/api/jsonVerify authorization with each type of accountSample verification
import jenkins.model.Jenkins
import hudson.security.*
def j = Jenkins.get()
println "version          : " + Jenkins.VERSION
println "securityRealm    : " + j.securityRealm.class.simpleName
println "authorization    : " + j.authorizationStrategy.class.simpleName
println "crumbIssuer      : " + (j.crumbIssuer?.class?.simpleName ?: "NONE (CSRF disabled!)")
println "built-in execs   : " + j.numExecutors
def qia = jenkins.security.QueueItemAuthenticatorConfiguration.get().authenticators
println "build identity   : " + (qia ? qia*.class*.simpleName : "SYSTEM (default)")
def sa = org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval.get()
println "forceSandbox     : " + sa.forceSandbox
println "dangerous sigs   : " + sa.dangerousApprovedSignatures.toList()
println "pending sigs     : " + sa.pendingSignatures.size()
def admins = hudson.model.User.getAll().findAll { u ->
  try { j.ACL.hasPermission2(u.impersonate2(), Jenkins.ADMINISTER) } catch (e) { false } }
println "admin users      : " + admins*.id
def warn = j.updateCenter.sites.collectMany { s -> s.data?.warnings ?: [] }.findAll { it.isRelevant() }
println "active warnings  : " + warn*.id
version          : 2.580.2
securityRealm    : HudsonPrivateSecurityRealm
authorization    : ProjectMatrixAuthorizationStrategy
crumbIssuer      : DefaultCrumbIssuer
built-in execs   : 0
build identity   : [GlobalQueueItemAuthenticator]
forceSandbox     : true
dangerous sigs   : []
pending sigs     : 0
admin users      : [admin]
active warnings  : []

Notes:impersonate2() Only valid for users the Security Realm can resolve (SSO users' groups may not be resolvable offline, so the administrator count should be reviewed together with group membership in the authorization configuration). API names in the script follow 2.580.2 and the corresponding plugin versions; some plugins' internal APIs may change. If collection fails, fall back to checking in the UI.

# Run the same script via the API and save the evidence (admin token)
cd ~/jenkinslab
curl -s -u "admin:$(cat .secrets/admin_token)" --data-urlencode "script@governance-facts.groovy" \
  http://127.0.0.1:8080/manage/scriptText | tee review-$(date +%F).txt
curl -s -u "admin:$(cat .secrets/admin_token)" http://127.0.0.1:8080/manage/configuration-as-code/export -X POST \
  -o running-casc-$(date +%F).yaml; wc -l running-casc-*.yaml

Lab 8: a governance review of jenkinslab (about 8 min)

Collect: save the script from the “Commands” page as ~/jenkinslab/governance-facts.groovy, run it via the API and save the output as review-date.txt; export the running JCasC.
Compare drift:
grep -A3 'authorizationStrategy' running-casc-*.yaml | head
grep -c 'numExecutors: 0' running-casc-*.yaml

keys that appear in the export but are absent from casc/ = someone changed them in the UI (or they are plugin defaults); confirm each one.

Score against the checklist: on the “Animations” page choose “Preset: this lesson's jenkinslab”, then adjust the ticks according to your collection results to get a priority list. For this local environment, the expected remaining issues are: a local user database rather than SSO, agent1 mounting the Docker socket (if configured that way in Lesson 1), and audit logs not forwarded externally.
Write improvement tickets: for each problem write one line: “problem / evidence / rating / fix PR / owner / deadline”.
Rehearse the incident response: assume alice's API token has leaked. Revoke the token in the UI → search the Audit Trail for that user's actions in the last 24 hours → list the credentials in the team-a folder and rotate them at the source (Gitea token, Vault secret_id).

Cleanup: The review evidence files contain configuration information; treat them as secrets (do not commit them to a public repository).

Case 1: 6 Jenkins instances inherited from an acquisition

Problem: After an acquisition, 6 instances were taken over, on versions ranging from 2.4xx to 2.5xx; 2 of them had “logged in means administrator”. Fix: In the first week, only P1 items: upgrade everything to LTS 2.580.2, change the authorization policy, set 0 executors, upgrade Script Security; in weeks 2–4, unify the custom image and the JCasC baseline; in Q2, migrate to unified SSO and Vault. Limitations: Old Jobs depend on approved dangerous signatures, so each must be refactored before its approval is revoked.

Case 2: the review found 14 administrators

Problem: The administrator list included local accounts of departed employees and several administrators “temporarily added to install plugins”. Fix: Grant Administer only to jenkins-admins an Entra group (by object ID); platform operations switches to Overall/Manage + SystemRead; plugin installation only via plugins.txt PRs; keep only 1 local break-glass account. Limitations: Some plugin configuration pages still require Administer; list the exceptions and handle them through JCasC.

Case 3: security incident: a malicious Jenkinsfile exfiltrates credentials

Problem: A contractor base64-encoded a system GLOBAL credential in the Jenkinsfile on a feature branch and printed it to the log. Fix: Follow the “first hour” process: disable the account, delete the related build records, rotate the printed credential and all credentials in the same store. Root-cause improvements: push credentials down to folders + Vault, run builds as the triggering user, and let contractors read only the main branch. Limitations: The logs may already have been collected by the log platform, so downstream copies must be cleaned up as well.

Interactive troubleshooting tree: permission / login / credentials / sandbox

Start from the symptom, answer the questions step by step, and get the diagnosis and fix commands.

After applying JCasC: io.jenkins.plugins.casc.ConfiguratorException: Invalid configuration elements for type …

Cause: A misspelled key name, a plugin that is not installed, or a version that does not support the key (for example, the format of matrix-auth 3.x entries ).

Fix: Check Manage Jenkins → Configuration as Code → Documentation / Reference; compare with the CasC test samples in the plugin repository; verify in staging first.

Command-line questions
1. Write one Script Console statement that determines whether CSRF protection is disabled.
println(jenkins.model.Jenkins.get().crumbIssuer == null ? "CSRF DISABLED" : "CSRF on")
Scenario analysis
You have one day to review a Jenkins that has never been governed. In what order do you work?

Morning: collect facts (version, authorization, CSRF, executors, administrators, plugin warnings, approval status), then immediately handle P1 items (upgrade the core and Script Security, fix the authorization policy, 0 executors, clean up dangerous signatures). Afternoon: inventory credentials (what is in the GLOBAL system store and who can use it), check whether audit is forwarded externally, and check build identity; output P2/P3 tickets and a roadmap (SSO, Vault, custom image, plugin gate).

Verified videos

▶
Common Pitfalls in Jenkins Security and How to Avoid Them
CloudBeesTV · English · verified with oEmbed (2026-11-16)
Purpose: review material for the review checklist.
▶
Brautigam Gergely - Best Practices for Jenkins
Emarsys Craftlab · English · verified with oEmbed (2026-11-16)
Purpose: experience sharing on operations and governance practice (published earlier; for version details, follow this lesson).

Official documentation

Video storyboard

Shot 1 · 0:00–0:30
Visual: Eight dashboard lights turn on one after another: version, authentication, authorization, CSRF, credentials, sandbox, isolation, audit.
Narration: A governance review means lighting up each of these eight lights one by one and leaving evidence.
Shot 2 · 0:30–1:10
Visual: Red lights become tickets, tickets become PRs in Git, and next quarter the lights turn green.
Narration: Every problem must become a reviewable configuration change, and the next review verifies that it was really closed.
Quiz ≥ 70% marks it automatically

Command cheat sheet

Enterprise security and governance: the most-used endpoints, JCasC snippets and Script Console statements
Jenkins LTS 2.580.2

Authentication self-check and API tokens

J=http://127.0.0.1:8080
curl -s -u "u:$TOKEN" $J/whoAmI/api/json | jq '{name,authorities}'
# password + crumb + cookie (old scripts only)
CRUMB=$(curl -s -c cj -u "u:$PW" $J/crumbIssuer/api/json | jq -r '.crumbRequestField+":"+.crumb')
curl -s -b cj -u "u:$PW" -H "$CRUMB" -X POST $J/job/team-a/job/myapp/build
# generate a token
curl -s -b cj -u "u:$PW" -H "$CRUMB" -X POST \
  "$J/me/descriptorByName/jenkins.security.ApiTokenProperty/generateNewToken" --data newTokenName=ci

Authorization: Project Matrix (JCasC)

jenkins:
  authorizationStrategy:
    projectMatrix:
      entries:
        - group: { name: "jenkins-admins", permissions: [Overall/Administer] }
        - group: { name: authenticated, permissions: [Overall/Read] }
# folder (Job DSL)
properties { authorizationMatrix {
  inheritanceStrategy { inheriting() }   // inheritingGlobal() / nonInheriting()
  entries { group { name('team-a-dev'); permissions(['Job/Read','Job/Build']) } } } }

Authorization: Role-based (JCasC)

jenkins:
  authorizationStrategy:
    roleBased:
      roles:
        global:
          - name: admin
            permissions: ["Overall/Administer"]
            entries: [{ group: "jenkins-admins" }]
        items:
          - name: team-a-dev
            pattern: "team-a(/.*)?"
            permissions: ["Job/Read", "Job/Build"]
            entries: [{ group: "team-a-dev" }]

SSO (JCasC)

securityRealm:
  oic:
    serverConfiguration:
      wellKnown: { wellKnownOpenIDConfigurationUrl: "https://idp/.well-known/openid-configuration" }
    clientId: jenkins
    clientSecret: "${oidc_client_secret}"
    groupsFieldName: groups
    properties: ["pkce", { escapeHatch: { username: breakglass, secret: "${bg_pw}" } }]
# Entra: securityRealm.azure {clientid, tenant, credentialtype: WorkloadIdentity}
# SAML: securityRealm.saml {idpMetadataConfiguration.url, groupsAttributeName}

Credentials

# create a credential in a folder store
curl -u "admin:$T" -H 'Content-Type: application/xml' --data-binary @cred.xml \
  "$J/job/team-a/credentials/store/folder/domain/_/createCredentials"
# Azure Key Vault provider: the tag determines the type
az keyvault secret set --vault-name kv --name gitea-myapp --value "$PAT" --tags type=username username=ci-bot
# AWS Secrets Manager provider
aws secretsmanager create-secret --name x --secret-string "$V" \
  --tags Key=jenkins:credentials:type,Value=string Key=jenkins:credentials:folder,Value=team-a

Script Security

security:
  scriptApproval:
    forceSandbox: true          # applies to non-administrators
    approvedSignatures:
      - "method java.net.URI getHost"
# Script Console:
# ScriptApproval.get().dangerousApprovedSignatures   → must be empty
# ScriptApproval.get().pendingSignatures*.signature

Plugin governance

jenkins-plugin-cli -f plugins.txt --latest=false            # install pinned versions
jenkins-plugin-cli --view-all-security-warnings --no-download
jenkins-plugin-cli -f plugins.txt --available-updates --output txt --no-download
curl -s -u "admin:$T" "$J/pluginManager/api/json?depth=1&tree=plugins[shortName,version]" \
  | jq -r '.plugins[]|"\(.shortName):\(.version)"' | sort > plugins.txt

Isolation, build identity and audit

jenkins:
  numExecutors: 0
security:
  queueItemAuthenticator:
    authenticators:
      - global: { strategy: "triggeringUsersAuthorizationStrategy" }
  apiToken:
    creationOfLegacyTokenEnabled: false
unclassified:
  audit-trail:
    logBuildCause: true
    loggers:
      - logFile: { log: "/var/jenkins_home/audit/audit-%g.log", limit: 25, count: 10 }

Quick troubleshooting table

SymptomMost likely causeFirst command
403 No valid crumbSession/password request without crumb or cookieSwitch to an API token; curl -c/-b
X is missing the Job/Build permissionObject ACL missing a permission / inheritance cut offScript Console getACL().hasPermission2
An existing Job returns 404No Job/Read or Discover, or the parent folder is not visibleadmin checks authorization at each folder level
SSO login yields no groupsToken has no groups claim / JMESPath errorDecode the ID token; /whoAmI/api/json
Could not find credentials entryCredentials in another folder / SYSTEM scope / build identity has no permissionList the credential IDs in the folder and system stores
Scripts not permitted to use …Sandbox interceptionReview the signature; prefer replacing it with a step
Running scripts out of the sandbox is not allowedforceSandbox applies to non-administratorsChange to sandbox or a trusted library
‘alice’ lacks permission to run on ‘agent1’Build identity lacks Agent/Build/queue/api/json?tree=items[why]
Warnings have been published…Installed plugin version matches an advisoryUpgrade / remove / accept the risk

Recommended baseline (copy into casc/10-security.yaml and adjust as needed)

jenkins:
  numExecutors: 0
  disableRememberMe: true
  markupFormatter: plainText
  securityRealm: { oic: { … } }              # or azure / saml
  authorizationStrategy: { projectMatrix: { … } }   # or roleBased
security:
  apiToken: { creationOfLegacyTokenEnabled: false, tokenGenerationOnCreationEnabled: false, usageStatisticsEnabled: true }
  scriptApproval: { forceSandbox: true }
  queueItemAuthenticator: { authenticators: [ { global: { strategy: "triggeringUsersAuthorizationStrategy" } } ] }
unclassified:
  audit-trail: { logBuildCause: true, loggers: [ { console: { output: STD_OUT } } ] }

Capstone lab + final quiz

Turn jenkinslab into a security baseline that can be handed to multiple teams, and prove it with evidence
≈ 40 minutesNo cloud costs

Scenario

You have taken over the jenkinslab built in Lesson 1, and the company requires that team-a and team-b be migrated in next week. The security team's acceptance criteria: teams cannot see each other's Jobs and credentials; no build runs on the controller; Pipelines can only run in the sandbox; secrets do not land on Jenkins disks; all key actions are audited; and the plugin versions can be shown to have no known vulnerabilities.

Baseline configuration: complete the compose.override.yaml from Module 0,.secrets/,casc/10-security.yaml and 20-teams.yaml; confirm X-Jenkins: 2.580.2.
Authorization verification: run the 4×3 matrix test from the m1 lab, confirm the results match expectations, and keep team-a's inheritance strategy as inheriting().
External credentials: start the Vault dev server, and put myapp's Redis password in secret/myapp; the AppRole goes in the team-a folder store; bob cannot use vault-team-a (the build reports Could not find credentials entry).
Sandbox and approval: forceSandbox: true; sandbox-demo is rejected and the approval queue is empty; in the Script Console, dangerousApprovedSignatures is empty.
Isolation and build identity: numExecutors: 0; enable triggeringUsersAuthorizationStrategy; grant Agent/Build to alice and bob; verify that builtin-probe cannot start.
Audit: enable casc/50-audit.yaml, perform one configuration save, one build, one failed login and one Script Console execution, and confirm that all 4 types of events appear in the audit log.
Plugins and images: export plugins.txt → ci/plugin-gate.sh passes → build jenkinslab/jenkins:2.580.2-p6 (base image pinned by digest) → generate an SBOM and sign it.
Review report: run the governance-facts script from m8, save the output as review-date.txt, and write out the remaining risks (local user database, Docker socket, audit not forwarded externally) and the improvement plan.
Acceptance checklist

Open-ended self-test (6 questions)

1. Why is “Job/Configure a high-privilege permission”? Give three reasons.

It can change the authorization matrix of that object; it can rewrite Groovy that runs on the controller (relying on the strength of the sandbox); and when a build runs as SYSTEM it can use system GLOBAL credentials and move a label to any agent.

2. Why must Entra ID group authorization use object IDs?

Display names are neither unique nor immutable, and by default any tenant member can create a group with the same name. In SECURITY-3935, matching by display name led to privilege escalation; from 711.x, authorization uses only object IDs.

3. What problem does each of credential domains, scopes and stores solve? Which one is the boundary of team isolation?

Domain: classification and matching by URL; scope: SYSTEM (only for Jenkins itself) vs GLOBAL (usable by builds); store: determines which Jobs can see it. Team isolation relies on folder stores (plus scope).

4. Explain the use case of “Approve assuming permissions check”.

For methods that perform ACL checks themselves (such as ItemGroup getItems): allowed when the script runs as a real user, and denied when it runs as SYSTEM, to prevent borrowing the SYSTEM identity to bypass permissions.

5. What can Agent → Controller access control prevent, and what can it not prevent?

It prevents a compromised agent from making the controller run commands or read files (always on since 2.326). It cannot prevent other builds on the same agent, credentials passed to the agent, or the network the agent can reach, so divide agents by trust level.

6. For a plugin with a high-severity vulnerability and no fix, what is your decision framework?

Assess exploitability conditions and exposure → inventory the users → compensating controls (tighten permissions, disable the feature) → rotate related secrets → replacement plan and removal deadline → add it to the gate's deny list; record the risk acceptor and the deadline.

Sources and version notes

Verified date 2026-11-16; subject to jenkins.io, plugins.jenkins.io, Update Center metadata and plugin source code

Version and fact verification table

TopicVerification resultSource (accessed 2026-11-16)
Jenkins LTS / weeklyLTS 2.580.2 (2026-10-28, tested on JDK 21 and 25); weekly 2.590; stable latestCore = 2.580.2LTS Changelog · updates.jenkins.io
Java and 2.555.1 changesSince 2.555.1, Java 21+ is required; Overall/Manage is enabled by default; API tokens can expire; crumb no longer includes IPLTS Changelog 2.555.1
CSRFcrumb = username + web session ID + instance salt; API token requests are exempt; disabling requires a system property (not recommended)CSRF Protection
PermissionsOverall/Manage (JEP-223) and SystemRead as optional permissions (system property or Extended Read Permission plugin)Permissions
Controller isolationbuilt-in 0 executors recommended; Agent → Controller access control always on since 2.326, cannot be customizedController Isolation
Script ApprovalSandbox + approval; Approve assuming permissions check; scripts saved by administrators are no longer auto-approved; forceSandbox (source code: applies only to non-administrators); default hash SHA512In-process Script Approval · script-security source code / README
Security advisories2026-10-28 (15 core items, fixed in 2.588 / 2.580.2); 2026-09-16 (Script Security 1422.x etc.); 2026-09-02 (SAML 4.623.x, Entra 711.x, Parameterized Remote Trigger no fix)2026-10-28 · 2026-09-16 · 2026-09-02
Plugin versionsmatrix-auth 3.3; role-strategy 928.vc60b_edb_fea_e1; oic-auth 4.737.vb_3d1a_0e7cf0b_; saml 4.623.v7875d61cd9f5; azure-ad 723.v212c114e2fb_f; hashicorp-vault-plugin 384.vda_86ec66c537; azure-keyvault 381.vdfc9241e640e; aws-secrets-manager-credentials-provider 2.227.v1b_359849c4a_2; script-security 1436.v1082791135e4; credentials 1514.vb_01eb_014e7d4; credentials-binding 728.v902a_273b_8947; configuration-as-code 2147.v8a_8d38668c72; cloudbees-folder 6.1107.v31f8955765c8; authorize-project 534.v2f208c45e11c; audit-trail 472.vb_51e5934ec50; jobConfigHistory 1380.v762185b_9a_793; oidc-provider 234.vca_b_26b_f4b_dda_plugins.jenkins.io API
Maintenance statusEntra ID plugin: community-maintained; the README states Microsoft has not supported it since 2024-02-29; permissive-script-security: adopt-this-plugin, last released 2021; folder-auth: current version affected by SECURITY-3062 (matches an Update Center warning); Parameterized-Remote-Trigger 3.2.3 affected by SECURITY-3768/3800Plugin README · update-center.actual.json
JCasC syntaxmatrix-auth entries, role-strategy roleBased, oic serverConfiguration.wellKnown, azure clientid/tenant/credentialtype, saml, audit-trail, authorize-project, and scriptApproval key names are all taken from each plugin repository's CasC test resources or READMEeach plugin's GitHub repository
External secrets conventionsKey Vault tag type; Secrets Manager tag jenkins:credentials:type / folder, IAM requires ListSecrets + GetSecretValue; Vault AppRole fields roleId / secretId / pathplugin README / docs, VaultAppRoleCredential.java
Tool versionsjenkins/jenkins:2.580.2-jdk21 (consistent with Lesson 1); plugin-installation-manager-tool 2.16.0 (default --latest=true); hashicorp/vault 2.2.2; syft v1.57.2; cosign v3.1.4 (sign-blob no --tlog-upload parameter, uses the signing configuration); Jenkins Helm chart 5.13.3 (appVersion 2.580.2)Docker Hub, GitHub releases, cosign documentation
Jenkins and OIDCThe core does not natively issue OIDC tokens; the OpenID Connect Provider plugin can make Jenkins a token issueroidc-provider · Entra ID plugin README

Video verification notes

All videos had their titles and channel names verified on 2026-11-16 through YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json); durations are not provided by oEmbed, so refer to the page. Some videos are older, so for interface and version details, follow this lesson.

ModuleVideoChannel
m1 / m5 / m8Common Pitfalls in Jenkins Security and How to Avoid ThemCloudBeesTV
m1Jenkins Security Best Practices | Jenkins User Management | Jenkins AdvancedBribe By Bytes
m2Jenkins Tutorial For Beginners - Using the Role-Based Authorization Strategy + Manage RolesCodeBind
m2DevOps: Jenkins Matrix-Based Security | ACL for UsersDevOps - Free Tutorials
m2How to Secure Jenkins with Keycloak OIDC IntegrationMiddleware Technologies
m3The Correct Way to Handle Credentials in a Jenkins PipelineCloudBeesTV
m3How To Define Credentials at a Folder Level in JenkinsCloudBeesTV
m3How to Integrate HashiCorp Vault With JenkinsCloudBeesTV
m4Abusing Jenkins: Groovy Script ConsolePentester Academy TV
m4How To Run a Groovy Script in JenkinsCloudBeesTV
m5Understanding Security soft-spots of Jenkins | Importance of Jenkins security advisory | OpsMxOpsMx
m6What Is a Jenkins Agent?CloudBeesTV
m7Sigstore demo with cosignSigstore
m7What is sigstore? The future of supply chain security?Cloud Native Skunkworks
m8Brautigam Gergely - Best Practices for JenkinsEmarsys Craftlab

No verified dedicated videos were found for In-process Script Approval decisions, Agent → Controller access control / Authorize Project, or the Audit Trail plugin; storyboards are provided for these modules.

Audio narration notes

The “Audio” page uses the browser's built-in Web Speech API (zh-CN to read the narration aloud, en-US to read terms). This courseware cannot embed MP3 or generate video directly; the narration and storyboards can be given to TTS / video tools. If there is no Chinese voice pack, install one following the hint on the audio page.

Known limitations

  • All command output in this lesson is labeled as “example”: it was not run line by line in a real jenkinslab environment; status codes and log formats (such as the Audit Trail line format, queue why wording,/signup status codes) may differ slightly between versions.
  • The JCasC key names come from plugin repository test resources and READMEs; when a key name changes in a new version, follow Manage Jenkins → Configuration as Code → Reference. The Python snippet in the Role-based lab that deletes the authorization section assumes the indentation format of the baseline file.
  • The details of whether forceSandbox reports errors at save time or run time were not verified on a live instance; the source code confirms it applies only to users without Administer.
  • After Authorize Project is enabled, the exact visibility scope of credential lookup depends on the Credentials plugin's permission settings (UseOwn / UseItem, etc.); this lesson conservatively requires verification in staging.
  • cosign v3 uses the public Sigstore infrastructure (transparency log) by default; private deployment parameters are not demonstrated in this lesson. Whether the Jenkins image ships with an official SBOM / signature was not verified; this lesson generates its own.
  • The optional Keycloak OIDC lab and the Entra ID / Key Vault / Secrets Manager configurations were not run in a real tenant; they are configuration examples only. For cloud resources, follow the permission and cost notes in Lessons 3 and 4.
  • agent1's Docker access method follows the actual configuration from Lesson 1; if the host Docker socket is mounted, builds on that agent effectively have host root capability (noted several times in this lesson).