Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 04 · 40 minutes

Manage keys and secrets and rotate a key without a break

After this lesson you can
  • Keep keys as hashes at rest and as files of mode 600 in use
  • Rotate a key with an overlap window so that no client breaks
  • Scan a folder for keys in the wrong place and fix each finding
Lab files of this lesson (19)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Team beta has asked for a new key because a developer pasted the old one into a chat. Your lead adds two questions: "How old are our keys? And what is in the repository today that should not be there?" You need a way to replace a key without taking a client down, and a scan that finds keys where they do not belong. A rotation that breaks a client at 03:00 is one that nobody does again.

Recall

Lesson 3: which part of the gateway stores the keys, and in what form?

keystore.py stores them in keys.json as SHA-256 hashes, with the client name, the scopes and the dates. The key itself is shown once and saved in a file of mode 600.

Lesson 3: a request with the key of beta (scope read) gets 403. Which stage returns it?

authenticate. It finds the record, sees no predict in the scopes, and returns 403. An unknown key gets 401 earlier.

The idea

A secret is a value that gives access: an API key, a token, a password. Three questions decide how you handle it.

QuestionPractice
Where is it stored?As a hash when you only need to check it (client keys). As a file of mode 600 when a program must send it (a client's own key, the gateway token). Never in the code, in a chat, or in the model's prompt.
How is it passed on?By a file that the program reads, or by an environment variable. Both have costs (step 2).
How does it end?Every key has an expiry. A rotation replaces it before that date, with an overlap: the old key keeps working for a few days, so that clients can switch without a break.

Lesson 7 of "Web applications and APIs" covers secrets in code and a simple rotation. This lesson adds the overlap and a scanner. A thief of keys.json holds fingerprints that cannot be sent as keys. The client's own key file must stay private.

A rotation with an overlap of 7 days
2026-11-01alpha-1 is made and ends in 90 days2026-12-01rotate alpha: alpha-2 is made, shown once2026-12-01alpha-1 now ends on 2026-12-081 to 7 Decboth keys work: clients put alpha-2 in their file2026-12-08alpha-1 stops working2027-03-01alpha-2 ends: rotate again before this day2026-11-01alpha-1 is made and ends in 90 days2026-12-01rotate alpha: alpha-2 is made, shown once2026-12-01alpha-1 now ends on 2026-12-081 to 7 Decboth keys work: clients put alpha-2 in theirfile2026-12-08alpha-1 stops working2027-03-01alpha-2 ends: rotate again before this day

Worked example

1. See what a thief of keys.json gets

Each key has one record in keys.json.

A record of keys.json
alpha-1id of the keyalphathe client3b7e5a90c1...SHA-256 hash of the key["predict"]scopes2026-11-01created2027-01-30expires: the key stops that dayalpha-1id of the keyalphathe client3b7e5a90c1...SHA-256 hash of the key["predict"]scopes2026-11-01created2027-01-30expires: the key stops that day

A hash is not a key. Look up the stored hash as if it were a key, and then look up the real key from its file. json.load reads a JSON file.

python - <<'EOT'
import json, keystore
stolen = json.load(open("keys.json"))["keys"][0]["hash"]
real = open("secrets/alpha.key").read().strip()
print(keystore.lookup(stolen, "2026-11-21"))
print(keystore.lookup(real, "2026-11-21")["id"])
EOT
None
alpha-1

The gateway hashes what it receives, so a thief of keys.json cannot call it with a stored hash.

2. Compare an environment variable with a file

An environment variable is a named value that a program receives from the program that started it. Every child of that program receives it too. /proc/PID/environ is a Linux file that shows the environment of the process with that number. tr '\0' '\n' turns its separators into line ends. stat -c '%a' prints the mode of a file as digits: 4 is read, so 400 means read for the owner and nothing for anybody else.

KR_DEMO=hunter2 sleep 30 &
stat -c '%a' /proc/$!/environ
tr '\0' '\n' < /proc/$!/environ | grep KR_DEMO
kill $!
400
KR_DEMO=hunter2

The mode 400 means that only the owner of the process (and root) can read the file, and the owner reads the value in clear while the process runs. This is a secret in use: encrypting the disk (data at rest) does not help, because the program holds the value in memory (lesson 9 names the controls for data in use). Another program of the same user can read it. So can ps e, a crash report, a container inspection command and every child process. A file that the program opens only when it needs the value has fewer such leaks. It must have mode 600, and the code should refuse a file that others can read. Neither way protects against code that runs as you: lesson 5 limits what a process may touch.

To keep the lab short, the service and the gateway of this course read their token from an environment variable. A production service would read a file of mode 600, or get a secret from a secrets manager, which hands it over as a file in memory (a tmpfs) or as a short-lived token. The course cannot test one.

3. Save the scanner

scan_secrets.py looks for two things: text that looks like a key (the pattern kr_ and 20 or more letters, digits, _ or -) or like an assignment of a secret (password: ...), and files in a secrets folder, or named .env or *.key, that group or others can read. re.compile prepares a pattern. stat.S_IMODE gives the permission bits of a file, and & 0o077 keeps the group and other bits. A secret file may hold a key, so the scanner reads only its mode.

scan_secrets.py

"""scan_secrets.py: find keys in the wrong place and secret files that other users can read.

    python3 scan_secrets.py [folder]          exit code 1 when it finds something
"""
import re
import stat
import sys
from pathlib import Path

PATTERNS = {"lab key": re.compile(r"kr_[A-Za-z0-9_-]{20,}"),
            "assigned secret": re.compile(r"(?i)(api[_-]?key|secret|token|password)\s*[=:]\s*['\"]?[A-Za-z0-9_-]{12,}")}
SKIP = {".venv", "__pycache__"}


def scan(root):
    """Return a list of (file, what) for every finding under root."""
    found = []
    for path in sorted(Path(root).rglob("*")):
        if not path.is_file() or SKIP & set(path.parts):
            continue
        in_secrets = "secrets" in path.parts or path.name == ".env" or path.suffix == ".key"
        if in_secrets and stat.S_IMODE(path.stat().st_mode) & 0o077:
            found.append((str(path), f"secret file with mode {stat.S_IMODE(path.stat().st_mode):o}"))
        if in_secrets:
            continue   # a key may live here, if the mode is right
        for number, line in enumerate(path.read_text(errors="ignore").splitlines(), 1):
            for kind, pattern in PATTERNS.items():
                if pattern.search(line):
                    found.append((f"{path}:{number}", kind))
    return found


if __name__ == "__main__":
    findings = scan(sys.argv[1] if len(sys.argv) > 1 else ".")
    for where, what in findings:
        print(f"{where}  {what}")
    print(f"{len(findings)} findings")
    sys.exit(1 if findings else 0)

Make a folder of fake problems. This script writes the fake key in two pieces ("kr""_demo..."), so that a scan of the script itself finds nothing. A split value is a known way to hide a key from a scanner: do not rely on a scanner alone.

make_scan_demo.sh

K="kr""_demo_0123456789abcdefghij"
PW="correct""horse1234"
rm -rf scan-demo && mkdir -p scan-demo/secrets
printf 'API_KEY = "%s"\nprint("start")\n' "$K" > scan-demo/app.py
printf 'meeting notes\npassword: %s\n' "$PW" > scan-demo/notes.txt
printf '{"api_key": "%s"}\n' "$K" > scan-demo/config.json
printf 'hello\n' > scan-demo/README.md
printf '%s\n' "$K" > scan-demo/secrets/token.key
printf '%s\n' "kr""_demo_zzzzzzzzzzzzzzzzzzzz" > scan-demo/secrets/ok.key
chmod 644 scan-demo/secrets/token.key
chmod 600 scan-demo/secrets/ok.key
bash make_scan_demo.sh
python scan_secrets.py scan-demo
echo "exit code $?"
scan-demo/app.py:1  lab key
scan-demo/app.py:1  assigned secret
scan-demo/config.json:1  lab key
scan-demo/notes.txt:2  assigned secret
scan-demo/secrets/token.key  secret file with mode 644
5 findings
exit code 1

Fix the file mode first, then look at the folder again. chmod 600 sets the mode to read and write for the owner only.

chmod 600 scan-demo/secrets/token.key
python scan_secrets.py scan-demo | tail -1
4 findings

4. Save the full key store and the rotation script

keystore.py now has rotate, which gives every old key of the client an end date (overlap days from today, if that is earlier than its own end date) and adds a new key. A key works up to the day before its end date. argparse reads the options of the command line.

keystore.py

"""keystore.py: API keys of the clients. Only hashes are stored in keys.json. The key itself goes to a file with mode 600.

    python3 keystore.py add CLIENT SCOPE      make a key for CLIENT, save it in secrets/CLIENT.key
    (rotate.py replaces a key; scan_secrets.py looks for keys in the wrong place)
"""
import hashlib
import hmac
import json
import os
import secrets
import sys
from datetime import date, timedelta


def digest(key):
    return hashlib.sha256(key.encode()).hexdigest()


def read_keys(path="keys.json"):
    with open(path) as f:
        return json.load(f)


def save_keys(data, path="keys.json"):
    with open(path, "w") as f:
        json.dump(data, f, indent=1)


def lookup(key, today, path="keys.json"):
    """Return the record of a key that is known and not expired, else None. A key stops working on its `expires` date."""
    found = None
    for record in read_keys(path)["keys"]:  # no early exit: the time does not tell which record matched
        if hmac.compare_digest(digest(key), record["hash"]):
            found = record
    return found if found and found["expires"] > today else None


def add_key(client, scopes, today, days=90, path="keys.json"):
    """Add a record with the hash of a new random key. Return the key: show it once, never store it here."""
    key = "kr_" + secrets.token_urlsafe(24)
    data = read_keys(path) if os.path.exists(path) else {"keys": []}
    number = 1 + sum(r["client"] == client for r in data["keys"])
    data["keys"].append({"id": f"{client}-{number}", "client": client, "hash": digest(key), "scopes": scopes,
                         "created": today, "expires": (date.fromisoformat(today) + timedelta(days=days)).isoformat()})
    save_keys(data, path)
    return key


def rotate(client, today, overlap=7, days=90, path="keys.json"):
    """Make a new key for the client. Its old keys stop working `overlap` days from today (0: today, for a leak)."""
    data = read_keys(path)
    mine = [r for r in data["keys"] if r["client"] == client]
    stop = (date.fromisoformat(today) + timedelta(days=overlap)).isoformat()
    for record in mine:
        record["expires"] = min(record["expires"], stop)
    save_keys(data, path)
    return add_key(client, mine[-1]["scopes"], today, days, path)


def write_secret(path, text):
    """Write a file that only its owner can read: mode 600, whether the file is new or old.
    A new file gets the mode when it is made. An old file keeps its mode on open, so fchmod sets it."""
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    os.fchmod(fd, 0o600)
    with os.fdopen(fd, "w") as f:
        f.write(text + "\n")


if __name__ == "__main__" and sys.argv[1:2] == ["add"]:
    os.makedirs("secrets", exist_ok=True)
    client, scope = sys.argv[2], sys.argv[3]
    write_secret(f"secrets/{client}.key", add_key(client, [scope], date.today().isoformat()))
    print(f"key for {client} saved in secrets/{client}.key, hash saved in keys.json")

rotate.py

"""rotate.py: replace the key of a client. The old key keeps working for the overlap, so that no client breaks.

    python3 rotate.py alpha [--today 2026-12-01] [--overlap 7] [--keys keys.json] [--secrets secrets]
"""
import argparse
import os
from datetime import date

import keystore

parser = argparse.ArgumentParser()
parser.add_argument("client")
parser.add_argument("--today", default=date.today().isoformat())
parser.add_argument("--overlap", type=int, default=7)
parser.add_argument("--keys", default="keys.json")
parser.add_argument("--secrets", default="secrets")
args = parser.parse_args()

key = keystore.rotate(args.client, args.today, args.overlap, path=args.keys)
keystore.write_secret(os.path.join(args.secrets, args.client + ".key"), key)
for record in keystore.read_keys(args.keys)["keys"]:
    if record["client"] == args.client:
        print(record["id"], "created", record["created"], "expires", record["expires"])

5. Test the rotation with fixed dates

test_keys.py builds a key store in a temporary folder with fixed dates. It checks that only a hash is stored, that the old key works on the last day of the overlap and not after it (and with no overlap, not at all), that the new key works, that a secret file gets mode 600 (also one that existed with a looser mode), and that the scanner finds the right things. Open the block and save the file.

The finished file: test_keys.py

test_keys.py

"""test_keys.py: tests for key rotation, hashing at rest and the secret scanner."""
import os
import stat
import tempfile
import unittest
from pathlib import Path

import keystore
import scan_secrets


class KeyTests(unittest.TestCase):
    def setUp(self):
        self.dir = Path(tempfile.mkdtemp())
        self.path = str(self.dir / "keys.json")
        self.old = keystore.add_key("alpha", ["predict"], "2026-11-01", path=self.path)

    def test_only_the_hash_is_stored(self):
        self.assertNotIn(self.old, Path(self.path).read_text())

    def test_rotation_has_an_overlap(self):
        new = keystore.rotate("alpha", "2026-12-01", overlap=7, path=self.path)
        valid = lambda key, day: keystore.lookup(key, day, self.path) is not None
        self.assertTrue(valid(self.old, "2026-12-07"))    # the overlap is still open
        self.assertFalse(valid(self.old, "2026-12-08"))   # the old key has stopped
        self.assertTrue(valid(new, "2026-12-08"))
        self.assertEqual(keystore.lookup(new, "2026-12-08", self.path)["scopes"], ["predict"])

    def test_rotation_without_overlap_stops_the_old_key_today(self):
        new = keystore.rotate("alpha", "2026-12-01", overlap=0, path=self.path)
        self.assertIsNone(keystore.lookup(self.old, "2026-12-01", self.path))
        self.assertIsNotNone(keystore.lookup(new, "2026-12-01", self.path))

    def test_secret_file_mode_is_600(self):
        target = self.dir / "alpha.key"
        keystore.write_secret(str(target), self.old)
        self.assertEqual(stat.S_IMODE(target.stat().st_mode), 0o600)

    def test_old_secret_file_gets_mode_600(self):
        target = self.dir / "old.key"
        target.write_text("loose")
        os.chmod(target, 0o644)
        keystore.write_secret(str(target), self.old)
        self.assertEqual(stat.S_IMODE(target.stat().st_mode), 0o600)

    def test_scanner(self):
        (self.dir / "secrets").mkdir()
        (self.dir / "secrets" / "good.key").write_text(self.old)
        os.chmod(self.dir / "secrets" / "good.key", 0o600)
        self.assertEqual(scan_secrets.scan(self.dir), [])
        (self.dir / "notes.txt").write_text(f"api_key = {self.old}\n")
        self.assertEqual([what for _, what in scan_secrets.scan(self.dir)], ["lab key", "assigned secret"])


if __name__ == "__main__":
    unittest.main()
python test_keys.py
......
----------------------------------------------------------------------
Ran 6 tests in 0.003s

OK

6. Rotate a demo key

Make a demo store with one key from 1 November, rotate it on 1 December with an overlap of 7 days, and look at the result. --keys and --secrets point the script at the demo files and not at your real ones.

python -c "import keystore; keystore.add_key('alpha', ['predict'], '2026-11-01', path='demo-keys.json')"
mkdir -p demo-secrets
python rotate.py alpha --today 2026-12-01 --overlap 7 --keys demo-keys.json --secrets demo-secrets
ls -l demo-secrets
alpha-1 created 2026-11-01 expires 2026-12-08
alpha-2 created 2026-12-01 expires 2027-03-01
total 4
-rw------- 1 you you 36 Nov 21 13:41 alpha.key

The old key alpha-1 stops working on 8 December, and the new key alpha-2 on 1 March. For seven days both work. The new key is in demo-secrets/alpha.key, and write_secret made that file with mode 600.

Your turn

Fix scan-demo so that the scanner prints 0 findings. Move no secret into a place that the scanner skips only to hide it: the code in app.py must read its key from a file in secrets/ at run time, the config must not hold the key, and the notes must not hold the password. Run bash make_scan_demo.sh again first, so that you start from the five findings. If the scanner still flags a line that you fixed, a long name after the = looks like a value to it: read the pattern in scan_secrets.py, shorten the call, and note this false positive.

Then do the rotation again with an overlap of 10 days: delete demo-keys.json, make it again with the command of step 6, rotate on 2026-12-01, and read the end date of alpha-1.

Check yourself

Why is the overlap needed, and why not make it 90 days?

Clients cannot all switch at the same moment, and a client that was down for a day would fail on its first request. The overlap is the time in which the old key is still a risk. A short overlap (days) lets clients switch and gives the old key little time to be misused. A long one makes the rotation pointless.

The scanner prints 0 findings on a folder that holds a key. What are two reasons?

The key does not match the patterns (it is split, encoded, or has another shape), or it lives in a file that the scanner treats as a secret file and reads by mode only. A scan finds careless mistakes, not a determined person.

A key was pasted into a chat. Is rotating enough?

Rotate at once with --overlap 0, because the old key is now public: it stops on the day of the rotation. Then read the audit log for calls with the old key (lesson 3 logs the key id of each call) and check whether anything unusual happened. Rotation ends the exposure, but it does not tell you what the key did before.

Field notes

  • Short-lived credentials are better than long-lived keys: a token that lasts an hour needs no rotation. Platforms issue them, for example through workload identity.
  • Here the gateway proves itself to the service with a shared token on loopback. Across a network, use mutual TLS (each side shows a certificate) or short-lived workload identity, so that a copied token is worth nothing.
  • Give each client its own key and one scope. When one team leaks a key, you rotate one key, and the audit log shows which client did what.
  • Run a secret scanner on every change before it is saved in version control. Once a key is in the history of a repository, treat it as public.
  • Do not put a key in a URL. Servers and proxies log URLs.
  • Compare keys with hmac.compare_digest. Use a slow password hash (for example scrypt) for human passwords. An API key is random and long, so a fast hash is enough.