# Pathrule Pattern: Application Encryption and Key Management (1.0.0)
# ::pathrule:package:application-encryption-key-management

### [RULE] Use reviewed authenticated-encryption primitives  (path: /src/crypto)
<!-- scope: folder | priority: high | strict -->

Confidentiality without integrity allows attackers to modify ciphertext and influence decrypted data. Custom composition creates subtle nonce, padding, oracle, and verification failures.

- Use a maintained platform or cryptographic library and an approved authenticated-encryption mode through its high-level API.
- Generate keys with a cryptographically secure source at the required size and keep encryption, signing, wrapping, and derivation purposes separate.
- Verify authentication before releasing plaintext or distinguishing detailed failure causes to an untrusted caller.
- Version the ciphertext envelope with algorithm and key identity so future readers can select the correct reviewed implementation.

See /ops/keys for the adjacent decision or procedure that completes this constraint.

---

### [RULE] Guarantee nonce uniqueness for each key  (path: /src/crypto)
<!-- scope: folder | priority: high | strict -->

Nonce reuse can reveal relationships between plaintexts or destroy authentication guarantees even when the key remains secret. A timestamp or per-process counter can collide across restart or scale-out.

- Follow the chosen library's nonce generation or sequencing contract and use a secure random source where that contract expects random uniqueness.
- Store the nonce with ciphertext; it is normally not secret, but it must match the exact encryption operation.
- Do not derive nonce solely from time, record count, process ID, or an identifier that can repeat across tenants, retries, restore, or concurrent writers.
- Treat any suspected reuse under one key as a security incident requiring scope analysis and key replacement, not only regeneration of future nonces.

See /src/data for the adjacent decision or procedure that completes this constraint.

---

### [RULE] Bind ciphertext to its immutable context  (path: /src/data)
<!-- scope: folder | priority: high | strict -->

Valid ciphertext copied from one row or tenant to another may decrypt successfully unless the encryption operation binds it to the location and purpose the application expects.

- Construct canonical associated data from stable tenant, entity, field, schema, and purpose identifiers that both encryption and decryption can reproduce.
- Do not include mutable display values or values unavailable during recovery in the binding.
- Fail closed when context, key identity, tag, or envelope version does not match and preserve only a non-sensitive diagnostic category.
- Include context migration in schema change plans because renaming or moving an encrypted field can require controlled re-encryption.

See /src/crypto for the adjacent decision or procedure that completes this constraint.

---

### [RULE] Keep master keys outside application data and general runtime access  (path: /ops/keys)
<!-- scope: folder | priority: high | strict -->

Storing the master key beside ciphertext defeats separation, while exporting broad key material into every process increases compromise and logging risk.

- Use a managed or protected key service to generate or wrap data keys and restrict access by application identity, environment, tenant or context where supported.
- Keep plaintext data keys in memory only for the bounded operation and clear references promptly; never log them or write them to temporary files.
- Separate production, test, backup, and tenant key scopes according to the threat and recovery model.
- Audit key use, denied operations, policy changes, disablement, deletion scheduling, and unusual decryption patterns without logging protected plaintext.

See /src/crypto for the adjacent decision or procedure that completes this constraint.

---

### [MEMORY] Envelope encryption creates a rotatable key hierarchy  (path: /src/crypto)

Encrypting every record directly with one master key couples data operations to the key service and makes key scope and rotation coarse. Envelope encryption separates bulk data encryption from key protection.

- Generate a data key at the appropriate record, file, tenant, batch, or other bounded scope based on blast radius and operational cost.
- Store ciphertext, nonce, wrapped data key, wrapping-key identity, associated-data schema, and envelope version together.
- Decrypt by authorizing and unwrapping the data key through the key service, then authenticating ciphertext and context locally.
- Rotate wrapping keys by rewrapping data keys where policy permits, and rotate data keys by decrypting and re-encrypting the protected data.

See /ops/keys for the rule or workflow that puts this decision into practice.

---

### [MEMORY] Key deletion is a data-deletion and recovery decision  (path: /ops/keys)

Destroying a key can make every protected copy permanently unreadable, including backups needed for incident recovery. Retaining it forever can violate deletion policy.

- Map each key to active ciphertext, replicas, caches, queues, backups, exports, retention, and recovery environments.
- Use disablement and a review window before irreversible deletion where the key platform supports it.
- Test disaster recovery with restored ciphertext and the authorized key path before changing retention or rotation policy.
- Record approvals, owner, scope, date, recovery consequence, and evidence for key disablement and destruction.

See /src/data for the rule or workflow that puts this decision into practice.

---

### [SKILL] rotate-application-encryption-key  (path: /)

---
name: rotate-application-encryption-key
description: Rotate an application encryption, data, wrapping, or key-management key.
---

# Rotate Application Encryption Key

Run this procedure when the affected surface changes, before the result is promoted to production. Record evidence for every step instead of accepting a plausible-looking result.

1. Inventory algorithms, key hierarchy, ciphertext envelope versions, contexts, data locations, backups, readers, writers, permissions, and recovery dependencies.
2. Create the replacement key under approved policy and deploy readers that can decrypt both old and new envelopes before changing writers.
3. Switch new writes to the replacement identity and migrate old data through idempotent batches with a durable cursor, verification, and bounded load.
4. Measure remaining old-key ciphertext, decryption failures, context failures, throughput, and backup implications; rehearse interruption and resume.
5. Disable old use only after active and recoverable copies are accounted for, retain rollback through the approved window, and destroy material only through the irreversible-deletion review.

## Exit criteria

The change is complete only when the expected behavior, failure behavior, and rollback path have all been exercised with representative data. Preserve the evidence with the change so the next operator can repeat the same checks.
