diff --git a/CHANGELOG.md b/CHANGELOG.md index bd7ae20..85e62d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ Both packages share one version number and one `v*` tag. +## 0.7.0 (2026-11-27) + +Both packages: + +- `audit(values, options)` counts a column's values by state: readable + canonical tokens per key version, `unbound` (decrypts only without the + context), `plaintext`, `legacy`, `unknownVersion` (Python + `unknown_version`) and `invalid` (token-shaped but not decryptable). + `classify(value, options)` returns one value's state (TS `{ state, + version }`, Python `(state, version)`). Neither throws on bad data; + both throw `KeyNotConfiguredError` for a dormant namespace. +- README: "Audit a column" section; ROADMAP brought up to date. + ## 0.6.1 (2026-10-29) Both packages: diff --git a/README.md b/README.md index 5e795f6..ffc2b3a 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ const sf = createSealedFields({ }); ``` -New writes seal under v2. Old rows keep reading under v1. Re-encrypt at your leisure with a backfill script, then drop the retired key. If a token names a version you no longer hold, `unseal` throws instead of returning ciphertext. The `onUnknownVersion: "passthrough"` option exists for the migration window only. +New writes seal under v2. Old rows keep reading under v1. Re-encrypt at your leisure with a backfill script, then drop the retired key once `sf.audit` (below) shows no rows left under it. If a token names a version you no longer hold, `unseal` throws instead of returning ciphertext. The `onUnknownVersion: "passthrough"` option exists for the migration window only. Rotate well before one key has sealed about 4 billion (2^32) values. Each seal uses a random 96-bit nonce, and NIST SP 800-38D caps random-nonce GCM at 2^32 encryptions per key, because past that point a repeated nonce becomes likely enough to matter. A repeated nonce under one key leaks the XOR of the two plaintexts and lets an attacker forge tokens. Most applications never get close, but a hot column with frequent rewrites can. @@ -143,10 +143,30 @@ const sf = createSealedFields({ Reads understand the old tokens. Every write produces the canonical format. A legacy-shaped token that no key can authenticate throws, because that is an integrity problem, not plaintext. -**Audit plaintext before turning on a key or a legacy decoder.** Plaintext written in dormant mode before 0.6.1, written before 0.4.0, or still sitting in a mixed table may contain user input shaped like a token. Once a key or decoder is on, those values fail authentication. The row helpers null them, and enough of them on one page trip `SystemicUnsealError`. Before enabling, scan the column with `isSealed` (plus your legacy shape). Re-seal or clear any row that matches a token shape but doesn't decrypt under your keys. +**Audit plaintext before turning on a key or a legacy decoder.** Plaintext written in dormant mode before 0.6.1, written before 0.4.0, or still sitting in a mixed table may contain user input shaped like a token. Once a key or decoder is on, those values fail authentication. The row helpers null them, and enough of them on one page trip `SystemicUnsealError`. Before enabling, run `sf.audit` over the column from a one-off script built with the new key and decoder. Re-seal or clear every row it counts as `invalid`: token-shaped but not decryptable under your keys. **Close the door once the backfill is done.** By default `unseal` passes plaintext through, which also lets a value written around the library, by a raw SQL fix or a second service, sit unencrypted forever without anyone noticing. After every row is sealed, set `plaintext: "reject"`. Then `unseal` throws on a non-token value, and the row helpers null it and count it toward `SystemicUnsealError`. It cannot be combined with `mode: "dormant"`, because dormant mode writes plaintext. Since 0.6.1, dormant mode refuses to write a value shaped like a token (canonical or an enabled legacy format) and throws `SealedFieldsError` instead. +## Audit a column + +`audit` counts a column's values by state, so "is the rotation done" and "is every row bound" are a query, not a guess. Pass the same namespace and context the column is sealed with: + +```ts +const report = sf.audit(rows.map((r) => r.email), { namespace: "PII", context: ["users", "email"] }); +// { total: 1200, activeVersion: "v2", versions: { v2: 1180, v1: 12 }, +// empty: 3, plaintext: 2, legacy: 0, unbound: 4, unknownVersion: 0, invalid: 1 } +``` + +| Count | Means | Action | +| --- | --- | --- | +| `versions` | Readable canonical tokens by key version | Rotation is done when only `activeVersion` is left | +| `unbound` | Decrypts only without the context | Re-encrypt before removing `contextFallback` | +| `plaintext`, `legacy` | Not yet in the canonical format | Backfill, then consider `plaintext: "reject"` | +| `unknownVersion` | Names a key you don't hold | Find the missing retired key | +| `invalid` | Token-shaped but doesn't decrypt | Re-seal or clear it before it trips `SystemicUnsealError` | + +`classify(value, options)` returns one value's state (`{ state, version }`), for finding the rows behind a count. Neither one throws on bad data, and neither writes anything. Both need a key: a dormant namespace throws `KeyNotConfiguredError`. For a large table, audit each page and sum the counts. Python: `sf.audit(values, "PII", context=[...])` returns the same counts with snake_case keys, and `sf.classify(...)` returns `(state, version)`. + ## Fail closed by default With no key configured, `seal` throws. If you need the deploy window where code ships before keys are provisioned, opt in explicitly: diff --git a/ROADMAP.md b/ROADMAP.md index 96f0f7c..9923fda 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -30,19 +30,39 @@ row helpers with systemic-failure detection, and legacy-format decoders. - [x] Release workflow publishes the Python package to PyPI by trusted publishing on the same `v*` tag as npm. -## v0.4 candidates +## v0.4 – v0.6.1 (shipped) + +- [x] Row-helper trust boundary: `sealRow` seals every listed string, so + token-shaped user input can't be stored unencrypted (0.4.0). +- [x] Strict config and key parsing, short-token guard, pinned GCM tag + length (0.4.0, 0.5.0). +- [x] Blind-index `context` to keep columns from being joinable (0.5.0). +- [x] Context binding: tokens bound to table/column/row via GCM AAD, with + `contextFallback` and `stats().unboundReads` for migrating (0.6.0). +- [x] `plaintext: "reject"` for fully migrated columns (0.6.0). +- [x] Dormant mode refuses token-shaped input instead of storing it as + plaintext (0.6.1). + +## v0.7 + +- [x] Key-audit helper: `audit` / `classify` count a column by state + (sealed per key version, unbound, plaintext, legacy, unknown version, + invalid) so "is the rotation done" is a query, not a guess. + +## Candidates + - [ ] Drizzle column helpers: a `sealedText()` / `sealedJson()` custom type so schema declarations carry the sealing, mirroring the SQLAlchemy TypeDecorator pattern in the Python reference. -- [ ] Backfill script template: cursor-paginated re-encrypt for plaintext - rows and for retired-key rows, with dry-run counts and progress - checkpoints. -- [ ] Key-audit helper: scan a table and report rows by state (plaintext, - active version, each retired version, unknown version) so "is the - rotation done" is a query, not a guess. +- [ ] Backfill script template: cursor-paginated re-encrypt for plaintext, + legacy, unbound and retired-key rows, with dry-run counts (from + `audit`) and progress checkpoints. ## Later / on demand +- [ ] Rollback/replay protection (out of scope for context binding; see + `docs/design/context-binding.md`). + - [ ] Additional legacy decoders if adopters bring other common formats (for example the compact binary `base64(iv|tag|ct)` shape). - [ ] scrypt/HKDF key-derivation helper for teams that manage passphrase diff --git a/package-lock.json b/package-lock.json index a205ba0..f0678f0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sealed-fields", - "version": "0.6.1", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sealed-fields", - "version": "0.6.1", + "version": "0.7.0", "license": "MIT", "devDependencies": { "@types/node": "^22.20.5", diff --git a/package.json b/package.json index 2601f1f..b152f37 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sealed-fields", - "version": "0.6.1", + "version": "0.7.0", "description": "Field-level encryption for PII at rest: AES-256-GCM with versioned key rotation, key namespaces, HMAC blind indexes for equality lookups on encrypted columns, and row helpers with systemic-failure detection. Zero dependencies, bring your own database.", "license": "MIT", "author": "Michael Pointer ", diff --git a/python/README.md b/python/README.md index ea05731..24b3680 100644 --- a/python/README.md +++ b/python/README.md @@ -24,8 +24,8 @@ sf.blind_index("alice@example.com") # HMAC lookup token See the [repository README](https://github.com/mpointer/sealed-fields) for the full design: key rotation without a flag day, key namespaces, blind -index entropy rules, row helpers, legacy-format decoders, and the -fail-closed default. +index entropy rules, row helpers, legacy-format decoders, column audits +(`sf.audit` / `sf.classify`), and the fail-closed default. ## SQLAlchemy column types diff --git a/python/pyproject.toml b/python/pyproject.toml index 8eb467b..8e52e57 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "sealed-fields" -version = "0.6.1" +version = "0.7.0" description = "Field-level encryption for PII at rest: AES-256-GCM with versioned key rotation, key namespaces, HMAC blind indexes, and row helpers with systemic-failure detection. Wire-compatible with the sealed-fields npm package." readme = "README.md" license = "MIT" diff --git a/python/src/sealed_fields/__init__.py b/python/src/sealed_fields/__init__.py index 486b1be..781ddc7 100644 --- a/python/src/sealed_fields/__init__.py +++ b/python/src/sealed_fields/__init__.py @@ -436,6 +436,103 @@ def stats(self) -> dict[str, int]: before fallback is turned off. Per instance and per process.""" return {"unbound_reads": self._unbound_reads} + def classify( + self, + value: str | None, + namespace: str | None = None, + *, + context: str | Sequence[str] | None = None, + ) -> tuple[str, str | None]: + """Classify one stored value without raising on bad data. Returns + ``(state, version)``; version is the key version a canonical token + names, else None. ``context`` is the one the column is sealed with. + + empty None or "" + plaintext not token-shaped + sealed canonical token that decrypts under ``context`` + unbound decrypts only without the context (needs re-encrypt) + legacy enabled legacy format that decrypts + unknown-version names a key version the keyring doesn't hold + invalid token-shaped but does not decrypt: re-seal or clear it + + Raises KeyNotConfiguredError for a dormant namespace: nothing can be + verified without a key.""" + aad_context = _encode_context(context) + ns = self._resolve_ns(namespace) + ring = self._rings[ns] + if ring is None: + raise KeyNotConfiguredError(f'namespace "{ns}" has no key configured; cannot audit.') + if value is None or value == "": + return ("empty", None) + m = _TOKEN_RE.fullmatch(value) + if m: + version = m.group(1) + key = ring.keys.get(version) + if key is None: + return ("unknown-version", version) + try: + raw = _decode_blob(m.group(2)) + except (binascii.Error, ValueError): + return ("invalid", version) + if len(raw) < NONCE_BYTES + TAG_BYTES: + return ("invalid", version) + nonce, ct = raw[:NONCE_BYTES], raw[NONCE_BYTES:] + + def opens(ctx: str | None) -> bool: + try: + AESGCM(key).decrypt(nonce, ct, _build_aad(version, ctx)) + return True + except InvalidTag: + return False + + if opens(aad_context): + return ("sealed", version) + if aad_context is not None and opens(None): + return ("unbound", version) + return ("invalid", version) + if any(_match_legacy(value, f) for f in self._legacy): + try: + self._try_legacy(value, ring) + return ("legacy", None) + except Exception: + return ("invalid", None) + return ("plaintext", None) + + def audit( + self, + values: Iterable[str | None], + namespace: str | None = None, + *, + context: str | Sequence[str] | None = None, + ) -> dict[str, Any]: + """Count a column's values by state (see ``classify``). ``versions`` + counts readable canonical tokens (sealed + unbound) by key version, so + a rotation is done when it holds only ``active_version``. For a large + table, audit each page and sum the counts.""" + ns = self._resolve_ns(namespace) + ring = self._rings[ns] + if ring is None: + raise KeyNotConfiguredError(f'namespace "{ns}" has no key configured; cannot audit.') + report: dict[str, Any] = { + "total": 0, + "active_version": ring.active_version, + "empty": 0, + "plaintext": 0, + "legacy": 0, + "unbound": 0, + "unknown_version": 0, + "invalid": 0, + "versions": {}, + } + for value in values: + state, version = self.classify(value, ns, context=context) + report["total"] += 1 + if state in ("sealed", "unbound"): + report["versions"][version] = report["versions"].get(version, 0) + 1 + if state != "sealed": + report[state.replace("-", "_")] += 1 + return report + def maybe_seal( self, value: str | None, diff --git a/python/tests/test_sealed_fields.py b/python/tests/test_sealed_fields.py index 1779476..cb49d3c 100644 --- a/python/tests/test_sealed_fields.py +++ b/python/tests/test_sealed_fields.py @@ -531,3 +531,80 @@ def test_legacy_needs_fallback_with_context(self): migrating = make_sf(legacy=["iv-ct-tag"], context_fallback=True, logger=lambda m: None) assert migrating.unseal(token, context="t.c") == "old" assert migrating.stats()["unbound_reads"] == 1 + + +class TestAudit: + CTX = ["users", "email"] + + @staticmethod + def _iv_ct_tag(plaintext: str, key_str: str) -> str: + key = base64.urlsafe_b64decode(key_str + "=" * (-len(key_str) % 4)) + nonce = os.urandom(12) + ct_tag = AESGCM(key).encrypt(nonce, plaintext.encode(), None) + b64 = lambda b: base64.b64encode(b).decode() + return f"{b64(nonce)}:{b64(ct_tag[:-16])}:{b64(ct_tag[-16:])}" + + def _sfs(self): + before = make_sf() + sf = create_sealed_fields( + namespaces={"PII": {"key": KEY_B, "version": "v2", "retired": {"v1": KEY_A}}}, + legacy=["iv-ct-tag"], + ) + return before, sf + + def test_classifies_every_state(self): + before, sf = self._sfs() + stranger = create_sealed_fields(namespaces={"PII": {"key": generate_key()}}) + cases = [ + (None, ("empty", None)), + ("", ("empty", None)), + ("alice@example.com", ("plaintext", None)), + (sf.seal("a", context=self.CTX), ("sealed", "v2")), + (before.seal("a", context=self.CTX), ("sealed", "v1")), + (sf.seal("a"), ("unbound", "v2")), + (self._iv_ct_tag("a", KEY_A), ("legacy", None)), + (self._iv_ct_tag("a", generate_key()), ("invalid", None)), + ("v9:" + "A" * 40, ("unknown-version", "v9")), + ("v2" + stranger.seal("a", context=self.CTX)[2:], ("invalid", "v2")), + ("v2:AAAA", ("invalid", "v2")), + ("v2:AAAAA", ("invalid", "v2")), # undecodable base64 length + (sf.seal("a", context=["contacts", "email"]), ("invalid", "v2")), + ] + for value, expected in cases: + assert sf.classify(value, context=self.CTX) == expected, value + + def test_without_context(self): + _, sf = self._sfs() + assert sf.classify(sf.seal("a", context=self.CTX))[0] == "invalid" + assert sf.classify(sf.seal("a")) == ("sealed", "v2") + + def test_counts_a_column(self): + before, sf = self._sfs() + column = [ + sf.seal("a", context=self.CTX), + sf.seal("b", context=self.CTX), + before.seal("c", context=self.CTX), + sf.seal("d"), + "plain", + None, + self._iv_ct_tag("e", KEY_A), + "v2:AAAA", + ] + assert sf.audit(column, context=self.CTX) == { + "total": 8, + "active_version": "v2", + "empty": 1, + "plaintext": 1, + "legacy": 1, + "unbound": 1, + "unknown_version": 0, + "invalid": 1, + "versions": {"v2": 3, "v1": 1}, + } + + def test_refuses_dormant(self): + sf = create_sealed_fields(namespaces={"PII": {}}, mode="dormant", logger=lambda _m: None) + with pytest.raises(KeyNotConfiguredError): + sf.audit([]) + with pytest.raises(KeyNotConfiguredError): + sf.classify("x") diff --git a/src/index.ts b/src/index.ts index 62fef5b..0d28e5e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -74,6 +74,27 @@ export interface SealedFieldsConfig { * or be empty. "" and [] mean no context. */ export type SealContext = string | readonly string[]; +export type AuditState = "empty" | "plaintext" | "sealed" | "unbound" | "legacy" | "unknown-version" | "invalid"; + +export interface AuditResult { + state: AuditState; + /** Key version named by a canonical token. */ + version?: string; +} + +export interface AuditReport { + total: number; + activeVersion: string; + empty: number; + plaintext: number; + legacy: number; + unbound: number; + unknownVersion: number; + invalid: number; + /** Readable canonical tokens (sealed + unbound) by key version. */ + versions: Record; +} + /** Second argument of seal/unseal: a namespace name, or options. */ export type SealOptions = string | { namespace?: string | undefined; context?: SealContext | undefined }; @@ -304,6 +325,82 @@ export class SealedFields { return { unboundReads: this.unboundReads }; } + /** + * Classify one stored value without throwing on bad data. For audits: + * "is the rotation done", "is every row bound", "is anything token-shaped + * that won't decrypt". `context` is the one the column is sealed with. + * empty null, undefined or "" + * plaintext not token-shaped + * sealed canonical token that decrypts under `context` + * unbound decrypts only without the context (needs re-encrypt) + * legacy enabled legacy format that decrypts + * unknown-version names a key version the keyring doesn't hold + * invalid token-shaped but does not decrypt: re-seal or clear it + * Throws KeyNotConfiguredError for a dormant namespace: nothing can be + * verified without a key. + */ + classify(value: string | null | undefined, options?: SealOptions): AuditResult { + const { namespace, context } = splitOptions(options); + const ns = this.resolveNs(namespace); + const ring = this.rings.get(ns); + if (!ring) throw new KeyNotConfiguredError(`namespace "${ns}" has no key configured; cannot audit.`); + if (value == null || value === "") return { state: "empty" }; + const parsed = parseToken(value); + if (parsed) { + const { version } = parsed; + if (!ring.keys.has(version)) return { state: "unknown-version", version }; + const opens = (ctx: string | null): boolean => { + try { + unsealWithKeyring(value, ring, ns, "throw", ctx); + return true; + } catch { + return false; + } + }; + if (opens(context)) return { state: "sealed", version }; + if (context !== null && opens(null)) return { state: "unbound", version }; + return { state: "invalid", version }; + } + if (this.legacy.some((f) => matchLegacy(value, f))) { + try { + tryLegacyFormats(value, this.legacy, ring); + return { state: "legacy" }; + } catch { + return { state: "invalid" }; + } + } + return { state: "plaintext" }; + } + + /** Count a column's values by state (see classify). `versions` counts + * readable canonical tokens (sealed + unbound) by key version, so a + * rotation is done when it holds only `activeVersion`. For a large table, + * audit each page and sum the counts. */ + audit(values: Iterable, options?: SealOptions): AuditReport { + const ns = this.resolveNs(splitOptions(options).namespace); + const ring = this.rings.get(ns); + if (!ring) throw new KeyNotConfiguredError(`namespace "${ns}" has no key configured; cannot audit.`); + const report: AuditReport = { + total: 0, + activeVersion: ring.activeVersion, + empty: 0, + plaintext: 0, + legacy: 0, + unbound: 0, + unknownVersion: 0, + invalid: 0, + versions: {}, + }; + for (const value of values) { + const { state, version } = this.classify(value, options); + report.total++; + if (state === "sealed" || state === "unbound") report.versions[version!] = (report.versions[version!] ?? 0) + 1; + if (state === "unknown-version") report.unknownVersion++; + else if (state !== "sealed") report[state]++; + } + return report; + } + /** Seal only when a value is present. Convenience for nullable columns. */ maybeSeal(value: string | null | undefined, options?: SealOptions): string | null { if (value == null || value === "") return null; diff --git a/test/audit.test.ts b/test/audit.test.ts new file mode 100644 index 0000000..cfe3e53 --- /dev/null +++ b/test/audit.test.ts @@ -0,0 +1,79 @@ +import { createCipheriv, randomBytes } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { KeyNotConfiguredError, createSealedFields, generateKey } from "../src/index.js"; + +const OLD = generateKey(); +const NEW = generateKey(); +const CTX = ["users", "email"]; + +/** Legacy "iv-ct-tag": ::, no AAD. */ +function ivCtTag(plaintext: string, key: string): string { + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", Buffer.from(key, "base64url"), iv); + const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); + return `${iv.toString("base64")}:${ct.toString("base64")}:${cipher.getAuthTag().toString("base64")}`; +} + +describe("audit", () => { + const before = createSealedFields({ namespaces: { PII: { key: OLD } } }); + const sf = createSealedFields({ + namespaces: { PII: { key: NEW, version: "v2", retired: { v1: OLD } } }, + legacy: ["iv-ct-tag"], + }); + const stranger = createSealedFields({ namespaces: { PII: { key: generateKey() } } }); + + it("classifies every state", () => { + const cases: [string | null, string, string?][] = [ + [null, "empty"], + ["", "empty"], + ["alice@example.com", "plaintext"], + [sf.seal("a", { context: CTX }), "sealed", "v2"], + [before.seal("a", { context: CTX }), "sealed", "v1"], + [sf.seal("a"), "unbound", "v2"], + [ivCtTag("a", OLD), "legacy"], + [ivCtTag("a", generateKey()), "invalid"], + ["v9:" + "A".repeat(40), "unknown-version", "v9"], + [stranger.seal("a", { context: CTX }).replace(/^v1/, "v2"), "invalid", "v2"], + ["v2:AAAA", "invalid", "v2"], + [sf.seal("a", { context: ["contacts", "email"] }), "invalid", "v2"], + ]; + for (const [value, state, version] of cases) { + expect(sf.classify(value, { context: CTX }), String(value)).toEqual(version ? { state, version } : { state }); + } + }); + + it("without a context, a bound token is invalid and an unbound one is sealed", () => { + expect(sf.classify(sf.seal("a", { context: CTX })).state).toBe("invalid"); + expect(sf.classify(sf.seal("a"))).toEqual({ state: "sealed", version: "v2" }); + }); + + it("counts a column, with readable tokens by version", () => { + const column = [ + sf.seal("a", { context: CTX }), + sf.seal("b", { context: CTX }), + before.seal("c", { context: CTX }), + sf.seal("d"), + "plain", + null, + ivCtTag("e", OLD), + "v2:AAAA", + ]; + expect(sf.audit(column, { context: CTX })).toEqual({ + total: 8, + activeVersion: "v2", + empty: 1, + plaintext: 1, + legacy: 1, + unbound: 1, + unknownVersion: 0, + invalid: 1, + versions: { v2: 3, v1: 1 }, + }); + }); + + it("refuses a dormant namespace, even for an empty column", () => { + const dormant = createSealedFields({ namespaces: { PII: {} }, mode: "dormant", logger: { warn: () => {} } }); + expect(() => dormant.audit([])).toThrow(KeyNotConfiguredError); + expect(() => dormant.classify("x")).toThrow(KeyNotConfiguredError); + }); +});