読み物Application Security · Privacy

Level: Pro

Production Security: Testing, Monitoring, and Incident Response

Keep security working after launch: security tests in CI, safe logging, alerts that matter, a vulnerability disclosure policy, and an incident response plan you have practiced.

Edeeson Opina9 min read

A Pro lesson card: lesson 15 of the Security & Privacy series, Production Security: Testing, Monitoring, and Incident Response, with the Miso fox cheering.

What you’ll learn

  • Combine unit security tests, SAST, dependency scans, and DAST in CI
  • Log security events without logging secrets or personal data
  • Write alerts that point to action
  • Publish a vulnerability disclosure policy and security.txt
  • Run an incident from detection to lessons learned
On this page
  1. Before you start
  2. Layers of security testing
  3. Security regression tests
  4. Putting it in the pipeline
  5. Logging security events
  6. What never to log
  7. Alerts that lead to action
  8. Vulnerability disclosure
  9. Incident response
  10. Legal and communication duties
  11. A runbook example: leaked API key
  12. Practice
  13. Common mistakes and troubleshooting
  14. Practical exercise: a production security baseline
  15. Key takeaways
  16. References
  17. What's next

An application is secure on launch day only for as long as nothing changes, and something always changes: new code, new dependencies, new attack techniques, new people with access. Production security is the ongoing practice of catching regressions before they ship, noticing attacks while they happen, and responding well when something goes wrong. This final lesson covers security testing in CI, safe and useful logging, alerts that lead to action, a vulnerability disclosure policy, and an incident response plan you've actually practiced.

Before you start

This lesson builds on the whole series, especially Software Supply Chain Security for CI pipelines and Privacy Engineering: Encryption, Retention, Deletion, and Data Protection for breach duties. Examples use TypeScript, Vitest, GitHub Actions, and standard command-line tools. Run scanners only against environments you own or are authorized to test.

Layers of security testing

No single kind of test finds everything. Combine several, each catching what the others miss:

  • Security unit and integration tests encode your own rules: user A can't read user B's invoice, the SSRF guard refuses private addresses, the CSP header is present. They're the most precise tests you have, because they know your business logic.
  • Static application security testing (SAST) analyzes source code for dangerous patterns, such as string-built SQL, innerHTML with variables, or disabled certificate checks. Tools include Semgrep and GitHub's CodeQL.
  • Software composition analysis scans dependencies for known vulnerabilities (lesson 13), plus secret scanning for committed credentials.
  • Dynamic application security testing (DAST) probes a running application from outside, as an attacker would, finding missing headers, exposed files, and some injection points. OWASP ZAP is a widely used free scanner.
  • Manual testing and review, including periodic penetration tests by people who think creatively about your specific application, find logic flaws that automated tools can't.

Security regression tests

Every security bug you fix should leave a test behind, so the same bug can't return. Group them so they're easy to find and run:

security.test.tsTypeScript
import request from "supertest";
import { describe, expect, it } from "vitest";
import { app } from "../app";
import { signInAs } from "./helpers";

describe("security regressions", () => {
  it("sends the required security headers, including on errors", async () => {
    for (const path of ["/", "/does-not-exist"]) {
      const res = await request(app).get(path);
      expect(res.headers["content-security-policy"]).toMatch(/object-src 'none'/);
      expect(res.headers["x-content-type-options"]).toBe("nosniff");
    }
  });

  it("refuses cross-organization access (fixed in SEC-41)", async () => {
    const alice = await signInAs("alice@org-a.test");
    const res = await alice.get("/api/invoices/org-b-invoice-1");
    expect(res.status).toBe(404);
  });

  it("never returns password hashes from the users API", async () => {
    const alice = await signInAs("alice@org-a.test");
    const res = await alice.get("/api/users/me");
    expect(JSON.stringify(res.body)).not.toMatch(/passwordHash|\$argon2/);
  });
});

Putting it in the pipeline

Run fast checks on every pull request and slower ones on a schedule or before releases:

security.ymlYAML
name: security
on:
  pull_request:
  schedule:
    - cron: "0 3 * * 1" # weekly, for new advisories against unchanged code

permissions:
  contents: read

jobs:
  checks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - run: npm ci --ignore-scripts
      - run: npm test -- tests/security
      - run: npm audit --omit=dev --audit-level=high
      - run: npx --yes semgrep@latest scan --config p/owasp-top-ten --error

For DAST, run a baseline scan against a staging environment you control. ZAP's baseline scan is passive (it spiders and inspects responses without attacking), which makes it a safe first step:

Shell
docker run --rm -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.your-app.test/

Tune what fails the build. A check that fails on every low-severity finding gets disabled within a month. Fail on high-severity, high-confidence findings, and track the rest.

Logging security events

Logs are how you detect attacks, investigate incidents, and prove what happened. OWASP's A09, Security Logging and Alerting Failures, exists because many breaches go undetected for months. Log events that matter for security:

  • sign-in successes and failures, MFA changes, password resets, and session revocations;
  • authorization failures (403 and suspicious 404 patterns on object IDs);
  • input validation failures on sensitive endpoints;
  • administrative actions: role changes, data exports, configuration changes;
  • security-control events: rate limits triggered, CSP violation reports, webhook signature failures.

Make each event structured, with a stable name, a timestamp, an actor, the target, and the outcome:

security-log.tsTypeScript
type SecurityEvent = {
  event: "auth.sign_in" | "auth.sign_in_failed" | "authz.denied" | "admin.role_changed" | "ratelimit.hit";
  outcome: "success" | "failure";
  actorId?: string;
  target?: string;
  ip?: string;
  requestId: string;
};

export function securityLog(entry: SecurityEvent) {
  // One JSON line per event: easy to search, alert on, and retain separately.
  process.stdout.write(`${JSON.stringify({ ts: new Date().toISOString(), type: "security", ...entry })}\n`);
}

What never to log

Logs are copied widely, kept for a long time, and read by many people and tools. Never log passwords, session IDs, tokens, API keys, full card numbers, or the contents of Authorization and Cookie headers. Minimize personal data: an account ID usually serves better than an email address. Give logs a retention period, protect them from modification (ship them to a separate system the application can't edit), and limit who can read them. Lesson 4's redaction helper is a useful safety net.

Alerts that lead to action

A log nobody reads is only useful after the fact. Alerts turn logs into detection, but too many alerts train people to ignore them. Good alerts are:

  • Specific: "40 failed sign-ins for one account in 5 minutes" rather than "unusual activity."
  • Actionable: each alert links to a short runbook saying what to check and what to do.
  • Rare: tuned so that most alerts are worth someone's attention.

Useful starting alerts include: a spike in failed sign-ins across many accounts (credential stuffing), many 403 or 404 responses for sequential object IDs from one user (enumeration), an admin role granted outside the normal process, a sudden large data export, a secret detected in a commit, and certificates nearing expiry. Review alerts monthly: remove those nobody acts on and add ones that would have caught recent incidents earlier.

Vulnerability disclosure

Outside researchers sometimes find vulnerabilities in your application. Make it easy for them to tell you, and safe for them to do so in good faith. Publish a vulnerability disclosure policy that says how to report, what's in scope, what testing is acceptable, how quickly you'll respond, and that you won't pursue good-faith reporters who follow it. Then point to it from a security.txt file (RFC 9116), served at /.well-known/security.txt:

HTTP
Contact: mailto:security@your-company.test
Expires: 2027-11-01T00:00:00.000Z
Policy: https://your-company.test/security-policy
Preferred-Languages: en

Contact and Expires are required. Make sure someone monitors that inbox, and renew the file before it expires.

Incident response

An incident is any event that compromises, or threatens to compromise, the confidentiality, integrity, or availability of your systems or data. NIST SP 800-61 Revision 3 (2025) aligns incident response with the NIST Cybersecurity Framework 2.0; the classic lifecycle it builds on remains a practical way to run an incident:

  1. Prepare: an up-to-date contact list, clear roles (an incident lead, a communications owner, technical responders), access to logs and systems, runbooks for likely incidents, and a way to communicate if your usual tools are affected.
  2. Detect and analyze: confirm what happened, its scope, and its severity. Start a timeline immediately, recording what you observe and do, with times.
  3. Contain: stop the damage from spreading. Revoke leaked credentials, block an attacking IP range, disable a vulnerable feature, or isolate a compromised server. Preserve evidence (logs, disk snapshots) before destroying anything.
  4. Eradicate and recover: remove the cause (patch the vulnerability, remove malicious code, rotate every secret the attacker could have seen), restore from known-good artifacts, and monitor closely for recurrence.
  5. Learn: hold a blameless review. Write down what happened, what went well, what didn't, and the changes that would prevent or shorten the next incident. Then make those changes.

When personal data is involved, the clock for notification may start when you become aware of the breach. As covered in lesson 14, the GDPR generally requires notifying the regulator within 72 hours, and other laws set their own deadlines. Involve legal counsel early, and prepare notification templates in advance. Communicate with affected users honestly and specifically: what happened, what data was involved, what you've done, and what they should do.

A runbook example: leaked API key

Shell
# 1. Contain: revoke the key in the provider's dashboard or API, then confirm it is rejected
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $OLD_KEY" https://api.provider.test/v1/ping   # expect 401

# 2. Recover: issue a new key with minimal scope, store it in the secrets manager, and redeploy

# 3. Analyze: review the provider's access logs for the old key from the time it may have leaked

# 4. Clean up: remove the key from Git history only after it is revoked, and add secret scanning if it was missing

Practice

A plan you've never rehearsed tends to fall apart under stress. Run a tabletop exercise once or twice a year: gather the team, walk through a realistic scenario ("a researcher reports that invoice PDFs are downloadable without signing in"), and talk through each step. You'll find missing access, unclear roles, and outdated contacts while the stakes are low.

Common mistakes and troubleshooting

  • Relying on one kind of testing. Combine your own tests, SAST, dependency and secret scans, DAST, and manual review.
  • Fixing a vulnerability without a regression test. Leave a test behind every time.
  • Logging secrets or whole request bodies. Log chosen fields, and redact the rest.
  • Alerts nobody owns. Every alert needs an owner and a runbook.
  • No way for researchers to reach you. Publish a policy and security.txt, and monitor the inbox.
  • Destroying evidence while containing. Snapshot and export logs before rebuilding.
  • Skipping the review. The learning step is what makes the next incident shorter.

If a scanner floods you with findings, start by confirming a few by hand. Mark false positives in the tool's configuration with a reason, so the signal improves over time instead of being ignored.

Practical exercise: a production security baseline

For an application you run, in a staging environment you control:

  1. Add a security regression test file with at least the header, cross-account, and sensitive-field tests above.
  2. Add the security workflow to CI, and tune it until it passes on current code without hiding real issues.
  3. Implement structured security events for sign-in, authorization failures, and admin actions, and confirm no secrets appear in them.
  4. Define three alerts with owners and one-paragraph runbooks.
  5. Publish a disclosure policy and security.txt.
  6. Run a 45-minute tabletop exercise on a leaked-credential scenario, and record three improvements.

Key takeaways

  • Layer security testing: your own regression tests, SAST, dependency and secret scanning, DAST, and manual review.
  • Log security events in a structured way, never log secrets, and minimize personal data in logs.
  • Alerts must be specific, actionable, owned, and rare.
  • Publish a vulnerability disclosure policy and security.txt so researchers can reach you.
  • Prepare, detect, contain, eradicate, recover, and learn; practice the plan before you need it.

References

What's next

You've finished the Security & Privacy series, from the vocabulary of security and privacy through secure architecture and production operations. The best next step is to apply it: pick one application, revisit the audit from lesson 5 with everything you've learned since, and start again at What Is Web Security and Privacy? A Developer's Guide whenever you need a refresher on the foundations.

See every lesson in Security & Privacy: Building Secure Applications