Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 53 ยท Defense, Detection and Response

Secure Coding and DevSecOps

Learn the secure software lifecycle, code review checklists, SAST, DAST and dependency scanning, secrets management and supply-chain risks with a runnable scanner.

Penetration tests find bugs after the software exists. It is far cheaper to stop them from being written, and to catch the rest while they are still one commit old. Secure development means building security into how code is designed, written, reviewed, tested and shipped. DevSecOps is the habit of automating those checks in the same pipeline that builds and deploys the software, so security is not a gate at the end.

This lesson covers the secure software lifecycle, review checklists, the main kinds of automated scanning, secrets management and supply-chain risk. Real scanners, pipelines and package registries cannot run in this tutorial, so their commands and configuration are read-only. The runnable part is a Node stand-in: a tiny scanner that looks for hard-coded secrets in sample code. It shows the principle behind real tools, which are much more thorough.

Security in every stage

Design Threat model before coding.
Code Safe defaults, reviewed changes.
Test Scanners run on every commit.
Release Signed, scanned, reproducible.

The earlier a bug is found, the cheaper it is to fix.

1 / 2

The secure development lifecycle

A secure SDLC adds a small number of security activities to each stage rather than a separate process:

  • Requirements. Write security requirements next to features: "all admin actions are logged", "passwords are stored with a slow hash". Decide what data is sensitive.
  • Design. Threat model new features. Ask what is trusted, where data crosses a boundary, and what happens if a component is compromised.
  • Implementation. Use frameworks' safe defaults, follow a team coding standard, and prefer well-reviewed libraries over home-made security code (especially cryptography).
  • Verification. Code review, automated scanning, unit tests for security rules, and occasional penetration testing.
  • Release and operations. Hardened configuration, monitoring (logging and SIEM), a patching process, and a way for researchers to report problems.

Three principles do most of the work: validate input and encode output, deny by default (allow-lists, least privilege), and fail safely (an error should not open a door).

Security code review

Code review is the cheapest control you have, but reviewers need to know what to look for. A short checklist the team agrees on works better than expecting everyone to remember everything:

  • Input. Is every external input (URL, header, body, file, environment) validated for type, length and range? Are database queries parameterized? (See SQL injection.)
  • Output. Is data encoded for the place it lands, such as HTML, SQL or a shell? (See XSS and CSRF.)
  • Authentication and access. Is there a server-side check for every sensitive action, tied to the object being accessed? (See authentication flaws.)
  • Secrets. Any key, token or password in the diff? Any secret in logs or error messages?
  • Errors. Do error pages leak stack traces, paths or SQL?
  • Dependencies. Does the change add a new package? Is it needed, maintained and from the right source?
  • Crypto. Standard algorithms through standard libraries, no custom schemes, no fixed IVs.
  • Tests. Is there a test for the new rule, including a case that must be rejected?

Reviews should target the change's risk: a new login endpoint deserves more scrutiny than a CSS tweak. Keep the tone about the code, not the person.

Automated scanning in the pipeline

Different tools see different things, and none sees everything.

SAST: static application security testing

SAST tools read source code without running it, looking for risky patterns: string-built SQL, use of dangerous functions, missing checks, hard-coded secrets. They run fast and point at an exact line, which is ideal in a pull request. They also produce false positives (flagging safe code) and miss problems that only exist at run time, such as misconfigured servers.

DAST: dynamic application security testing

DAST tools test a running application from outside, like a simple automated attacker: sending odd input, checking headers and cookies, probing for known weaknesses. They find configuration and runtime issues, but they cannot see inside the code, are slower, and must only be pointed at systems you own or are authorized to test (see Law, Scope and Rules of Engagement). A staging environment is the usual target.

SCA: software composition analysis

Most of a modern application is other people's code. SCA tools list your dependencies, including indirect ones, and compare their versions with databases of known vulnerabilities. They tell you which advisories apply and often propose an upgrade. Triage works as in Vulnerability Scanning and Triage: a vulnerable library that your code never calls is lower priority than one on a public code path.

Secret scanning

Secret scanners look for strings shaped like API keys, tokens and private keys, both in the working tree and in git history, because a secret deleted in a later commit is still in the repository's past. Run them as a pre-commit hook and again in the pipeline.

A typical pipeline step looks like the sketch below. It is read-only here, because the tool names and syntax vary by product:

YAML
# Read-only illustration of a CI pipeline (syntax varies by CI product)
jobs:
  security:
    steps:
      - checkout
      - run: run-secret-scanner --fail-on-finding
      - run: run-dependency-audit --severity-threshold high
      - run: run-static-analysis --fail-on high
      - run: build-and-test
      - run: deploy-to-staging
      - run: run-dynamic-scan --target https://staging.example.test

Failing the build on high findings and reporting lower ones as tickets avoids blocking developers for noise while still stopping the serious problems.

Secrets management

A secret is anything that grants access: passwords, API keys, tokens, private keys, database connection strings. The rules are simple, and breaking them is a leading cause of breaches:

  1. Never commit secrets to source control, not even in a private repository, and not "just for testing".
  2. Inject them at run time through environment variables, or better a secrets manager that stores, encrypts, audits and rotates them.
  3. Give each secret a narrow scope. A key that can only read one bucket is less dangerous than an account-wide key.
  4. Rotate regularly and immediately after any suspected exposure.
  5. Treat exposure as compromise. If a key reaches a public repository, assume it was copied within minutes. Revoke it first, then clean up the history.
PHP
// Read-only: the wrong and the right way to get a database password
$bad  = 'S3cretPassw0rd!';              // hard-coded in the repository
$good = getenv('DB_PASSWORD');          // supplied by the environment at run time

Supply-chain risks

Your software is built from a supply chain: dependencies, build tools, container base images, CI plugins and the registries that deliver them. Attackers target it because one compromise reaches many victims. Common patterns:

  • Typosquatting. A malicious package with a name one letter away from a popular one.
  • Dependency confusion. A public package with the same name as a private internal one, picked up because its version number is higher.
  • Hijacked maintainers. A trusted package receives a malicious update after an account takeover.
  • Compromised build systems. The code is clean but the build process inserts something.

Defenses include lock files with pinned versions and hashes, reviewing dependency updates, using an internal registry or proxy, keeping the dependency list small, building in a clean and isolated environment, signing releases, and producing a software bill of materials (SBOM) so you can quickly answer "do we use the affected library?" when a new advisory appears.

Stand-in: a secret scanner

This scanner checks sample source files for a few secret-looking patterns and for assignments to suspicious names with long string values. The "keys" below are obviously fake. Real scanners add hundreds of provider-specific patterns, entropy checks and verification (asking the provider whether a candidate key is live), which is why they produce fewer false alarms than this simple version.

Node.js Find hard-coded secrets

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 node:readline or process.stdin), it gets the next line from this box.

Notice that server.js passes, because it reads the password from the environment, and that a clean scan does not prove there are no secrets. Scanners only know the shapes they were taught.

Stand-in: checking a lock file for risky versions

A software composition check compares installed versions with an advisory list. This version-comparison sketch uses made-up package names and advisories.

Node.js Dependency advisory check

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 node:readline or process.stdin), it gets the next line from this box.

What is real? Comparing versions against a fixed-in version and sorting by severity is how SCA reports work. The packages and advisories are invented, and real tools resolve the whole dependency tree and handle many version formats.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tool type tests a running application from the outside?

    DAST attacks a running instance like an outside user. SAST reads source code, and SCA checks dependencies.
  2. 2. A developer commits an API key and deletes it in the next commit. What should happen?

    Git history keeps the secret. Anyone with access may have copied it, so revoke it first and then clean up.
  3. 3. What is dependency confusion?

    If the build prefers a higher-versioned public package over the private one, an attacker can slip in code by publishing a same-named package.
  4. 4. Why should a security review focus extra attention on a new login endpoint?

    Review effort should follow risk. Changes that touch authentication, access control or sensitive data deserve the most scrutiny.
  5. 5. Which is the best way to give an application a database password?

    Secrets should live outside the code, be scoped narrowly, and be rotatable.

Summary

  • Secure development adds small, automated security activities to every stage of the lifecycle.
  • A short, shared review checklist covering input, output, access, secrets, errors, dependencies and crypto catches many bugs.
  • SAST reads code, DAST attacks a running app, SCA checks dependencies, and secret scanning finds leaked keys. Use them together.
  • Never commit secrets. Inject them at run time, scope them narrowly, rotate them, and treat any exposure as a compromise.
  • Reduce supply-chain risk with lock files, reviewed updates, isolated builds, signing and an SBOM.

Next: Writing a Penetration Test Report.