Secure Coding and DevSecOps: SAST, DAST and Secrets Management

Fixing security flaws after release is slow and expensive. Secure coding means writing software so that whole classes of flaws never appear; DevSecOps means building security checks into the same automated pipeline that builds and ships the software. This lesson gives you a practical set of coding rules, shows how to wire security tests into a pipeline and includes a lab where you set up automated checks on a sample project.

The Secure Software Development Life Cycle (SSDLC)

PhaseSecurity activity
RequirementsDefine security and privacy requirements; identify regulations
DesignThreat modelling, secure design patterns, data-flow diagrams
ImplementationSecure coding standards, peer review, secret scanning, IDE linters
TestingStatic analysis (SAST), dependency scanning (SCA), dynamic testing (DAST), fuzzing
ReleaseSigned builds, hardened configuration, infrastructure-as-code scanning
OperationsMonitoring, patching, incident response, vulnerability disclosure policy
RetirementSecure data disposal, decommissioning of endpoints and keys

The principle is “shift left”: find problems earlier, when they are cheapest to fix.

Ten Secure Coding Rules

  1. Validate input on the server. Check type, length, range and format, preferring allow-lists to block-lists.
  2. Encode output for its context (HTML, JavaScript, URL, SQL) to stop injection and XSS; see XSS and CSRF Explained.
  3. Use parameterised queries for all database access; see SQL Injection Explained and Prevented.
  4. Authenticate and authorise every request, deny by default.
  5. Never invent your own cryptography. Use vetted libraries and current algorithms; see Cryptography Fundamentals.
  6. Handle secrets properly. No passwords or keys in source code; use environment variables or a secrets manager and rotate them.
  7. Fail safely. Errors should deny access, not grant it, and should reveal no internals to users.
  8. Log security events, but never log passwords, tokens or full card numbers.
  9. Keep dependencies updated and remove unused ones.
  10. Apply least privilege to code, services, database accounts and cloud roles.

Before and after: handling a secret

# BAD: secret in source code (it will end up in version control)
DB_PASSWORD = "SuperSecret123"

# BETTER: read from the environment, supplied by a secrets manager at deploy time
import os
DB_PASSWORD = os.environ["DB_PASSWORD"]      # fails loudly if missing

Before and after: running a system command

# BAD: shell=True with user input allows command injection
import subprocess
subprocess.run("ping -c 1 " + host, shell=True)

# BETTER: pass arguments as a list, validate input, avoid the shell
import ipaddress
ipaddress.ip_address(host)                       # raises an error if not a valid IP
subprocess.run(["ping", "-c", "1", host], check=True, timeout=5)

Threat Modelling in Fifteen Minutes

Before writing code, sketch the system and ask four questions (from the Threat Modeling Manifesto approach): What are we building? What can go wrong? What will we do about it? Did we do a good job? A popular memory aid for “what can go wrong” is STRIDE:

LetterThreatViolatesTypical mitigation
SSpoofingAuthenticationStrong authentication, signed tokens
TTamperingIntegritySignatures, validation, access control
RRepudiationNon-repudiationAudit logs, signed transactions
IInformation disclosureConfidentialityEncryption, access control, minimal data
DDenial of serviceAvailabilityRate limits, resource quotas, redundancy
EElevation of privilegeAuthorisationLeast privilege, input validation, sandboxing

The DevSecOps Pipeline

A typical automated pipeline runs checks on every code change:

StageCheckExample open-source tools
Pre-commitSecret scanning, formatting, quick lintersGitleaks, pre-commit hooks
BuildSAST (reads source code for patterns of flaws)Semgrep, CodeQL, Bandit (Python), SpotBugs
BuildSCA (checks third-party libraries for known CVEs)OWASP Dependency-Check, Trivy, pip-audit, npm audit
BuildContainer and IaC scanningTrivy, Checkov, tfsec
TestDAST (probes a running test app)OWASP ZAP
ReleaseSign artefacts, produce a software bill of materials (SBOM)Sigstore Cosign, Syft
Deploy and runRuntime monitoring, configuration checks, alertingFalco, cloud-native tools

Design the pipeline to block on high-severity findings and report on lower ones, otherwise teams drown in noise and start ignoring the tools.

A simple pipeline definition (GitHub Actions style)

name: security-checks
on: [push, pull_request]
jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Secret scan
        run: |
          docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest detect --source=/repo
      - name: Static analysis
        run: |
          pip install semgrep
          semgrep --config=auto --error .
      - name: Dependency audit
        run: |
          pip install pip-audit
          pip-audit -r requirements.txt

The exact action versions and image names change over time, so check each tool’s documentation before copying this into a real project.

Practice Lab 1: Scan a Sample Project

  1. Create a small Python project in your lab VM with a requirements.txt listing an old library version (for example, an old release of a web framework you find in a vulnerability database).
  2. Install and run pip-audit. Record each vulnerable package, its CVE and the fixed version. See Vulnerability Management for prioritisation.
  3. Install Bandit (pip install bandit) and run bandit -r . on your code. Put in one deliberate mistake, such as the shell=True example above, and confirm Bandit flags it.
  4. Fix the issues and rerun until clean.

Practice Lab 2: Stop Secrets Reaching the Repository

  1. Initialise a Git repository and install Gitleaks.
  2. Create a file containing a fake key such as API_KEY = "EXAMPLEKEY-0000-NOT-REAL" and commit it. Run Gitleaks and see if the pattern is detected.
  3. Set up a pre-commit hook that runs Gitleaks so commits containing secrets are blocked.
  4. Write down what you would do if a real key were ever committed: rotate it immediately, because removing it from history does not undo exposure.

Practice Lab 3: Threat Model a Login Page

  1. Draw a data-flow diagram: browser, web server, database, email service.
  2. For each arrow and component, apply STRIDE and list at least one threat and one mitigation.
  3. Convert the top three threats into test cases and write them as automated tests.

Culture: Make the Secure Way the Easy Way

  • Provide secure libraries, templates and example code (“paved roads”).
  • Train developers on real examples from your own codebase.
  • Appoint security champions inside each team.
  • Track metrics: time to fix, number of high findings over time, percentage of repositories with scanning enabled.
  • Publish a vulnerability disclosure policy so that external researchers know how to report issues responsibly.
  • Treat security reviews as a help, not a gate imposed from outside.

Common Mistakes

  • Adding scanners but never fixing what they find.
  • Failing every build on low-risk noise, which encourages teams to disable checks.
  • Committing credentials or leaving them in container images.
  • Pulling dependencies without version pinning or integrity checks.
  • Doing a security review only at the end of a project.

Practice Exercises

  1. Explain “shift left” to a project manager in three sentences.
  2. Apply STRIDE to a password-reset feature and list six threats.
  3. Describe the difference between SAST, SCA and DAST and what each can miss.
  4. Write a short secure coding standard (ten rules) for a team using your favourite language.
  5. Design a pipeline policy: which findings block a release and which only create tickets?

Mentor tip: Tools find patterns; people find intent. Pair automated scanning with short peer reviews focused on authentication, authorisation, input handling and secrets. That combination catches most of what matters.

Educational use only: run scanners only on code and systems you own or are authorised to assess.

Key takeaways
  • Build security in early: requirements, design, code, test, release and operate.
  • Follow core rules: validate input, encode output, parameterise queries, protect secrets and apply least privilege.
  • Threat model with STRIDE before you code.
  • Automate SAST, SCA, secret scanning, container scanning and DAST in the pipeline.
  • Tune the pipeline so teams act on findings instead of ignoring noise.

Related Lessons