Skip to content

fix(vaultcrypto): HKDF rejected a zero-length salt, contrary to RFC 5869 (PRD Phase 3a) - #243

Merged
libravault-xyz merged 4 commits into
devfrom
feat/crypto-known-answer-tests
Aug 17, 2026
Merged

libravault-xyz merged 4 commits into
devfrom
feat/crypto-known-answer-tests

Conversation

@libravault-xyz

Copy link
Copy Markdown
Collaborator

Phase 3 of docs/TEST_COVERAGE_PRD.md, crypto half. Adding the tests found a real conformance bug.

The bug

Hkdf.kt had zero test references anywhere in the repo — an S1 gap in the inventory. It was exercised only indirectly, through vault round-trips, which is exactly the coverage shape that hides a broken KDF: a wrong-but-deterministic HKDF round-trips perfectly and every existing test still passes.

Adding RFC 5869 Appendix A known-answer tests surfaced it immediately:

FAILED: RFC 5869 A_3 handles zero-length salt and info()
java.lang.IllegalArgumentException: Empty key

Hkdf.extract passed the salt straight to SecretKeySpec, which rejects a zero-length key. RFC 5869 §2.2 requires an absent salt be treated as HashLen zero bytes.

Impact: none in production, and provably so

  • The only production caller is deriveFileContentKey, which passes a fixed non-empty salt (verified by grepping every Hkdf.* call site).
  • The empty-salt path previously threw rather than returning a value, so no stored key material can possibly depend on the old behaviour.
  • The golden fixture from test(vault): pin the on-disk vault format across Android and iOS (PRD Phase 2) #238 certifies it: sha256(testdata/vault-format/v1/golden.vault) is byte-identical before and after this change, and all 224 tests across core:vaultcrypto, core:vaultstore, core:vaultcontent and feature:vault still pass.

That is the fixture doing precisely the job it was added for — letting a change to shared crypto be shown safe rather than argued safe.

Why the standard, not just the other platform

iOS never had this gap: it calls CryptoKit.HKDF, which does the substitution itself.

This is the concrete argument for a KAT on top of #238's golden fixture. The fixture proves Android and iOS agree with each other, and by construction cannot notice the hand-rolled implementation diverging from the spec on a path neither platform exercises. Exactly what happened here.

Also in this PR

Added Covers
HkdfKnownAnswerTest.kt RFC 5869 A.1/A.2/A.3 + domain separation, determinism, prefix property
FileContentKeyTest.kt deriveFileContentKey — known vector, per-file isolation, size, rejects wrong-length fileId
VaultCryptoPrimitivesTests.swift iOS deriveFileContentKey, BigEndian, SecureRandom, secureZero — all previously 0 references

A.2 (L=82) is included specifically because it spans three HMAC blocks, catching an off-by-one in the expand counter or the final partial-block copy that a single-block derivation cannot.

The file-content-key vector is a shared constant asserted identically in Kotlin and Swift, pinning the salt/info composition across two different HKDF implementations (hand-rolled vs CryptoKit).

All expected values were computed independently (Python hmac/hashlib) from the documented inputs, not captured from our own output — genuine known-answers, not regression snapshots. My recalled RFC values and the independent computation agreed on all three vectors before anything was committed.

core:vaultcrypto 91.0% → 91.3%; baseline raised.

Review notes

  • Touches core/vaultcrypto/** (sensitive path) — the production change is two lines in Hkdf.extract.
  • The secureZero tests are explicit in their doc comments about what they cannot prove (that the optimizer kept the write, or that no earlier copy survives). SecureZero.swift is candid that it is best-effort; the tests do not overclaim.
  • SecureRandom is not given a randomness-quality test — that would be theatre against the platform CSPRNG. It checks the concrete wrapper bugs: constant output, reused buffer, all-zeros.

Remaining in Phase 3

The Room half — room.schemaLocation, checked-in schemas, and real-SQLite tests for migrations 1→2 … 5→6 — is not in this PR and is still open.

🤖 Generated with Claude Code

libravault-xyz and others added 3 commits August 17, 2026 07:32
dev-agent.yml's triage-crash branch (no PR found yet) only stripped
status:in-progress, leaving status:ready-for-dev in place if the crash
happened after triage self-applied it. Re-triggering the pipeline by
clearing status:needs-info alone would then silently re-fire triage
without a human ever having looked at the issue.

principal-review.yml's crash branch had the same gap for a re-review
round: it stripped status:needs-review but never cleared a stale
status:approved-auto-merge/status:needs-human-merge left over from an
earlier round on the same PR (the verdict path below already does this
cleanup, but crashes skip that path entirely).

Both branches now clear every stale outcome label alongside adding
status:needs-info.

Closes #236

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
PRD Phase 3. Hkdf.kt had zero test references anywhere in the repo (an S1 gap)
— exercised only indirectly through vault round-trips, which is exactly the
coverage shape that hides a broken KDF: a wrong-but-deterministic HKDF
round-trips perfectly and every existing test still passes.

Adding RFC 5869 Appendix A known-answer tests found a real conformance bug.
`Hkdf.extract` passed the salt straight to SecretKeySpec, which rejects a
zero-length key with `IllegalArgumentException: Empty key`, so vector A.3
(zero-length salt and info) threw instead of deriving. RFC 5869 §2.2 requires
an absent salt be treated as HashLen zero bytes.

Not exploitable, and not a behaviour change for this app: the only production
caller (deriveFileContentKey) passes a fixed non-empty salt, and the
empty-salt path previously *threw* rather than returning a value, so no stored
key material can depend on the old behaviour. The golden vault fixture proves
it: its sha256 is byte-identical before and after this change, and all 224
tests across the four vault modules still pass.

iOS never had this gap — it calls CryptoKit.HKDF, which does the substitution
itself. Which is the point of testing against the standard rather than only
against the other platform: PR #238's golden fixture proves Android and iOS
agree with each other, and by construction cannot notice both of them (or, as
here, the hand-rolled one) diverging from the spec on a path neither exercises.

Also adds direct tests for deriveFileContentKey on both platforms, and for the
iOS primitives that had zero references — BigEndian, SecureRandom, secureZero.
The file-content-key vector is a shared constant asserted identically in
Kotlin and Swift, pinning the salt/info composition across two different HKDF
implementations (hand-rolled vs CryptoKit).

All expected values were computed independently (Python hmac/hashlib) from the
documented inputs, not captured from our own output, so they are genuine
known-answers rather than regression snapshots.

core:vaultcrypto 91.0% -> 91.3%; baseline raised.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…QLite

PRD Phase 3, Room half.

Six migrations exist; two had execution coverage. MIGRATION_4_5 was tested
against a *mocked* SupportSQLiteDatabase asserting SQL substrings — which
verifies the string looks right, not that SQLite accepts it — and only
MIGRATION_6_7 ran for real. Migrations 1→2, 2→3, 3→4 and 5→6 had none.

Adds MigrationChainTest: builds a real v1 database, seeds every v1 table, and
lets Room apply all six migrations in sequence, then asserts

  - the chain completes and passes Room's own schema validation (via a real
    query, since Room only validates when one runs — merely opening the
    database would pass against a broken schema),
  - v1 rows survive with correct values, and columns added mid-chain carry
    their declared defaults,
  - tables introduced mid-chain (highlights at 1→2, collections at 2→3) exist
    and accept writes at v7,
  - the CASCADE deletes on those tables are actually in force afterwards, not
    merely present in the DDL text.

A chain rather than four isolated tests, deliberately: the sequence is what
users execute — someone opening an old install after a long gap — and isolated
tests cannot catch an interaction between migrations.

Also fixes exportSchema being a no-op. LibravaultDatabase declares
exportSchema = true, but without room.schemaLocation Room had nowhere to write
and silently exported nothing, which is why core/database/schemas/ did not
exist. 7.json is now generated and committed, so from v7 onward Room validates
migration end-states at build time and MigrationTestHelper can construct any
exported version. It cannot help retroactively for v1..v6 — those schemas were
never exported — which is exactly why the chain test derives v1 instead.

The v1 DDL is derived, not guessed: migrations are the complete record of
schema change, so v1 = the verbatim v6 capture already in
Migration6To7RealExecutionTest minus precisely what migrations 1→6 add.

Writing this caught one of my own wrong assumptions rather than a product bug:
markdownScrollOffset is transient. 5→6 adds it as INTEGER pixels, 6→7 replaces
it with markdownScrollFraction (REAL) and sets it NULL for every migrated row,
because a pixel offset cannot be converted to a fraction without the document
height. The test now asserts that deliberate behaviour, verified against the
newly-exported schema.

core:database 63.3% -> 67.4%.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: FAILED

❌ iOS Simulator Build & Unit Tests - cancelled
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@libravault-xyz

Copy link
Copy Markdown
Collaborator Author

Update: the Room half of Phase 3 is now in this PR too, so Phase 3 is complete rather than split.

Room migrations

Six migrations existed; two had execution coverage. MIGRATION_4_5 was tested against a mocked SupportSQLiteDatabase asserting SQL substrings — that verifies the string looks right, not that SQLite accepts it. Migrations 1→2, 2→3, 3→4 and 5→6 had none at all.

MigrationChainTest builds a real v1 database, seeds every v1 table, and lets Room apply all six migrations in sequence. It asserts:

  • the chain completes and passes Room's own schema validation — via a real query, because Room only validates when one runs, so a test that merely opened the database would pass against a broken schema;
  • v1 rows survive with correct values, and mid-chain columns carry their declared defaults;
  • tables introduced mid-chain (highlights at 1→2, collections at 2→3) exist and accept writes at v7;
  • the CASCADE deletes on those tables are actually in force afterwards, not just present in the DDL text.

A chain rather than four isolated tests, deliberately: the sequence is what users execute (an old install opened after a long gap), and isolated tests cannot catch an interaction between migrations.

exportSchema was a no-op

LibravaultDatabase declares exportSchema = true, but without room.schemaLocation Room had nowhere to write and silently exported nothing — which is why core/database/schemas/ did not exist despite the annotation claiming it should. 7.json is now generated and committed, so from v7 onward Room validates migration end-states at build time and MigrationTestHelper can construct any exported version.

It cannot help retroactively for v1..v6 — those schemas were never exported and reconstructing them would mean checking out historical revisions. That is precisely why the chain test derives v1, and the derivation is sound rather than guessed: migrations are the complete record of schema change, so v1 = the verbatim v6 capture already in Migration6To7RealExecutionTest minus exactly what migrations 1→6 add.

One thing worth flagging

Writing this caught my own wrong assumption, not a product bug. markdownScrollOffset is transient: 5→6 adds it as INTEGER pixels, and 6→7 replaces it with markdownScrollFraction (REAL), setting it NULL for every migrated row — a pixel offset cannot be converted to a fraction without knowing the document height. My first assertion expected the old column at v7 and failed. The test now asserts that deliberate behaviour, verified against the newly-exported schema.

Notably the headline chain test passed all along, which is what told me the failure was my assumption rather than the migrations.

core:database 63.3% → 67.4%.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Unit Tests - success
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

All five S1 gaps from the original inventory are now closed:
cross-platform vault interop (#238), HKDF known-answer coverage (this PR),
the dead emulator gate and the never-run TTS gate (#222/#226), and dev
branch protection (#222).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Unit Tests - success
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

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.

1 participant