Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 80 ยท Secure Coding

Security Code Review, SAST and Testing

Learn how to review code for security bugs, what static and dynamic testing find, how fuzzing works, and how to write security unit tests in Python.

Most security bugs are not clever. They are a missing check, a string glued into a query, a secret left in a file. They survive because nobody looked at that line with an attacker's eyes, or because nothing in the build would have failed if they had been there. Security review and testing are the habits that put those eyes and that safety net into everyday work.

In this lesson you'll learn how to review code for security, what automated tools (SAST and DAST) can and cannot find, how fuzzing finds crashes nobody predicted, and how to turn a past vulnerability into a unit test that keeps it from coming back. It builds on Secure Coding Principles and Python Security Pitfalls.

Three ways to look for bugs

flowchart LR
    C["Source code"] --> R["Manual review<br/>(people)"]
    C --> S["SAST<br/>(reads code, does not run it)"]
    C --> T["Tests and fuzzing<br/>(run code with bad input)"]
    A["Running application"] --> D["DAST<br/>(attacks from outside)"]
    R --> F["Findings: fix, then add a test"]
    S --> F
    T --> F
    D --> F

Each technique sees a different slice of the problem, so mature teams combine them.

  • Manual code review is a person reading a change. It is the only technique that can judge intent: "should this user be allowed to see this record at all?"
  • SAST (static application security testing) tools analyze source code without running it. They are fast, run on every commit, and find patterns such as eval(), hard-coded passwords or string-built SQL. They produce false positives and cannot see problems that exist only at runtime.
  • DAST (dynamic application security testing) tools probe a running application from the outside, the way an attacker would: sending odd requests and watching responses. They find configuration and deployment issues SAST cannot see, but they need a running system and know nothing about your code, so coverage can be shallow.
  • Tests and fuzzing run your own code with hostile input and check that it behaves.

No single method is enough. A SAST tool will never notice that a "delete invoice" endpoint forgets to check ownership, while a human reviewer is poor at spotting a thousand outdated calls in a large codebase.

What to look for in a review

A good security review is not a hunt through every line. It follows the data. Start where untrusted input enters (request parameters, headers, uploaded files, messages from queues), follow it to where it is used, and ask what happens on the way. A short checklist keeps reviews consistent:

  1. Input: is every external value validated against an allow-list, with type, length and range limits? See Input Validation and Sanitization.
  2. Output and queries: is data encoded or parameterized before it reaches HTML, SQL, shell commands or file paths?
  3. Authentication: are passwords hashed with a slow algorithm, are tokens checked for signature and expiry?
  4. Authorization: does every endpoint check that this user may touch this object, not merely that they are logged in? See Authorization and Access Control Models.
  5. Secrets and logging: no keys in code, no passwords or tokens in logs. See Secrets, Logging and Error Handling.
  6. Errors: do failures reveal stack traces, SQL or paths, and do they fail closed (deny) rather than open?
  7. Dependencies: are new libraries needed, maintained and pinned? See Dependency and Supply Chain Security.
  8. Crypto: standard libraries only, no home-made schemes, no fixed IVs or keys.

Review the change, not the author. Phrase findings as a risk and a fix ("this value reaches execute() unescaped; use a parameter"), and block the merge only for issues that matter. Authentication, payments, file handling and anything that parses untrusted data deserve the closest look and a second reviewer.

Keep the checklist in the pull-request template. A reviewer who has to tick "I checked authorization on every new endpoint" actually checks.

Static analysis: a tiny SAST tool

Real SAST tools build a syntax tree and look for risky shapes. Python ships the tool you need to do the same: the ast module parses source into a tree you can walk. The rules below flag a few dangerous calls and a hard-coded secret. The code being scanned is only text here; it is parsed, never executed.

Python A mini static analyzer with ast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice what the tool did not flag: the parameterized query in safe(). That is the point of looking at the tree rather than grepping for the word execute. Even so, this scanner has the typical weaknesses of SAST. It misses a query built in one function and executed in another, and it would flag a harmless constant. Treat every finding as a lead to triage, and tune the rules so developers don't learn to ignore the output.

Dynamic testing and scanners

A DAST scanner (or a manual tester with an intercepting proxy) works on a deployed test environment. It crawls pages, sends payloads in every parameter, and watches for error messages, reflected input, missing headers and exposed admin paths. Use it against staging, never against production without permission, and never against systems you do not own. The lessons on HTTP Security Headers and API Security describe the kind of weaknesses it reports.

Two related terms are worth knowing. SCA (software composition analysis) checks your dependencies against known vulnerabilities. IAST instruments the running app during tests to combine both views. In a pipeline, the usual order is: SAST and SCA on every commit, DAST on each deployment to staging, and a human penetration test before major releases.

Fuzzing: let the computer be nasty

A fuzzer feeds a function huge numbers of random or mutated inputs and watches for crashes, hangs and exceptions. It finds the inputs a developer never thought of: empty strings, enormous numbers, odd Unicode, nested structures. The core idea fits in a few lines. Below, a small parser of "key=value;key=value" settings is fuzzed with a fixed random seed, so the run is repeatable.

Python A seeded fuzzer finds a crash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The author only thought about text that is not a number, which raises ValueError. The fuzzer also finds 90=0 (the key is just text), a value that parses fine and then divides by zero. In a web service, an unhandled exception like that is at best a 500 error and at worst a denial of service or an information leak. Real fuzzers (libFuzzer, AFL++, Atheris for Python) add coverage guidance: they keep the inputs that reach new code paths and mutate those, which is far more effective than pure randomness. Fuzzing is especially valuable for parsers, file formats and protocol handlers, the code that eats untrusted bytes.

Security unit tests

Every vulnerability you fix should leave a test behind. A security test states a rule the system must never break: "an attacker-supplied path never escapes the upload folder", "a user cannot read another user's invoice". Write tests for the bad cases (negative tests) as carefully as for the good ones, and include the boundaries: empty input, the longest allowed value, one character more.

Python Security tests with a tiny test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details are worth copying. The last test checks that a forbidden invoice and a nonexistent invoice produce the same error, so an attacker cannot learn which IDs exist. And the tests are named as rules, so a failing line tells a reader exactly which guarantee broke. In a real project you would run them with pytest or unittest on every push, and the build would fail when a rule is violated.

Making it routine

  • Run SAST, dependency scanning and secret scanning in continuous integration, and fail the build on high-severity findings.
  • Keep a list of past vulnerabilities and add a regression test for each one.
  • Fuzz parsers and anything that handles untrusted files on a schedule, saving the crashing inputs as test cases.
  • Do not test attacks against systems you do not own; use a local or staging copy.
  • Track findings to closure with an owner and a deadline, as covered in Vulnerability Management and Patching.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between SAST and DAST?

    SAST reads source code or compiled code statically, so it finds patterns early in development. DAST attacks the deployed application and sees runtime and configuration problems.
  2. 2. Which problem is a human reviewer best placed to find?

    Tools can match patterns, but whether a user should be allowed to see an object depends on business intent, which a reviewer must judge.
  3. 3. Why does coverage-guided fuzzing beat purely random input?

    By observing which branches an input reaches, the fuzzer builds on interesting inputs instead of starting from scratch, which exposes deeper bugs.
  4. 4. After fixing a path traversal bug, what should you also do?

    A test turns the fix into a lasting guarantee. Without it, a later refactor can silently reintroduce the same bug.
  5. 5. What should you do with a SAST finding that you believe is a false positive?

    Findings are leads. Recording why one is safe and suppressing only that case keeps the tool trusted and the signal useful.

Summary

  • Combine manual review, SAST, SCA, DAST, fuzzing and tests; each one sees problems the others miss.
  • Review by following untrusted data from entry point to use, with a short checklist covering input, output, authentication, authorization, secrets, errors, dependencies and crypto.
  • SAST reads code and is fast but noisy; DAST attacks a running system and needs a safe test environment.
  • Fuzzing throws large volumes of odd input at parsers and finds unhandled failures.
  • Every fixed vulnerability deserves a regression test, including negative cases and boundaries.

Next: Malware Types and How They Spread, where the course moves from the code you write to the threats that run on machines.