TecnoShop's chain now integrates, delivers and deploys with quality guarantees: tests, coverage, the Quality Gate, immutable artifacts, approvals and rollback. But none of those stages asks whether the code contains a forgotten API key, whether one of the 80 dependencies of orders-api has a vulnerability published last week, or whether someone could modify the Jenkinsfile itself to walk away with ssh-production. DevSecOps means integrating security into the chain the same way the tests were integrated: automatically, on every change and as early as possible. In this lesson you will build the pipeline's threat model, create a custom agent image with the security tools, add secret scanning with gitleaks and dependency analysis with OWASP Dependency-Check, Trivy and npm audit, generate a CycloneDX SBOM that will travel with the jar, prepare image scanning for module 8, learn about artifact signing and provenance, decide what blocks and what only warns, and review the security of Jenkins itself within the chain. You will finish the module with the complete state of the two orders-api pipelines.
Mandatory review with security and compliance. The thresholds, exceptions, tools and permissions in this lesson are a reasonable starting point for a team like TecnoShop's, not an approved policy. Before applying them in a real organization, review them with the information security officer and, where applicable, with whoever is responsible for regulatory compliance (for example, PCI DSS if card payments are processed, the GDPR for personal data, or ISO 27001 or Spain's ENS if the organization is certified). The pipeline enforces the policy; it does not define it.
Shift Left and the Threat Model of a Pipeline
Shift left means detecting security problems as close as possible to the moment they are introduced: a key in the code is caught in the PR that adds it, not in an audit six months later, when it is already in a hundred clones. It is the same fast-feedback principle from 07-01, applied to security.
But a pipeline does not only protect software: it is also a target. It holds production credentials, runs code from anyone who opens a PR and decides what reaches customers. A threat model answers "what can be attacked, and how?":
flowchart LR
DEV["Developer"] -->|"1 code"| GH["GitHub<br/>orders-api"]
DEP["Dependencies<br/>(Maven Central, npm)"] -->|"2 dependencies"| NX["Nexus"]
GH -->|"3 Jenkinsfile, ci/, deploy/"| J["Jenkins<br/>controller"]
LIB["tecnoshop-lib"] -->|"4 trusted library"| J
J --> A["5 linux-agent-01"]
CR["6 credentials"] --> A
NX --> A
A -->|"7 artifact"| NX
A -->|"8 deployment"| P["staging and production"]
| # | What | Typical threat | Example at TecnoShop |
|---|---|---|---|
| 1 | Code | Secrets in the repository; vulnerabilities (injection, deserialization) | Diego leaves a service token in application.properties |
| 2 | Dependencies | Known vulnerabilities; malicious or impersonated packages (typosquatting) | A version of a JSON library with a critical CVE |
| 3 | Pipeline definition | A modified Jenkinsfile that exfiltrates credentials or skips stages |
A PR that adds sshagent(['ssh-dev']) and a curl to an external server |
| 4 | Shared library | Trusted code, outside the sandbox (04-06) | A change to tecnoshop-lib that affects every pipeline |
| 5 | Agents | Persistent state shared between builds; tampered tools | A poisoned Maven cache (06-02) |
| 6 | Credentials | Excessive scope; reuse across environments | A key that opens both dev and production |
| 7 | Artifacts | The artifact is swapped between the build and the deployment | A jar in Nexus that differs from the one that was tested |
| 8 | Deployment | Unauthorized deployment or deployment outside the process | Someone with SSH access to prod-01 who copies a jar by hand |
What TecnoShop already has against some of these: the Trust policy for PRs from forks (04-05), the Nexus mirror that rules out arbitrary Maven repositories (06-05), a versioned known_hosts (06-06), immutable releases and the SHA-256 check between CI and CD (07-02, 07-03), per-environment credentials in the orders-delivery folder, and approvals. What is missing are automated controls on the content (code and dependencies) and some protections for the chain itself.
Controls by Phase
| Phase | Control | Tool at TecnoShop | Lesson |
|---|---|---|---|
| Before the commit | Local secret detection; hooks | gitleaks (optional, in the pre-commit hook from 03-06) |
This one |
| Push | Blocking known secrets on push | GitHub push protection (depending on the repository's plan) | This one |
PR and main |
Secrets in the code | gitleaks | This one |
PR and main |
Known vulnerabilities in dependencies (SCA) | OWASP Dependency-Check; npm audit |
This one |
main |
Static application security testing (SAST) | SonarQube and its Quality Gate | 06-04 and this one |
| PR review | Changes to the pipeline and the deployment approved by the platform team | CODEOWNERS + protect-main |
This one |
| Packaging | Component inventory | CycloneDX SBOM | This one |
| Nightly | Secrets across the whole history | gitleaks in git mode |
This one |
| Promotion | Vulnerabilities known today in the release | Trivy on the SBOM | This one |
| Image | Vulnerabilities in the base system and the application in the image | Trivy image |
08-01 |
| Deployment | Integrity and origin of the artifact | The CI SHA-256; signing (cosign) as the next step | 07-03 and this one |
The Tools on the Agent: The tecnoshop/linux-agent Image
gitleaks and Trivy are binaries that the agent needs. The rule from 05-01 still applies: nothing is installed by hand on linux-agent-01; if the container were rebuilt, it would disappear. Since the agent does not run Docker yet (that comes in 08-01), the solution is a custom agent image, versioned in the lab directory.
~/tecnoshop-jenkins/linux-agent/Dockerfile:
# TecnoShop agent image: jenkins/inbound-agent + security tools at pinned versions.
FROM jenkins/inbound-agent:latest-jdk21
# Versions and SHA-256 checksums of the Linux x86_64 .tar.gz files, copied from the checksums file
# published with each release (gitleaks_<v>_checksums.txt and trivy_<v>_checksums.txt) and reviewed in the PR.
ARG GITLEAKS_VERSION=X.Y.Z
ARG GITLEAKS_SHA256=replace-with-the-sha256-of-the-linux_x64-tar-gz
ARG TRIVY_VERSION=X.Y.Z
ARG TRIVY_SHA256=replace-with-the-sha256-of-the-Linux-64bit-tar-gz
USER root
RUN set -eu; \
cd /tmp; \
curl -fsSLo gitleaks.tar.gz \
"https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"; \
echo "${GITLEAKS_SHA256} gitleaks.tar.gz" | sha256sum -c -; \
tar -xzf gitleaks.tar.gz gitleaks; \
install -m 0755 gitleaks /usr/local/bin/gitleaks; \
curl -fsSLo trivy.tar.gz \
"https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"; \
echo "${TRIVY_SHA256} trivy.tar.gz" | sha256sum -c -; \
tar -xzf trivy.tar.gz trivy; \
install -m 0755 trivy /usr/local/bin/trivy; \
rm -f /tmp/gitleaks* /tmp/trivy*; \
gitleaks version; \
trivy --version
ENV TRIVY_CACHE_DIR=/home/jenkins/agent/.cache/trivy
USER jenkinsLine by line:
FROM jenkins/inbound-agent:latest-jdk21: the same image the service has used since 05-01. For a production image, pin the exact tag (or the digest), following the same criterion as for the controller in 05-04.ARG ...: the version and checksum of each tool. The values in the example are placeholders: until you replace them, the download or the verification will fail and the image will not build, which is the safe outcome. Pinning the version makes the agent reproducible; upgrading it is a visible PR.USER root/USER jenkins: installing requiresroot; the agent must run unprivileged, like the original image.curl -fsSLo: downloads, failing on any HTTP error (-f), with no progress bar (-s) but showing errors (-S), following redirects (-L), to the given file (-o).sha256sum -c -: checks that the downloaded file has exactly the checksum you pinned. If GitHub served a different file (or someone had replaced it after you reviewed the checksum), the build fails. For a guarantee of authenticity as well as integrity, Trivy publishes its binaries signed with cosign (section 12), which you can verify withcosign verify-blob.tar -xzf ... gitleaks: extracts only the binary.install -m 0755: copies it to/usr/local/binwith execute permissions.gitleaks versionandtrivy --version: if something went wrong, the image build fails here and not in the first pipeline build.ENV TRIVY_CACHE_DIR: Trivy downloads its vulnerability database (hundreds of MB) and caches it. Inside/home/jenkins/agent, which is thelinux_agent_01volume, it survives rebuilding the container, just like the local Maven repository.
In docker-compose.yml, the linux-agent-01 service switches from image: to build: (everything else stays the same):
linux-agent-01:
build: ./linux-agent
image: tecnoshop/linux-agent:1
container_name: linux-agent-01
restart: unless-stopped
# ... depends_on, environment and volumes as in 05-01 ...cd ~/tecnoshop-jenkins
docker compose up -d --build linux-agent-01
docker compose exec linux-agent-01 sh -c 'gitleaks version && trivy --version'The agent reconnects on its own (the secret and the name do not change) and keeps its workspace and caches. Every time you upgrade a tool, bump the tag number (tecnoshop/linux-agent:2). In 08-01, this image will be published to registry.tecnoshop.local and will serve as the base for ephemeral agents.
Secret Scanning with gitleaks
gitleaks searches files or the Git history for strings that look like secrets: AWS keys, GitHub or Slack tokens, private keys, passwords in URLs... It combines regular expressions per type of secret with measures of entropy (how "random" a string is).
It has two modes:
| Mode | Command | What it scans | When at TecnoShop |
|---|---|---|---|
| Directory | gitleaks dir . |
The files as they are now | PR and main: fast, catches what is being added |
| History | gitleaks git . |
Every commit in the repository | The nightly main build: catches secrets that were added and later "deleted" but are still in the history |
(Older versions of gitleaks used the detect and protect subcommands; they still work, but dir and git are the current ones.)
.gitleaks.toml
At the root of orders-api:
title = "gitleaks for orders-api (TecnoShop)"
[extend]
useDefault = true
[[rules]]
id = "tecnoshop-internal-token"
description = "TecnoShop internal API token"
regex = '''\btks_[A-Za-z0-9]{32}\b'''
keywords = ["tks_"]
[allowlist]
description = "Build output and clearly fake test values"
paths = [
'''(^|/)target/''',
'''(^|/)node_modules/''',
]
regexes = [
'''NotARealPassword-\d+''',
][extend] useDefault = true: starts from the rules that ship with gitleaks (hundreds of secret types) and adds your own.[[rules]]: a new rule for a fictitious TecnoShop internal token format (tks_followed by 32 characters).keywordsspeeds up the scan: the expression is only applied to lines that containtks_.[allowlist]: what must not raise an alarm.pathsexcludes build output (the scan runs in parallel with other stages that write totarget/);regexesexcludes the course's fake values. Recent versions of gitleaks also support several lists with[[allowlists]].- A specific exception (a false positive on one line) is recorded in
.gitleaksignorewith the fingerprint gitleaks prints for that finding, instead of widening theallowlist.
These two files, .gitleaks.toml and .gitleaksignore, decide what is not detected: CODEOWNERS will protect them (section 14).
Complements Outside Jenkins
- On push: GitHub offers secret scanning and push protection, which rejects the push if it contains a secret from a known provider. Its availability depends on the type of repository and the plan. If you have it, turn it on: it is even further left than the PR.
- Locally: gitleaks can run in the
pre-commithook you saw in 03-06 (gitleaks git --pre-commit --staged). It is a help for the developer, not a control: it can be bypassed.
scanSecrets in tecnoshop-lib v1.5.0
Secret scanning is the same for every TecnoShop project: it is a library step. vars/scanSecrets.groovy:
/**
* Scans for secrets with gitleaks (included in the tecnoshop/linux-agent image).
*
* scanSecrets() // workspace files
* scanSecrets history: true, report: 'gitleaks-history.json' // the whole Git history
*
* Fails the build if it finds anything. The report is archived with the values redacted (--redact).
*/
def call(Map config = [:]) {
String report = config.report ?: 'gitleaks.json'
String mode = config.history ? 'git' : 'dir'
String configOption = fileExists('.gitleaks.toml') ? '--config .gitleaks.toml' : ''
int status = sh(script: "gitleaks ${mode} ${configOption} --redact --no-banner --exit-code 2 " +
"--report-format json --report-path ${report} .",
returnStatus: true, label: "Secrets (gitleaks ${mode})")
archiveArtifacts artifacts: report, allowEmptyArchive: true
if (status == 2) {
error "scanSecrets: gitleaks found possible secrets. Check ${report} " +
'(values redacted) and follow the exposed-secrets procedure.'
}
if (status != 0) {
error "scanSecrets: gitleaks ended with an error (code ${status})"
}
}mode:dirby default;gitif the history is requested.--redact: hides the value of the secret in the console and in the report. A scanner that prints the secret in the Jenkins log would expose it to everyone who can read the build.--exit-code 2: gitleaks exits with1both when it finds secrets and when it hits an internal error. With a dedicated code for "findings", the step can tell the two cases apart and give each one a suitable message.returnStatus: true: theshstep returns the code instead of failing, so that the report can be archived before deciding.archiveArtifacts ... allowEmptyArchive: true: the JSON report (file, line, rule, commit, author; never the value) stays with the build.- The interpolated variables (
mode,configOption,report) come from theJenkinsfileitself or from the library, not from external data.
With its vars/scanSecrets.txt and a JenkinsPipelineUnit test that mocks the three exit codes, it is released as v1.5.0 (a new, compatible feature).
In orders-api, two new branches in the parallel Checks stage:
stage('Secrets') {
steps {
scanSecrets()
}
}
stage('Secrets in history') {
when {
allOf {
branch 'main'
triggeredBy 'TimerTrigger'
}
}
steps {
scanSecrets history: true, report: 'gitleaks-history.json'
}
}Secrets: in every build (PRs,main, tags). It takes a few seconds and does not depend onRUN_TESTS: security cannot be unchecked.Secrets in history: only in the nightlymainbuild (triggeredBy 'TimerTrigger', thecronintriggers). It needs the full history: it would not work with a shallow clone (06-01).
What to Do When a Secret Turns Up
Deleting the line is not the solution. As soon as a secret reaches a commit that has been pushed, you have to consider it compromised: it is in the history, in the whole team's clones, in forks, perhaps in GitHub caches and in build logs.
| Step | What | Why |
|---|---|---|
| 1 | Revoke or rotate the secret at its source (regenerate the token, change the password, replace the SSH key) | It is the only thing that prevents it from being used. Everything else is cleanup |
| 2 | Update the Jenkins credential (same ID) and the services that use it | So that nothing breaks with the new value |
| 3 | Move the value out of the code: into a Jenkins credential, the server configuration (/etc/orders-api/) or a secrets manager |
So that it does not happen again |
| 4 | Review the logs of the affected service for suspicious use | To find out whether someone took advantage of it |
| 5 | (Optional) Rewrite the history (git filter-repo) and ask everyone to re-clone |
It reduces future exposure, but does not undo past exposure; it requires coordination and bypassing protect-main |
| 6 | Record the incident and report it to security | Traceability; there may be notification obligations |
The order matters: if the history is rewritten without rotating, the secret is still valid and someone may already have it.
Software Composition Analysis (SCA)
The code written for orders-api itself is a few hundred lines; its dependencies (Spring Boot, embedded Tomcat, Jackson, Logback...) add up to hundreds of thousands. The most frequent vulnerabilities in modern applications are not in your own code but in third-party components with already published vulnerabilities (CVEs). Software composition analysis compares the list of dependencies against vulnerability databases.
OWASP Dependency-Check in orders-api
OWASP Dependency-Check identifies each dependency and cross-references it with the NVD (NIST's National Vulnerability Database), among other sources. It is integrated as a Maven plugin. In pom.xml:
<properties>
<!-- ... previous properties ... -->
<dependency-check.version>X.Y.Z</dependency-check.version> <!-- pin the latest stable -->
</properties> <plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>${dependency-check.version}</version>
<configuration>
<nvdApiKeyEnvironmentVariable>NVD_API_KEY</nvdApiKeyEnvironmentVariable>
<failBuildOnCVSS>7</failBuildOnCVSS>
<formats>
<format>HTML</format>
<format>XML</format>
</formats>
<suppressionFiles>
<suppressionFile>dependency-check-suppressions.xml</suppressionFile>
</suppressionFiles>
<ossindexAnalyzerEnabled>false</ossindexAnalyzerEnabled>
</configuration>
</plugin>- No
<executions>: the plugin is not bound to any phase, so./mvnw verifyon Diego's laptop does not run it. The pipeline invokes it explicitly withdependency-check:check. nvdApiKeyEnvironmentVariable: the NVD heavily throttles downloads without an API key; with one, the first database download takes minutes instead of hours. The plugin reads the key from theNVD_API_KEYvariable, which the pipeline injects from a credential: never inpom.xmlor as a command-line argument. (If your plugin version did not have this option, the alternative isnvdApiServerId, which reads the key from a<server>entry in the managed settings.)failBuildOnCVSS 7: the build fails if any dependency has a vulnerability with a CVSS score of 7 or more (high or critical severity). CVSS scores range from 0 to 10.formats: HTML for people and XML for the Jenkins plugin.suppressionFiles: the documented exceptions (section 13).ossindexAnalyzerEnabled false: the Sonatype OSS Index analyzer requires its own credentials; TecnoShop uses the NVD.
The NVD key: you can request one for free on the NVD website (the Developers section). In Jenkins, a Secret text credential, ID nvd-api-key, global scope (every build uses it, PRs included, and it only serves to download public data; its risk is low), fake example value 00000000-0000-0000-0000-fake00000000, description NVD API key for Dependency-Check. Owner: Laura.
The cache: Dependency-Check stores its database in the local Maven repository (.../org/owasp/dependency-check-data/), which on linux-agent-01 is on the persistent volume. Only the first run downloads everything; after that, it updates what is new at most every few hours. Run a main build by hand before enabling the stage on PRs, so that nobody has to sit through that first download. If two builds try to update the database at the same time, the second one waits for the first.
In Jenkins, the OWASP Dependency-Check plugin (add it to plugins.txt) provides the dependencyCheckPublisher step, which shows the results in the build and as a trend. The Dependency analysis branch of Checks becomes:
stage('Dependency analysis') {
options {
timeout(time: 15, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
withCredentials([string(credentialsId: 'nvd-api-key', variable: 'NVD_API_KEY')]) {
mavenTecnoShop goals: 'dependency-check:check', label: 'Known vulnerabilities (OWASP Dependency-Check)'
}
}
post {
always {
archiveArtifacts artifacts: 'dependencies.txt,target/dependency-check-report.html', allowEmptyArchive: true
dependencyCheckPublisher pattern: 'target/dependency-check-report.xml', unstableTotalMedium: 1
}
}
}- A 15-minute
timeout: plenty for a database update. withCredentials([string(...)]): the key exists as an environment variable only for the duration of the Maven call, and it is masked in the log.post { always }: the report is archived and published also when the build fails because of a vulnerability, which is exactly when it is needed most.unstableTotalMedium: 1: with one or more medium-severity vulnerabilities, the build turns UNSTABLE (yellow); high and critical ones have already turned it red throughfailBuildOnCVSS.
Trivy in fs Mode, as an Alternative or a Complement
Trivy (from Aqua Security, open source) is a versatile scanner: dependencies, images, infrastructure configuration, secrets, licenses. For a repository's dependencies:
fs .: scans the dependency files it finds (pom.xml,package-lock.json...). With Maven, it may need to query the artifact repository to resolve transitive dependencies.--scanners vuln: vulnerabilities only.--severity HIGH,CRITICAL: only the serious ones.--exit-code 1: exits with an error if it finds any.- It uses its own databases (compiled from GitHub advisories, distributions and ecosystems), which it downloads and stores in
TRIVY_CACHE_DIR.
TecnoShop uses Dependency-Check in the Java CI and Trivy at promotion time (section 10) and for images: two different data sources complement each other.
Comparison
| Tool | Ecosystems | Vulnerability source | Strengths | Things to keep in mind |
|---|---|---|---|---|
| OWASP Dependency-Check | Java (and others, with less precision) | NVD and others | Maven and Jenkins plugins; expiring suppressions | Large database; false positives from approximate identification (CPE) |
| Trivy | Many languages, images, IaC | Several (GitHub Advisories, distributions...) | A single tool for everything; fast; SBOM | For Java in fs mode, it may need to resolve dependencies |
npm audit |
npm | npm registry advisories | Included in npm; nothing to install | Depends on the registry (or the proxy) supporting the audit endpoint |
| Dependabot / Renovate | Many | GitHub Advisories and others | They open update PRs automatically | They are not a pipeline gate: they propose changes |
| Commercial products (Snyk, Mend, Sonatype Lifecycle...) | Many | Proprietary databases | Curated data, prioritization, policies | Cost; vendor dependence |
Detecting is half the job; the other half is upgrading. A bot such as Dependabot or Renovate that opens PRs with new versions (and the CI that tests them) is the natural complement to any scanner.
SAST: SonarQube and Semgrep
Static application security testing (SAST) looks for vulnerabilities in your own code without running it. TecnoShop has been doing this since 06-04: SonarQube includes security rules (vulnerabilities and security hotspots, sensitive snippets that a person must review), and its "TecnoShop" Quality Gate blocks main with waitForQualityGate abortPipeline: true. To make sure the security part carries the weight it should, Laura reviews the Quality Gate conditions on new code with the security officer: a security rating of A and 100% of security hotspots reviewed.
Two limits worth knowing: data-flow analysis for detecting injections (taint analysis) is in the paid editions of SonarQube, and the Community Build only analyzes the main branch. Semgrep (with an open source engine and community rules per language, such as p/java) is a lightweight complement that can run on PRs (semgrep scan --config p/java --error) and publish its results in SARIF format, which Warnings NG can display. TecnoShop notes it down as the next step if PRs need security feedback before they reach main.
SBOM with CycloneDX
An SBOM (Software Bill of Materials) is the inventory of every component in an artifact: name, version, identifier (a purl, such as pkg:maven/com.fasterxml.jackson.core/[email protected]), license and relationships. It answers in seconds the question that comes up every time a high-profile vulnerability is published: "are we affected, and in which deployed versions?". More and more customers and regulations require it. The two standard formats are CycloneDX (OWASP) and SPDX (Linux Foundation).
In the orders-api pom.xml:
<plugin>
<groupId>org.cyclonedx</groupId>
<artifactId>cyclonedx-maven-plugin</artifactId>
<version>X.Y.Z</version> <!-- pin the latest stable -->
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>makeBom</goal>
</goals>
</execution>
</executions>
<configuration>
<outputFormat>json</outputFormat>
<outputName>bom</outputName>
</configuration>
</plugin><phase>package</phase>andmakeBom: the SBOM is generated on everypackageand, therefore, inPackageand inPublish, without changing any command.outputFormat jsonandoutputName bom: the file istarget/bom.json. By default it includes runtime dependencies, not test ones.- The plugin attaches the SBOM to the project with the
cyclonedxclassifier:./mvnw deploypublishes it to Nexus next to the jar, asorders-api-1.2.0-cyclonedx.json. Every release carries its inventory in the artifact repository, with the same immutability guarantees.
In Package, the SBOM is also archived with the build:
To make use of the SBOMs of every version at once, there is OWASP Dependency-Track: it ingests SBOMs, continuously watches them for new vulnerabilities and raises alerts. It is the natural next step once TecnoShop has more services.
Promotion Gate: Reviewing the Release Before Deploying It
A release published on Monday with no known vulnerabilities may have a critical CVE by Wednesday, when its move to production is approved. That is why orders-api-cd takes another look at promotion time, on the exact SBOM that was published with it.
deploy/fetch-release.sh also downloads the SBOM, if there is one (releases older than this lesson do not have it):
SBOM_URL="$NEXUS_URL/repository/maven-releases/com/tecnoshop/orders-api/$VERSION/orders-api-$VERSION-cyclonedx.json"
rm -f target/bom.json
if curl --fail --silent --location -o target/bom.json "$SBOM_URL"; then
echo "==> Release SBOM downloaded"
else
rm -f target/bom.json
echo "WARNING: release $VERSION has no published SBOM"
fiAnd a new script, ci/review-vulnerabilities.sh:
#!/bin/sh
# Promotion gate: vulnerabilities known TODAY in the release that is about to be deployed.
# Blocks on CRITICAL; shows HIGH and CRITICAL. Exceptions in .trivyignore (with an expiry date).
set -eu
if [ -f target/bom.json ]; then
set -- sbom target/bom.json
else
echo "WARNING: no SBOM; scanning the jar"
set -- rootfs --scanners vuln target
fi
trivy "$@" --severity HIGH,CRITICAL --ignorefile .trivyignore --format table --exit-code 0
trivy "$@" --severity CRITICAL --ignorefile .trivyignore --exit-code 1 --quietset -- ...: replaces the script's arguments with the Trivy subcommand and its target;"$@"reuses them in both calls with no quoting problems.trivy sbom target/bom.json: scans the components in the SBOM. Without an SBOM,trivy rootfsscans the jar (in this mode Trivy recognizes the dependencies packaged inside a Spring Boot jar).- First call: shows the table of high and critical vulnerabilities without failing (
--exit-code 0), so that the approver can see them in the console. - Second call: fails if there is any critical one that is not exempted. High-severity ones that appeared after the build do not block promotion, but they stay in plain view of whoever approves; high-severity ones known at build time would already have blocked CI.
.trivyignore: Trivy's exceptions, versioned at the root of the repository (section 13).
In ci/Jenkinsfile.cd, between Fetch release and Staging:
stage('Vulnerability review') {
agent {
label 'linux'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
unstash 'release'
sh label: 'Trivy on the release SBOM', script: 'sh ci/review-vulnerabilities.sh'
}
post {
cleanup {
cleanWs()
}
}
}The release stash now includes target/bom.json and .trivyignore.
Container Image Scanning with Trivy
In module 8, orders-api will also be packaged as an image. Besides the jar, an image contains a base operating system (Debian or Alpine packages, or a distroless image) with its own vulnerabilities, which neither Dependency-Check nor the Maven SBOM can see. Trivy scans them:
// PREVIEW of 08-01: requires the image built in the 'Image' stage from 06-05
sh label: 'Image vulnerabilities', script: '''
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 \
--format table "$IMAGE:$IMAGE_TAG"
trivy image --format cyclonedx --output image-bom.json "$IMAGE:$IMAGE_TAG"
'''trivy image: downloads the image (or reads it from the local Docker) and scans its layers: system packages and application dependencies.--ignore-unfixed: ignores vulnerabilities that do not have a published fix yet. It is a common criterion for not blocking on something that cannot be fixed yet; security must decide it, and the ignored ones must still be monitored.--format cyclonedx --output: the SBOM of the image, which complements the jar's.
Two practices that cut the number of findings more than any exception: minimal base images (distroless or -slim variants), and rebuilding images frequently to pick up fixes to the base system. Trivy also scans configuration (trivy config on a Dockerfile and Kubernetes manifests), which will be useful in 08-02.
Signing and Provenance: cosign and SLSA
The SHA-256 check between CI and CD guarantees that the deployed jar is the one CI tested, as long as Jenkins is trusted. Two ideas take the guarantee further:
- Artifact signing: the build signs the artifact with a key (or with a short-lived identity), and the deployment verifies the signature before using it. cosign, from the Sigstore project, is the de facto standard for container images:
cosign signon the image's digest reference andcosign verifybefore deploying, with managed keys or in keyless mode (short-lived certificates tied to an OIDC identity and recorded in a public transparency log). For Maven artifacts there are classic GPG signatures and Sigstore projects for Java. - Provenance: a signed document that says how the artifact was built: from which repository and commit, with which build system, with which parameters. SLSA (Supply-chain Levels for Software Artifacts, pronounced "salsa") defines maturity levels for the build chain:
| SLSA level (Build) | Main requirement | TecnoShop today |
|---|---|---|
| L1 | Provenance describing the build exists | Roughly: build-info.txt, the build description, fingerprints (not in a standard format) |
| L2 | The build runs on a dedicated build platform and the provenance is signed by it | Jenkins is the platform; generating and signing the provenance is still missing (for example, with cosign attest and the in-toto format) |
| L3 | The platform is hardened: builds are isolated from one another, and signing secrets are inaccessible to the build's code | Requires ephemeral, isolated agents (08-01, 08-02) and separating signing from builds |
TecnoShop does not implement signing or formal provenance yet; it is the natural next step once images reach Kubernetes, where admission policies can reject images without a valid signature.
Gate Policy and Expiring Exceptions
A gate is a control that decides whether the change moves on. If every gate blocks, the team learns to bypass them; if none blocks, nobody looks at the warnings. TecnoShop's policy:
| Control | Where | Result if it finds something | Why |
|---|---|---|---|
| Secret detected (gitleaks) | Every build | FAILURE | An exposed secret is an incident, not a warning |
| Dependency vulnerability with CVSS ≥ 7 (Dependency-Check) | Every build | FAILURE | High or critical: it does not get into main and is not published |
| Vulnerability with CVSS 4 to 6.9 | Every build | UNSTABLE | The upgrade has to be planned, without blocking the work |
npm audit high or critical (catalog-web) |
Every build | FAILURE | The same criterion as for Java |
| SonarQube Quality Gate (security included) | main |
FAILURE | Since 06-04 |
| Critical known today in the release (Trivy on the SBOM) | Promotion (CD) | FAILURE (it does not reach staging) |
It may have appeared after the build |
| High known today in the release | Promotion (CD) | Only reported in the console | Visible to whoever approves; fixed with a new release |
| Image with fixable high or critical vulnerabilities (Trivy) | 08-01 | FAILURE | The same criterion |
Documented, Expiring Exceptions
There will always be false positives (Dependency-Check sometimes misidentifies a library) and vulnerabilities that do not apply (a CVE in a module that is not used). The answer is not to lower the threshold but an exception that meets four conditions: it is versioned (in the repository, with review), justified (why it does not apply), approved (by security, thanks to CODEOWNERS) and it expires (forcing a review).
dependency-check-suppressions.xml, at the root of orders-api:
<?xml version="1.0" encoding="UTF-8"?>
<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.3.xsd">
<suppress until="2027-01-31Z">
<notes><![CDATA[
SEC-2026-031 (fictitious example). False positive: CVE-2026-99999 affects the XML module
of fictitious-library, which orders-api does not include. Reviewed by the security team.
]]></notes>
<packageUrl regex="true">^pkg:maven/org\.example/fictitious-library@.*$</packageUrl>
<cve>CVE-2026-99999</cve>
</suppress>
</suppressions>until="2027-01-31Z": from that date on, the suppression stops applying and the build will fail again if the vulnerability is still there. Nobody has to remember to review it.notes: the review reference and the reason.packageUrl+cve: the exception is for that vulnerability in that library, not for every vulnerability in the library.
.trivyignore, with the same idea for Trivy:
# SEC-2026-031 (fictitious example): does not apply, see dependency-check-suppressions.xml CVE-2026-99999 exp:2027-01-31
exp:2027-01-31: the exception expires on that date.
The Security of Jenkins Within the Chain
The scanners protect the content. This list protects the chain:
Credentials: Least Privilege and per Environment
| Credential | Scope | Used by | Residual risk |
|---|---|---|---|
github-tecnoshop |
Global | Multibranch, CD, library | A GitHub App with minimal permissions (06-01) |
nexus-deployer (via maven-settings-tecnoshop-publish) |
Global | Publish |
A Jenkinsfile from a trusted PR could request it: mitigated by Trust, review and CODEOWNERS |
ssh-dev |
Global | Deploy to dev |
Same as the previous one; accepted for dev |
ssh-staging, ssh-production |
orders-delivery folder |
Only orders-api-cd and orders-api-rollback |
Whoever can change ci/ on main: covered by CODEOWNERS |
nvd-api-key |
Global | Dependency-Check | Low: it only downloads public data |
sonar-token, slack-token, registry-tecnoshop... |
Global | Their stages | Review each one with the same criterion |
The pending improvement, noted down by Laura: move the multibranch job into a folder too (orders-ci), with nexus-deployer and ssh-dev as folder credentials, so that no other Jenkins job can request them. And, in the medium term, replace long-lived keys with short-lived credentials issued on demand (federated cloud identities or a manager such as Vault, 04-04).
Changes to the Pipeline: CODEOWNERS
The protect-main rule requires an approval, but any approval: one of Diego's teammates can approve a PR that changes ci/Jenkinsfile.cd. With a CODEOWNERS file, GitHub automatically requests a review from the team that owns each path. .github/CODEOWNERS in orders-api (the GitHub teams are fictitious):
# Owners of each path. The LAST matching rule applies. * @tecnoshop/orders /Jenkinsfile @tecnoshop/platform /ci/ @tecnoshop/platform /deploy/ @tecnoshop/platform /.github/ @tecnoshop/platform /.gitleaks.toml @tecnoshop/platform @tecnoshop/security /.gitleaksignore @tecnoshop/security /.trivyignore @tecnoshop/security /dependency-check-suppressions.xml @tecnoshop/security
*: by default, theorders-apiteam reviews everything./Jenkinsfile,/ci/,/deploy/: the pipeline definition, CD, the rollback and the deployment scripts, which handle the production credentials, are reviewed by platform./.github/: protects the CODEOWNERS file itself.- Security exceptions are reviewed by security: nobody can silence a scanner without them seeing it.
And in the protect-main ruleset from 06-01, check Require review from Code Owners. Do the same in jenkins-shared-lib with * @tecnoshop/platform: the library is trusted and runs outside the sandbox, with access to the whole controller (04-06). Having pipelines use it by tag (@v1.5.0) protects against changes on its main, provided the v* tags are protected against being moved or deleted with a tag ruleset, as recommended in 06-05.
The Rest of the List
| Aspect | Measure at TecnoShop | Lesson |
|---|---|---|
| PRs from forks | Trust limited to users with write permission; never Everyone | 04-05 |
| Replay and configuration | Run/Replay and Job/Configure only for administrators; especially in orders-delivery |
05-02, 07-03 |
| Controller | 0 executors: no build runs on it | 05-01 |
| Agents | Permanent today, with workspace and caches shared between builds; the goal is ephemeral agents, one per build, destroyed when it finishes | 08-01, 08-02 |
| Build identity | Builds run with the system identity; the Authorize Project plugin lets them run with a user's identity and permissions | This one (mention) |
| Auditing | Audit Trail records configuration changes and build triggers; approvals stay in each build's log. Send both to a central store that Jenkins administrators cannot delete | 05-02 |
| Plugins | Security warnings from the plugin manager; planned upgrades | 05-04 |
catalog-web: Secrets and npm audit
catalog-web moves to @Library('[email protected]') _ (all the intermediate versions are compatible) and gains a new stage, Security, after Build:
stage('Security') {
agent {
label 'linux'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
scanSecrets()
nodejs(nodeJSInstallationName: 'node-22', configId: 'npmrc-tecnoshop') {
sh label: 'Dependency vulnerabilities (npm audit)',
script: 'npm audit --audit-level=high --omit=dev'
}
}
post {
cleanup {
cleanWs()
}
}
}- A single stage with an agent and two steps, because
catalog-webuses a globalagent noneand each agent costs an allocation. npm audit --audit-level=high: fails if there are high or critical vulnerabilities. It only needspackage-lock.json, notnode_modules, sonpm ciis not required.--omit=dev: only production dependencies, the ones that end up in what gets published. Development dependencies (Jest) run on the agent, not in customers' browsers; decide with security whether they should block too.npm auditcalls the audit endpoint of the configured registry, which is the Nexusnpm-publicgroup. If your Nexus version does not serve it, the command will fail with a registry error, not a vulnerability error; in that case, usetrivy fs --scanners vuln --severity HIGH,CRITICAL --exit-code 1 package-lock.jsoninstead, or point just this command at the public registry with--registry=https://registry.npmjs.org(it sends the list of dependencies, not the code).- The
catalog-web.gitleaks.tomlis like theorders-apione; it already excludesnode_modules/.
The orders-api Jenkinsfile at the End of Module 7
@Library('[email protected]') _
pipeline {
agent {
label 'linux'
}
options {
timestamps()
timeout(time: 30, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5'))
disableConcurrentBuilds(abortPrevious: env.CHANGE_ID != null)
preserveStashes(buildCount: 5)
}
parameters {
booleanParam(name: 'RUN_TESTS', defaultValue: true,
description: 'Uncheck only to quickly verify that the code compiles. Without tests nothing is analyzed, published or deployed, and the CD pipeline is not triggered. Security checks always run.')
}
triggers {
cron(env.BRANCH_NAME == 'main' ? 'TZ=Europe/Madrid\nH 2 * * 1-5' : '')
}
environment {
MAVEN_ARGS = '-B -ntp'
MAVEN_SETTINGS_ID = 'maven-settings-tecnoshop'
IMAGE = 'registry.tecnoshop.local/orders-api'
APP_VERSION = sh(script: './mvnw -q help:evaluate -Dexpression=project.version -DforceStdout',
returnStdout: true, label: 'Read the version from the pom').trim()
IMAGE_TAG = "${APP_VERSION}-${BUILD_NUMBER}"
}
stages {
stage('PR info') {
when {
changeRequest()
}
steps {
echo "PR #${env.CHANGE_ID} by ${env.CHANGE_AUTHOR}: ${env.CHANGE_BRANCH} → ${env.CHANGE_TARGET} (${env.CHANGE_URL})"
}
}
stage('Build') {
steps {
echo "Build ${env.BUILD_NUMBER} of ${env.JOB_NAME} | branch ${env.BRANCH_NAME} | version ${env.APP_VERSION} | RUN_TESTS=${params.RUN_TESTS}"
mavenTecnoShop 'clean compile'
}
}
stage('Checks') {
failFast true
parallel {
stage('Tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop 'test'
recordCoverage(
tools: [[parser: 'JACOCO', pattern: 'target/site/jacoco/jacoco.xml']],
id: 'jacoco',
name: 'Coverage (JaCoCo)',
sourceCodeRetention: 'LAST_BUILD',
qualityGates: [
[metric: 'LINE', baseline: 'PROJECT', threshold: 70.0, criticality: 'UNSTABLE'],
[metric: 'BRANCH', baseline: 'PROJECT', threshold: 60.0, criticality: 'UNSTABLE']
]
)
}
post {
always {
junit testResults: 'target/surefire-reports/*.xml', allowEmptyResults: false
}
failure {
echo 'The tests failed: check the Test Result page of the build.'
}
}
}
stage('Dependency analysis') {
options {
timeout(time: 15, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'dependency:tree -DoutputFile=dependencies.txt', label: 'Dependency tree'
withCredentials([string(credentialsId: 'nvd-api-key', variable: 'NVD_API_KEY')]) {
mavenTecnoShop goals: 'dependency-check:check', label: 'Known vulnerabilities (OWASP Dependency-Check)'
}
}
post {
always {
archiveArtifacts artifacts: 'dependencies.txt,target/dependency-check-report.html', allowEmptyArchive: true
dependencyCheckPublisher pattern: 'target/dependency-check-report.xml', unstableTotalMedium: 1
}
}
}
stage('Secrets') {
steps {
scanSecrets()
}
}
stage('Secrets in history') {
when {
allOf {
branch 'main'
triggeredBy 'TimerTrigger'
}
}
steps {
scanSecrets history: true, report: 'gitleaks-history.json'
}
}
}
}
stage('Integration tests') {
when {
expression { params.RUN_TESTS }
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
mavenTecnoShop goals: 'failsafe:integration-test failsafe:verify', label: 'Integration tests'
}
post {
always {
junit testResults: 'target/failsafe-reports/TEST-*.xml', allowEmptyResults: false
}
}
}
stage('Package') {
steps {
mavenTecnoShop '-DskipTests package'
infoBuild application: 'orders-api', version: env.APP_VERSION, image: "${env.IMAGE}:${env.IMAGE_TAG}"
archiveArtifacts artifacts: 'target/*.jar,target/bom.json,build-info.txt', fingerprint: true
stash name: 'jar', includes: 'target/*.jar'
}
}
stage('Smoke') {
options {
timeout(time: 3, unit: 'MINUTES')
}
steps {
smokeSpringBoot extraPath: '/api/orders', expectedText: 'SHIPPED'
}
}
stage('Quality analysis') {
when {
allOf {
branch 'main'
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
withSonarQubeEnv('sonar-tecnoshop') {
mavenTecnoShop goals: 'sonar:sonar', label: 'SonarQube analysis'
}
}
}
stage('Quality Gate') {
when {
allOf {
branch 'main'
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
waitForQualityGate abortPipeline: true
}
}
stage('Publish') {
when {
allOf {
expression { params.RUN_TESTS }
anyOf {
allOf {
branch 'main'
expression { env.APP_VERSION.endsWith('-SNAPSHOT') }
}
tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
}
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
milestone(label: 'Publish')
sh label: 'Check that the tag matches the version', script: '''
if [ -n "${TAG_NAME:-}" ] && [ "$TAG_NAME" != "v$APP_VERSION" ]; then
echo "ERROR: the tag $TAG_NAME does not match the pom version ($APP_VERSION)"
exit 1
fi
'''
mavenTecnoShop goals: '-DskipTests -Dmaven.install.skip=true deploy',
settings: 'maven-settings-tecnoshop-publish',
label: 'Publish to Nexus (jar and SBOM)'
}
}
stage('Deploy to dev') {
when {
allOf {
branch 'main'
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
environment {
DEV_SERVER = 'dev-01.tecnoshop.local'
}
steps {
unstash 'jar'
sshagent(credentials: ['ssh-dev']) {
sh label: 'Deploy to dev-01 over SSH', script: 'sh deploy/deploy.sh "$DEV_SERVER"'
}
}
}
stage('Trigger CD') {
when {
allOf {
tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP'
expression { params.RUN_TESTS }
}
}
steps {
script {
def sha256 = sh(script: 'sha256sum target/orders-api-*.jar | cut -d " " -f 1',
returnStdout: true, label: 'SHA-256 of the published jar').trim()
build job: '/orders-delivery/orders-api-cd',
wait: false,
parameters: [
string(name: 'VERSION', value: env.APP_VERSION),
string(name: 'SHA256', value: sha256)
]
currentBuild.description = "${currentBuild.description} → orders-api-cd"
}
}
}
}
post {
always {
notifyTeam channel: '#ci-orders', email: '[email protected]'
}
cleanup {
cleanWs()
}
}
}ci/Jenkinsfile.cd at the End of Module 7
@Library('[email protected]') _
def updateNode(String nodeName) {
withEnv(["NODE=${nodeName}"]) {
sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
sleep time: 10, unit: 'SECONDS'
sh label: "${nodeName}: deploy and check", script: 'sh deploy/deploy.sh "$NODE"'
sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
}
}
def revertNode(String nodeName) {
withEnv(["NODE=${nodeName}"]) {
sh label: "${nodeName}: remove from the load balancer", script: 'sh deploy/load-balancer.sh remove "$NODE"'
sh label: "${nodeName}: go back to the previous version", script: 'sh deploy/revert.sh "$NODE"'
sh label: "${nodeName}: put back into the load balancer", script: 'sh deploy/load-balancer.sh restore "$NODE"'
}
}
pipeline {
agent none
options {
timestamps()
buildDiscarder(logRotator(numToKeepStr: '100'))
skipDefaultCheckout()
}
parameters {
string(name: 'VERSION', defaultValue: '', trim: true,
description: 'Release X.Y.Z published in maven-releases (e.g. 1.1.0). Never a SNAPSHOT.')
string(name: 'SHA256', defaultValue: '', trim: true,
description: 'SHA-256 of the jar tested in the tag build. Filled in by CI; empty when triggered by hand.')
}
environment {
NEXUS_URL = 'http://nexus:8081'
STAGING_SERVER = 'staging-01.tecnoshop.local'
PRODUCTION_NODES = 'prod-01.tecnoshop.local prod-02.tecnoshop.local'
LOAD_BALANCER = 'lb.tecnoshop.local'
APP_VERSION = "${params.VERSION}"
DEPLOY_VERSION = "${params.VERSION}"
}
stages {
stage('Validate parameters') {
steps {
script {
if (!(params.VERSION ==~ /\d+\.\d+\.\d+/)) {
error "VERSION must have the form X.Y.Z (e.g. 1.1.0); received '${params.VERSION}'"
}
if (params.SHA256 && !(params.SHA256 ==~ /[0-9a-f]{64}/)) {
error 'SHA256, if given, must be 64 lowercase hexadecimal characters'
}
currentBuild.displayName = "#${env.BUILD_NUMBER} · ${params.VERSION}"
}
}
}
stage('Fetch release') {
agent {
label 'linux'
}
options {
timeout(time: 5, unit: 'MINUTES')
}
steps {
checkout scm
sh label: 'Download from Nexus and verify (jar and SBOM)', script: 'sh deploy/fetch-release.sh "$APP_VERSION"'
fingerprint 'target/orders-api-*.jar'
stash name: 'release', includes: 'target/orders-api-*.jar,target/bom.json,.trivyignore,deploy/**,ci/**'
}
post {
cleanup {
cleanWs()
}
}
}
stage('Vulnerability review') {
agent {
label 'linux'
}
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
unstash 'release'
sh label: 'Trivy on the release SBOM', script: 'sh ci/review-vulnerabilities.sh'
}
post {
cleanup {
cleanWs()
}
}
}
stage('Staging') {
agent {
label 'linux'
}
options {
lock(resource: 'env-staging')
timeout(time: 15, unit: 'MINUTES')
}
stages {
stage('Deploy to staging') {
steps {
milestone(label: 'Staging')
script { env.CURRENT_ENV = 'staging' }
unstash 'release'
sshagent(credentials: ['ssh-staging']) {
sh label: 'Deploy to staging-01 over SSH', script: 'sh deploy/deploy.sh "$STAGING_SERVER"'
}
}
post {
failure {
sshagent(credentials: ['ssh-staging']) {
sh label: 'Rollback of staging-01', script: 'sh deploy/revert.sh "$STAGING_SERVER" || true'
}
}
}
}
stage('Acceptance tests') {
steps {
sh label: 'QA acceptance criteria',
script: 'sh ci/acceptance.sh "http://$STAGING_SERVER:8081" "$APP_VERSION" staging'
notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'staging',
version: params.VERSION, result: 'PENDING'
}
}
}
post {
cleanup {
cleanWs()
}
}
}
stage('Approval') {
options {
timeout(time: 24, unit: 'HOURS')
}
input {
message 'Deploy the version validated in staging to production?'
ok 'Deploy to production'
submitter 'laura,production-approvers'
submitterParameter 'APPROVED_BY'
parameters {
string(name: 'CHANGE_REFERENCE', defaultValue: '',
description: 'Reference of the approved change and a short reason (e.g. CHG-2026-0142: filter orders by status)')
}
}
steps {
script {
if (!env.CHANGE_REFERENCE?.trim()) {
error 'Approval without a change reference: not deploying to production.'
}
env.APPROVAL = "${env.APPROVED_BY} (${env.CHANGE_REFERENCE.trim()})"
currentBuild.description = "orders-api ${params.VERSION} · approved by ${env.APPROVAL}"
}
}
}
stage('Deploy to production') {
agent {
label 'linux'
}
options {
lock(resource: 'env-production')
timeout(time: 20, unit: 'MINUTES')
}
steps {
milestone(label: 'Production')
script { env.CURRENT_ENV = 'production' }
unstash 'release'
sh label: 'Deployment window', script: 'sh ci/deploy-window.sh'
sshagent(credentials: ['ssh-production']) {
script {
List touched = []
try {
for (String nodeName : env.PRODUCTION_NODES.tokenize(' ')) {
touched << nodeName
updateNode(nodeName)
}
sh label: 'Production verification through the load balancer',
script: 'sh ci/acceptance.sh "http://$LOAD_BALANCER" "$APP_VERSION" production'
} catch (err) {
echo "Production failure: ${err}. Reverting, in reverse order: ${touched.reverse().join(', ')}"
List notReverted = []
for (String nodeName : touched.reverse()) {
try {
revertNode(nodeName)
} catch (revertErr) {
echo "ERROR: could not revert ${nodeName}; it stays OUT of the load balancer (${revertErr})"
notReverted << nodeName
}
}
env.REVERTED = notReverted ? "partial; not reverted: ${notReverted.join(', ')}" : 'yes'
throw err
}
}
}
}
post {
cleanup {
cleanWs()
}
}
}
}
post {
success {
notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
version: params.VERSION, detail: "Approved by ${env.APPROVAL}"
}
failure {
notifyDeployment application: 'orders-api', channel: '#ci-orders',
environment: env.CURRENT_ENV ?: 'preparation', version: params.VERSION,
result: env.REVERTED ? 'REVERTED' : 'FAILED',
detail: env.REVERTED == 'yes' ? 'Automatic rollback completed' : env.REVERTED
}
aborted {
notifyDeployment application: 'orders-api', channel: '#ci-orders', environment: 'production',
version: params.VERSION, result: 'CANCELLED'
}
}
}How the two pipelines evolved over the module:
| Lesson | Jenkinsfile (CI) |
ci/Jenkinsfile.cd (CD) and environment |
|---|---|---|
| 07-01 | No changes: diagnosis and roadmap | - |
| 07-02 | No ENVIRONMENT; abortPrevious on PRs; Package and Smoke before SonarQube; milestone in Publish; Trigger CD; build-info and /actuator/info |
- |
| 07-03 | - | The orders-delivery folder, orders-api-cd, folder-scoped ssh-staging and ssh-production, staging-01, prod-01, prod-02, acceptance, approval, lock, milestone, notifyDeployment (tecnoshop-lib v1.4.0) |
| 07-04 | Revised deploy.sh (also in dev) |
lb.tecnoshop.local and orders-api-lb, rolling, verification through the load balancer, automatic rollback, orders-api-rollback, deployment window |
| 07-05 | [email protected]; Secrets, Secrets in history and Dependency-Check in Checks; SBOM archived and published |
SBOM downloaded; Vulnerability review stage with Trivy |
And around them: the tecnoshop/linux-agent:1 agent image with gitleaks and Trivy; the .gitleaks.toml, .trivyignore, dependency-check-suppressions.xml and .github/CODEOWNERS files; the nvd-api-key credential; the OWASP Dependency-Check plugin; and Require review from Code Owners in protect-main.
Common Mistakes and Tips
- Printing the secret when it is detected: without
--redact, the scanner copies it into the build log. That is a second leak. - Deleting the secret and considering the matter closed: it is still in the history. Rotate first.
- Lowering
failBuildOnCVSSor raising the threshold "temporarily" to unblock a build: it affects every vulnerability, present and future. Use a specific, justified, expiring suppression. - The first Dependency-Check run hits the
timeout: the initial NVD download is long, and much longer without an API key. Run it once by hand and check thatnvd-api-keyreaches the process. npm auditfails with a registry error rather than a vulnerability error: the proxy does not serve the audit endpoint; use the alternative from section 15.trivy: command not found: the build is running on an agent without the new image, or the container was not rebuilt (docker compose up -d --build linux-agent-01).- Trivy takes a long time on every build: the cache is not persisting. Check that
TRIVY_CACHE_DIRpoints to the agent's volume. - CODEOWNERS not enforced in the ruleset: GitHub suggests the reviewers but does not require their approval. Check Require review from Code Owners.
- Treating every finding the same: a policy with no nuance (everything blocks or nothing blocks) ends up ignored. Review the gate table with security every quarter.
- Tip: measure how long it takes the team to fix a high-severity vulnerability from the moment it is published. It is the security metric that most resembles the DORA ones: it tells you whether the chain, besides detecting, lets you fix things quickly.
Exercises
Exercise 1. Build the tecnoshop/linux-agent:1 image (with real versions and checksums you have verified), release tecnoshop-lib v1.5.0 and add the Secrets stage. In a PR, add a line service.token=tks_ followed by 32 alphanumeric characters to application.properties. What happens in the build and what do you see in the report? Then delete the line in a second commit on the same PR. Does the build pass? What would detect it after merging with a merge commit, and what would you have to do if it were a real token?
Exercise 2. Add Dependency-Check and, on a branch, force an old version of a dependency with known vulnerabilities (for example, by explicitly declaring an old version of a commonly used library in pom.xml). Look at the result. Then suppose security confirms that one of the CVEs does not apply: write the corresponding suppression with a 60-day expiry and explain which review GitHub will require to merge it.
Exercise 3. An auditor asks: "If a critical vulnerability in Jackson is published tomorrow, how do you know which versions of orders-api are affected, whether any of them is in production, and what prevents an affected one from being deployed?" Answer with the specific pieces of TecnoShop's chain.
Solutions
Solution 1. The Secrets branch of Checks fails: gitleaks detects the string with the tecnoshop-internal-token rule and exits with code 2; scanSecrets archives gitleaks.json and fails with the "possible secrets" message. With failFast true, the other parallel branches are aborted. The console and the report show the file, the line, the rule and the fingerprint of the finding, but the value is replaced with REDACTED. After the second commit, the PR build passes: dir mode scans the current files, which no longer contain the token. But the token is still in the PR's first commit; with a merge commit, that commit enters the history of main and the Secrets in history branch of the next nightly build will detect it (with a squash merge it would not reach main, although it would remain on the PR branch in GitHub). If it were real: revoke it at its source immediately, create a new one as a Jenkins credential or server configuration, review the usage logs and report it to security; cleaning up the history, if you decide to, comes afterward. GitHub push protection, if available, would have rejected it even before the PR (if the format belonged to a known provider; for an in-house format like tks_ you would need a custom pattern).
Solution 2. The Dependency analysis branch fails with a Dependency-Check message saying that one or more dependencies exceed the configured CVSS (7), with the list of CVEs; dependencyCheckPublisher still publishes the report in the build (in post { always }), and the HTML is archived. The suppression, in dependency-check-suppressions.xml:
<suppress until="YYYY-MM-DDZ"> <!-- today + 60 days -->
<notes><![CDATA[SEC-2026-0xx (fictitious): CVE-XXXX-YYYY does not apply because ... Reviewed by security.]]></notes>
<packageUrl regex="true">^pkg:maven/the\.group/library@.*$</packageUrl>
<cve>CVE-XXXX-YYYY</cve>
</suppress>The other CVEs for the same dependency will keep failing, which is correct: the right move for them is to upgrade the version. To merge, GitHub will require approval from @tecnoshop/security (the CODEOWNERS of dependency-check-suppressions.xml, with Require review from Code Owners enabled), in addition to the usual approval and the Jenkins check.
Solution 3. (1) Which versions are affected: every release has its CycloneDX SBOM published in Nexus next to the jar (orders-api-X.Y.Z-cyclonedx.json) and archived in its tag build; you just search them for the Jackson purl and its version (continuously, with Dependency-Track). (2) Whether it is in production: /actuator/info on prod-01 and prod-02 (or the active link in /opt/orders-api/) gives the running version, and the history of orders-api-cd and orders-api-rollback tells you what was deployed, when and who approved it. (3) What prevents an affected one from being deployed: in CI, Dependency-Check with failBuildOnCVSS 7 prevents a new release with the vulnerability from being published; in CD, the Vulnerability review stage scans the release's SBOM with Trivy at promotion time and blocks if there is a critical one, even if the release was built before the CVE was published. Exceptions are only possible through a suppression that is versioned, justified, approved by security (CODEOWNERS) and expiring. To fix it: upgrade Jackson (or the Spring Boot version that brings it in), publish a new release and take it through the chain; if it is urgent, the deployment can be done outside the window with the procedure from 07-04.
Conclusion
With this lesson you close module 7, and TecnoShop's chain is now designed with intent from end to end: continuous integration on trunk-based development, a measured and well-ordered commit stage, a delivery pipeline that promotes the same Nexus artifact to staging and production with acceptance tests and approval, zero-downtime rolling deployments with automatic and manual rollback, and now security built into every phase. You have built the pipeline's threat model and you know which control belongs to each phase; tecnoshop/linux-agent carries gitleaks and Trivy at pinned versions with verified checksums; scanSecrets, new in tecnoshop-lib v1.5.0, detects secrets in every build and across the whole history every night, and you know that an exposed secret is rotated before anything else; OWASP Dependency-Check, with the nvd-api-key credential and its cache, blocks dependencies with a CVSS of 7 or more and marks medium ones as unstable, npm audit does the same in catalog-web, and SonarQube keeps watching your own code. Every release carries its CycloneDX SBOM in Nexus, which CD scans again with Trivy at promotion time; you know the image scanning you will apply in module 8 and what lies ahead with cosign signing and the SLSA levels; you have an explicit gate policy, with versioned, approved and expiring exceptions; and the chain itself is protected with per-environment credentials, CODEOWNERS over the pipeline, the deployment and the exceptions, a trusted library pinned by tag and Audit Trail, all of it still to be reviewed with the security and compliance officer before it can be called policy. One weakness has come up again and again in this module: linux-agent-01 is a permanent agent that shares its workspace, caches and tools across every build, and each new tool means rebuilding it. Module 8 starts right there: in Jenkins with Docker you will run builds in ephemeral containers, build and publish the orders-api image and apply to it the Trivy scan you have just prepared.
