Cyber Knowledge · Domain 06 of 11 · Practitioner field guide

Secure Code & Application Security

Build software that resists realistic abuse from requirement to retirement. This guide connects secure design, code review, application and API testing, software-supply-chain assurance, production telemetry, AI-system controls, and defensible release evidence.

Safety and scope

Test only software, APIs, accounts, and environments you own or are explicitly authorized to assess. Use synthetic data in labs, protect credentials and customer information, define stop conditions, and never convert a scanner result into a vulnerability claim without reproduction and context.

Version 1.0 Published Source review: Status: maintained practitioner guide Maintained by Andrey Pautov Editorial policy and corrections

Orientation

How to use this field guide

Application security is not “run a scanner before release.” It is a set of engineering decisions, verification activities, evidence, and response loops spanning people, design, code, dependencies, build systems, deployment, and production.

Developer path

Complete Modules 1–9, add negative security tests beside ordinary tests, then use Modules 10–13 to make the result reproducible in CI and supportable in production.

Security engineer path

Start with the operating model and ASVS profile, review threat boundaries, validate high-risk flows manually, and attach reproducible evidence to each finding.

Engineering leader path

Define ownership, risk tiers, release criteria, exception expiry, remediation service levels, secure defaults, and metrics that measure control effectiveness—not scanner volume.

AI product path

Complete the full baseline first. Module 14 augments normal AppSec with model, prompt, retrieval, tool, output, and autonomous-action controls; it does not replace them.

Working principle: a tool finding is a lead. A defensible finding connects an exact code or runtime path to a violated requirement, reachable attack precondition, business impact, reproducible evidence, owner, fix, and verification result.

System view

The application-security operating model

Use one traceable chain from business requirement to production observation. Each handoff should preserve the reason a control exists and the evidence that it works.

Risk tiers

Tier services by data sensitivity, privilege, internet exposure, transaction value, safety impact, tenancy, regulatory scope, and blast radius. The tier determines review depth—not whether security applies.

Definition of done

A control is done when its requirement, implementation, test, result, owner, and residual risk are recorded. “The scan passed” is not a complete definition.

Shared language

Core concepts and current standards

Secure by design

Make architecture and product decisions that prevent entire defect classes and reduce customer exposure rather than transferring every security burden to operators.

Secure by default

The initial configuration should be safe: strong authentication, least privilege, restricted exposure, protected secrets, useful logs, and no avoidable insecure compatibility mode.

Requirement

A testable statement about expected security behavior. Version framework references; for example, ASVS recommends including the ASVS version with requirement identifiers.

Threat model

A maintained model of assets, trust boundaries, attacker goals, abuse paths, controls, assumptions, and evidence—not a one-time diagram.

Vulnerability

A weakness that can violate a security property under stated conditions. Record reachability and product context before asserting exploitability.

Risk

The combination of impact, likelihood, exposure, control strength, exploitability, and business context. Severity scores inform prioritization but do not make the decision alone.

SBOM and provenance

An SBOM inventories components and relationships; provenance records how an artifact was produced. Neither independently proves that the result is secure.

Compensating control

A verified alternative that reduces a specific risk when the preferred control cannot be implemented. Give it an owner, evidence, expiry, and re-evaluation trigger.

ReferenceUse it forDo not misuse it as
OWASP Top 10:2025Awareness and executive/developer conversation about common web-application risk themes.A complete verification standard or proof of coverage.
OWASP ASVS 5.0.0Versioned, testable application-security requirements and verification planning.A certification claim without scoped evidence.
OWASP API Security Top 10:2023API-specific awareness, especially object/function authorization, resource abuse, inventory, SSRF, and unsafe upstream consumption.A substitute for service-specific abuse cases and authorization matrices.
NIST SSDF 1.1Organization-wide secure development practices: prepare, protect, produce well-secured software, and respond to vulnerabilities.A product penetration-test checklist.
SLSA 1.2Source/build supply-chain guarantees, provenance, verification, and progressive assurance tracks.A guarantee that application logic has no vulnerabilities.

Curriculum

Fourteen modules: design, build, verify, operate

Each module produces a reviewable artefact. Use the sequence for a new service or enter at the relevant control, then trace backward to requirements and forward to production evidence.

Requirements, ownership, inventory, and data flow

Establish what the application is, who owns it, what it protects, where it runs, and which security behaviors are mandatory.

Module 01
  1. Record service name, owner, repository, build pipeline, environments, public endpoints, APIs, scheduled jobs, data stores, queues, third-party integrations, and end-of-support plan.
  2. Classify processed data and high-value actions. Distinguish public, internal, confidential, regulated, authentication, financial, and customer-controlled data.
  3. Define user and machine identities, tenant boundaries, administrative roles, support access, and break-glass paths.
  4. Select an ASVS 5.0.0 profile by service risk and record every included, excluded, or adapted requirement with rationale.
  5. Define measurable abuse resistance: login throttling, idempotency, transaction limits, log fields, secrets policy, dependency policy, recovery objectives, and response contacts.
Output: application inventory, data-flow sketch, owner register, risk tier, versioned requirement profile, and acceptance criteria linked to work items and tests.

Practice connection: NIST SSDF begins with preparing the organization and defining criteria; CISA Secure by Design emphasizes ownership of customer security outcomes.

Threat modeling and secure architecture

Find design-level abuse paths before they become distributed implementation defects.

Module 02
  1. Draw components, data stores, identities, privilege levels, entry points, egress paths, and trust boundaries. Label protocols, authentication, encryption, and data classification.
  2. Write attacker-centered abuse cases: “an external user accesses another tenant’s invoice,” “a compromised worker reaches metadata credentials,” or “an untrusted document changes an AI agent’s tool plan.”
  3. Use STRIDE, attack trees, misuse cases, or another consistent method to avoid blind spots; the diagram alone is not the model.
  4. Choose controls that prevent the path closest to its root: capability separation, isolation, allowlists, least privilege, nonces, state machines, quotas, signatures, and safe failure.
  5. Record assumptions and triggers for review: new identity provider, new data type, new public endpoint, privilege change, AI tool, dependency architecture, or acquisition.
Review question: if every perimeter control fails, what prevents one ordinary account, token, file, request, dependency, or model response from becoming an organization-wide compromise?
Output: versioned threat model, abuse-case backlog, security architecture decisions, control owners, and tests mapped to each material path.

Authentication, sessions, and identity lifecycle

Make identity proof, credential use, token validation, session state, recovery, and revocation explicit.

Module 03
  1. Prefer a maintained identity provider and standard protocol. Define issuer, audience, algorithm policy, key rotation, clock skew, token lifetime, and revocation behavior.
  2. Separate user sessions, service identities, API keys, OAuth clients, workload identities, webhooks, support impersonation, and emergency access.
  3. Protect password storage with an appropriate adaptive password hash; never encrypt passwords for later recovery. Rate-limit and monitor authentication and recovery.
  4. Set cookie attributes deliberately: Secure, HttpOnly, appropriate SameSite, narrow path/domain, rotation after privilege change, and invalidation on logout or compromise.
  5. Test negative states: expired, future, revoked, wrong audience, wrong issuer, downgraded algorithm, missing MFA, reused recovery token, parallel refresh, and disabled account.
Output: identity-flow diagram, token/cookie policy, recovery threat model, negative authentication test suite, and observable audit events.

Authorization, object access, and tenant isolation

Enforce policy at the resource and action boundary, not merely in navigation or route names.

Module 04
  1. Build an authorization matrix: subject/role, action, resource, ownership or tenant, condition, decision point, and required audit event.
  2. Resolve tenant and ownership context server-side. Treat IDs, role names, account claims, prices, status fields, and hidden form values as attacker-controlled.
  3. Use deny-by-default policy and central enforcement where possible. Protect background jobs, exports, bulk APIs, search indexes, cached objects, and indirect references as carefully as primary routes.
  4. Test horizontal access, vertical escalation, cross-tenant aggregation, nested resources, alternate HTTP methods, batch operations, stale tokens, race conditions, and administrative support paths.
  5. Ensure denials and high-value approvals create useful, privacy-aware telemetry without leaking object existence or sensitive policy detail.
API focus: object-level and function-level authorization are different. A user permitted to read one invoice is not necessarily permitted to list every invoice or invoke an administrative action.
Output: policy matrix, policy tests, cross-tenant regression suite, denial telemetry, and reviewed exception list.

Input boundaries, injection prevention, and safe output

Preserve the distinction between data and instructions through every interpreter and downstream service.

Module 05
  1. Inventory interpreters and contexts: SQL/NoSQL, OS commands, templates, LDAP, XPath, regular expressions, browser HTML/JS/CSS/URL contexts, log formats, and AI prompts.
  2. Use parameterized APIs, structured builders, strict schemas, contextual output encoding, fixed command invocation, and allowlisted values. Escaping is context-specific.
  3. Validate type, length, range, format, encoding, recursion, cardinality, and state transition at the trusted boundary; client-side validation is usability support, not enforcement.
  4. Avoid constructing shell commands. If process execution is essential, pass arguments separately, use an absolute executable path, restrict the execution identity, and test metacharacters and encoding variants.
  5. Test second-order paths where stored data later reaches a query, template, export, log processor, automation rule, or model prompt.
// Good pattern: SQL text and values remain separate.
const result = await db.query(
  "SELECT id, owner_id, status FROM orders WHERE id = $1 AND owner_id = $2",
  [orderId, authenticatedUser.id]
);
Output: interpreter inventory, banned-pattern rules, framework-specific safe examples, unit/property tests, and code-review checks.

Browser, frontend, and cross-origin security

Control browser execution, credentials, cross-site requests, embedded content, third-party scripts, and sensitive client state.

Module 06
  1. Model DOM and reflected/stored injection sources and sinks. Prefer framework auto-escaping; isolate or sanitize necessary rich HTML with a maintained library and restrictive policy.
  2. Deploy a tested Content Security Policy as defense in depth, not as a substitute for correct encoding. Minimize third-party script trust and document exceptions.
  3. Protect state-changing browser requests with SameSite cookies plus an anti-CSRF pattern appropriate to the architecture. Validate Origin where useful.
  4. Configure CORS by explicit trusted origin, method, header, and credential need. Never combine wildcard assumptions with sensitive credentialed behavior.
  5. Set HSTS, content-type options, referrer policy, framing policy, cache controls, and permissions policy according to data and feature needs; validate the deployed response, not only application code.
  6. Keep sensitive tokens out of URLs and avoid durable browser storage for high-value credentials. Treat source maps, bundles, feature flags, and client configuration as public.
Output: header baseline, CSP report review, XSS/CSRF regression tests, CORS matrix, third-party script inventory, and browser-storage decision.

First-party practice: the OWASP ZAP guide shows a practical DAST workflow; use it only against an authorized target and reproduce every finding manually.

API, GraphQL, webhook, and business-logic security

Protect resource access, computational capacity, workflow integrity, inventories, and upstream/downstream trust.

Module 07
  1. Maintain a machine-readable API inventory with owners, versions, authentication, sensitivity, consumers, environment, exposure, and retirement date. Include shadow, partner, mobile, and internal APIs.
  2. Apply object, property, and function authorization after parsing and before sensitive data access or state change. Use response schemas to prevent accidental overexposure.
  3. Bound pagination, nesting, GraphQL depth/complexity, file size, batch size, concurrency, query duration, webhook retries, and costly business operations.
  4. Protect sensitive business flows against automation and economic abuse using stateful controls, friction, risk signals, quotas, and observability—not IP throttling alone.
  5. Verify webhook signatures over the exact raw body, include timestamp/replay controls, rotate secrets, process idempotently, and isolate retries.
  6. Treat third-party API responses as untrusted: validate schema, cap size/time/redirection, restrict egress, and avoid blindly transferring upstream fields or errors.
Output: API catalogue, authorization and abuse tests, resource limits, webhook verification fixtures, upstream trust policy, and retirement plan.

Primary source: OWASP API Security Top 10:2023 distinguishes object/property/function authorization, resource consumption, SSRF, inventory, and unsafe API consumption.

Cryptography, secrets, and key lifecycle

Use reviewed primitives and managed lifecycle controls instead of custom cryptographic constructions or long-lived embedded secrets.

Module 08
  1. Define the property required: confidentiality, integrity, authenticity, password verification, token uniqueness, or non-repudiation. “Encrypt it” is not a requirement.
  2. Use current platform libraries and approved modes. Never invent algorithms, nonce handling, padding, signing formats, or key derivation.
  3. Keep keys and secrets outside source, images, logs, tickets, prompts, and browser bundles. Prefer short-lived workload identity and a managed secret/KMS/HSM service.
  4. Separate keys by purpose, tenant or environment where appropriate; define generation, access, rotation, revocation, backup, recovery, audit, and destruction.
  5. Test certificate and hostname validation, downgrade resistance, random-number failures, key-rotation overlap, revoked credentials, unavailable secret stores, and accidental disclosure paths.
Output: cryptographic design record, key/secret inventory, automated secret scanning, rotation exercise, and failure/recovery tests.

Files, parsers, serialization, URL fetching, and isolation

Constrain complex attacker-controlled formats and the services that process them.

Module 09
  1. For uploads, verify authorization, size, count, extension, detected type, parser limits, storage isolation, generated name, retrieval policy, and lifecycle. Do not trust client MIME metadata.
  2. Process risky documents, archives, media, and converters in a sandboxed worker with no unnecessary credentials or network access, strict CPU/memory/time quotas, and patched parsers.
  3. Prevent archive traversal, decompression bombs, recursive containers, polyglots, XML external entities, unsafe native deserialization, and parser differential attacks.
  4. For server-side URL fetching, validate the canonical destination, scheme, port, DNS resolution, redirects, IP ranges, response size/type, and egress policy at every hop.
  5. Use simple data-only formats and explicit schemas across trust boundaries. Never deserialize attacker-controlled objects into executable language types.
Boundary: antivirus or content-disarm output can reduce risk but does not make an untrusted file safe. Preserve isolation, authorization, and least privilege.
Output: parser/upload threat model, sandbox profile, corpus of hostile fixtures, egress tests, and resource-exhaustion tests.

Dependencies, source control, builds, artifacts, and supply-chain assurance

Know what enters the product, protect how it is built, and let consumers verify what was released.

Module 10
  1. Inventory direct, transitive, build-time, runtime, container, operating-system, action/plugin, model, and externally downloaded dependencies. Record provenance and support state.
  2. Require review for new dependencies: necessity, maintainer health, release history, permissions, install scripts, license, known vulnerabilities, namespace risk, and replacement/exit plan.
  3. Pin immutable identities where possible; protect branches and tags; minimize CI token permissions; isolate untrusted pull-request code; prohibit secrets in attacker-controlled build contexts.
  4. Generate an SBOM from the resolved build, not only the manifest. Produce build provenance, sign artifacts, and verify identities/provenance before deployment.
  5. Use vulnerability intelligence with reachability, deployed version, exposure, EPSS/KEV where relevant, and compensating controls. VEX can communicate contextual exploitability decisions but requires evidence.
  6. Progressively adopt the current SLSA 1.2 source/build tracks and preserve verification results as release artefacts.
Output: dependency policy, reviewed lockfile, resolved SBOM, provenance/signature, CI permission report, artifact verification log, and time-bounded vulnerability decisions.

Ecosystem: explore software-supply-chain behaviors in the public Threat Matrix T1195 page. It is threat context, not proof that a particular dependency is compromised.

Code review, SAST, SCA, secrets, IaC, and container analysis

Combine human reasoning and automated breadth while controlling noise and preserving developer feedback quality.

Module 11
  1. Review the change’s security delta: new data, trust boundaries, public routes, parsers, privileges, dependencies, cryptography, logging, deployment permissions, and failure modes.
  2. Run language-aware SAST and focused pattern checks on changed code; baseline legacy results transparently and prevent new high-confidence regressions.
  3. Scan dependencies, lockfiles, images, IaC, workflow definitions, and secrets. Avoid exposing secrets to pull-request forks or uploading sensitive source to unapproved services.
  4. Triage each result by exact path, source-to-sink semantics, reachability, control context, deployment, exploit preconditions, and impact. Suppress with owner, rationale, scope, and expiry.
  5. Convert confirmed defects into secure framework wrappers, lint rules, reusable tests, and review examples so the class becomes harder to reintroduce.
Quality control: a very large “zero-new-findings” baseline can hide real risk. Track scanner health, coverage, rule/version changes, timeout/skipped jobs, false-negative tests, and suppression age.
Output: reviewed diff, analysis artefacts, triage ledger, suppression register, control tests, and reviewer decision.

Dynamic testing, fuzzing, abuse simulation, and security regression

Verify running behavior and state transitions that static analysis cannot establish alone.

Module 12
  1. Deploy the exact candidate to an isolated, representative environment with synthetic identities, data, external-service stubs, logs, and reset capability.
  2. Build API/UI tests for authentication, authorization, validation, rate limits, workflow ordering, replay, concurrency, idempotency, and safe failure.
  3. Use DAST spidering and active checks only within approved scope. Seed authentication correctly, preserve requests/responses, and distinguish coverage gaps from clean results.
  4. Fuzz parsers and stateful APIs with seed corpora, boundary values, generated structures, malformed encodings, timeouts, resource limits, and crash minimization.
  5. Turn every confirmed security defect into the smallest reliable regression test at the appropriate layer: unit, property, integration, contract, browser, or system.
  6. Exercise telemetry and response: can operators distinguish an attack, control failure, and benign validation error without logging secrets or customer content?
Output: environment identity, test scope, authenticated coverage, raw evidence, minimized reproducer, security regression, and telemetry confirmation.

First-party practice: use the OWASP ZAP testing guide alongside controlled 1200km labs; for orchestration boundaries, see the HexStrike research index.

Vulnerability handling, remediation, disclosure, and learning

Move from discovery to verified correction without losing evidence, ownership, urgency, or customer context.

Module 13
  1. Normalize reports into one record: affected product/version/environment, entry point, preconditions, impact, evidence, reporter, disclosure constraints, owner, and status.
  2. Reproduce safely, determine the root cause and variant scope, and separate vulnerability, exposure, exploitability, and observed exploitation.
  3. Prioritize using business impact, reachability, internet exposure, privilege, affected customers, ease of exploitation, known exploitation, and compensating controls—not CVSS alone.
  4. Fix the root cause, search for variants, add regression tests, update secure components/patterns, and verify the deployed artifact rather than the source branch only.
  5. Coordinate advisories, CVE/CWE references where appropriate, customer mitigations, patch availability, disclosure timing, and internal communications.
  6. Feed lessons back into requirements, threat models, templates, scanners, libraries, training, monitoring, and release criteria.
Output: reproducible finding, severity rationale, variant analysis, fix commit, tests, deployed verification, disclosure record, and prevention action.

Deeper research: the separate Vulnerability Research & Exploit Development field guide covers root-cause analysis, exploitability validation, coordinated disclosure, and remediation verification.

AI-generated code, RAG, models, agents, and MCP-connected tools

Add AI-specific trust boundaries without weakening the normal application, identity, data, supply-chain, and operational baseline.

Module 14
  1. Inventory models, providers, prompts, system instructions, retrieval sources, embeddings, vector stores, tool servers, credentials, plugins, generated code, evaluation sets, and retained content.
  2. Classify all external documents, retrieved text, webpages, messages, model responses, and tool output as untrusted data. Keep instructions and data structurally separated where the platform allows.
  3. Enforce authorization and tenant isolation before retrieval and again before returning source passages. Security trimming must apply to chunks, caches, citations, exports, and derived summaries.
  4. Place a deterministic policy boundary between the model and MCP/tools: explicit tool allowlist, strict input/output schema, constrained identity, destination and path validation, quotas, timeouts, audit, and human approval for consequential actions.
  5. Validate model-generated code like untrusted third-party code: review, isolated execution, tests, dependency inspection, secret scan, and least-privilege deployment. Never paste production secrets into a prompt.
  6. Test direct/indirect prompt injection, retrieval poisoning, cross-tenant leakage, insecure output handling, tool confusion, excessive agency, denial of wallet/service, unsafe file/URL handling, and failure of the model/provider.
  7. Record provider, model/version, prompt/template version, retrieved source identifiers, tool calls, policy decisions, human approvals, and final disposition without retaining prohibited sensitive content.
Control boundary: a model may propose code, tests, triage, or tool arguments. It must not be the authority that grants itself access, changes policy, approves its own result, or silently executes high-impact actions.
Output: AI system data-flow model, retrieval ACL tests, MCP/tool contracts, prompt-injection evaluation set, human-approval policy, audit schema, and safe-degradation tests.

First-party implementation context: start with the AI Security practitioner field guide, then review AdversaryGraph, its documentation, AI in Offensive Security, HexStrike/MCP research, and AIDebug. These demonstrate workflows; they are not automatic assurance claims.

Selection, not shopping

Tool-selection matrix

Choose tools by question, evidence, integration, and failure mode. Coverage claims must name languages, frameworks, routes, authentication state, rules, versions, skipped files, and scan health.

CapabilityExample toolsBest questionEvidence and common limit
Threat modelingOWASP Threat Dragon, diagrams-as-code, architecture decision recordsWhere can an attacker cross trust, identity, data, or privilege boundaries?Versioned model and decisions. A diagram without abuse paths and owners is incomplete.
SAST / semantic analysisCodeQL, Semgrep, language-native analyzersCan data or control flow reach a dangerous sink or violate a secure pattern?Exact path and rule version. Framework coverage and false negatives vary.
Dependency analysisOSV-Scanner, Dependabot, Renovate, ecosystem audit toolsWhich resolved components have relevant advisories or support risks?Resolved version and graph. A CVE match does not prove reachable exploitability.
SBOMCycloneDX generators, Syft, ecosystem-native exportersWhat components and relationships exist in the built product?Build-derived SBOM. Manifest-only inventory may omit generated/runtime content.
SecretsGitleaks, detect-secrets, provider-side secret protectionDid a credential-like value enter source, history, artifact, log, or configuration?Location and fingerprint. Detection does not rotate or revoke a real secret.
IaC / containersCheckov, Trivy, Hadolint, kube-linter, policy enginesDoes deployment configuration violate a defined hardening policy?Exact resource and policy. Runtime mutation may differ from source.
DAST / proxyOWASP ZAP, Burp Suite, browser automationHow does the running application behave under crafted requests and workflows?Raw request/response and environment. Authentication and crawl coverage are frequent gaps.
API testingSchemathesis, REST-assured, Postman/Newman, custom property testsDoes implementation obey schema, authorization, state, and resource constraints?Seed, schema, identities, and failing case. Schema-valid does not mean business-authorized.
FuzzinglibFuzzer, AFL++, Jazzer, property-based test librariesWhich input or state sequence causes crash, hang, resource exhaustion, or invariant failure?Minimized corpus and sanitizer trace. Harness quality determines reachable code.
Supply-chain postureOpenSSF Scorecard, SLSA tooling, Sigstore/cosignHow are source, build, artifact identity, provenance, and project practices protected?Verified identity and attestation. A score or signature alone does not prove secure code.
Mobile analysisMobSF, JADX, apktool, Frida, platform test toolingHow do package, storage, network, IPC, authentication, and runtime controls behave?App version, device state, traces. Static declarations and runtime behavior can differ.
AI assistanceLocal/approved LLM, RAG, MCP-connected analysis toolsCan a model accelerate review, test generation, explanation, or triage?Prompt/model/source/tool trace plus human decision. Fluency is not verification.

Applied reasoning

Six end-to-end field cases

Case 1 — Cross-tenant invoice access

Signal: a route loads /api/invoices/{id} and the UI hides invoices from other organizations.

Steps

  1. Use two synthetic tenants and capture an invoice ID from each.
  2. Replay read, update, export, attachment, search, and batch paths with the other tenant’s identity.
  3. Trace the repository query and confirm the tenant predicate comes from trusted session context.
  4. Check background jobs, caches, object storage keys, and audit records for the same boundary.
  5. Fix centrally, add cross-tenant negative tests, search for sibling resources, and verify the deployed build.

Evidence: before/after HTTP exchange with synthetic data, code path, policy test, deployed version, and denial event.

Case 2 — CI workflow credential exposure

Signal: an external pull request can influence a privileged workflow that receives a repository token or cloud credential.

Steps

  1. Map event type, checked-out ref, actor trust, token permissions, environment approvals, and reusable workflows.
  2. Prove exposure using a harmless canary in a private test repository—never exfiltrate a real secret.
  3. Separate untrusted build/test from privileged publish; use immutable actions and least-privilege tokens.
  4. Require approval and artifact identity verification before promotion.
  5. Rotate any potentially exposed credential and retain audit evidence.

Evidence: workflow diff, permissions snapshot, canary result, rotated credential record, and protected release run.

Case 3 — SSRF through document preview

Signal: a preview service accepts a URL and follows redirects to fetch remote content.

Steps

  1. Model URL parse, DNS resolution, redirect, fetch worker, cloud metadata, and response rendering boundaries.
  2. Use an authorized local lab with controlled public and private destinations.
  3. Test alternate IP forms, DNS changes, redirects, user-info confusion, schemes, ports, and oversized responses.
  4. Implement an egress proxy and revalidate canonical destination after every resolution and redirect.
  5. Remove worker credentials, cap resources, and add regression fixtures.

Evidence: lab topology, request chain, denied private destination, egress logs, and resource-limit test.

Case 4 — Vulnerable transitive library

Signal: SCA reports a high-severity advisory in a package included through a framework dependency.

Steps

  1. Confirm package identity, resolved version, artifact, environment, dependency path, and affected function/version range.
  2. Determine whether the vulnerable feature is included and reachable from untrusted input.
  3. Check exposure, mitigations, known exploitation, and supported upgrade path.
  4. Upgrade or remove the component, rebuild the SBOM, run regression/security tests, and verify the deployed artifact.
  5. If temporarily not affected, record a scoped VEX-style rationale with evidence and expiry.

Evidence: resolved graph, SBOM diff, reachability test, advisory source, rebuilt provenance, and deployment verification.

Signal: an exported mobile activity accepts an external deep link that selects a privileged account action.

Steps

  1. Inspect manifest, intent filters, app links, exported components, WebView behavior, and server API authorization.
  2. Exercise the link on an isolated emulator with synthetic accounts and Frida/log tracing where authorized.
  3. Prove whether client routing alone, stale session state, or backend object authorization enables impact.
  4. Require verified links and server-side authorization; reject unsafe schemes/hosts/paths and sensitive parameters.
  5. Add device and API regression tests and verify release signing/configuration.

Practice: use the deliberately vulnerable Android app, analysis-lab guide, and APK vulnerability-research guide.

Case 6 — Indirect prompt injection reaches an MCP tool

Signal: a RAG assistant retrieves a document telling the model to ignore policy and call a filesystem or scanner tool.

Steps

  1. Place a synthetic hostile instruction in an authorized test document and record its retrieval ACL and chunk identity.
  2. Observe whether the model changes task, leaks other retrieved data, constructs a dangerous tool request, or hides citations.
  3. Keep policy outside the prompt: allowlist tools, validate typed arguments, constrain identity/destination/path, and require approval.
  4. Sanitize tool output as untrusted data, cap recursive calls, and test provider/tool failure.
  5. Preserve model, prompt, retrieval, tool, policy, and human-decision traces.

Practice: use the architecture patterns in AdversaryGraph and the HexStrike/MCP guide collection; verify the actual deployment configuration.

Hands-on progression

Twelve labs from secure baseline to release assurance

Use disposable local environments, synthetic identities and records, known vulnerable targets, and explicit authorization. Each lab ends with evidence and a regression—not only exploitation.

  1. Inventory and ASVS profile: choose a small demo service, document data flow and identities, assign a risk tier, and map a focused ASVS 5.0.0 requirement set.
  2. Threat model: produce a trust-boundary diagram, ten abuse cases, control decisions, owner assignments, and three review triggers.
  3. Authentication negatives: test issuer/audience, expiry, revocation, recovery replay, session rotation, MFA step-up, and disabled-account behavior.
  4. Multi-tenant authorization: create two organizations and automate cross-tenant read/write/export/batch denials across UI and API.
  5. Injection prevention: repair deliberately unsafe SQL and command execution, add property tests, and enforce safe wrapper use with a static rule.
  6. Browser controls: eliminate a lab XSS, add CSP in report-only then enforcement mode, verify CSRF protection, and test explicit CORS policy.
  7. API abuse: test object/function authorization, GraphQL complexity or REST pagination, sensitive business-flow automation, and webhook replay.
  8. Upload and SSRF isolation: process hostile archive/parser fixtures in a restricted worker and enforce URL-fetch egress policy across redirects.
  9. Supply-chain evidence: review a new dependency, produce a resolved CycloneDX SBOM, generate provenance, sign an artifact, and verify before install.
  10. Integrated pipeline: combine tests, SAST, dependency, secret, IaC/container, SBOM, and policy checks with clear failure and suppression handling.
  11. Mobile AppSec: use the 1200km vulnerable Android lab to connect manifest/static findings to emulator behavior and server-side controls.
  12. AI/RAG/MCP boundary: create a synthetic poisoned retrieval item, verify chunk-level ACLs, prove tool policy blocks unsafe arguments, and document human approval plus audit evidence.
Completion rule: retain lab scope, source/build identity, setup, synthetic data, commands or tests, raw observations, screenshots where useful, interpretation, remediation, regression, and cleanup evidence.

Defensibility

Evidence and report schema

A common record lets development, security, operations, leadership, customers, and disclosure coordinators understand the same result without inflating uncertainty.

finding_id: APP-2026-0042
title: Cross-tenant invoice export authorization failure
status: confirmed | mitigated | accepted | fixed | verified | closed
scope:
  product: billing-service
  source_commit: <immutable commit>
  build_digest: sha256:<artifact digest>
  environment: isolated-staging
  endpoint: POST /api/invoices/{id}/export
requirement:
  framework: OWASP ASVS
  version: 5.0.0
  id: <versioned requirement id>
classification:
  weakness: CWE-<id>
  data_class: confidential-customer
  exposure: authenticated-internet
preconditions:
  - valid account in another synthetic tenant
evidence:
  request_id: <redacted request reference>
  response_hash: sha256:<sanitized evidence hash>
  code_path: src/invoices/export-handler
  test: tests/security/cross-tenant-export
analysis:
  impact: another tenant's invoice becomes accessible
  exploitability: reproduced with ordinary synthetic account
  confidence: confirmed
remediation:
  owner: billing-team
  root_cause: repository query omitted trusted tenant predicate
  fix_commit: <immutable commit>
  variants_reviewed: list/read/update/attachment/batch/cache
verification:
  test_result: pass
  deployed_digest: sha256:<verified digest>
  verified_at: 2026-07-27T12:00:00Z
exceptions:
  decision: none
  approver: null
  expires_at: null

Evidence rules

  • Use immutable source, dependency, image, and deployment identities.
  • Sanitize customer data, tokens, cookies, credentials, internal hostnames, and exploit details not needed for the decision.
  • Separate observation, interpretation, assumption, reproduction, and business decision.
  • Record negative results and coverage limits: unauthenticated crawl, skipped route, unsupported language, timeout, unavailable environment, or untested role.
  • Link the requirement, threat/abuse case, control, test, result, owner, remediation, and deployed verification.
  • Record AI-generated suggestions as suggestions; retain model/source/tool context and the human decision.

Common breakdowns

Failure atlas: symptom, cause, corrective action

SymptomLikely causeCorrective action
Hundreds of findings, few fixesTools were deployed without ownership, triage capacity, risk policy, or developer feedback design.Start with high-confidence changed-code controls, name owners, measure time to verified fix, and tune transparently.
“OWASP compliant” claimAn awareness list was treated as certification or proof.Name the exact standard/version, scoped requirements, evidence, exclusions, assessor, and date; avoid unsupported compliance language.
UI hides action but API allows itAuthorization was implemented as presentation logic.Enforce server-side at the object/action boundary and add negative tests for every route and identity.
DAST returns clean immediatelyScanner never authenticated, crawled the SPA, or reached protected flows.Verify session state and route coverage, seed workflows/API schema, inspect logs, and report gaps.
Every dependency CVE blocks releasePackage identity was not joined with deployed version, reachability, exposure, or controls.Keep the inventory complete, then prioritize with context and time-bound evidence; never hide unfixed risk.
Signed image is still untrustedSignature identity/provenance was not verified, or the build itself was compromised.Verify issuer/subject, source, builder, parameters, materials, policy, and deployment identity.
Secret scan passes, credential leaksSecrets entered logs, tickets, prompts, artifacts, history, or runtime configuration outside scanned paths.Map the secret lifecycle, scan multiple artefacts, use short-lived identity, and test revocation/rotation.
AI-generated fix creates a new flawGenerated code bypassed review, tests, dependency policy, or secure framework patterns.Treat generated output as untrusted code and apply the same gated engineering lifecycle.
RAG leaks another tenant’s documentACLs applied only at document ingest or UI, not at chunk retrieval/cache/response.Apply identity-aware filtering before retrieval and output; test chunk-level cross-tenant negatives.
Security exception becomes permanentNo owner, compensating-control evidence, expiry, or review trigger.Make exceptions time-bound, visible, testable, and automatically re-opened before expiry.

Operational acceptance

Secure release gate

Tune the gate by risk tier, but make every decision reproducible. A green build means the defined checks ran successfully on the identified source and artifact; it never means “no vulnerabilities exist.”

Before merge

  • Owner, scope, risk tier, security requirements, and threat model are current.
  • Security-sensitive design and code received independent review.
  • Unit, property, integration, authorization, and abuse tests passed.
  • SAST, dependency, secret, IaC/container, and workflow checks ran without hidden skips.
  • New dependencies and privileges were explicitly reviewed.
  • Exceptions include rationale, evidence, owner, approval, expiry, and compensating control.

Before production

  • Candidate artifact identity, SBOM, provenance, signature, and verification result are retained.
  • Representative dynamic and security regression tests passed on the candidate.
  • Secrets, environment policy, migrations, external integrations, and safe failure were exercised.
  • Security telemetry and alert routing were validated without sensitive-data leakage.
  • Backup, recovery, rollback, feature-disable, response owner, and communication path are ready.
  • The deployed digest and configuration match the accepted candidate.
After release: verify the live artifact, critical controls, external exposure, logs, and alerts; monitor new advisories and exploitation context; feed incidents and near misses back into requirements and tests.

Primary sources and 1200km ecosystem

Authoritative references and further practice

Standards and primary guidance

1200km first-party practice

Evidence boundary: framework alignment, tool execution, and lab reproduction do not establish universal security, compliance, or exploitability. State the scope, version, environment, evidence, limitations, and reviewer decision.