Skip to content

fix(encryption)!: resolve tenant_id once for HKDF and AAD (LAB-4668) - #133

Merged
27Bslash6 merged 3 commits into
mainfrom
lab-4668-ts-tenant-aad-hkdf-mismatch
Sep 25, 2026
Merged

27Bslash6 merged 3 commits into
mainfrom
lab-4668-ts-tenant-aad-hkdf-mismatch

Conversation

@27Bslash6

@27Bslash6 27Bslash6 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Overview

EncryptionManagerCore used two independent fallbacks for an unconfigured tenantId: tenantId ?? 'default' when calling deriveTenantKeys (HKDF), and tenantId ?? '' when assembling the AAD in buildAAD. Ciphertext produced by a secure() client with no tenant configured was therefore keyed to "default" but bound to "", and could not authenticate against a spec-conformant reader.

Changes

  • packages/cachekit/src/encryption/manager-core.ts
    • Added a private readonly effectiveTenantId: string field, assigned once in the constructor as tenantId ?? 'default'.
    • The constructor parameter tenantId is no longer a private readonly property — the raw, unresolved value is no longer retained on the instance, eliminating any path to a second fallback.
    • deriveTenantKeys and buildAAD now both read this.effectiveTenantId; the local effectiveTenantId variable previously computed inside the init path was removed.

Constructor signature and arity are unchanged; tenantId remains string | undefined and externally optional. The only observable API change is the removal of the internal tenantId property from the instance shape.

Test Coverage

manager-core.test.ts adds a decodeAadTenantId helper that parses component 1 out of the serialized AAD (4-byte big-endian length prefix at offset 1, payload at offset 5) and two regression cases asserting that the tenant ID passed to deriveTenantKeys matches the tenant component of the AAD handed to encryptWithTenantKeys — verified for both the unset ("default") and explicitly configured ("acme-corp") cases.

Compatibility

Entries written by an unconfigured-tenant secure client prior to this change carry AAD tenant "". Decryption now rebuilds the AAD with "default", so the AES-GCM tag verification fails. No read-side fallback to the legacy AAD is implemented; affected cache entries must be invalidated.


Summary

Strengthens encryption test coverage for the default tenant identifier, addressing LAB-4668 (tenant_id mismatch between HKDF key derivation and AAD construction).

Changes

packages/cachekit/src/encryption/manager.integration.test.ts

The edge-case test for an unset tenant ID has been rewritten from a same-instance round-trip to a cross-instance compatibility check:

  • Instantiates two managers with the same key — one with no tenant ID, one with an explicit 'default'.
  • Verifies ciphertext produced by either manager decrypts correctly with the other, in both directions.
  • Both instances are disposed in the finally block.

Rationale

A single-manager encrypt/decrypt round-trip cannot detect a discrepancy between the tenant value used for HKDF derivation and the one embedded in the AAD, since both operations share the same (possibly inconsistent) resolution path. Exercising the boundary between an unset tenant and an explicit 'default' — the value written by the Python and Rust implementations — validates that the resolved tenant identifier is consistent across key derivation and authenticated data, preserving cross-language payload interoperability.

API Impact

None. The change is confined to test code; no public interfaces were modified.

Breaking change

BREAKING CHANGE: a secure cache created without a tenantId now binds tenant "default" into the AES-GCM AAD instead of "". That is the value HKDF already derived its key from and the value the protocol requires, so a tenant-less cachekit-ts secure cache now shares ciphertext with cachekit-py and cachekit-rs on tenant "default". Caches with an explicit tenantId are unaffected.

Entries written by a tenant-less secure cache on @cachekit-io/cachekit 0.1.5 or earlier no longer authenticate, so every read of one fails decryption. To migrate, delete those entries (or switch to a fresh namespace or key prefix) once no pre-upgrade instance is still writing; during a rolling upgrade, old and new instances cannot read each other's entries. Do not wait out the TTL instead. Under the secure preset's default reliability settings, each undecryptable read is retried and counted as a circuit-breaker failure, so five within a minute open the breaker, and while it is open every read misses and every write is dropped, for all keys.

BEGIN_COMMIT_OVERRIDE
fix(encryption)!: resolve tenant_id once for HKDF and AAD (LAB-4668) (#133)

BREAKING CHANGE: a secure cache created without a tenantId now binds tenant "default" into the AES-GCM AAD instead of "". That is the value HKDF already derived its key from and the value the protocol requires, so a tenant-less cachekit-ts secure cache now shares ciphertext with cachekit-py and cachekit-rs on tenant "default". Caches with an explicit tenantId are unaffected. Entries written by a tenant-less secure cache on @cachekit-io/cachekit 0.1.5 or earlier no longer authenticate, so every read of one fails decryption. To migrate, delete those entries (or switch to a fresh namespace or key prefix) once no pre-upgrade instance is still writing; during a rolling upgrade, old and new instances cannot read each other's entries. Do not wait out the TTL instead. Under the secure preset's default reliability settings, each undecryptable read is retried and counted as a circuit-breaker failure, so five within a minute open the breaker, and while it is open every read misses and every write is dropped, for all keys.
END_COMMIT_OVERRIDE

manager-core.ts derived HKDF keys with `tenantId ?? 'default'` but built
the AAD tenant component with `tenantId ?? ''` - two independent
fallbacks for the same value. With no tenantId configured, secure()
ciphertext was bound to AAD tenant "" while the key was derived for
"default", so it can never authenticate against a conformant py/rs
reader (spec/intent-presets.md section Master Key Input, rule 5).

Hoists a single effectiveTenantId field, resolved once in the
constructor, and reads it from both call sites - no second ?? fallback
remains.

BREAKING CHANGE: existing secure() ciphertext written by cachekit-ts
with no tenantId configured used AAD tenant "" and will fail
authentication after this fix (the key is now correctly derived and
bound to "default" everywhere). Zero-knowledge caches hold no
irreplaceable state - flush/invalidate secure-preset entries written by
an unconfigured-tenant cachekit-ts client before upgrading; there is no
read-fallback for the old AAD.
…4668)

Expert-panel follow-up on the tenant_id single-resolution fix:

- Drop the "private readonly" modifier on the tenantId constructor
  parameter. Nothing read it after construction once effectiveTenantId
  existed, and a dead field with a name one character off from the
  resolved value is exactly the ambiguity the original bug came from.
- Trim the effectiveTenantId JSDoc to one line; the ticket narrative
  belongs in the PR, not permanently embedded as a comment block.
- Drop the redundant third assertion in the new regression test - it
  was implied by the two literal-equality assertions preceding it.

Spec citation (spec/intent-presets.md Master Key Input rule 5) verified
against cachekit-io/protocol main this pass.
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Warning

Review limit reached

Next included review available in 45 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 110 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository: cachekit-io/cachekit-ts/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Team

Run ID: 0ddaaaa1-ee87-4c97-85aa-554b72efb904

📥 Commits

Reviewing files that changed from the base of the PR and between 6485ff7 and 6df8d68.

📒 Files selected for processing (1)
  • packages/cachekit/src/encryption/manager.integration.test.ts

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: cachekit-io/cachekit-ts/.coderabbit.yaml

Review profile: ASSERTIVE

Plan: Team

Run ID: 35697f39-13c4-444b-a926-031d24436f00

📥 Commits

Reviewing files that changed from the base of the PR and between 2ab042f and 6485ff7.

📒 Files selected for processing (2)
  • packages/cachekit/src/encryption/manager-core.test.ts
  • packages/cachekit/src/encryption/manager-core.ts

Included review availability: 0 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 1 review per hour.


Walkthrough

Changes

Tenant ID consistency

Layer / File(s) Summary
Normalise and verify tenant ID
packages/cachekit/src/encryption/manager-core.ts, packages/cachekit/src/encryption/manager-core.test.ts
EncryptionManagerCore stores tenantId ?? 'default' and uses it for HKDF derivation and AAD construction. Tests cover the default tenant ID and the configured acme-corp tenant ID.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 6485f

The encryption preset now consistently uses the protocol default tenant ID. Existing cache entries created with the former unset-tenant behavior require the stated invalidation before upgrade, but no actionable implementation risk remains in the reviewed change.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: resolving the tenant ID once and reusing it for HKDF and AAD. It includes the relevant issue reference and accurately signals a breaking change.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Sep 23, 2026
@27Bslash6

Copy link
Copy Markdown
Contributor Author

@kody start-review

@kodus-27b

kodus-27b Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

Kody Code Review — 2 suggested fixes.
Paste the prompt below to your agent and all review fixed at once!

🛠️ Open Agent Prompt
A code review identified the following issues in this pull request.
Each section describes what was found and includes a reference implementation where available.

Files involved:
- packages/cachekit/src/encryption/manager-core.ts:377
- packages/cachekit/src/encryption/manager-core.ts:140

---

### [1/2] packages/cachekit/src/encryption/manager-core.ts:377
Issue identified during code review:
AAD format change in manager-core.ts: The AAD component for tenant now encodes `this.effectiveTenantId` (which falls back to `'default'`) instead of the previous `this.tenantId ?? ''`, making all existing ciphertexts for tenant-less deployments undecryptable. Add a 'BREAKING CHANGE' section to the PR describing the AAD format change, affected consumers (caches encrypted without an explicit tenantId), and a migration path such as versioning the AAD, trying legacy '' AAD on decrypt failure, or forcing cache invalidation/rotation.

---

### [2/2] packages/cachekit/src/encryption/manager-core.ts:140
Issue identified during code review:
Missing test coverage in manager-core.ts: This change alters runtime behavior for tenant key derivation and AAD with a 'default' fallback but lacks accompanying test updates, leaving high-risk encryption changes without regression coverage. Add tests covering construction with `tenantId === undefined` to assert the derived key and AAD use 'default' and that round-trip encrypt/decrypt works, or document `no-tests: <reason>` in the PR description.

---

Review each issue in context, use the reference implementations as guidance, and apply fixes that are consistent with the surrounding codebase.

Comment thread packages/cachekit/src/encryption/manager-core.ts
Comment thread packages/cachekit/src/encryption/manager-core.ts
…t" (LAB-4668)

The existing real-crypto edge case round-tripped on one instance, which
passes even with the HKDF/AAD tenant mismatch this PR fixes: the same
instance binds the same wrong AAD on both sides. Encrypting with an
unset-tenant manager and decrypting with an explicit 'default' manager
(and back) is what a py/rs reader does; verified to fail with
"Authentication verification failed" against the pre-fix manager-core.ts.
@27Bslash6 27Bslash6 changed the title fix(encryption): resolve tenant_id once for HKDF and AAD (LAB-4668) fix(encryption)!: resolve tenant_id once for HKDF and AAD (LAB-4668) Sep 23, 2026
@27Bslash6

Copy link
Copy Markdown
Contributor Author

@kody start-review

@kodus-27b

kodus-27b Bot commented Sep 23, 2026

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the `@kody start-review` command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Providing Context (Files & MCPs)

Add these hints in your PR description (or a comment) to unlock deeper checks:

  • Ticket / Acceptance Criteria: `Refs: ABC-123` (Linear/Jira/Asana/ClickUp/Trello) or a direct ticket link.
  • Bugfix Validation: a Sentry/Datadog/Bugsnag event link (or paste the stack trace/error message).
  • Endpoint Risk: mention the route (e.g., `POST /api/payments`) or controller/action name.
  • Attach a repo file as context: use an explicit marker like `@file:docs/guide.mdx#L10-L50` (replace with your real path).
  • API Contract Docs: include `@file:openapi.yaml` or `@file:swagger.json` when changing routes/schemas.
  • Definition of Done / Standards: include `@file:DOD.md` or `@file:CONTRIBUTING.md` if your repo has them.
  • Design System Source of Truth: include `@file:ui/index.ts` (replace with your DS entrypoint path).
  • Feature Flags: include the flag key/name and `@file:flags.ts` / `@file:config.json` (and optionally the PostHog flag name).
  • Edge/CDN Rules: link the Cloudflare rule/zone or describe the intended redirect/header behavior.
  • Attach an MCP tool output: use `@mcp<provider|tool>` (replace with an installed MCP provider + tool, e.g., `@mcp<sentry|events.search>`).
Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

@27Bslash6
27Bslash6 merged commit 8bb5269 into main Sep 25, 2026
21 of 23 checks passed
@27Bslash6
27Bslash6 deleted the lab-4668-ts-tenant-aad-hkdf-mismatch branch September 25, 2026 10:23
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