PRACTITIONERCHAPTER 06

Secure code review and AppSec

Read a diff the way an attacker would, write findings a developer will fix, and run SAST, DAST and SCA without drowning the teams in noise

45 MINSECURITYUPDATED 2026-11-05
PREDICT

A SAST tool and an experienced reviewer look at the same pull request, which adds an endpoint to a multi-tenant SaaS product. Which bug is the reviewer most likely to catch that the tool misses?

Application security, AppSec, is the part of security engineering that lives inside the software development life cycle. You review designs and code, you choose and run the tools that scan it, you triage what they find, and you teach the teams to find the next bug themselves. The ladder title is usually AppSec Engineer or Security Engineer; at the Senior Security Engineer or Security Lead rung you own the programme rather than the reviews.

The track’s ladder says practitioners are judged on findings fixed, not findings filed. That one line explains most of this chapter. A finding nobody fixes has cost the developer an interruption and bought the company nothing. Everything below, how you read a diff, how you write a finding, how you configure a scanner, is in service of the fix.

What AppSec is for

The model is simple to state and hard to live. Developers ship code. Some fraction of it contains vulnerabilities. You cannot read all of it, and you would not want to: you would become the bottleneck, and the teams would learn that security is something done to them. So you put your attention where the risk concentrates, you use tools for the patterns tools are good at, and you spend the rest of your time making the secure way the easy way.

Three activities follow from that.

Review, by hand, of the changes that carry the most risk: authentication, authorisation, anything that touches money, file uploads, deserialisation, outbound requests to URLs a user supplies, cryptography, and new external endpoints. The threat model from Threat modelling tells you which components those are.

Tooling: static analysis on every change, dependency scanning on every build, dynamic scanning against a running environment, secrets scanning on every push. Tools give you coverage you cannot give by hand. They also give you noise, and managing the noise is half the job.

Enablement: secure defaults in the frameworks the teams use, a library that does the hard thing correctly so nobody writes it twice, training that uses your own codebase’s bugs as examples. The Lead-level chapter on security champions and paved roads covers this at scale. At practitioner level, the habit is this: every time you find the same bug twice, ask what would make it impossible the third time.

Reading a diff like an attacker

A functional reviewer asks whether the code does what it should. You ask what else it lets someone do. Five questions, in this order, catch most of what matters.

1. Where does untrusted data enter? Request bodies, query strings, headers, cookies, file contents, webhook payloads, messages from a queue another team owns, and rows in a database that a user once wrote. These are the sources. Mark them.

2. Where does it end up? A SQL query, an HTML page, a shell command, a file path, an outbound HTTP request, a log line, a template, a deserialiser. These are the sinks. For each source-to-sink path, ask what encoding or validation sits between them, and whether it matches the sink. HTML escaping does nothing for SQL. A parameterised query cannot bind a column name. The mechanisms are in the SQL injection, XSS and SSRF lessons; you need them well enough to recognise the shape in a diff.

3. Who is allowed to do this, and where is that checked? Find the authentication check, then find the authorisation check, then confirm it checks the right thing. Most serious bugs in modern web applications are here: an endpoint that checks the caller is logged in but not that the record is theirs. Tools miss these because the code is correct; only the rule is missing. The IDOR lesson works one through.

4. What changed about state? A check followed by an action on shared state is a race window, the pattern in the TOCTOU lesson. A state-changing GET, or a form without a token, invites CSRF. A refund endpoint that reads the balance, checks it, then writes it, can be called twice at once.

5. What does failure look like? Exceptions that leak stack traces, error paths that skip the check, a fallback that fails open, a comparison of secrets that returns early on the first wrong byte (the timing attack lesson). The OWASP Top 10:2025 added Mishandling of Exceptional Conditions as its own category for this reason.

Language matters too. In C and C++, every length calculation and every copy is a candidate for the bug in the buffer overflow lesson, and review there is slower and more careful. In memory-safe languages your attention moves up to logic and authorisation. The harden a login flow capstone is a good rehearsal: it puts several of these classes in one feature. When a coding agent wrote the diff, reviewing AI-written code covers what changes.

Read the diff in its context, not on its own. Open the file, read the function the change sits in, find the callers. A two-line change that removes a check can be the most dangerous change of the week, and the diff view hides what the check was protecting.

Writing a finding a developer will fix

A finding is a small argument. It has to convince a busy engineer, who did not ask for your opinion, that this is real, that it matters, and that the fix is worth an hour of their afternoon. Findings fail in predictable ways: no location, no exploit, a severity copied from a tool, a fix that says “sanitise the input”, or a tone that makes the author defensive.

A finding that gets fixed has seven parts.

Part Weak Usable
Where “the export endpoint” invoices/export.ts line 42
What “SQL injection risk” The sort parameter is interpolated into ORDER BY; SQL injection, OWASP A05:2025
Who and how not stated Any logged-in user of any tenant can send a crafted sort value
Impact “data breach” Blind extraction of other tenants’ rows, one bit per request
Severity “Critical (tool)” High: authenticated, but any of 4,200 tenants qualifies
Fix “sanitise input” Map sort to an allowlist of three column names; reject anything else
Test not stated A request with an unknown sort value returns 400

Write about the code, not the person. “This handler loads the invoice before checking the organisation” lands better than “you forgot the check”. Offer the fix as code where you can. If the fix is more than a few lines, send the pull request yourself: nothing builds trust faster than an AppSec engineer whose findings arrive with a patch.

Separate blocking from non-blocking. Google’s code review guide, in the reading, sets the standard for ordinary review: approve once the change definitely improves the overall health of the code, even if it is not perfect, and prefix optional suggestions with “Nit:”. Security review inherits that standard, with one exception. An exploitable vulnerability in the change is a blocker, and you say so plainly. Everything else, hardening, defence in depth, a better pattern, is a follow-up with a ticket and a date, and the change merges.

Severity deserves its own sentence in every finding. A tool’s label is a starting point, not an answer. Reason from impact (what the attacker gets) and likelihood (who can reach it, what they need, whether it is internet-facing) in this system. Most teams use four levels, critical, high, medium and low, with response times attached. The scoring systems, CVSS and EPSS, and the SLA tiers that go with them belong to vulnerability management; in review, a clear sentence of reasoning is worth more than a vector string.

The tools: SAST, DAST, SCA and what each misses

Three families of tool, each with a different blind spot.

Tool What it examines Good at Misses Noise
SAST (static analysis) Source code, without running it Injection, unsafe functions, hard-coded secrets, taint from source to sink Authorisation, business logic, anything that depends on configuration or runtime High until tuned; many findings on unreachable or already-sanitised paths
DAST (dynamic scanning) A running application, over HTTP Missing headers, reflected XSS, misconfiguration, things that are really exploitable Pages behind login unless scripted; anything it cannot reach; where in the code the bug is Lower per finding, but coverage is shallow
SCA (software composition analysis) Your dependencies and their versions Known CVEs in libraries, licence issues Whether your code calls the vulnerable function; bugs not yet published Very high; most flagged CVEs are in code paths you never execute

Add secrets scanning, which looks for credentials in commits and is the one tool where a true positive is always urgent, and IAST, which instruments the running application and sits between SAST and DAST.

SCA deserves a word because it produces the largest volume. When Log4Shell (CVE-2021-44228) landed in December 2021, SCA was how most companies found out where they ran Log4j, often several levels deep in the dependency tree. That is the tool at its best. The same tool, on an ordinary Tuesday, reports dozens of CVEs in transitive dependencies that the application never loads. Reachability analysis, which checks whether your code can call the vulnerable function, cuts that list sharply where your tool supports it. Where it does not, the triage question is the same one you ask by hand.

False positives are a product problem

The honest truth about static analysis is that its precision decides whether anyone reads it. Google’s paper on its static analysis platform, in the reading, defines an effective false positive as any finding a developer does not act on: the tool may be wrong, or it may be right but unclear, and the developer’s reaction is the only measure that counts. Checks shown in Google’s code review must stay under 10% effective false positives, and an analyser whose ‘not useful’ rate goes above that is disabled until its authors fix it. The paper also describes an earlier attempt to show FindBugs results to developers, which failed partly because false positives made them lose confidence in the tool as a whole.

That is the dynamic to fear. A tool that cries wolf on four findings in five trains developers to dismiss the fifth. You are responsible for the tool’s precision, not the vendor.

Triage without drowning

A workable process for any scanner, applied the same way every time:

  1. Baseline. On first run, record every existing finding. The pipeline blocks only on new findings in changed lines. The baseline is a backlog, worked separately.
  2. Sample by rule, not by finding. Group findings by rule. Read ten from each of the noisiest rules. If eight are false, tune or disable the rule for your codebase; do not dismiss two hundred findings one at a time.
  3. Classify each finding you read: true positive (ticket with severity and owner), false positive (suppressed in code with a comment saying why and linking the review), or accepted risk (true but not worth fixing now, signed off by someone with the authority to accept it under your vulnerability policy, with an expiry date).
  4. Block on a small set of high-precision rules. Injection with confirmed taint, committed secrets, known-exploited CVEs in reachable code. Everything else is a comment in the pull request, not a gate.
  5. Measure. Track the fix rate and the dismissal rate per rule. A rule that is dismissed more often than it is fixed is costing more than it saves.

Standards: the OWASP Top 10 and ASVS

Two OWASP documents come up in every AppSec conversation, and they do different jobs.

The OWASP Top 10 is an awareness document. The current edition is 2025, which replaced the 2021 list; it ranks ten categories by data and survey, with Broken Access Control still first and Software Supply Chain Failures, a broadening of the 2021 list’s vulnerable-components category, at third. It is the shared vocabulary for findings (“A01, broken access control”) and a good syllabus for developer training. It is not a standard you can comply with, and a pentest report that says “we tested the OWASP Top 10” has told you little.

The OWASP Application Security Verification Standard, ASVS, is the standard. Version 5.0, released in May 2025, is a set of numbered, testable requirements grouped into chapters, with three levels: Level 1 as the baseline for every application, Level 2 for most applications holding sensitive data, and Level 3 for the most critical. Requirement identifiers can change between versions, so the project asks you to cite them with the version, for example v5.0.0-1.2.5. Use ASVS in two places: as acceptance criteria when a team builds an authentication or session feature, and as the checklist when you review it. “Meets ASVS Level 2 chapters on authentication and session management” is a requirement an engineer can test.

Working with developers

This is where practitioners disagree most, and where the job is won or lost.

One school treats security review as a gate: nothing touching authentication or payments ships without AppSec sign-off. It is defensible in regulated settings, and PCI DSS v4 requirement 6.2.3 expects bespoke code to be reviewed for vulnerabilities before release. Its failure mode is a queue. When the queue is a week long, teams route around it, and the changes you most needed to see are the ones that arrive late or not at all.

The other school treats AppSec as a service: review is advisory, tools comment rather than block, and the AppSec engineer’s job is to be useful enough that teams ask. Its failure mode is that a team under deadline never asks.

Most mature programmes land in between. A short list of triggers (a new external endpoint, a change to authentication, a new dependency that parses untrusted input, anything moving money) requires a security reviewer, with a turnaround promise you can keep, often one working day. Everything else is reviewed by the team, with tooling in the pull request and you available. The relationship matters more than the policy. Concretely, that means:

  • Being early beats being thorough. Ten minutes on the design doc saves two days on the diff.
  • Your findings are a product. If developers do not act on them, the problem is the finding, the tool or the timing, not the developers.
  • Fix one yourself. When a class of bug recurs, write the safe helper, the lint rule, or the framework default, and send the pull request.
  • Say what you would ship. “Merge it with F3 as a follow-up” is a sentence that earns trust for the day you say “this cannot merge”.
  • Credit the catch. When a developer finds a vulnerability in their own team’s code, say so in the channel. It is the behaviour you want more of.

Day to day

The rhythm of an AppSec engineer at a company with a few dozen developers per security engineer looks like this.

Every day, an hour or two: the review queue. Pull requests tagged for security review by the trigger rules, and ones a developer asked you to look at. Most take fifteen to forty minutes. You comment in the pull request, mark findings blocking or not, and approve when the blockers are gone. Keep the turnaround promise; it is the thing teams remember.

Every day, twenty minutes: scanner triage. New findings from SAST, SCA and secrets scanning that the pipeline did not block. Secrets first, always: a live credential in a commit is an incident, rotated today. Then new high-severity SCA findings, checked for reachability. Then SAST, by rule.

Weekly: design reviews. One or two design documents or threat-model sessions for features starting build. Thirty to sixty minutes each. This is where the cheapest fixes happen.

Weekly: office hours. An hour a week in a public channel or a calendar slot where anyone can bring a question. Many of your best findings arrive here as “is this fine?”.

Fortnightly or monthly: rule tuning. Review the dismissal rates per rule, disable or rewrite the noisy ones, add a custom rule for the bug class you keep finding by hand.

Monthly: the backlog review with each engineering manager whose team owns open findings. Fifteen minutes per team: what is overdue, what is blocked, what you can help with. Bring the list; do not make them build it.

Quarterly: training and metrics. One session for developers built from the quarter’s real findings, anonymised. A short report to your manager: findings fixed by severity, median time to fix, the rules you tuned, and the classes of bug that are falling or rising.

The meetings that matter are the design reviews and the backlog reviews. The first is where you prevent vulnerabilities; the second is where findings turn into fixes.

BY ORG SIZE
STARTUPunder 30 people

There is no AppSec engineer. A senior developer with an interest in security is the de facto reviewer, and the review happens because someone tagged them on a pull request. What works: a written list of triggers (authentication, payments, uploads, outbound URLs) that require a second reviewer with that person on it; free tiers of SAST, dependency and secrets scanning switched on in CI, with only secrets blocking; and one afternoon a quarter reading the riskiest code end to end. The danger is the opposite of noise: nobody looks at the scanner output at all.

SCALE-UP30 to 300

You are the first or second AppSec hire, and the ratio means you cannot read every diff. Your first quarter is triage and trust: baseline the scanners, tune the noisiest rules, publish the review triggers with a one-day turnaround, and fix three recurring bug classes at the framework level. Security champions start to appear in the teams that liked working with you. The first enterprise customer’s security questionnaire arrives and asks about secure code review; this is when your process needs to exist on paper as well as in practice.

ENTERPRISE300 and up

There is an AppSec team, several scanners producing overlapping findings, and a platform that deduplicates them. Applications are tiered, with an ASVS level per tier. Review is partly a gate, because PCI DSS, SOC 2 auditors or a banking regulator expect evidence of it, and the evidence trail can start to matter more than the review. The hard problems are scale and politics: hundreds of repositories, teams that dispute severity, an exception process where a business owner signs to accept a risk, and keeping the gate from becoming a queue.

ARTEFACT Write security review findings for a diff ~50 MIN
YOU PRODUCESecurity review findings with severity and fix

Template

# Security review: <PR title> (<repo>#<number>)
Reviewer · Date · Author · Verdict: approve | approve with follow-ups | changes required
Scope: <files and functions reviewed; what was out of scope>
Context: <what the change does; trust boundaries it crosses; data it handles>
Tools: <SAST / SCA / secrets results on this PR>

## Summary
<Two or three sentences: the worst finding, the verdict, what must change before merge.>

## Findings
### F1. <short title> (<Critical | High | Medium | Low>)
**Where:** <file:line>
**What:** <the flaw in one sentence; class; OWASP Top 10:2025 or ASVS v5.0.0 reference>
**Who and how:** <who can reach it, from where, what they need, what they get>
**Severity reasoning:** <impact and likelihood here; what raises or lowers it>
**Fix:** <the change, as code where possible>
**Test:** <the test that fails now and passes after the fix>
**Blocking:** yes | no (ticket <link>, due <date>)

### F2. ...

## Dismissed tool findings
| Tool | Rule | Location | Why dismissed |
|---|---|---|---|

## Non-blocking notes
- Nit: / Optional: <hardening suggestions>
WORKED EXAMPLE

Teal Ledger is a fictional accounting and payments SaaS for small businesses: 120 people, 45 engineers, 4,200 customer organisations, one AppSec engineer. A developer on the invoicing team opened a pull request adding an endpoint that exports an invoice’s line items as CSV. Node and TypeScript, Postgres, 140 lines. Review time: 50 minutes.

Summary. The export endpoint lets any logged-in user read any organisation’s invoices and injects a request parameter into SQL. Changes required: F1 and F2 block the merge; F3 and F4 are follow-ups.

F1. Invoice loaded without an organisation check (High). Where: invoices/export.ts line 31. The handler fetches the invoice by numeric id alone; ids are sequential. Any user of any of the 4,200 organisations can enumerate every invoice, including customer names and amounts. OWASP A01:2025. Fix: add AND org_id = $2 with the session’s organisation, and return 404, not 403, so ids do not leak. Test: a user from organisation B requesting organisation A’s invoice gets 404. Blocking.

F2. Sort parameter interpolated into ORDER BY (High). Where: line 42. Bind parameters cannot carry a column name, so the developer used a template string. An authenticated user can run blind boolean extraction across tenants. OWASP A05:2025. Fix: map sort to an allowlist of date, amount, description; anything else is 400. Test: sort=amount;-- returns 400. Blocking.

F3. CSV formula injection (Medium). Line items are customer-entered; a description starting with = runs as a formula when the accountant opens the file in a spreadsheet. Needs the victim to open the file and accept a warning, hence Medium. Fix: prefix cells beginning with = + - @ with a single quote. Ticket INV-881, 14 days.

F4. Full invoice logged at info level (Low). Line 55 logs the invoice object, including the customer’s bank account number. Fix: log the id only. Ticket INV-882, 30 days.

Dismissed. SAST rule for reflected XSS on res.send(csv): false positive, because the response is text/csv with an attachment disposition and nosniff is set globally. Suppressed inline with a link to this review.

Now you

You are the AppSec engineer at Gadwall, a fictional push-notification service: 70 engineers, 2,300 customer apps, running on a public cloud. A senior backend engineer has opened the pull request below, which lets a customer register a callback URL for delivery receipts. The account manager for Gadwall’s largest customer needs it merged by Thursday for their launch, and it is Tuesday afternoon. The SAST tool reported two findings on the change: SQL injection on the UPDATE (correct) and a hard-coded credential in a test fixture that is also in the PR but not shown (the fixture uses a dummy key). load_api_key is defined earlier in the file and returns None for an app id it does not recognise. Write the review: every finding with severity, fix and test, what blocks Thursday and what does not, and the tool finding you dismiss. Two serious problems are ones the tool did not find.

--- a/gadwall/api/webhooks.py
+++ b/gadwall/api/webhooks.py
@@ -1,6 +1,7 @@
 import hmac
 import hashlib
+import requests
 from flask import Blueprint, request, abort, jsonify
 from gadwall.db import db
 
 bp = Blueprint("webhooks", __name__)
@@ -40,1 +41,12 @@ def delivery_status():
     return jsonify(status)
+
+
+@bp.post("/v1/apps/<app_id>/callback-url")
+def set_callback_url(app_id):
+    if request.headers.get("X-Api-Key") != load_api_key(app_id):
+        abort(401)
+    url = request.json["url"]
+    db.execute(f"UPDATE apps SET callback_url = '{url}' WHERE id = %s", (app_id,))
+    # check the endpoint is reachable before saving
+    r = requests.get(url, timeout=5)
+    return jsonify({"ok": True, "status": r.status_code, "body": r.text[:500]})

Self-check

DECIDE

You joined Teal Ledger three weeks ago as its first AppSec engineer: 45 engineers, one monolith and six services. The CTO bought a SAST licence before you arrived. Its first full scan reports 400 findings, 38 of them labelled critical or high. The CTO wants the tool blocking merges by the end of the month, and the engineering managers have already heard the number. What do you do with the 400?

READING
  1. DOC
    OWASP Top 10:2025 OWASP Foundation, 2025

    The current edition of the awareness list and the vocabulary every finding and training session uses. Read each category's 'how to prevent' section and the list of mapped CWEs.

  2. DOC
    OWASP Application Security Verification Standard OWASP Foundation, 2025

    Version 5.0, the testable requirements behind a review. Read the authentication, session and access-control chapters, and use them as acceptance criteria rather than a checklist after the fact.

  3. HANDBOOK
    Google Engineering Practices: The Standard of Code Review Google

    The principle that review approves changes which improve code health rather than demanding perfection, and the Nit: convention. Read it to calibrate what you block on and what you mark optional.

  4. PAPER
    Lessons from Building Static Analysis Tools at Google Caitlin Sadowski, Edward Aftandilian, Alex Eagle, Liam Miller-Cushon, Ciera Jaspan, 2018

    Why developer trust decides whether static analysis works, and the 10% effective false-positive bar. The best argument for tuning before you block. Read: Communications of the ACM 61(4), 2018; read the sections on effective false positives and the criteria for code-review checks.

  5. POST
    Apple's SSL/TLS bug Adam Langley, 2014

    The goto fail analysis from the Why: one duplicated line, what it broke, and an honest look at what code review, testing and compiler warnings could each have done.

  6. DOC
    OWASP Secure Code Review Cheat Sheet OWASP Cheat Sheet Series

    A compact method for baseline and diff-based review, with checklists per vulnerability class. Use the checklists while you build your own instinct.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Vulnerability management →