Keys that rotate themselves #

What is new: an API key here has a plan, scopes and a lifetime, and it knows when it should be replaced. Every response tells the client when to rotate; the client rotates the key in its own file, crash-safe, and the old key keeps working for a grace period so nothing breaks in between. The server keeps only the sha256 of each key, and every issue, rotation and revocation is an event in a hash-linked log.

Why it matters: leaked or forgotten keys are the most common way APIs get abused. Keys that expire, rotate without anyone touching them, and can be revoked with effect on the very next request turn key hygiene from a chore into a property of the system.

A key on a plan, with a read-only sibling #

import json, os, warnings
from pathlib import Path
warnings.simplefilter("ignore")
from fastapi.testclient import TestClient
from tensorchain.service.app import create_app
from tensorchain.service.config import Settings
from tensorchain.keys import KeyFile

now = [1795400000000]                                  # a clock we can move: one day = 86 400 000 ms
DAY = 86_400_000
app = create_app(Settings(data_dir=Path("service"), keys_file=None, dev_key=None), wall=lambda: now[0])
http = TestClient(app)
store = app.state.registry.keys

raw, key = store.issue("acme", plan="trial")           # on the server, as `tc-cloud key add` does
ro, _ = store.issue("acme", plan="trial", scopes=("read",))
print("issued a", key["plan"], "key:", "| expires in", (key["expires"] - now[0]) // DAY, "days",
      "| rotate after day", (key["rotate_after"] - now[0]) // DAY)

h = {"Authorization": "Bearer " + ro}
print("read-only key, GET :", http.get("/v1/workspaces", headers=h).status_code)
print("read-only key, POST:", http.post("/v1/workspaces", json={"id": "x"}, headers=h).json()["error"]["code"])
assert (key["expires"] - now[0]) // DAY == 30 and key["plan"] == "trial"
assert http.post("/v1/workspaces", json={"id": "x"}, headers=h).status_code == 403
Output (captured at build)
issued a trial key: | expires in 30 days | rotate after day 20
read-only key, GET : 200
read-only key, POST: scope

The client rotates its own key file #

Path("acme.key").write_text(raw + "\n"); os.chmod("acme.key", 0o600)

def send(method, url, data, headers, timeout):
    r = http.request(method, url.replace("http://testserver", ""), content=data, headers=headers)
    return r.status_code, r.content

kf = KeyFile("acme.key", "http://testserver", send=send, clock=lambda: now[0])
print("day 0: ", kf.rotate_due()["note"])
now[0] += 21 * DAY                                     # two thirds of a 30-day key
out = kf.rotate_due()
print("day 21:", "rotated to a new key id:", out["key_id"] != out["previous"])
old = {"Authorization": "Bearer " + raw}
print("old key during grace:", http.get("/v1/workspaces", headers=old).status_code)
now[0] += 3 * DAY                                      # trial grace: 3 days
print("old key after grace :", http.get("/v1/workspaces", headers=old).json()["error"]["code"])
print("the file's key      :", http.get("/v1/workspaces", headers={"Authorization": "Bearer " + kf.read()}).status_code)
assert out["rotated"] and Path("acme.key.prev").read_text().strip() == raw
assert http.get("/v1/workspaces", headers=old).status_code == 401
assert http.get("/v1/workspaces", headers={"Authorization": "Bearer " + kf.read()}).status_code == 200
Output (captured at build)
day 0:  not due
day 21: rotated to a new key id: True
old key during grace: 200
old key after grace : key_expired
the file's key      : 200

Revoked on the next request, and every event on record #

current = kf.describe()["key_id"]
store.revoke(current)
r = http.get("/v1/workspaces", headers={"Authorization": "Bearer " + kf.read()})
print("after revoke:", r.status_code, r.json()["error"]["code"])
events = [e["event"] for e in reversed(store.events())]
print("events:", events)
print("event chain verifies:", store.verify_events()["ok"])
raw_bytes = b"".join(p.read_bytes() for p in Path("service").glob("keys.sqlite*"))
print("raw keys in the store:", sum(k.encode() in raw_bytes for k in (raw, ro, kf.read())))
assert r.status_code == 401 and events[-1] == "revoke"
assert store.verify_events()["ok"] is True
assert not any(k.encode() in raw_bytes for k in (raw, ro, kf.read()))
http.close()
Output (captured at build)
after revoke: 401 auth
events: ['issue', 'issue', 'rotate', 'grace', 'revoke']
event chain verifies: True
raw keys in the store: 0

The rotation needed no person: the key file was due, the client asked for a successor, proved it, and swapped it in. The old key worked through its grace period and then stopped. On the server, the store never held a raw key.