Scan Source Code, Dependencies, Containers, and Infrastructure as Code

TL;DR

CI security scanning should produce evidence about the exact source and artifact being considered for release. Use static analysis for supported code patterns, package assessment for known component vulnerabilities, secret detection for exposed credentials, and configuration checks for infrastructure definitions. Preserve each method’s scope instead of combining their outputs into an unsupported claim that the application is secure.

This installment connects Semgrep Community Edition and Trivy to the series’ bounded assessment model. It provides collector command excerpts and a normalization design, including a synthetic transitive-dependency scenario. The commands were checked against documentation but not executed; no downloadable collector, executed normalizer test suite, image build, or deployment is supplied.

Scan the inputs, scan the resulting artifact, and prove which evidence belongs to each. A successful source check is not an assessment of everything shipped.

In This Article

Introduction

A pull request changes one line in the document portal. Static analysis reports no new findings. The build then resolves a different base image and includes a dependency that the source-focused check never examined.

Should that image inherit the pull request’s green status?

In Example Enterprise’s proposed pipeline, it should not. Source assessment, build execution, artifact assessment, and release approval are separate transitions. The previous installment established the controller and job lifecycle. This article supplies build-time assessment operations behind that boundary, without granting a model arbitrary command execution.

The objective is a bounded continuous integration (CI) path that produces findings and coverage evidence tied to a commit and build. Dynamic application testing and live cloud posture belong to the next installment. The existing EE-APP-001 deployment uncertainty remains unresolved.

Decide What Each Assessment Can Establish

Assign tools to questions, not to an undifferentiated security stage. The proposed reference stack uses Semgrep CE for static application security testing (SAST) and Trivy for supported dependency, image, secret, and infrastructure-as-code (IaC) checks. Semgrep documents a standalone CE workflow using semgrep scan; Trivy documents distinct scanners and target types. Semgrep: Semgrep Community Edition in CI

AssessmentEvidence to retainWhat the result does not establish
Static code analysisRule, file, location, scanned paths, errors, commitComplete business-logic coverage or runtime exploitability
Dependency assessmentPackage identity/version, advisory source, dependency contextThat the component is deployed or its vulnerable function is reachable
Secret detectionRestricted match evidence, detector, location, scopeThat every credential was found or that a candidate credential is valid
Container assessmentExact image input, package inventory, database revisionLive workload configuration, mounted content, or past compromise
IaC assessmentDefinition or rendered input, values, checks, exclusionsThat the live environment matches the definition

Existing enterprise tools can replace either reference implementation when they provide the necessary scope, identity, and result evidence. Do not install overlapping products merely to reproduce the diagram.

Bind the Assessment to the Commit and Build Output

Record the exact commit tested, including whether it is a pull-request head or a generated merge commit. Keep the CI run and attempt separate from the commit: the same source can produce multiple builds.

The source worker and image worker receive different inputs. Both use protected assessment configuration, and neither decides whether an artifact may be deployed.

Retain the source snapshot hash, builder identity, build configuration, resolved inputs, resulting artifact identity, and relevant assessment records. SLSA’s provenance model describes verifiable information connecting artifacts to how they were produced. The local build-receipt template expresses similar information needs; it is not a SLSA attestation or a claim of a SLSA level. SLSA

Distinguish image identities carefully. An archive’s SHA-256 protects the archive bytes. An Open Container Initiative (OCI) manifest digest identifies that manifest; an image configuration digest identifies another object. For multi-platform releases, record the index and relevant platform manifests. Do not place all of these values into one ambiguous image_hash field. Open Container Initiative: OCI Content Descriptors

A trusted handoff must verify the relationship between the delivered archive and the artifact selected for promotion. Hashing a report after the wrong image was scanned cannot repair that relationship.

Prevent Pull Requests from Rewriting Their Own Assessment

Load the wrapper, rules, exception policy, and normalizer from a protected control repository or admitted worker image. Mount the application source separately as input. A pull request that changes its own scanner configuration must not thereby change the checks deciding whether that pull request is acceptable.

GitHub’s security guidance warns against processing untrusted pull-request code under privileged pull_request_target or workflow_run contexts. It also recommends least-privilege tokens and full-commit pinning for third-party actions. A pinned action still needs review of the code, dependencies, and permissions it invokes. GitHub: Secure use reference

Use separate short-lived identities for source collection, build execution, scanning, evidence publication, and deployment. The scanner needs no repository write token, production credential, or container-daemon socket when assessing an already delivered image archive.

Treat dependency resolution and building as code-execution activities. Do not install application dependencies in the scanner process merely to make a missing lockfile disappear. Run any required build or resolver in its approved isolated environment, preserve the resulting inputs, and report unresolved dependencies honestly.

Prepare the Toolchain and Knowledge Snapshot

The documented collector selects Semgrep 1.185.0 and Trivy 0.76.2, checked against their official release records on November 18, 2026. These are explicit candidates for validation, not a claim that the combination was installed or tested here. Semgrep: Release v1.185.0

Semgrep CE’s engine is LGPL-2.1, while Semgrep-maintained rules have separate terms and commercial products have their own boundaries. This example supplies one authored rule rather than assuming access to proprietary analysis. Trivy’s repository uses Apache-2.0; review the actual binaries, rules, feeds, and distribution obligations used in your environment. Semgrep: Licensing

For a real run, prepare an isolated Linux worker with the pinned tools, Bash, GNU timeout, private scratch storage, and read-only source and policy mounts. The image stage additionally requires an actual builder-delivered archive. No package installation or image build occurs inside the collector.

Pre-stage the admitted vulnerability database and configuration-check bundle. Record their content identities and freshness, then keep them stable for the assessment. Trivy documents separate database-update controls; --offline-scan concerns dependency-identification requests, not a complete network-isolation guarantee. Disable telemetry and version checks separately, and enforce egress restrictions outside the tool. Trivy: Databases

Run Static Analysis with a Protected Rule Set

A protected policy/semgrep.yml can begin with a deliberately narrow rule that flags Python eval calls for review without executing the target file. Such a teaching check is not a replacement for an organization’s supported language and rule coverage.

rules:
  - id: ee.no-eval
    languages: [python]
    message: Review dynamic expression execution.
    severity: ERROR
    pattern: eval(...)

Inside the prepared worker, the collector uses an explicit local configuration and writes restricted JSON evidence:

semgrep scan --oss-only --config /policy/semgrep.yml \
  --metrics=off --disable-version-check \
  --disable-nosem --no-git-ignore --strict \
  --jobs 2 --timeout 10 --max-memory 1024 \
  --json --output /work/evidence/sast.json /work/source

The wrapper supplies an outer process deadline as well. Semgrep’s per-analysis timeout is not a substitute for an overall job budget. --strict exposes warning-level errors; the result still needs inspection for skipped or unsupported inputs. Semgrep: CLI reference

Target filtering deserves its own check. Semgrep documents default exclusions, ignored submodules, and .semgrepignore behavior. Reject repository-controlled ignore policies where the assessment requires trusted coverage, disable inline suppression for that profile, and compare expected files with actual coverage. Those controls do not make every repository file a supported analysis target. Semgrep ignore behavior

Assess Dependencies Without Assuming They Are Direct

Software composition analysis (SCA) connects discovered components to vulnerability information. Use supported resolved inputs, not a manifest that merely expresses version ranges. Trivy’s Node.js documentation describes transitive dependency support for package-lock.json; its Python documentation shows that capabilities differ across requirements files, lockfiles, and installed-package metadata. Trivy: Node.js

For source assessment, the collector invokes Trivy’s vulnerability scanner against the exported snapshot. It includes development dependencies for the supported formats because build-time components belong to this profile’s scope. That does not imply those components ship in the runtime image. Trivy: Node.js

The commands below show the shared settings and dependency operation. /work/state/trivy-cache must already contain the approved database/check state; the flags do not populate it.

COMMON=(
  --config /policy/trivy.yaml
  --cache-dir /work/state/trivy-cache
  --ignorefile /policy/trivyignore
  --secret-config /policy/trivy-secret.yaml
  --skip-db-update --skip-java-db-update --skip-check-update
  --offline-scan --skip-version-check --disable-telemetry
  --timeout 5m --parallel 2 --exit-code 0
)

trivy fs "${COMMON[@]}" --scanners vuln --include-dev-deps \
  --format json --output /work/evidence/dependencies.json \
  /work/source

These options are documented in the Trivy v0.76 command reference. The wrapper also constrains the environment and preserves process exit status separately from the resulting findings. Trivy: Filesystem, v0.76 CLI reference

Preserve distribution-specific package identities and advisory sources. Trivy’s vulnerability documentation explains its use of operating-system vendor advisories, including the significance of backported fixes. A lower upstream-looking version is not sufficient evidence that a vendor package remains vulnerable. Trivy: Vulnerability

Keep findings without available fixes visible. A filter that hides unfixed vulnerabilities may simplify a report, but it cannot establish that those exposures disappeared.

Keep Secrets and Configuration Findings Distinct

Run source secret detection separately so its raw results have a restricted handling path. Retain the detector and location for authorized review, but do not send matched credential values or surrounding source lines into the model, public annotations, or general build logs. Trivy supports secret scanning for files and images; those targets are not equivalent to a complete historical repository-secret audit. Trivy

The normalizer deliberately omits secret matches and source snippets. Its remaining paths and component identifiers still require classification. When a real credential is confirmed exposed, route revocation and exposure investigation through the credential owner; removing the string is not the entire response.

For IaC, the reference profile selects Dockerfile and Kubernetes checks explicitly. Trivy supports additional configuration types, but this collector does not silently extend its approved scope to them. Trivy: Filesystem, v0.76 CLI reference

Assess rendered definitions when templates, environment values, or overlays determine the deployed configuration. Preserve those inputs and their versions. Terraform planning and external-module resolution need their own approved execution boundary; a scanner should not receive cloud credentials simply to make its static input more complete. A static configuration result remains separate from a live-state assessment.

Scan the Built Image and Bind Its SBOM

After the separate build stage, deliver the approved image archive to the artifact worker. Trivy documents scanning supported image archives through --input, avoiding a requirement to attach a privileged container-daemon socket to this worker. Trivy

Using the previously defined settings, collect image-package evidence and a separate software bill of materials (SBOM):

trivy image "${COMMON[@]}" --input /work/input/image.tar \
  --scanners vuln --format json \
  --output /work/evidence/image-vulnerabilities.json

trivy image "${COMMON[@]}" --input /work/input/image.tar \
  --format cyclonedx --output /work/evidence/image.cdx.json

The full collector also runs a separate image-secret check. SBOM generation is inventory production, not a substitute for vulnerability assessment. Preserve the SBOM producer, version, hash, scope, and verified artifact relationship. Trivy: Image, v0.76 CLI reference

Trivy warns that SBOMs produced by other tools can lack properties needed for accurate matching. Validate the actual producer/consumer combination. An unlisted package may reflect incomplete inventory rather than absence. Trivy: SBOM scanning

Assess base-image packages as part of the resulting image, not only application lockfiles. Keep builder-only tools in a separate assessment scope. After a fix, rebuild and assess the new artifact; do not attach the old image’s report to a new tag. Runtime-mounted code and configuration still require deployment evidence.

Use Change-Focused Checks Without Losing the Baseline

A pull-request result should identify its comparison base and tested commit. Semgrep supports baseline-commit comparisons, but the baseline must exist and meet the command’s repository-state requirements. If the comparison cannot be established, hold the differential result or run an explicitly labeled full scan rather than reporting no new findings. Semgrep: CLI reference

TriggerProposed assessment scope
Pull requestChange-focused code review plus relevant dependency, secret, and IaC checks
Merge or release candidateFull required source checks and exact-build artifact assessment
Database, rule, or advisory changeReassessment of relevant retained artifacts and component evidence
Scheduled reconciliationFull coverage review, stale results, missed events, and unresolved jobs

Keep full or periodic assessment because unchanged code and dependencies can become relevant when external intelligence changes. Do not suppress existing findings simply because a change-focused job did not rediscover them. Detailed event routing follows later in the series.

Normalize Findings Without Erasing Execution Failures

Keep three fields separate: assessment execution, required coverage, and release decision. Trivy normally returns zero even when it detects issues unless configured otherwise. The sample explicitly retains that behavior and applies finding policy after collecting the report. Semgrep JSON likewise contains results and errors that must be interpreted separately. Trivy

The normalizer binds report bytes to a controller-owned receipt and expected subject before extracting observations. The subject carries the repository, full commit, input digest, build identifier, and environment. Findings preserve tool-specific identity and evidence rather than merging unrelated reports solely because their titles resemble one another.

A package finding records a possible affected component and any supplier fix candidates. It does not assert runtime reachability or local upgrade approval. A SAST rule’s ERROR severity is not silently converted into a CVSS score. An IaC finding does not become evidence about a running cluster.

The example’s local policy holds missing, failed, partial, stale, or unverified evidence. Admitted findings block promotion for review. Even an empty report with verified coverage requires an owner decision; the code never grants production authority.

Follow a Transitive Dependency Through Example Enterprise

The authored fixture extends the document portal’s source inventory with a fictional dependency chain:

The synthetic dependency chain is Portal source → example-preview 2.0.0 → example-renderer 1.4.2.

The package names and dependency relationship are synthetic. An authored Trivy-shaped observation can represent LAB-ADV-001 for normalization tests; this does not claim that Trivy’s public database recognizes the fictional advisory.

The relationship matters because changing only the direct dependency list may leave the resolved renderer unchanged. A supported remediation proposal must determine which parent update or reviewed override resolves the affected component, regenerate the appropriate lockfile, build the candidate, and assess its actual contents. Naming 1.4.3 in a ticket is not evidence that it entered the image.

The normalized source observation remains potentially affected pending the advisory’s relevant conditions. Current runtime applicability remains unknown because EE-DEP-002 is still unresolved. The source record can inform EE-FIND-001, but it neither approves EE-CHG-001 nor closes EE-VER-001. The withdrawn-fix counterfactual from earlier articles remains a separate branch.

Define the Evidence Replay Acceptance Cases

Implement an offline evidence replay before connecting real collectors. Use authored scanner-shaped records, a known local Git commit, and an explicit expected subject for each report. Preserve the raw records and comparison results.

Record the fixture commit and, if needed, a Git bundle so the input can be reproduced. Mark EE-BUILD-FIXTURE-001 as not_executed until a builder actually produces an artifact. Do not substitute a fabricated container digest or build result.

Require the replay to retain the authored dependency finding, hold a missing report, hold an empty report without verified coverage, and reject a mismatched subject. These are normalization and decision-handling acceptance cases, not measured scanner detection results.

Validate shell syntax, actual Semgrep and Trivy execution, database intake, image construction, and CI isolation separately in the approved environment. Keep release authorization on hold until a trusted handoff verifies coverage and assembles authenticated receipts. No passing local test count or completed collector integration is claimed here.

Admit the Real Pipeline Only After Its Failure Paths Work

Run harmless positive and negative fixtures with the actual pinned tools before registering a live profile. Confirm the intended languages, files, components, configuration resources, and rule versions were assessed. Exercise an invalid source file, missing database, unsupported lockfile, missing image, and substituted artifact.

A timeout or nonzero tool exit should preserve available evidence while holding the incomplete assessment. An oversized or malformed report should fail parsing without becoming an empty clean result. A stale report from a previous job must not satisfy the current job merely because its filename matches.

Security engineering owns rules and exceptions; application owners own supported dependency changes; the platform team owns worker isolation and build identity. Keep exception rationale, target scope, owner, and expiry outside the source branch under assessment. Permit the model to explain authorized evidence and draft work, not suppress findings, edit its own gate, or promote the image.

Conclusion

Build-time security assessment becomes useful when every result names what was assessed, which checks ran, which evidence supports the finding, and which decision remains outstanding. Source, dependency, image, secret, and infrastructure checks contribute different evidence to that chain.

Start with one repository and one artifact type. Establish the immutable handoff, run the supported tools in isolated workers, preserve failures and exclusions, and require the release gate to inspect coverage as well as findings.

The next installment, Coordinate Security Scans Across Networks, Servers, Cloud, and Applications, extends the same assessment contract to live environments, authentication, and complementary methods.

A release decision should follow the artifact’s evidence, not inherit confidence from an earlier green job.

External References

Continue reading

Trigger Security Reassessment After Releases, Patches, and Configuration Changes

Route releases, patches, advisories, and configuration changes into bounded security reassessment with durable obligations, deduplication, and reconciliation. Read the article

1 thought on “Scan Source Code, Dependencies, Containers, and Infrastructure as Code”

Leave a Comment