Sample File: 35_secret_management.py

Companion verification log or original code sample for the linked tutorial, preserved in full with local user paths redacted; execution scope follows the recorded run.

"""Credential lifecycle demo: creates only dummy keys and a temporary Git repository inside a temporary directory.
A one-way hash verifier can validate incoming random tokens, but cannot replace an encrypted secret vault when outbound calls need the raw key.
"""
import hashlib, hmac, os, pathlib, secrets, shutil, subprocess, sys, tempfile

FAKE = "sk-FAKE-not-a-real-key-for-demo-only"
print("== (1) Environment variable injection: child process receives an explicit environment; never print full secrets")
env = {k:v for k,v in os.environ.items() if k.upper() in {"SYSTEMROOT", "WINDIR", "PATH", "TEMP", "TMP"}}
env["LLM_API_KEY"] = FAKE
out = subprocess.check_output([sys.executable, "-X", "utf8", "-c", "import os; print('Received dummy key:', bool(os.environ.get('LLM_API_KEY')))"] , env=env, text=True, encoding="utf-8")
print("  ", out.strip())

with tempfile.TemporaryDirectory(prefix="k6-secret-demo-") as td:
    task = pathlib.Path(td)
    print("== (2) POSIX file permissions (Windows uses NTFS ACLs instead of POSIX mode bits)")
    p = task / "key"; p.write_text(FAKE, encoding="utf-8")
    if os.name == "posix":
        for mode in (0o644, 0o600):
            p.chmod(mode); print("   Mode:", oct(p.stat().st_mode & 0o777))
        print("   Mode bit demo does not test other users' effective access; ACLs/root can override mode bits")
    else:
        print("   Skipping Unix 600/644 mode enforcement on Windows; inspect NTFS ACLs instead")

    print("== (3) Removing a dummy key from the working tree still leaves it in Git history")
    if shutil.which("git"):
        repo=task/"repo"; repo.mkdir()
        # Disable global/system Git config and hooks; operate strictly inside this temporary repository.
        git_env=env.copy(); git_env.pop("LLM_API_KEY", None)
        git_env["GIT_CONFIG_NOSYSTEM"]="1"; git_env["GIT_CONFIG_GLOBAL"]=os.devnull
        def git(*args):
            return subprocess.check_output(["git", "-c", "core.hooksPath="+os.devnull, "-c", "commit.gpgsign=false", *args], cwd=repo, env=git_env, text=True, encoding="utf-8", stderr=subprocess.STDOUT)
        git("init", "-q"); git("config", "user.email", "demo@example.invalid"); git("config", "user.name", "K6 demo")
        app=repo/"app.py"; app.write_text(f"KEY = {FAKE!r}\n", encoding="utf-8")
        git("add", "app.py"); git("commit", "-q", "-m", "demo fake secret")
        app.write_text("import os\nKEY = os.environ['LLM_API_KEY']\n", encoding="utf-8")
        git("add", "app.py"); git("commit", "-q", "-m", "remove fake secret")
        print("   Current file contains dummy key:", FAKE in app.read_text(encoding="utf-8"))
        print("   Still discoverable in Git history:", FAKE in git("log", "-p", "--all", "-S", FAKE))
    else:
        print("   Git not installed: skipping history branch")

print("== (4) Hash verifier for random tokens (not a retrievable secret vault)")
issued=secrets.token_urlsafe(32)
digest=lambda value: hashlib.sha256(value.encode()).hexdigest()
db={"svc-demo":digest(issued)}
def check(name, candidate):
    saved=db.get(name)
    return saved is not None and hmac.compare_digest(digest(candidate), saved)
print("   Valid / invalid / unknown principal:", check("svc-demo",issued),check("svc-demo","wrong"),check("unknown",issued))
print("   Outbound calls to third-party APIs require retrieving the raw key from KMS/encrypted storage; not implemented here")

print("== (5) Dual-key rotation window: tested with an explicit clock without sleeping")
keys={"current":secrets.token_urlsafe(32),"previous":issued,"previous_until":100}
def accept(candidate, now):
    if hmac.compare_digest(candidate,keys["current"]): return "current"
    if now < keys["previous_until"] and hmac.compare_digest(candidate,keys["previous"]): return "previous-grace"
    return "reject"
print("   New key:",accept(keys["current"],99),"Old key within grace window:",accept(issued,99),"At expiration cutoff:",accept(issued,100))
print("   If an old key was compromised, revoke it immediately rather than keeping a grace window")
Back to Tutorials Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram