Credentials, masking and scope

Folder scope, masking, what masking misses, and what is stored on disk.

Intermediate15 min · lesson 10 of 15
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (22 files, 7 KB): credentials.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/ci-jenkins/credentials.tar.gz && tar -xzf credentials.tar.gz, which creates ~/lab/credentials/. SHA-256: 8e708bc20592561a07ce097ac65197911fb420e4c10f02827a2ce6db5d856327

Jenkins prints **** where your token would be, and it's tempting to conclude that the secret is safe. That's what many teams assume. Masking is a text filter applied to the console, and the step that holds the token can do anything it wants with it. In this lesson you'll use credentials the right way, then watch a pipeline print a masked token in a form the filter misses, so you know what the **** does and doesn't buy you.

HOW A SECRET REACHES A BUILD SAFELY
1Encrypted store
credential kept in JENKINS_HOME, referenced by id
2withCredentials block
resolves the id, binds value to an env var
3Step uses the var
secret available only for these steps
4Log masking
exact stored string replaced with ****
5Block ends
variable unset; secret gone from the pipeline
The Jenkinsfile only names an id; the value lives encrypted and is exposed for the narrowest possible window.

Binding a credential for one block

A credential lives in Jenkins's store under an ID, and a Jenkinsfile only ever names the ID. withCredentials makes the value available as an environment variable for one block:

app/Jenkinsfile
pipeline {
agent { label 'linux' }
stages {
stage('Use the token') {
steps {
withCredentials([string(credentialsId: 'api-token', variable: 'TOKEN')]) {
sh 'echo "length: ${#TOKEN}"'
sh 'echo "plain: $TOKEN"'
}
sh 'echo "after the block: ${TOKEN:-unset}"'
}
}
}
}
ubuntu@secopslog-cicd:~/lab/credentials · Jenkins 2.580.2
$ ./up.sh
agent lab-agent: online Jenkins 2.580.2 is up on http://127.0.0.1:8080
$ echo lab-token-0123456789 | ./add-secret.sh api-token
credential api-token stored
$ ./seed.sh app app/ && ./newjob.sh use app && ./newjob.sh leak app Jenkinsfile.leak && ./newjob.sh missing app Jenkinsfile.missing
pushed app: 57065ce first commit job use reads Jenkinsfile from git://git/app.git job leak reads Jenkinsfile.leak from git://git/app.git job missing reads Jenkinsfile.missing from git://git/app.git
$ ./run-job.sh use
Started by user admin Running on lab-agent in /home/jenkins/agent/workspace/use [Pipeline] withCredentials Masking supported pattern matches of $TOKEN + echo length: 20 length: 20 + echo plain: **** plain: **** + echo after the block: unset after the block: unset Finished: SUCCESS build #1 result: SUCCESS

Length 20, so the real value was available to the step. Printing it gave ****, in the trace line too. After the block, the variable is unset, which limits how much of the pipeline can touch the secret. Keep these blocks as short as you can.

What masking misses

app/Jenkinsfile.leak
pipeline {
agent { label 'linux' }
stages {
stage('Leak') {
steps {
withCredentials([string(credentialsId: 'api-token', variable: 'TOKEN')]) {
sh 'printf %s "$TOKEN" | base64'
sh 'printf %s "$TOKEN" | rev'
sh "echo groovy interpolated: ${TOKEN}"
}
}
}
}
}
ubuntu@secopslog-cicd:~/lab/credentials · Jenkins 2.580.2
$ ./run-job.sh leak
Started by user admin Running on lab-agent in /home/jenkins/agent/workspace/leak [Pipeline] withCredentials Masking supported pattern matches of $TOKEN + base64 + printf %s **** **** + printf %s **** + rev 9876543210-nekot-bal 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 groovy interpolated: **** groovy interpolated: **** Finished: SUCCESS build #1 result: SUCCESS

Three things happened. The base64 form was masked as well, because Jenkins also watches for common encodings of the value. Then rev printed 9876543210-nekot-bal, right there in the console. Anyone who can read this build's log can undo that:

ubuntu@secopslog-cicd:~/lab/credentials · Jenkins 2.580.2
$ ./jk.sh /job/leak/lastBuild/consoleText | grep -x '[0-9]*[0-9a-z-]*-nekot-bal' | rev
lab-token-0123456789

That's the token, recovered from a "masked" log. Any transformation the filter doesn't know about gets past it, and a build could also just curl the value to a remote server, which no log filter can see at all. Masking stops accidents. Anyone who controls the pipeline code gets past it.

The third thing is the warning. In sh "echo ${TOKEN}", Groovy expanded the secret before the shell started, so the value became part of the command text that Jenkins handles and can record. The fix is the same single-quote rule from the parameters lesson: sh 'echo "$TOKEN"'. Treat this warning as an error in review.

ControlStopsDoesn't stop
MaskingA debug echo printing a secretA transformed value, or sending it elsewhere
Short withCredentials blockLater stages using the variable by accidentCode inside the block
Folder-scoped credentialsJobs in other folders asking for the IDAnyone who can edit a job in that folder
Separate agentsOther jobs reading files left on an agentThe job itself
Short-lived tokensA leaked value working next weekUse during the build

Who can bind a credential

Every credential so far sits in the global store, which any job on this Jenkins can bind, including a branch job whose Jenkinsfile anyone with push rights wrote. A folder narrows that. A credential stored in a folder is visible only to jobs inside it. Create a folder for one team, give it a token, and put one job inside and one outside, both running the same Jenkinsfile:

app/Jenkinsfile.team
pipeline {
agent { label 'linux' }
stages {
stage('Deploy') {
steps {
withCredentials([string(credentialsId: 'team-token', variable: 'TOKEN')]) {
sh 'echo "team token available, length ${#TOKEN}"'
}
}
}
}
}
ubuntu@secopslog-cicd:~/lab/credentials · Jenkins 2.580.2
$ ./jk.sh "/createItem?name=team-a" -X POST -H "Content-Type: application/xml" --data-binary @folder.xml && echo lab-team-secret-42 | FOLDER=team-a ./add-secret.sh team-token && ./newjob.sh team-a/job/deploy app Jenkinsfile.team && ./newjob.sh outsider app Jenkinsfile.team
credential team-token stored in folder team-a job team-a/job/deploy reads Jenkinsfile.team from git://git/app.git job outsider reads Jenkinsfile.team from git://git/app.git
$ ./run-job.sh team-a/job/deploy
Started by user admin Running on lab-agent in /home/jenkins/agent/workspace/team-a/deploy [Pipeline] withCredentials Masking supported pattern matches of $TOKEN + echo team token available, length 18 team token available, length 18 Finished: SUCCESS build #1 result: SUCCESS
$ ./run-job.sh outsider
Started by user admin Running on lab-agent in /home/jenkins/agent/workspace/outsider [Pipeline] withCredentials ERROR: Could not find credentials entry with ID 'team-token' Finished: FAILURE build #1 result: FAILURE

Inside the folder, the job bound the 18-character token. Outside it, the same Jenkinsfile failed at withCredentials with Could not find credentials entry with ID 'team-token', exactly as if the credential didn't exist.

Out of the box, builds run as Jenkins's internal SYSTEM user with every permission, so the folder is the boundary that counts: any job inside it can bind the token, whoever started the build. The Authorize Project plugin can make builds run as the user who triggered them, so a build can do only what that user may do. For a release key, combine a folder with agents that only that folder's jobs can use, through a label nobody else is allowed to request.

A wrong ID, and storage at rest

ubuntu@secopslog-cicd:~/lab/credentials · Jenkins 2.580.2
$ ./run-job.sh missing
Started by user admin Running on lab-agent in /home/jenkins/agent/workspace/missing [Pipeline] withCredentials ERROR: Could not find credentials entry with ID 'no-such-id' Finished: FAILURE build #1 result: FAILURE
$ docker compose exec -T controller sh -c "grep -c lab-token /var/jenkins_home/credentials.xml || true"; docker compose exec -T controller grep -oE "<secret>.{12}" /var/jenkins_home/credentials.xml
0 <secret>{AQAAABAAAAA
$ ./jk.sh '/credentials/store/system/domain/_/api/json?tree=credentials[id,typeName]' | jq -c '.credentials[]'
{"id":"api-token","typeName":"Secret text"}
$ ./down.sh
lab stopped and its data removed

A wrong ID fails the build with a clear message, at the point of use. On disk, credentials.xml doesn't contain the plaintext (grep -c finds 0 matches), and the value is encrypted with a key in secrets/. That protects a stray copy of the XML file, and it doesn't help if an attacker has both the file and that directory, which is one more reason builds never run on the controller. The API lists IDs and types, and it has no way to read a value back.

Hands-on

In a fresh lab, add a stage to app/Jenkinsfile.leak that prints the token with its characters separated by spaces: sh 'echo "$TOKEN" | sed "s/./& /g"'. Does masking catch that? Then rotate the credential: add a new one with a new ID, change the Jenkinsfile to use it, and delete the old one with ./jk.sh /credentials/store/system/domain/_/credential/api-token/doDelete -X POST. Run both jobs: which one breaks, and how? Finish with ./down.sh. Worked files are in solutions/.

What you should see: masking misses the spaced form, and the console shows l a b - t o k e n - 0 1 2 3 4 5 6 7 8 9 in full. After the rotation, the API lists only api-token-2, and use runs with the new 20-character token. leak, which still names api-token, fails at once with Could not find credentials entry with ID 'api-token'. That's the useful side of rotating by ID: every job you forgot to update fails loudly.

Remember

Your control over a secret ends with whoever can change a pipeline that binds it, since rev was all it took here. Scope credentials to folders, keep tokens short-lived, and rotate any secret you suspect was printed, however masked it looked.

Quick check
01A reviewer finds sh "curl -H 'Authorization: Bearer ${TOKEN}' $URL" inside withCredentials. The console shows ****. What should the reviewer say?
Incorrect — The mask covers only console output. The interpolation problem is elsewhere.
Incorrect — That reduces shell tracing and does nothing about Groovy expanding the value.
Correct — Jenkins warns about exactly this. With single quotes, the shell reads the variable from its environment.
Incorrect — Parameters are shown on the build page, which is much worse.
02A contributor can edit a Jenkinsfile that binds a production token. The logs are masked and the token is folder-scoped. What is true?
Correct — They could transform it or send it elsewhere. Limit who can edit that job, or use a different credential.
Incorrect — The lab printed a reversed token to the console, past the mask.
Incorrect — The folder scope allows jobs in the folder. That is what it's for.
Incorrect — Their pipeline does not need admin. The binding hands it the value.
03A backup of credentials.xml alone is leaked. How exposed are the secrets in it?
Incorrect — The lab showed the value encrypted there, with no plaintext matches.
Correct — Encryption depends on keys kept elsewhere in JENKINS_HOME, so back them up separately and carefully.
Incorrect — Jenkins must recover the value for builds, so it can't be a one-way hash.
Incorrect — The API lists IDs and types and does not return secret values.

Related