Security and Supply Chain

Reading time
20 min read
Word count
3801 words
Diagram count
5 diagrams

Source: Victor Bona's Obsidian Compendium snapshot, Knowledge base/Software Engineering/09 Security and Supply Chain.md.

Security and Supply Chain

Security engineering is the disciplined reduction of exploitable risk under adversarial conditions. Supply chain security extends that discipline across the path from source code to running production systems: developer laptops, repositories, dependencies, CI, build workers, artifacts, registries, deployment controllers, runtime identity, and operational access.

Security is not a single feature. It is a system property produced by clear trust boundaries, secure defaults, least privilege, reviewable change paths, verifiable artifacts, monitored production behavior, and fast recovery when controls fail.

Existing anchor

  • Software Supply Chain Security

Security model

LayerPrimary questionMain failure modeTypical controls
Product behaviorWhat can a user or attacker do?Abuse case is not modeledAbuse cases, rate limits, fraud controls, safe defaults
Application codeCan input cross a trust boundary safely?Injection, auth bypass, confused deputyValidation, encoding, authorization checks, tests
IdentityWho or what is acting?Spoofed actor or stale privilegeMFA, SSO, short-lived tokens, workload identity
DataWhat must remain private, correct, and available?Data leak, corruption, cross-tenant accessEncryption, tenant scoping, backups, access review
NetworkWhich flows are allowed?Excessive reachabilityDefault deny, segmentation, egress control, mTLS
RuntimeCan a compromised component spread?Container or process escape, lateral movementSandboxing, non-root, seccomp, network policies
Build systemCan code be transformed into artifacts safely?CI secret theft, artifact substitutionIsolated runners, provenance, signing, protected refs
DependenciesCan external code introduce risk?Malware, vulnerable package, maintainer takeoverLockfiles, review, SBOM, scanning, pinning
OperationsCan response be proven and recovered?No audit trail or delayed containmentAudit logs, alerts, break glass, incident runbooks
Rendering diagram...

Threat modeling

A threat model names assets, actors, entry points, trust boundaries, assumptions, abuse cases, and required controls. The output should be concrete enough to drive design changes, tests, monitoring, and review checklists.

ElementWhat to captureExample
AssetData, capability, system, key, or reputation valueCustomer PII, signing key, production deploy rights
ActorHuman, service, dependency, internal admin, external attackerTenant admin, CI runner, compromised package
Entry pointWhere input, commands, or artifacts enterAPI endpoint, webhook, pull request, package install
Trust boundaryWhere identity, privilege, network, or ownership changesBrowser to API, CI to cloud account, tenant A to tenant B
AssumptionSecurity claim that must remain trueOnly deployment controller can write production namespace
Abuse caseMisuse path that harms confidentiality, integrity, or availabilityUser exports another tenant's data by guessing an ID
ControlPreventive, detective, or corrective mechanismTenant scoped query, audit log, rate limit, alert
Residual riskRemaining risk accepted after controlsAdmins can read limited support metadata

Threat model process

  1. Draw the data flow and mark trust boundaries.
  2. List assets and rank them by confidentiality, integrity, availability, and business impact.
  3. Identify actors, including non-human actors such as services, CI jobs, dependencies, and deployment controllers.
  4. Apply STRIDE to each boundary and high-value asset.
  5. Convert threats into controls, tests, logs, and operational playbooks.
  6. Record assumptions and review them when architecture, hosting, identity, or dependencies change.
Rendering diagram...

STRIDE

STRIDE categorySecurity property at riskDesign questionExampleCommon controls
SpoofingAuthenticityCan an attacker pretend to be another user, service, or build system?Forged webhook calls admin endpointMFA, signed webhooks, mTLS, workload identity, token audience checks
TamperingIntegrityCan data, config, code, or artifacts be modified without detection?Container image replaced after buildImmutable artifacts, signing, protected branches, checksums, append-only logs
RepudiationNon-repudiationCan an actor deny a sensitive action because evidence is missing?Admin changes billing plan without traceStructured audit logs, request IDs, signed events, clock sync
Information disclosureConfidentialityCan sensitive data be read by unauthorized parties?Tenant IDOR returns another tenant invoiceAuthorization checks, encryption, redaction, tenant scoping, least privilege
Denial of serviceAvailabilityCan the system be exhausted, blocked, or made costly to run?Expensive search endpoint hammeredRate limits, quotas, backpressure, circuit breakers, autoscaling limits
Elevation of privilegeAuthorizationCan a lower privilege actor gain higher privilege?Read-only token calls write endpointRBAC, capability checks, privilege separation, scoped tokens, policy tests

Boundary focused questions

BoundaryQuestions
Browser to applicationWhat input is untrusted? Which cookies are sent? Are CSRF and CORS rules explicit?
Application to databaseAre queries tenant scoped? Are migrations controlled? Can app credentials mutate schema?
Service to serviceHow is caller identity proven? Is authorization based on identity, network location, or both?
CI to cloudWhich jobs can mint credentials? Are credentials bound to protected branches and environments?
Repository to package registryCan a malicious dependency run install scripts? Are lockfile changes reviewed?
Registry to runtimeCan the deployer verify provenance and signature before rollout?
Operator to productionAre admin actions approved, logged, scoped, and reviewable?

Identity and access boundaries

Security decisions should distinguish authentication, authorization, delegation, tenancy, and operational access. Mixing them creates confused deputy problems and privilege leaks.

ConceptDefinitionCommon mistakeBetter pattern
AuthenticationProves who the actor isTreating login as permissionAuthenticate, then evaluate authorization per action
AuthorizationDecides what the actor can doChecking role only in the UIEnforce server-side with object and tenant context
DelegationLets one actor act through another systemReusing broad user tokens in backend jobsUse scoped grants with explicit audience and expiry
ImpersonationAdmin acts as a user for support or debuggingNo visible marker or audit eventRequire reason, approval for sensitive scope, and audit trail
Workload identityNon-human identity for services and jobsStatic cloud keys in CIOIDC federation, short-lived credentials, audience restrictions
Tenant boundaryOwnership boundary between customers or environmentsGlobal IDs without tenant filtersTenant scoped storage, policy tests, isolation checks

Authentication

Authentication should make account takeover expensive, token theft less useful, and session abuse detectable.

AreaRecommended practiceReview prompt
PasswordsUse a modern password hashing function with unique saltsIs the hash algorithm current and cost tuned?
MFARequire MFA for admins, deployers, billing owners, and support accessCan high-risk actions bypass MFA?
SSOPrefer centralized identity for employees and enterprise tenantsAre groups and claims mapped explicitly?
SessionsUse secure, HttpOnly cookies for browser sessions where practicalAre session lifetimes, rotation, and revocation defined?
TokensBind issuer, audience, subject, expiry, and scopesDoes every verifier check issuer and audience?
RecoveryTreat recovery paths as authentication pathsCan email takeover or support workflow bypass MFA?

Authorization

Authorization should answer four questions every time: who is acting, on whose behalf, against which object, and for which action.

ModelGood fitRisk
RBACCoarse organizational rolesRole names become too broad over time
ABACContext-sensitive decisions using attributesPolicy can become hard to reason about
ReBACRelationship based sharing and collaborationRequires careful graph consistency
Capability tokensNarrow delegated access to a resource or actionTokens must be short-lived and unforgeable
Policy as codeCentralized and testable authorization rulesPolicy and app context can drift

Authorization checks belong at the server-side enforcement point that owns the state change or read. UI checks improve usability but are not security controls.

Rendering diagram...

Tenant isolation

Tenant isolation is an authorization and data modeling problem, not just a UI filter.

Isolation modelDescriptionStrengthsRisks
Shared database, shared schemaTenant ID column on shared tablesCost efficient and simple operationsEasy to miss tenant predicates
Shared database, separate schemasSchema per tenantStronger logical separationMigration and pooling complexity
Separate databasesDatabase per tenantStronger blast radius controlHigher operational cost
Separate runtimeDedicated deployment or namespace per tenantStrong isolation for regulated customersMore infrastructure and release complexity

Required tenant controls:

  • All tenant-owned rows carry an immutable tenant identifier.
  • Server-side queries include tenant predicates by default.
  • Object IDs are not treated as authorization.
  • Background jobs preserve tenant context.
  • Caches include tenant in the cache key.
  • Search indexes, analytics exports, and logs are tenant scoped or redacted.
  • Admin access has explicit tenant selection, reason capture, and audit events.
  • Tests include cross-tenant negative cases.

Secrets management

Secrets are credentials, private keys, tokens, passwords, signing keys, API keys, database URLs, webhook secrets, and anything that grants access when copied.

RequirementPracticeFailure signal
No secrets in gitUse secret scanning in pre-commit, CI, and hosted repository controlsA token appears in code, tests, fixtures, docs, or screenshots
Central storageStore secrets in a managed secret manager or encrypted sealed secret workflowSecrets live in chat, local notes, or CI variables without ownership
Runtime injectionInject secrets at runtime through platform identitySecrets are baked into images or frontend bundles
Least privilegeScope each secret to one system, action set, and environmentOne API key can read and write across prod and staging
ExpiryPrefer short-lived credentials and automatic renewalStatic keys live longer than the service that uses them
AuditabilityLog secret reads, rotations, and policy changesNo one can answer who accessed a key
RotationDocument trigger, owner, interval, and rollbackRotation requires a risky manual deploy

Key rotation pattern

Rotating keys without outages requires overlap.

  1. Generate a new key or credential.
  2. Publish the new public key or store the new secret version.
  3. Configure verifiers or consumers to accept both old and new versions.
  4. Move signers or clients to the new version.
  5. Confirm reads, writes, and signatures use the new version.
  6. Revoke the old version.
  7. Record audit evidence and remove stale references.
Rendering diagram...

Secret review checklist

  • Is the secret needed, or can workload identity replace it?
  • Is the secret scoped to one environment?
  • Is the secret available only to the jobs, pods, or services that need it?
  • Is the value excluded from logs, traces, crash reports, and metrics labels?
  • Does rotation have an owner, a runbook, and a tested rollback?
  • Are exposed secrets invalidated, not merely removed from git history?

Network security

Network controls reduce reachability, lateral movement, and data exfiltration. They should complement identity and authorization, not replace them.

ControlPurposeReview prompt
Default deny ingressPrevent unexpected callersWhich source identities or networks may call this service?
Default deny egressLimit exfiltration and callback channelsWhich external destinations are required?
SegmentationSeparate workloads by sensitivity and ownershipCan a low-trust service reach a high-trust data store?
TLSProtect data in transitIs certificate validation enforced, including internal calls?
mTLSAuthenticate service identity at transport layerAre identities mapped to authorization policy?
Private endpointsAvoid public exposure for internal servicesDoes any admin or database endpoint need the internet?
WAF and edge policyFilter commodity attacks and enforce coarse rulesAre app-specific controls still present behind the edge?
DNS controlsReduce spoofing and unmanaged destinationsAre critical names monitored and protected?

Network posture should be reviewed as an allowlist. If a flow is not documented, monitored, and owned, it should not exist.

Application security

Application security controls should be built into normal design and review. The right control depends on the trust boundary and data flow.

RiskExamplePrimary controls
InjectionUser input reaches SQL, shell, LDAP, template, or query languageParameterized APIs, allowlists, escaping, sandboxing
XSSUntrusted HTML or script reaches browserOutput encoding, CSP, safe rendering APIs, sanitization
CSRFBrowser sends authenticated state-changing requestSameSite cookies, CSRF tokens, origin checks
SSRFServer fetches attacker-controlled URLURL allowlists, metadata IP blocks, egress controls
IDORUser guesses object ID from another tenantObject-level authorization and tenant predicates
DeserializationUntrusted data creates executable objectsSafe formats, schema validation, no polymorphic decode
File upload abuseMalicious file executed, served, or parsed unsafelyType validation, storage isolation, scanning, no execute permissions
Business logic abuseValid requests produce harmful outcomeAbuse cases, quotas, review workflows, anomaly detection
Race conditionConcurrent requests bypass limits or state transitionsTransactions, locks, idempotency keys, invariant tests
Sensitive loggingSecrets or PII stored in logsRedaction, structured fields, retention limits

Secure defaults

Secure defaults reduce the number of correct choices an engineer must remember.

AreaDefault
APIsDeny by default, require explicit authentication and authorization metadata
Data accessTenant scoped repository methods instead of raw global queries
CookiesSecure, HttpOnly, SameSite set intentionally
CORSNo wildcard origins on credentialed endpoints
ErrorsGeneric external messages, detailed internal correlation IDs
LogsStructured logs with redaction and retention policy
DependenciesLockfile required, no unreviewed install scripts for sensitive builds
CI permissionsRead-only by default, write permissions only per job
RuntimeNon-root, read-only filesystem where practical, minimal capabilities
NetworkDefault deny, explicit ingress and egress

Appsec review checklist

  • Does every endpoint define authentication and authorization expectations?
  • Are authorization checks made on the object being read or mutated?
  • Are tenant ID, user ID, and role derived from trusted context, not request body?
  • Are validation rules close to the boundary where data enters?
  • Are output encoding and rendering APIs safe for untrusted content?
  • Can the endpoint be abused with replay, high volume, or expensive inputs?
  • Does error handling avoid leaking secrets, internal IDs, stack traces, and policy details?
  • Are logs useful for investigation without storing credentials or excessive personal data?
  • Are tests present for negative authorization, cross-tenant access, and malformed input?

Audit logs

Audit logs are security evidence. They should answer who did what, to which resource, from where, when, under which authority, and with what result.

FieldPurpose
event_idStable identifier for deduplication and correlation
occurred_atTimestamp from synchronized clock
actor_typeUser, service, CI job, admin, support, dependency
actor_idStable actor identifier
tenant_idTenant or environment context
actionNormalized action name
resource_typeType of object affected
resource_idObject identifier, redacted if sensitive
decisionPermit, deny, fail, or partial
reasonPolicy reason or business justification
sourceIP, device, workload identity, repository, workflow
request_idLink to application logs and traces
before_after_hashIntegrity evidence without storing full sensitive payload

Audit logs should be append-only, access controlled, retained according to risk and regulation, and monitored for high-risk events such as failed admin access, privilege grants, secret reads, policy changes, deploy approvals, and signature verification failures.

Supply chain security

Supply chain security protects the integrity and provenance of software before it reaches production.

Rendering diagram...

SBOM

An SBOM, or software bill of materials, inventories components in an artifact or repository. It supports vulnerability response, license review, dependency ownership, and incident scoping.

SBOM propertyWhy it matters
Component name and versionIdentifies vulnerable or risky packages
Package URL or unique IDReduces ambiguity across ecosystems
Direct versus transitiveShows whether the project chose the dependency directly
LicenseSupports legal and compliance review
HashesHelps detect substitution
Build metadataLinks the SBOM to a specific artifact
FormatSPDX and CycloneDX are common interoperable formats

SBOMs are most useful when generated in CI for the exact artifact being released, stored with the artifact, and connected to vulnerability management. A source-level SBOM is helpful, but an artifact-level SBOM is stronger because it reflects what was actually built.

SLSA and provenance

SLSA, or Supply-chain Levels for Software Artifacts, describes increasing confidence that an artifact was built from the expected source by a trustworthy process. The practical goal is to make artifact origin verifiable and tampering harder.

SLSA concernPractical meaning
Source integrityProtected branches, reviewed changes, signed tags where needed
Build integrityControlled runners, isolated jobs, pinned actions, minimal permissions
ProvenanceMachine-readable statement of source, builder, inputs, commands, and output
Non-forgeabilityProvenance is generated by the build platform, not by arbitrary script
VerificationDeployment policy checks provenance before accepting artifact

Provenance should answer:

  • Which repository, ref, and commit produced this artifact?
  • Which workflow and builder produced it?
  • Which inputs, dependencies, and parameters were used?
  • Was the build triggered from a protected context?
  • Is the attestation signed by a trusted identity?

Artifact signing

Signing verifies artifact integrity and origin. It does not prove the code is secure, but it reduces substitution and tampering risk.

Signing targetExample purpose
Git tagsIdentify release source
Container imagesVerify deployable image origin
PackagesProtect package registry consumers
SBOMsBind inventory to artifact
Provenance attestationsBind build metadata to artifact
Policy bundlesEnsure security policy itself is trusted

Signing keys are high-value assets. Prefer keyless signing backed by workload identity where supported, or store signing keys in hardware-backed or managed key systems. Deployment should verify signatures and identity claims, not only the presence of a signature.

Dependency risk

Dependencies are executable trust relationships. A package can run during install, build, test, application startup, or runtime.

RiskSignalControl
Known vulnerabilityCVE or advisory affects used versionUpgrade, patch, mitigate, or remove
MalwareObfuscated code, unexpected network calls, credential accessReview, sandbox installs, block package
TyposquattingName resembles popular packagePackage allowlist, review new dependencies
Maintainer takeoverSudden ownership or release behavior changeMonitor publisher changes and release diffs
Dependency confusionInternal package name resolved from public registryPrivate registry configuration and namespace controls
License riskIncompatible license in transitive dependencySBOM license review
AbandonmentNo maintenance, old issues, unsupported runtimeReplace or vendor with ownership
Excessive privilegeBuild tool needs broad filesystem or network accessSandboxed builds, disable scripts where possible

Dependency review checklist

  • Is the dependency necessary, or can existing platform capability cover the need?
  • Is it direct or transitive?
  • Who maintains it, and is release activity healthy?
  • Does it run install scripts, code generation, native binaries, or postinstall hooks?
  • Does it request network, filesystem, credentials, or shell access?
  • Is the package pinned through a lockfile?
  • Are lockfile changes reviewed like code changes?
  • Is there a known vulnerability, malicious package advisory, or license concern?
  • What is the removal plan if the dependency becomes unsafe?

CI threat model

CI is a privileged automation environment. It reads source, runs untrusted code, accesses secrets, produces artifacts, and may deploy to production.

ThreatScenarioControl
Pull request secret theftUntrusted PR modifies test script to exfiltrate secretsDo not expose secrets to untrusted PRs, use restricted events
Token overpermissionTest job has repository write or cloud deploy rightsSet job-level permissions to least privilege
Runner persistenceMalicious build leaves state for later jobsEphemeral runners, workspace cleanup, isolation
Action compromiseThird-party action update runs malicious codePin actions to immutable SHAs and review updates
Artifact substitutionAttacker replaces build output before deploymentImmutable registry, signatures, provenance verification
Cache poisoningMalicious dependency or build cache reused by trusted branchScope caches by branch, lockfile, and trust level
Environment bypassDeployment runs without approval or protected refProtected environments, reviewers, branch rules
Log leakageSecret printed in command outputMasking, redaction, secret minimization, no debug echo
OIDC abuseJob mints cloud token from unintended branchOIDC subject conditions, audience checks, environment gates

CI hardening checklist

  • Declare job permissions explicitly.
  • Separate untrusted pull request validation from trusted release workflows.
  • Avoid running privileged workflows on mutable pull request code.
  • Pin third-party actions and base images.
  • Use ephemeral runners for sensitive jobs.
  • Scope caches by trust boundary.
  • Generate SBOM and provenance during release builds.
  • Sign artifacts before publishing.
  • Verify signatures and provenance before deployment.
  • Protect release branches, tags, and environments.
  • Store deployment credentials outside repository variables where possible.
  • Review workflow changes with the same rigor as application code.

Practical scenarios

Scenario: cross-tenant invoice download

An endpoint accepts invoice_id and returns a PDF. Authentication confirms the user is logged in, but authorization only checks that the invoice exists.

StepAnalysis
AssetCustomer invoice data
ThreatInformation disclosure through IDOR
BoundaryUser request to tenant-owned object
ControlQuery invoice by tenant_id from trusted session and invoice_id together
TestTenant A receives 404 or 403 for Tenant B invoice ID
AuditLog denied cross-tenant access attempts with actor, tenant, invoice ID hash, and request ID

Scenario: CI job deploys from a fork

A workflow runs on pull requests and has access to deployment credentials. A fork changes the test command to print secrets and call an attacker-controlled endpoint.

StepAnalysis
AssetCloud credentials and production deploy permission
ThreatSpoofing, elevation of privilege, information disclosure
BoundaryUntrusted fork code to trusted CI environment
ControlNo secrets for fork PRs, read-only token, separate trusted release workflow
TestVerify fork PR event cannot access secret or deploy environment
AuditLog credential minting with repository, workflow, ref, subject, and environment

Scenario: compromised package update

A direct dependency releases a minor version that includes a malicious postinstall script. The lockfile update is treated as routine and merged without review.

StepAnalysis
AssetDeveloper and CI credentials
ThreatTampering and information disclosure
BoundaryPublic package registry to local and CI execution
ControlReview dependency diffs, pin versions, restrict install scripts for sensitive builds
TestCI policy flags new dependencies and install-script changes
AuditRecord dependency changes, reviewer, package metadata, and SBOM diff

Scenario: signing key exposed in logs

A release job prints environment variables while debugging. The artifact signing key is masked in the CI UI but still appears in a downloaded raw log from a subprocess.

StepAnalysis
AssetArtifact signing authority
ThreatTampering and repudiation
BoundarySecret manager to build logs
ControlReplace static key with keyless signing or managed key, disable env dumps, rotate exposed key
TestSecret scanner covers logs and artifacts, not just source
AuditRecord exposure time, artifacts signed during exposure window, revocation, and replacement

Review checklists

Threat model review

  • Are assets, actors, entry points, and trust boundaries documented?
  • Are STRIDE categories considered for each boundary?
  • Are controls linked to tests, logs, and operational response?
  • Are assumptions explicit and still true?
  • Is residual risk accepted by the right owner?

Identity and access review

  • Is every sensitive action authenticated?
  • Is authorization enforced server-side for the exact object and action?
  • Are service accounts separate from human accounts?
  • Are privileges scoped by environment, tenant, and operation?
  • Are admin and support actions justified, time-bound, and audited?
  • Are break glass credentials stored, tested, and reviewed?

Network review

  • Is ingress default deny?
  • Is egress restricted to required destinations?
  • Are databases, admin panels, and metadata services shielded from general workloads?
  • Is TLS enforced for external and internal sensitive traffic?
  • Are service identities verified beyond source IP?

Supply chain review

  • Are branch protections and required reviews active for release sources?
  • Are dependency and lockfile changes reviewed?
  • Are CI workflows least privilege by default?
  • Are third-party actions pinned and owned?
  • Is an SBOM generated for release artifacts?
  • Is provenance generated by the trusted builder?
  • Are artifacts signed and verified before deployment?
  • Can the team rapidly answer whether a vulnerable dependency is present in production?

Logging and detection review

  • Are high-risk actions represented as structured audit events?
  • Are denied authorization checks logged without leaking sensitive data?
  • Are secret reads, rotations, policy changes, and deploys monitored?
  • Are logs protected from tampering and excessive access?
  • Are alerts tied to a response owner and runbook?