Skip to content

Add v2 post-quantum hybrid HPKE (MLKEM1024-P384) scheme - #267

Merged
thepwagner merged 5 commits into
Shopify:mainfrom
missing-piece:pqc-v2
Dec 4, 2026
Merged

thepwagner merged 5 commits into
Shopify:mainfrom
missing-piece:pqc-v2

Conversation

@missing-piece

@missing-piece missing-piece commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Draft / WIP: Building on #250 (@burke's pqc branch) as an iterative starting point for post-quantum EJSON v2. Do not merge until the final suite and wire-format decisions are signed off.

Summary

Adds an opt-in v2 post-quantum hybrid scheme alongside existing v1 (EJ[1:...]) using Go 1.26+ standard library crypto/hpke (zero new external dependencies):

  • Suite: RFC 9180 HPKE Base Mode with MLKEM1024-P384 (KEM 0x0051, draft-ietf-hpke-pq), HKDF-SHA384 (0x0002), and ExportOnly (0xFFFF), exporting a 32-byte AES-256-GCM data key per edit session.
  • Public key & Key ID (<= 253 chars):
    • _public_key: "v2:<base64 of 1,665-byte MLKEM1024-P384 public key>" (preserves offline encrypt-to-public-key; existing v1 binaries fail closed).
    • Key ID: "ejv2-" + hex(SHA-384(pubkey_bytes)) (101 chars — fits filesystem NAME_MAX 255, GCP Secret Manager secret IDs 255, and Kubernetes Secret keys 253, and stays distinct from v1 64-hex keys). Derived from _public_key rather than stored separately.
    • Private key: compact 32-byte RFC 9180 HPKE seed (64 lowercase hex chars), stored at <keydir>/<key_id>, derived & verified against _public_key on decrypt.
  • Per-edit-session encapsulation (avoids per-value ~2.2 KB bloat):
    • Each ejson encrypt run that encrypts ≥1 plaintext value performs one HPKE encapsulation and writes "_ejson_v2_session_<sid>": "<base64(enc)>" (sid = hex(SHA-384(enc)[:16])), spliced in place without reformatting or reordering keys (json/metadata.go).
    • Distinct session IDs let the records from both branches coexist. Git can still report a conflict when both branches insert a session field at the same place; keep both session fields and their corresponding encrypted values when resolving it. ejson encrypt prunes unreferenced session fields.
    • Values are encoded as EJ[2:<sid>:<n>:<base64(AES-256-GCM(k, nonce=be96(n), pt, aad="EJ[2:<sid>:<n>:"))>].
  • Fail-closed checks & migration:
    • Decrypt refuses EJ[1:...] in a v2 file, EJ[2:...] in a v1 file, missing session fields, mismatched seeds, and duplicate (sid, n) pairs (nonce reuse).
    • Adds ejson keygen --pqc / --scheme v2 (-w writes <keydir>/ejv2-<sha384> with mode 0400) and ejson reencrypt [--to-public-key <pub>] for whole-file v1→v2 migration and session compaction.
    • Checked-in known-answer + tamper test vectors in testdata/v2_vectors.json for cross-language readers.

What changed vs. PR #250

  • Renumbered v3 → v2 (EJ[2:...]) per @thepwagner's review on add v3 X25519 + ML-KEM-768 scheme #250.
  • Replaced custom HKDF-SHA256 / X25519+ML-KEM-768 / XChaCha20-Poly1305 combiner with stdlib crypto/hpke MLKEM1024P384() + HKDFSHA384() + ExportOnly() + AES-256-GCM.
  • Moved from per-value encapsulation (~2.2 KB/value) to per-edit-session encapsulation (_ejson_v2_session_<sid>).
  • Widened Key ID from truncated 128-bit SHA-256 (32 hex) to prefixed ejv2- + full SHA-384 (101 chars), with 64-hex seed private keys.
  • Added format-preserving metadata editing, unreferenced session pruning, reencrypt --to-public-key, duplicate-nonce rejection, and testdata/v2_vectors.json.

Verification

Run with Go 1.27.4:

  • go vet ./...: pass
  • go test -race -cover ./...: all 4 packages pass (ejson 82.3%, cmd/ejson 17.2%, crypto 70.0%, json 81.3%)
  • go test -bench=BenchmarkCore1700Values -benchmem -cpu=1 -run='^$' . (1,700 secrets, single core):
Operation (1,700 values, 1 core) v1 (EJ[1:) v2 (EJ[2: + 1 session)
File size 314,588 B (+120.0 B/val) 249,917 B (+80.7 B/val)
Encrypt 6.69 ms 8.08 ms
Decrypt 95.21 ms 5.86 ms (16× faster)

@r0mdau r0mdau left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. The crypto looks right to me: stdlib crypto/hpke with MLKEM1024-P384, the key ID bound into the HPKE info, a fresh data key per session with counter nonces, the private seed verified against the public key, and old binaries failing closed on v2 files.

Before this merges it is interesting to see:

  1. The v1 regression fixed, where a value shaped like EJ[1:...] is left in plaintext.
  2. reencrypt --to-public-key rejecting a duplicate _public_key. Today it reports success and keeps the old recipient.
  3. Copied encrypted values handled at encrypt time. Encrypt accepts them and decrypt fails, for a copy within a file and for a value whose session field is missing.
  4. The merge-conflict claim corrected. Two branches that each add a secret do conflict on the session line, though keeping both lines resolves it.

Comment thread ejson.go Resolved
Comment thread ejson.go Resolved
Comment thread crypto/hybrid.go Resolved
Comment thread ejson.go Resolved
@thepwagner

Copy link
Copy Markdown
Contributor

We found these issues in our review too and are already working on fixes. No action needed from Javier or his agent on this.

@thepwagner
thepwagner marked this pull request as ready for review December 3, 2026 16:52
@thepwagner
thepwagner requested a review from a team as a code owner December 3, 2026 16:52

@r0mdau r0mdau left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LG for the fixes.

One question: encrypt and decrypt still accept a duplicate _public_key and use the last one. That matches main for v1, so I assume it is intentional. Is it worth rejecting for v2 files?

Comment thread ejson.go Resolved
Comment thread crypto/boxed_message.go Resolved
@cryptaliagy

Copy link
Copy Markdown

Since it's already built I don't know if there's necessarily any value in changing it at this point, but we could have kept the XChaCha20-Poly1305 piece as it was since it's a lateral move as far as security goes compared to AES-256. I'm updating the draft guidance now to prevent additional false-positives of this low-priority work (they both have the same bits of security, but AES-256 is the only CNSA 2.0 approved because AES is the main approval source).

So far looks good to me, just waiting on a final reporting from my robot about it. I'm somewhat suspicious about the decryption speeds and want to make sure something is accounting for all the 'why' parts of it

Comment thread ejson.go Resolved
Comment thread ejson.go Resolved
Comment thread ejson.go Resolved
Comment thread json/key.go Resolved
kyli
kyli previously approved these changes Dec 3, 2026
missing-piece added a commit to missing-piece/ejson that referenced this pull request Dec 4, 2026
… skipped fields

- Require canonical positive decimal schema versions in parseBoxedEnvelope (rejecting EJ[02:...], EJ[+2:...], EJ[01:...], EJ[0:...], EJ[-1:...]) and align IsHybridBoxedMessage with loadHybridBoxedMessage (including rejecting embedded CR/LF in base64).
- Clarify the intentional v1/v2 separation exception in legacyMessageParser and ejson_v1_compat_test.go, and test that non-canonical EJ[02:...] is sealed in v1.
- Reject duplicate top-level _public_key fields on v2 encrypt/decrypt/reencrypt (ErrPublicKeyDuplicate) while keeping pure-v1 last-wins compatibility on encrypt/decrypt.
- Unify ExtractSessions across readers and writers so both reject malformed (ErrSessionInvalid) and duplicate (ErrSessionDuplicate) session records, and reject trailing non-whitespace JSON tokens, whitespace-padded public keys, and newline-padded base64 in public keys/sessions.
- Add json.SkippedHybridSessionRefs mirroring Walker's underscore scoping: Encrypt pruning preserves sessions still referenced under _-prefixed keys, and Reencrypt refuses (naming the key path and session ID) before dropping any session still referenced under a _-prefixed key.
@missing-piece

Copy link
Copy Markdown
Contributor Author

Addressed all open review comments in 2efda9b and added property-based testing with pgregory.net/rapid in 8e33178:

  • Decryption speed (~15–16× faster than v1 on 1,700 values): In v1 (crypto/crypto.go:153), every value carries its own ephemeral X25519 public key, so Decrypter.Decrypt performs 1,700 separate Curve25519 scalar multiplications (box.Open without precomputation) + 1,700 XSalsa20-Poly1305 openings (~98 ms single-core). In v2, HPKE decapsulation (MLKEM1024-P384 + HKDF-SHA384) runs once per session (1 decapsulation for the whole 1,700-value file) and all 1,700 values are then decrypted with AES-NI AES-256-GCM (~6.4 ms single-core).
  • Review fixes (2efda9b):
    • Canonical positive decimal schema versions only in parseBoxedEnvelope (rejects EJ[02:...], EJ[+2:...], EJ[01:...], EJ[0:...], EJ[-1:...]) and aligned IsHybridBoxedMessage with loadHybridBoxedMessage.
    • Documented and pinned the v1/v2 separation exception in crypto/boxed_message.go and ejson_v1_compat_test.go.
    • Fail closed on duplicate _public_key for v2 Encrypt/Decrypt/Reencrypt (ErrPublicKeyDuplicate) and unified ExtractSessions so Decrypt and Encrypt/Reencrypt both reject malformed (ErrSessionInvalid) and duplicate (ErrSessionDuplicate) session fields.
    • json.SkippedHybridSessionRefs: Encrypt pruning keeps sessions referenced under _-prefixed keys, and Reencrypt refuses (naming the key path and session ID) before dropping any session still referenced under a _-prefixed key.
    • Additional edge-case hardening found during audit: rejected whitespace-padded public keys in ParsePublicKeyString (matching legacy ExtractPublicKey), rejected embedded CR/LF in base64 for v2 public keys / sessions / ciphertexts, and rejected trailing non-whitespace tokens after the root JSON object in metadata parsers.
  • Property-based & stateful tests (8e33178): Added pgregory.net/rapid suites across crypto, json, and ejson (envelope canonicalization, key/session/AEAD invariants, format-preserving metadata edits, Walker vs SkippedHybridSessionRefs exact partition/path/order parity, fail-closed duplicate/trailing checks, v1 skip/seal/separation boundary, nested round-trips, concurrent branch merges, and a multi-session document state machine). Full go test -count=1 ./... completes in ~1.0s (~7.1s with -race -cover).

missing-piece and others added 5 commits December 4, 2026 06:18
Build on PR Shopify#250's hybrid scheme exploration, updated to Go 1.26+ stdlib
crypto/hpke and per-edit-session encapsulation:

- Schema v2 (EJ[2:<sid>:<n>:<ct>]) using RFC 9180 HPKE Base Mode
  (MLKEM1024-P384 KEM 0x0051, HKDF-SHA384, Export-Only AEAD 0xFFFF)
  exporting a 32-byte AES-256-GCM session data key with counted 96-bit
  big-endian nonces and AAD = "EJ[2:<sid>:<n>:".
- Key ID derived as "ejv2-" + lowercase hex SHA-384(pubkey) (101 chars),
  keeping keydir filenames, Secret Manager secret IDs (<=255), and
  Kubernetes Secret keys (<=253) under length limits while keeping v2
  names distinct from v1 64-hex keys. Private key stays a compact
  32-byte RFC 9180 seed (64 hex chars), verified against _public_key.
- One HPKE encapsulation per edit session stored in top-level
  _ejson_v2_session_<sid> (sid = SHA-384(enc)[:16] hex), preserving
  offline public-key encryption without merge conflicts and pruning
  unreferenced sessions.
- Strict v1/v2 separation per file, duplicate (sid, n) nonce rejection,
  `ejson keygen --pqc` / `--scheme v2`, `ejson reencrypt [--to-public-key]`,
  and cross-language known-answer test vectors in testdata/v2_vectors.json.
Restore the legacy v1 skip boundary and always seal decrypted values for the target recipient. Preserve v1 application fields on rotation, and reject ambiguous recipients and migration collisions before writing.

Validate v2 session records before pruning and in the final output. Reject missing sessions, repeated session/counter pairs and ciphertext shorter than the authentication tag. Exercise the production writer with known-answer vectors and regression tests for byte-preserving refusal.
… skipped fields

- Require canonical positive decimal schema versions in parseBoxedEnvelope (rejecting EJ[02:...], EJ[+2:...], EJ[01:...], EJ[0:...], EJ[-1:...]) and align IsHybridBoxedMessage with loadHybridBoxedMessage (including rejecting embedded CR/LF in base64).
- Clarify the intentional v1/v2 separation exception in legacyMessageParser and ejson_v1_compat_test.go, and test that non-canonical EJ[02:...] is sealed in v1.
- Reject duplicate top-level _public_key fields on v2 encrypt/decrypt/reencrypt (ErrPublicKeyDuplicate) while keeping pure-v1 last-wins compatibility on encrypt/decrypt.
- Unify ExtractSessions across readers and writers so both reject malformed (ErrSessionInvalid) and duplicate (ErrSessionDuplicate) session records, and reject trailing non-whitespace JSON tokens, whitespace-padded public keys, and newline-padded base64 in public keys/sessions.
- Add json.SkippedHybridSessionRefs mirroring Walker's underscore scoping: Encrypt pruning preserves sessions still referenced under _-prefixed keys, and Reencrypt refuses (naming the key path and session ID) before dropping any session still referenced under a _-prefixed key.
…invariants

Add pgregory.net/rapid property-based and stateful tests covering:
- Canonical boxed envelope parsing, mutual exclusion, key derivation/session parsing, and AEAD round-trip/tamper/duplicate-nonce checks (crypto/hybrid_prop_test.go).
- Format-preserving metadata edits, Walker vs SkippedHybridSessionRefs exact partition/path/order parity, and fail-closed duplicate/trailing-garbage checks (json/metadata_prop_test.go).
- Nested document round-trips (including raw multiline literals and v2<->v1<->v2 rotation), v1 skip/seal/separation boundary, multi-session state machine (rename-to-underscore pruning, backup promotion, reencrypt refusal, adversarial mutations), and concurrent branch merges (ejson_v2_prop_test.go).
@thepwagner
thepwagner merged commit b49b20c into Shopify:main Dec 4, 2026
1 check passed
@thepwagner thepwagner mentioned this pull request Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants