API keys: creation, rotation, and revocation as one lifecycle

A synthetic API key's lifecycle in MySQL 8.4/InnoDB: one-time issuance, bounded rotation, revocation, and decisions after a lost response.

Keys in different positions represent issuance, transition, and revocation of access.

A client has been reading an API with the same key for a long time. A new key must be issued, moved into several processes, and the old access removed. Simply replacing a database string would immediately disconnect some processes. Leaving both keys valid without an end boundary would turn a temporary transition into permanent additional access.

The problem starts before rotation: who receives the secret, what remains stored after disclosure, and how do we distinguish failed creation from a lost response? The independent exercise runs in one teaching Symfony application with MySQL 8.4/InnoDB through native PDO MySQL. All keys are synthetic; logical times define the scenario rather than a running service’s history. The current Demo has an effective PHP minimum of 8.4.1.

Running it requires the PDO MySQL extension and a prepared schema. In laboratory checks, the shared guarded MySQL fixture creates a disposable schema through App\Infrastructure\MysqlLab. A separate migrator executes DDL before business transactions; the runtime account performs DML and has no CREATE, ALTER, or DROP privileges. InnoDB tables use foreign keys and CHECK constraints. This is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database.

One client can have several keys

A key establishes possession of a secret. The operation permitted to that client and the scope of accessible data are separate decisions. A new secret must not, by itself, create a new client, restore revoked permissions, or reset consumed quota.

The model has a site, a client, and records for its keys. During a transition, both keys refer to the same identity. The current permission to read cards comes from the client's current record. Quota accounting remains a separate task: this exercise does not implement it.

Key metadata includes a public identifier, owner, state, expiry, activation time, and revocation time. The secret is a separate value that the client presents for verification. The identifier is useful for support and auditing; knowing it does not grant access.

Creation prepares access before activating it

The exercise generates the identifier and secret independently:

$identifier = bin2hex(random_bytes(12));
$secret = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
$credential = 'lab_' . $identifier . '.' . $secret;

The identifier is not cut from the secret portion. That portion uses 32 random bytes; encoding merely makes them suitable for transmission. PHP describes random_bytes as a source of cryptographically suitable random bytes. A generator failure must stop creation instead of switching it to a predictable counter.

MySQL stores a verification SHA-256 digest of the complete credential, not the plaintext secret. Verification computes the candidate's digest and compares it using hash_equals. The property of that comparison does not make the entire HTTP request take an identical amount of time. The model also does not extend this storage approach to passwords invented by people.

A new record starts as staged: it exists but cannot admit requests. Creation does not mean activation. This provides an explicit place to transfer the secret to the intended client and decide when the transition begins. Key management accepts a separate trusted host permission; an ordinary read key is not permission to issue other keys.

One-time disclosure is an issuance rule

The secret is returned only after the owned transaction has completed with a known outcome. The result object permits one explicit retrieval, hides the value in JSON and its diagnostic representation, and rejects cloning and ordinary serialization. Once the caller retrieves the secret, responsibility for storing it passes to that caller.

This is a limited contract. It neither erases every copy of the string from PHP memory nor protects against arbitrary code inside the same process. If the caller writes the retrieved value to a log, the issuance object cannot take it back.

The exercise's store cannot reconstruct the secret. Safe metadata remains available later, but there is no “show again” action. Storing an encrypted secret for controlled redisclosure would be a different policy, with additional encryption keys, permissions, and auditing.

Issuance uses a separate operation identifier. If commit occurred but the response was lost, a retry does not create another secret under the same identifier. An operator inspects metadata, revokes the undelivered staged record, and prepares a new issuance. An unknown response does not establish that the first record is absent.

Overlap needs an exact end

The exercise's planned transition works as follows: the old key is usable, the new one is prepared, then one transaction activates the new key and sets the old key's acceptance boundary. Separate writes to “enable the new one” and “disable the old one sometime” would leave an intermediate state without a defined end.

Choose a logical activation time of 200 and an overlap of 60 seconds. The old key is therefore accepted until 260, exclusive; its own expiry may occur earlier. These boundaries are exercise policy, not a recommended duration for every product.

Time or state Old key New key
New key is only staged Valid under its previous rules Refused
After activation, before 260 Admitted if neither revoked nor expired Admitted
Exactly 260 Refused Admitted under its own rules
Client is disabled Refused Refused

Confirming the transfer requires a request using the new key specifically. A successful response from another process using the old secret does not establish that. We need to know which consumers still use the old access and avoid silently extending the transition after each failure.

In this model, an old key can receive only one successor. Repeating rotation does not push its cutoff forward. The new record must belong to the same site and client; a foreign staged key cannot be substituted into the transition. Zero overlap ends old access at the moment the new key activates.

Revocation does not wait for planned rotation

Suspected exposure changes the objective. Preserving a convenient transition must not keep a compromised secret valid. OWASP treats creation, rotation, revocation, and expiration as separate parts of a secret's lifecycle and describes revoking unnecessary or potentially compromised secrets.

The teaching model's revoke is irreversible: repeating it neither restores the key nor changes the first revocation time. New access requires a new record. An expired or already revoked key cannot be rotated as though it had become valid again.

The time boundary is half-open: now >= expires_at means refusal. In MySQL, starting a transaction does not itself acquire the required row locks. The decision's time must account for waiting for those locks rather than preserve an already expired lifetime. The active state alone is insufficient: cutoff, expiry, and the client's validity matter too.

Revocation affects new admission decisions

Each request reads key state and current permissions afresh in a short owned MySQL/InnoDB transaction. Concurrent operations are coordinated through row locks, not a single writer for the entire database. Under REPEATABLE READ, this decision needs a current locking read rather than an earlier snapshot. InnoDB errors, including lock timeout 1205 and deadlock 1213, remain technical errors: the transaction owner rolls back, and the error propagates instead of becoming a domain rejection.

After admission, the protected read runs outside that transaction. If revocation happens later, already admitted work may finish. The example does not guarantee cancellation of those requests. The next decision after revocation commits must read the new state and refuse access.

Caching a positive authentication result would change this contract: old access could survive until the cache updates. A distributed system must separately define its revocation propagation delay. This exercise has no such cache, and a positive result from one request is not carried into the next.

Unavailable storage does not permit accepting a key “temporarily.” An invalid credential receives a neutral refusal, missing read permission receives a separate authorization refusal, and technical uncertainty means service unavailability. None of those branches reads protected content.

Logs receive an event, not a secret

The audit contains an allowlisted event name, site, internal key identifier, and time. It accepts no free-form message, raw header, digest, or exception object. A safe field list is easier to verify than trying to recognize every possible secret with a regular expression at the end.

The secret travels over a protected channel. An authorization header is appropriate for an HTTP adapter; Symfony describes default Bearer extraction and the risk of URL or body tokens reaching logs. Choosing a header does not disable its recording by a proxy, tracer, or debugger: those surfaces need separate configuration.

A public error in the teaching adapter contains only fixed wording. The internal exception is not attached to the response. Support metadata does not become public automatically either: reading a key list requires its own management permission.

Verify the entire transition

The scenarios check staged-key refusal, exact overlap boundaries, repeated revocation, changed permissions, a foreign site, and unavailable storage. Separate cases model lost acknowledgement after commit and rollback before it. The checks use actual MySQL 8.4 through native PDO; the fixture migrator prepares the schema beforehand, and the operations under test perform DML only. These are controlled failure seams, not a power-loss experiment.

The redaction scenario checked captured diagnostic surfaces for the synthetic secret, suffix and verifier. The wrapper redacts JSON/debug output; failure output does not print credentials. Revocation after admission was also checked: an already admitted callback finishes, while the next fresh decision refuses. This does not prove the safety of arbitrary logs or memory.

Concurrent rotate/rotate and revoke/admit checks use separate native PDO connections sharing a MySQL schema. The important invariant after the first operation commits is that the next rotation reads the committed successor, creates no second successor, and does not move cutoff 260; after revocation, a fresh admission decision refuses access without a protected read. A lock error does not count as satisfying this invariant: a separate successful transaction must read the current state. This is not a promise of automatic retries in a running service or a measurement of lock-wait duration. The checks do not establish HTTP ingress behavior, distributed revocation propagation, or crash durability.

The useful outcome of such an exercise is an explicit contract for every transition: what has already been stored, what may still be shown, until when the old key remains permitted, and what decision is justified after an unknown response. A random secret is only the beginning of that contract.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/KeyLifecycleLab
  1. Operations & Security Planned SSH key rotation: verifying new access and revoking the old key
  2. API Permission to act and permission to access data: two checks for one API request
  3. API API quota: accounting for concurrent requests without duplicate charges
  4. Platform Engineering Timeout after an external request: when the outcome is unknown