The CMS (Builds screen) and the worker (after each publish) call Jenkins's REST API as one Jenkins user, with that user's API token sent as HTTP basic auth. Three settings carry it:
| Setting | Example | Where it goes | Secret |
|---|---|---|---|
JENKINS_JOB_URL |
https://<JENKINS_HOST>/job/kims-production/job/kims-site-build |
Helm values, env.JENKINS_JOB_URL |
No |
JENKINS_USER |
kims-cms-production |
Helm values, env.JENKINS_USER |
No |
JENKINS_TOKEN |
(the API token) | Kubernetes Secret kims-jenkins, key token, read through secretEnv |
Yes |
Who does what:
| Step | Who |
|---|---|
| Create the user and its permissions | KIMS's Jenkins admin |
| Generate the API token | Someone signed in as that user (KIMS's admin, usually) |
Put the token in the kims-jenkins Secret |
KIMS's admin, or our engineer typing it straight into the command without saving it anywhere |
| Test with curl | Our engineer |
#One user per environment
Use a separate user for each environment, for example kims-cms-production and kims-cms-uat, each allowed on its own folder's kims-site-build only. Then a UAT token can never start a production build. One user allowed on both site jobs also works, if KIMS prefers fewer accounts.
#Create the user
How depends on KIMS's Security Realm (Manage Jenkins, Security):
#Jenkins' own user database
- Manage Jenkins, Users, Create User.
- Username:
kims-cms-production. This isJENKINS_USER(the user ID, not the full name). - Password and Confirm password: a long random one. Nobody signs in with it after the token is made; KIMS keeps it in their password vault.
- Full name:
KIMS v2 CMS (production). E-mail address: a team mailbox at KIMS. - Create User.
#LDAP, Active Directory or single sign-on
Jenkins cannot create the user itself. KIMS creates a service account in their directory (for example svc-kims-cms-prod), and that account signs in to Jenkins once so Jenkins knows it. Its user ID (what People or Manage Jenkins, Users shows as the ID) is JENKINS_USER.
#Give the user permission on the site job only
The calls the CMS makes (the overview's table) need:
| Permission | Where | Why |
|---|---|---|
| Overall/Read | global | Any API call at all, and the queue API |
| Job/Read | the kims-site-build job |
Job and build status, queue items, console log |
| Job/Build | the kims-site-build job |
buildWithParameters |
| Job/Cancel | the kims-site-build job |
Cancel on the Builds screen (/stop and queue/cancelItem) |
Nothing else: no Job/Configure, no Credentials, no access to other jobs or to kims-platform.
#With Project-based Matrix Authorization Strategy
Who does this: KIMS's Jenkins admin (needs the matrix-auth plugin and Overall/Administer).
- Manage Jenkins, Security, Authorization: this should already be Project-based Matrix Authorization Strategy on a shared Jenkins. Do not change KIMS's strategy.
- In the global matrix, Add user,
kims-cms-production, tick Overall, Read only. Save. - Open the folder
kims-production, Configure, tick Enable project-based security (if offered), Add userkims-cms-production, tick Job, Read only. Save. (Folder-level Read lets it see the job inside.) - Open
kims-production/kims-site-build, Configure, Enable project-based security, Add userkims-cms-production, tick Job: Read, Build, Cancel. Save.
#With Role-based Authorization Strategy
Manage Jenkins, Manage and Assign Roles:
- Manage Roles: a Global role
kims-cms-apiwith Overall/Read; an Item rolekims-site-build-productionwith Patternkims-production/kims-site-buildand Job/Read, Job/Build, Job/Cancel. Save. - Assign Roles: give
kims-cms-productionthe global rolekims-cms-apiand the item rolekims-site-build-production. Save.
#Generate the API token
- Sign in to Jenkins as the CMS user.
- Top right, click the user's name, then Security (on older Jenkins: Configure).
- Section API Token, Add new Token.
- Name it:
kims-cms-production-<YYYY-MM>. - Generate.
- Copy the token now. Jenkins shows it once only.
- Save (older versions need it to keep the token).
Put it straight into the Kubernetes Secret, from the clipboard, without writing it to a file, chat or email. The commands are on Secrets (Secret kims-jenkins, key token).
Make the token before you create the namespace's Secrets. The engineer's deploy.mjs kims secrets create helper stops if the Jenkins token is empty, and a Secret created with a placeholder token makes every publish fail to start a build. See deploy CLI.
#Why an API token and not the password
Jenkins protects state-changing requests (a POST) with a CSRF crumb. A request authenticated with an API token is exempt from the crumb (since Jenkins 2.96), so the CMS just sends one POST. With a password instead, every POST would need a crumb fetched first, and the CMS does not do that: buildWithParameters would answer 403 No valid crumb was included in the request. So JENKINS_TOKEN must be an API token.
#Test the token with curl
Run these from a machine that can reach Jenkins. The real path that matters is from the CMS pods; the last test covers it.
#Put the values in variables, without showing the token
export JENKINS_JOB_URL='https://<JENKINS_HOST>/job/kims-production/job/kims-site-build'
export JENKINS_ROOT="${JENKINS_JOB_URL%%/job/*}"
export JENKINS_USER='kims-cms-production'
printf 'API token: '; read -rs JENKINS_TOKEN; echo; export JENKINS_TOKENexport JENKINS_JOB_URL='https://<JENKINS_HOST>/job/kims-production/job/kims-site-build'
export JENKINS_ROOT="${JENKINS_JOB_URL%%/job/*}"
export JENKINS_USER='kims-cms-production'
printf 'API token: '; read -rs JENKINS_TOKEN; echo; export JENKINS_TOKEN$env:JENKINS_JOB_URL = 'https://<JENKINS_HOST>/job/kims-production/job/kims-site-build'
$env:JENKINS_ROOT = $env:JENKINS_JOB_URL.Substring(0, $env:JENKINS_JOB_URL.IndexOf('/job/'))
$env:JENKINS_USER = 'kims-cms-production'
$s = Read-Host "API token" -AsSecureString
$env:JENKINS_TOKEN = [System.Net.NetworkCredential]::new('', $s).Password
Remove-Variable sJENKINS_ROOT is everything before the first /job/, the same rule the CMS uses for the queue API.
#1. Who am I
curl -s -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_ROOT/whoAmI/api/json"; echocurl -s -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_ROOT/whoAmI/api/json"; echocurl.exe -s -u "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)" "$env:JENKINS_ROOT/whoAmI/api/json"You should see "anonymous":false, "authenticated":true and "name":"kims-cms-production". If name is anonymous, the token was not accepted.
#2. Read the job and its parameters
curl -sg -o /dev/null -w "%{http_code}\n" -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_JOB_URL/api/json"
curl -sg -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_JOB_URL/api/json?tree=name,inQueue,property[parameterDefinitions[name]]"; echocurl -sg -o /dev/null -w "%{http_code}\n" -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_JOB_URL/api/json"
curl -sg -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_JOB_URL/api/json?tree=name,inQueue,property[parameterDefinitions[name]]"; echocurl.exe -sg -o NUL -w "%{http_code}\n" -u "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)" "$env:JENKINS_JOB_URL/api/json"
curl.exe -sg -u "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)" "$env:JENKINS_JOB_URL/api/json?tree=name,inQueue,property[parameterDefinitions[name]]"You should see 200, then JSON with "name":"kims-site-build" and the three parameter names PUBLISH_VERSION, CAUSE and TRIGGER_ACTOR. If the names are missing, the CMS will get HTTP 400: add the parameters. -g stops curl reading the square brackets as a pattern.
#3. Read the queue
curl -sg -o /dev/null -w "%{http_code}\n" -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_ROOT/queue/api/json?tree=items[id,why]"curl -sg -o /dev/null -w "%{http_code}\n" -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_ROOT/queue/api/json?tree=items[id,why]"curl.exe -sg -o NUL -w "%{http_code}\n" -u "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)" "$env:JENKINS_ROOT/queue/api/json?tree=items[id,why]"You should see 200.
#4. Start a build (this really builds and deploys the website)
Only when a build is wanted, for example the first build once the content is loaded. It runs the same build a publish would.
curl -s -i -X POST -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_JOB_URL/buildWithParameters?PUBLISH_VERSION=1&CAUSE=manual" | grep -iE '^HTTP/|^location:'curl -s -i -X POST -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_JOB_URL/buildWithParameters?PUBLISH_VERSION=1&CAUSE=manual" | grep -iE '^HTTP/|^location:'curl.exe -s -i -X POST -u "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)" "$env:JENKINS_JOB_URL/buildWithParameters?PUBLISH_VERSION=1&CAUSE=manual" | Select-String -Pattern '^HTTP/|^location:'You should see HTTP/1.1 201 Created (or HTTP/2 201) and Location: https://<JENKINS_HOST>/queue/item/<ID>/. No crumb was needed. The number in Location is the queue item.
#5. Follow the queue item to its build number
curl -sg -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_ROOT/queue/item/<ID>/api/json?tree=why,cancelled,executable[number]"; echocurl -sg -u "$JENKINS_USER:$JENKINS_TOKEN" "$JENKINS_ROOT/queue/item/<ID>/api/json?tree=why,cancelled,executable[number]"; echocurl.exe -sg -u "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)" "$env:JENKINS_ROOT/queue/item/<ID>/api/json?tree=why,cancelled,executable[number]"While it waits you see "why":"Waiting for next available executor ..."; once it starts, "executable":{"number":<N>}. A queue item is forgotten a few minutes after it starts, and then this answers 404, which the CMS treats as an answer, not an error.
#With Invoke-RestMethod instead of curl.exe (Windows)
$pair = "$($env:JENKINS_USER):$($env:JENKINS_TOKEN)"
$h = @{ Authorization = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair)) }
Invoke-RestMethod -Headers $h -Uri "$env:JENKINS_ROOT/whoAmI/api/json"
(Invoke-RestMethod -Headers $h -Uri "$env:JENKINS_JOB_URL/api/json?tree=property[parameterDefinitions[name]]").property.parameterDefinitions.name
Remove-Variable pair, hYou should see your user's name and authenticated : True, then the three parameter names.
#Clear the token from your shell
unset JENKINS_TOKENunset JENKINS_TOKENRemove-Item Env:JENKINS_TOKEN#Test from inside the cluster
The CMS pods must reach Jenkins too, which a firewall may block even when your laptop can. This uses the worker pod's own settings, so no token is typed (the command is the same on every system, and its single-quoted JavaScript survives every shell):
kubectl -n kims exec deploy/kims-worker -- node -e "fetch(process.env.JENKINS_JOB_URL + '/api/json', {headers: {Authorization: 'Basic ' + Buffer.from(process.env.JENKINS_USER + ':' + process.env.JENKINS_TOKEN).toString('base64')}}).then(r => console.log('HTTP', r.status)).catch(e => console.log('FAILED', e.cause ? e.cause.code : e.message))"kubectl -n kims exec deploy/kims-worker -- node -e "fetch(process.env.JENKINS_JOB_URL + '/api/json', {headers: {Authorization: 'Basic ' + Buffer.from(process.env.JENKINS_USER + ':' + process.env.JENKINS_TOKEN).toString('base64')}}).then(r => console.log('HTTP', r.status)).catch(e => console.log('FAILED', e.cause ? e.cause.code : e.message))"kubectl -n kims exec deploy/kims-worker -- node -e "fetch(process.env.JENKINS_JOB_URL + '/api/json', {headers: {Authorization: 'Basic ' + Buffer.from(process.env.JENKINS_USER + ':' + process.env.JENKINS_TOKEN).toString('base64')}}).then(r => console.log('HTTP', r.status)).catch(e => console.log('FAILED', e.cause ? e.cause.code : e.message))"You should see HTTP 200. FAILED ETIMEDOUT or FAILED ENOTFOUND means the pods cannot reach Jenkins (Outbound access); FAILED UNABLE_TO_VERIFY_LEAF_SIGNATURE or SELF_SIGNED_CERT_IN_CHAIN means Jenkins uses a certificate from KIMS's own CA that the pods do not trust (Troubleshooting). HTTP 401 or 403 means the Secret holds the wrong token.
#Rotate the token
- As the CMS user, Security, API Token, Add new Token, copy it.
- Replace the
kims-jenkinsSecret'stoken(Secrets). - Restart the CMS and worker so they read it:
kubectl -n kims rollout restart deploy/kims-cms deploy/kims-worker. - Run test 1 from inside the cluster.
- Back on Security, API Token, delete the old token (the bin icon).
#If it goes wrong
| What you see | Likely cause | What to do |
|---|---|---|
401 Unauthorized, or whoAmI says anonymous |
Wrong user ID or token, or the token was revoked | Check JENKINS_USER is the user ID; make a new token |
403 Forbidden on api/json |
No Overall/Read, or no Job/Read on the folder or job | Give the user permission |
403 on buildWithParameters with is missing the Job/Build permission |
No Job/Build on the job | Same |
403 No valid crumb was included in the request |
A password was used, not an API token | Use an API token |
400 on buildWithParameters |
The job has no parameters defined yet | Site job |
404 |
URL wrong: missing /job/<folder>, a trailing typo, or the user cannot see the job (Jenkins answers 404 rather than 403 for an item you may not read) |
Compare with the job's address in the browser; check Job/Read |
302 to a login page |
KIMS's Jenkins sits behind a sign-in proxy that does not let basic auth through | KIMS must allow API calls with basic auth to reach Jenkins |
| The Builds screen says Jenkins is unavailable | JENKINS_JOB_URL is unset in the pod |
Set it in the Helm values and redeploy |
#Sources
kims-v2/apps/cms/src/lib/builds/jenkins.tskims-v2/apps/cms/src/lib/builds/request.tskims-v2/docs/CONFIG.md, Jenkins (site builds)kims-v2/deploy/jenkins/README.md(main), section 4, andREADME-site.md(main), "Who may start it"kims-v2/deploy/helm/kims/values-production.example.yaml(main),JENKINS_JOB_URL,JENKINS_USER,secretEnv.JENKINS_TOKEN- https://www.jenkins.io/doc/book/using/remote-access-api/
- https://www.jenkins.io/doc/book/security/csrf-protection/
- https://www.jenkins.io/doc/book/security/managing-security/
- https://www.jenkins.io/doc/book/managing/users/
- https://plugins.jenkins.io/matrix-auth/
- https://plugins.jenkins.io/role-strategy/