Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
24 changes: 22 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
34 changes: 27 additions & 7 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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 <mpointer@gmail.com>",
Expand Down
4 changes: 2 additions & 2 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion python/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
97 changes: 97 additions & 0 deletions python/src/sealed_fields/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
77 changes: 77 additions & 0 deletions python/tests/test_sealed_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Loading
Loading