Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 12 / Stage 3

Security and compliance

Goal: Earn the trust of the customer's security team: least privilege, personal data handled deliberately, secrets kept out of logs, and compliance requirements turned into architecture. Time: ~3 hours · Needs: Python 3.14+, the course venv

What you will learn

  • Least privilege for people and services
  • Personal data: minimising, redacting, retention
  • Secrets in logs: filters and reviews
  • Data residency and compliance requirements as architecture
  • Security reviews and questionnaires
  • Audit logging: who did what, when
  • Enterprise single sign-on: SAML and OpenID Connect at concept level

Topics in this part

Practice

Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.

Exercise 1: An access list as data

Model an access list as a list of dicts (who, system, level, reason, expires). Write review(access_list, today) that returns expired entries and any entry with level admin. Print the findings for a sample list.

Show the solution to Exercise 1
# Exercise 1: review the access list mechanically
from datetime import date

ACCESS = [
    {"who": "fde@vendor", "system": "acme-db", "level": "read", "reason": "pipeline dev", "expires": "2025-06-30"},
    {"who": "sync-service", "system": "acme-api", "level": "read", "reason": "nightly sync", "expires": "2026-01-01"},
    {"who": "fde@vendor", "system": "acme-cloud", "level": "admin", "reason": "setup week", "expires": "2025-03-15"},
]

def review(access_list, today):
    expired = [a for a in access_list if date.fromisoformat(a["expires"]) < today]
    admins = [a for a in access_list if a["level"] == "admin"]
    return expired, admins

expired, admins = review(ACCESS, date(2025, 4, 9))
for a in expired:
    print("EXPIRED:", a["who"], "on", a["system"], "since", a["expires"])
for a in admins:
    print("ADMIN  :", a["who"], "on", a["system"], "-", a["reason"], "(narrow this)")

Exercise 2: Test the redactor

Take the lesson's redact (card before phone) and write pytest tests run from the script: an email, a card with spaces, a phone with country code, and a clean sentence that must pass through unchanged. All must pass.

Show the solution to Exercise 2
# Exercise 2: redaction is a parser; test it like one
import pathlib, re, subprocess, sys, tempfile, textwrap

code = textwrap.dedent('''
    import re

    PATTERNS = {
        "EMAIL": r"[\\w.+-]+@[\\w-]+\\.[\\w.]+",
        "CARD":  r"\\b\\d(?:[ -]?\\d){12,15}\\b",
        "PHONE": r"\\+?\\d[\\d -]{8,}\\d",
    }

    def redact(text):
        for label, pattern in PATTERNS.items():
            text = re.sub(pattern, f"[{label}]", text)
        return text

    def test_email():
        assert redact("mail [email protected]") == "mail [EMAIL]"

    def test_card_with_spaces():
        assert redact("card 4111 1111 1111 1111 charged") == "card [CARD] charged"

    def test_phone_with_country_code():
        assert redact("call +91 98765 43210 now") == "call [PHONE] now"

    def test_clean_text_untouched():
        s = "shipment S-2001 delivered on 2025-03-01"
        assert redact(s) == s
''')
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "test_redact.py").write_text(code)
r = subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(folder)],
                   capture_output=True, text=True)
print(re.sub(r" in \d+\.\d+s", "", r.stdout.strip().splitlines()[-1]))

Exercise 3: One more secret shape

Extend SecretFilter to also mask password=... and AWS-style keys (AKIA followed by 16 uppercase alphanumerics). Log three lines (token, password, AKIA key) and show all masked.

Show the solution to Exercise 3
# Exercise 3: more secret shapes in the filter
import logging, re, sys

class SecretFilter(logging.Filter):
    PATTERNS = [
        re.compile(r"(Bearer\s+|token=|api_key=|password=)[^\s&]+", re.IGNORECASE),
        re.compile(r"\bAKIA[A-Z0-9]{16}\b"),
    ]
    def filter(self, record):
        msg = record.getMessage()
        msg = self.PATTERNS[0].sub(r"\1***", msg)
        msg = self.PATTERNS[1].sub("AKIA***", msg)
        record.msg, record.args = msg, None
        return True

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(message)s"))
handler.addFilter(SecretFilter())
log = logging.getLogger("sec"); log.addHandler(handler); log.setLevel(logging.INFO)

log.info("GET /v1/shipments?token=abc123")
log.info("db connect password=hunter2 host=db1")
log.info("aws key AKIAABCDEFGHIJKLMNOP in env")

Exercise 4: Audit a write path

Add an append-only audit log (a list of dicts) to a tiny update_status(actor, shipment_id, new_status) function. Perform three updates by two actors and answer "who changed S-2003?" with a filter over the log.


Show the solution to Exercise 4
# Exercise 4: an append-only audit trail answers "who changed S-2003?"
from datetime import datetime, timezone

SHIPMENTS = {"S-2001": "in_transit", "S-2003": "in_transit"}
AUDIT = []

def update_status(actor, shipment_id, new_status):
    old = SHIPMENTS[shipment_id]
    SHIPMENTS[shipment_id] = new_status
    AUDIT.append({"when": datetime.now(timezone.utc).isoformat(timespec="seconds"),
                  "actor": actor, "action": "shipment.status.update",
                  "object": shipment_id, "from": old, "to": new_status})

update_status("ravi@acme", "S-2003", "delivered")
update_status("meena@acme", "S-2001", "delayed")
update_status("ravi@acme", "S-2001", "delivered")

who = [(e["actor"], e["from"], e["to"]) for e in AUDIT if e["object"] == "S-2003"]
print("S-2003 changes:", who)
print("audit entries:", len(AUDIT), "(append-only: no update or delete path exists)")

Mini-project: Security pass

Take the Part 9 Shipments API and give it the security pass: PII redaction + secret masking on its logs, a least-privilege access list printed at startup, and an audit record for every PATCH. Demonstrate each with TestClient calls.

A solution is in solutions/mini_security_pass.py.

Stretch: answer a sample security questionnaire for the service (auth? encryption? logging? data flows?), with evidence for each answer.

Common mistakes

Mistake Why it hurts Fix
Asking for admin "to be safe" You carry the whole blast radius Narrowest access; written access list
Redaction patterns in careless order Card numbers labelled as phones Order from strict to loose; test on real samples
Scrubbing secrets only at call sites The next log line leaks Filter on the handler + log reviews
Treating residency as a deploy detail Re-architecture in week five Hard requirement, in the decision log, week one
Overselling in questionnaires One audit finding poisons everything Accurate answers with evidence
Editable or partial audit trails Useless in forensics, fails compliance Append-only, all writes, attributable

Quick recap

  • Grant least privilege to people and services alike, and document who has what.
  • Handle personal data by collecting the minimum, redacting with tested rules in the right order, and retaining it deliberately.
  • Secret filters live on the handler and rewrite the formatted message.
  • Compliance rules are architecture: residency decides where things run.
  • Answer security reviews with evidence; close findings fast.
  • An audit log records who did what and when, and it stays append-only and attributable.
  • For SSO, use SAML or OIDC against the customer's identity provider with a maintained library, and plan it early.

Checklist

  • I wrote an access list for my Stage 3 service.
  • I ran the redaction example and can explain the pattern-order bug.
  • My secret filter catches tokens in URLs and in %s arguments.
  • I can turn "data stays in-region" into three architectural consequences.
  • I logged one write action in audit form: actor, action, object, when.

Read more: Python logging filters · OpenID Connect

Search the guide