Secret Management (Generation, Storage, Injection & Rotation)

Secret management governs the full lifecycle of credentials from generation, provisioning, storage, and runtime use to rotation, revocation, and destruction; outbound calls to third-party services require retrieving the original secret from protected storage, whereas verifying inbound high-entropy tokens only requires storing a cryptographic verification digest.

Second-Draft Verification Note (2026-10-15): Concepts, applicability boundaries, and example interpretations have been revised against the official documentation and primary sources listed at the end. Debian/tool versions and outputs from the first draft are retained as historical source records and do not represent execution proof on Windows/Python 3.12.14 in this batch; see the attached verification logs for current execution scope. All sample products, accounts, datasets, and credentials are fictional.

One-Line Definition

Secret management governs the full lifecycle of credentials from generation, provisioning, storage, and runtime use to rotation, revocation, and destruction; outbound calls to third-party services require retrieving the original secret from protected storage, whereas verifying inbound high-entropy tokens only requires storing a cryptographic verification digest.

Scope Boundaries & Evaluation Criteria

A database that stores only one-way hashes cannot recover a third-party API key for outbound requests, so it should not be called a retrievable secret vault. High-entropy random tokens can be verified using a cryptographic hash paired with constant-time comparison, whereas low-entropy human passwords require dedicated password-hashing KDFs (such as Argon2id, bcrypt, or scrypt). Environment variables are an injection mechanism rather than encryption at rest or process isolation; .env files, child-process environment inheritance, crash dumps, and application logs must all be controlled. Finally, whenever a credential is confirmed or suspected to be compromised, revoke it immediately — dual-key grace periods apply only to routine scheduled rotation. References: OWASP Secrets Management Cheat Sheet; OWASP Session Management Cheat Sheet.

Why It Matters

  • Once an LLM API key or cloud Access Key is committed to a Git repository or baked into a container image, automated scanners and supply-chain attackers can discover and abuse it rapidly.
  • Default Kubernetes Secret objects are merely Base64-encoded (see k6.ops.kubernetes); production clusters should integrate envelope encryption via KMS or an external Secrets Manager.
  • Deleting a file in a later commit does not make a leaked secret safe — it remains in Git commit history and must be revoked and rotated.

How It Works / Diagram

OWASP Secrets Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html; GitHub Secret Scanning & Push Protection: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning

Figure 1
Practice Assessment
Hardcoding secrets in source code Never allowed
Committing .env files to Git Never allowed; always list .env in .gitignore
Injecting via environment variables / orchestrator Standard baseline
Cloud Secrets Manager + workload IAM roles Recommended for production
Baking secrets into container image layers Never allowed (intermediate layers remain extractable)

Runnable Example

Example Version & Verification Scope

The revised second-draft script uses cryptographically random tokens, constant-time comparison, and an isolated temporary Git repository, while explicitly skipping POSIX mode-bit checks when running on Windows. The archived first-draft output below reflects the original script run; see the batch verification log for the current run. See the revised script at examples/35_secret_management.py.

"""Credential lifecycle demo: creates dummy keys and an isolated temporary Git repository inside a temp folder.
Note: a one-way hash verifier validates inbound random tokens; it does not replace an encrypted vault for retrievable outbound API keys.
"""
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: pass an explicit minimal environment to child process without logging the secret")
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 effective access by other users; ACLs/root can alter access")
    else:
        print("   Skipping Unix 600/644 mode check; on Windows, inspect NTFS ACLs")

    print("== 3. A dummy secret removed from the working tree still persists in Git commit history")
    if shutil.which("git"):
        repo=task/"repo"; repo.mkdir()
        # Disable global/system Git config and hooks so we 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 secret:", 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 check")

print("== 4. Hash verifier for inbound 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 plaintext key from encrypted storage/KMS (not implemented here)")

print("== 5. Dual-key rotation window: tested with an explicit clock parameter")
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("   Current key:",accept(keys["current"],99),"Previous key during grace window:",accept(issued,99),"At cutoff:",accept(issued,100))
print("   If the previous key was leaked, revoke it immediately instead of granting a grace window")

First-Draft Archived Output (original environment record, not re-run in this batch):

== 1. Environment variable injection (process-level), keep out of code and images
   Child process read: sk-FAKE… len 36
== 2. File permissions: 600 vs 644
   644 permission: 0o644 world-readable
   600 permission: 0o600 owner-only
== 3. Secret tracked by Git: even after deleting from file, history remains
   Plaintext still in current working tree: False
   git log -S still finds it in commit history: True (must rotate key, not just edit the file)
== 4. Token hash store: store only digest, verify with compare_digest
   Valid key: True
   Invalid key: False
   No plaintext in store: 2f75be345056124f…
== 5. Rotation: dual-key grace window
   New key: current / Old key during grace window: previous-grace
   Old key after grace window expires: reject
  • 1. The child process receives the credential via its environment variables rather than hardcoded source constants (and the revised script avoids printing any prefix of the secret to logs).
  • 2. On POSIX filesystems, mode 0644 is world-readable whereas 0600 restricts read/write to the file owner (subject to parent directory permissions and ACLs); on Windows, access control is governed by NTFS ACLs.
  • 3. Even after replacing the hardcoded key with os.environ['LLM_API_KEY'] in a subsequent commit, git log -S sk-FAKE still finds the secret in commit history; the mandatory response to a committed secret is immediate revocation and rotation.
  • 4. The second draft clarifies that storing a SHA-256 digest and verifying with hmac.compare_digest works for validating inbound high-entropy bearer tokens that your own service issues; it cannot act as an outbound secret vault because third-party APIs require you to present the original secret.
  • 5. Dual-key rotation window: the newly issued key works immediately, while the previous key remains valid during a bounded grace window before returning reject, preventing downtime during routine rollout.

Common Pitfalls

  • "Our repository is private, so hardcoding keys is fine": Compromised developer laptops, contractor accounts, CI build logs, or converting the repo to public later will expose anything in Git history.
  • "Kubernetes Secrets are encrypted by default": By default they are stored as Base64-encoded strings in etcd unless envelope encryption with a KMS provider is configured (see k6.ops.kubernetes).
  • "Key rotation is too painful, so we only do it once a year": Automate rotation so routine rollouts use a brief dual-key grace window, and revoke immediately whenever a leak is suspected.

Connection to AI Development

  • Never embed long-lived server-side LLM provider API keys inside browser bundles or mobile apps; keep provider keys on your backend and issue short-lived, rate-limited user session tokens (or use a provider's dedicated short-lived client ephemeral token protocol where supported).
  • Provision separate, least-privilege credentials for each tool an AI Agent can invoke rather than sharing a single all-powerful master key across all tools.

Second-Draft Commentary Notes

"No plaintext in store" in the first-draft output only demonstrates that a one-way digest was stored; it does not implement encrypted secret retrieval, audit logging, or hardware-backed KMS storage. Also remember that a dual-key grace window is strictly for planned rotation, never for an actively leaked credential.

Self-Test & Answer

Question: If your service hashes a third-party LLM API key with SHA-256 and discards the plaintext, can your service still call that third-party API?

Answer: No. The upstream API provider expects the original bearer key in the Authorization header, and a one-way cryptographic hash cannot be reversed. Outbound secrets must be stored in an encrypted, access-controlled secret manager (or KMS-backed store) so authorized workloads can retrieve them at runtime. One-way hashing applies when your service is the verifier checking inbound random tokens presented by your clients.

Verified Sources & Conclusions

Unverified Scope & Follow-Up Checks

  • Live cloud KMS, HashiCorp Vault, and cloud Secrets Manager integrations were not executed; POSIX file mode enforcement was not tested on Windows.
  • Exact tool versions, timings, IPs, PIDs, and generated text in the first-draft log are historical observations rather than universal guarantees; record platform, dependencies, inputs, and logs when reproducing.

Current Example Execution Scope

2026-10-15: Partially Passed. Environment variable injection, token digest verification, rotation window logic, and temporary Git history leak scanning passed on Windows; the POSIX file mode (chmod 600/644) branch was skipped on Windows.

View current batch log.

"First-Draft Archived Output" retains the original log text and is not newly generated by the revised second-draft code; read its conclusions alongside the second-draft revisions and scope boundaries.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram