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)
| Phase | Security activity |
|---|---|
| Requirements | Define security and privacy requirements; identify regulations |
| Design | Threat modelling, secure design patterns, data-flow diagrams |
| Implementation | Secure coding standards, peer review, secret scanning, IDE linters |
| Testing | Static analysis (SAST), dependency scanning (SCA), dynamic testing (DAST), fuzzing |
| Release | Signed builds, hardened configuration, infrastructure-as-code scanning |
| Operations | Monitoring, patching, incident response, vulnerability disclosure policy |
| Retirement | Secure 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
- Validate input on the server. Check type, length, range and format, preferring allow-lists to block-lists.
- Encode output for its context (HTML, JavaScript, URL, SQL) to stop injection and XSS; see XSS and CSRF Explained.
- Use parameterised queries for all database access; see SQL Injection Explained and Prevented.
- Authenticate and authorise every request, deny by default.
- Never invent your own cryptography. Use vetted libraries and current algorithms; see Cryptography Fundamentals.
- Handle secrets properly. No passwords or keys in source code; use environment variables or a secrets manager and rotate them.
- Fail safely. Errors should deny access, not grant it, and should reveal no internals to users.
- Log security events, but never log passwords, tokens or full card numbers.
- Keep dependencies updated and remove unused ones.
- 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:
| Letter | Threat | Violates | Typical mitigation |
|---|---|---|---|
| S | Spoofing | Authentication | Strong authentication, signed tokens |
| T | Tampering | Integrity | Signatures, validation, access control |
| R | Repudiation | Non-repudiation | Audit logs, signed transactions |
| I | Information disclosure | Confidentiality | Encryption, access control, minimal data |
| D | Denial of service | Availability | Rate limits, resource quotas, redundancy |
| E | Elevation of privilege | Authorisation | Least privilege, input validation, sandboxing |
The DevSecOps Pipeline
A typical automated pipeline runs checks on every code change:
| Stage | Check | Example open-source tools |
|---|---|---|
| Pre-commit | Secret scanning, formatting, quick linters | Gitleaks, pre-commit hooks |
| Build | SAST (reads source code for patterns of flaws) | Semgrep, CodeQL, Bandit (Python), SpotBugs |
| Build | SCA (checks third-party libraries for known CVEs) | OWASP Dependency-Check, Trivy, pip-audit, npm audit |
| Build | Container and IaC scanning | Trivy, Checkov, tfsec |
| Test | DAST (probes a running test app) | OWASP ZAP |
| Release | Sign artefacts, produce a software bill of materials (SBOM) | Sigstore Cosign, Syft |
| Deploy and run | Runtime monitoring, configuration checks, alerting | Falco, 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
- Create a small Python project in your lab VM with a
requirements.txtlisting an old library version (for example, an old release of a web framework you find in a vulnerability database). - Install and run
pip-audit. Record each vulnerable package, its CVE and the fixed version. See Vulnerability Management for prioritisation. - Install Bandit (
pip install bandit) and runbandit -r .on your code. Put in one deliberate mistake, such as theshell=Trueexample above, and confirm Bandit flags it. - Fix the issues and rerun until clean.
Practice Lab 2: Stop Secrets Reaching the Repository
- Initialise a Git repository and install Gitleaks.
- 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. - Set up a pre-commit hook that runs Gitleaks so commits containing secrets are blocked.
- 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
- Draw a data-flow diagram: browser, web server, database, email service.
- For each arrow and component, apply STRIDE and list at least one threat and one mitigation.
- 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
- Explain “shift left” to a project manager in three sentences.
- Apply STRIDE to a password-reset feature and list six threats.
- Describe the difference between SAST, SCA and DAST and what each can miss.
- Write a short secure coding standard (ten rules) for a team using your favourite language.
- 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.
- 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.