Skip to content

[_]: feat(email): update email encryption structure and handling#90

Merged
xabg2 merged 1 commit into
masterfrom
refactor/remove-trial-decryption
Jul 15, 2026
Merged

[_]: feat(email): update email encryption structure and handling#90
xabg2 merged 1 commit into
masterfrom
refactor/remove-trial-decryption

Conversation

@jzunigax2

@jzunigax2 jzunigax2 commented Jul 14, 2026

Copy link
Copy Markdown
Contributor
  • Removed trial decryption logic
  • Changed the version of the EncryptionBlock from 'v1' to 'v2' to reflect changes.
  • Updated the projectForCaller function to use previewWrappedKeys instead of wrappedKeys, enhancing clarity on key usage.
  • Modified the EmailService to accommodate the new encryption structure, ensuring proper handling of encrypted previews and keys.
  • Adjusted related DTOs and tests to align with the updated encryption model, improving overall consistency and functionality.

Summary by CodeRabbit

  • New Features

    • Improved encrypted email previews by selecting wrapped keys for the intended recipient.
    • Added recipient email metadata to encrypted keys.
    • Introduced encryption format v2 with dedicated preview key support.
    • Improved external delivery of encrypted emails with unified payload and attachment decryption.
  • Bug Fixes

    • Invalid encrypted payloads now produce a clear request error.
    • Updated encrypted email summaries and threads to use preview-specific key data.

- Changed the version of the EncryptionBlock from 'v1' to 'v2' to reflect new features.
- Updated the `projectForCaller` function to use `previewWrappedKeys` instead of `wrappedKeys`, enhancing clarity on key usage.
- Modified the `EmailService` to accommodate the new encryption structure, ensuring proper handling of encrypted previews and keys.
- Adjusted related DTOs and tests to align with the updated encryption model, improving overall consistency and functionality.
@jzunigax2 jzunigax2 requested a review from xabg2 July 14, 2026 23:48
@jzunigax2 jzunigax2 self-assigned this Jul 14, 2026
@jzunigax2 jzunigax2 added the enhancement New feature or request label Jul 14, 2026
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The email encryption contract is upgraded to v2 with recipient-labeled wrapped keys and preview-specific keys. Caller projections and encryption metadata use preview keys, while external delivery decrypts a JSON payload containing the body and attachment session key.

Email encryption v2

Layer / File(s) Summary
Encryption v2 contracts and caller projection
src/modules/email/email.dto.ts, src/modules/email/email.types.ts, src/modules/email/email-encryption.ts, test/fixtures.ts, src/modules/email/*.spec.ts
DTOs and types replace attachmentWrappedKeys with previewWrappedKeys, add recipient email metadata, and update projections, fixtures, and metadata assertions.
Server decryption API
src/modules/email/server-crypto.ts, src/modules/email/server-crypto.spec.ts
Hybrid body decryption now receives complete wrapped-key objects, and the attachment-key unwrapping API and related tests are removed.
External delivery payload flow
src/modules/email/email.service.ts, src/modules/email/email.service.spec.ts
External delivery parses decrypted JSON payloads for the body and attachment session key, then derives attachment decryption from that session key.
Estimated code review effort: 3 (Moderate) ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant EmailService
  participant decryptBody
  participant PayloadEnvelope
  participant decryptAttachmentsForExternalDelivery
  EmailService->>decryptBody: decrypt encrypted payload
  decryptBody-->>EmailService: JSON payload text
  EmailService->>PayloadEnvelope: parse body and attachmentsSessionKey
  PayloadEnvelope-->>EmailService: decrypted body and session key
  EmailService->>decryptAttachmentsForExternalDelivery: decrypt attachments with session key
  decryptAttachmentsForExternalDelivery-->>EmailService: decrypted attachments
Loading

Suggested reviewers: xabg2

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: updated email encryption structure and handling.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/remove-trial-decryption

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/modules/email/email.service.ts (1)

244-266: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Validate the parsed payload envelope shape, not just JSON syntax.

The catch only handles JSON.parse syntax errors. If the decrypted text is valid JSON but missing/wrong-typed body (e.g. {}), payload.body is undefined, and htmlBody (Line 195) silently falls back to dto.htmlBody — which is typically absent for an encrypted send, resulting in an email delivered with no body content instead of a clear error.

🛡️ Suggested fix
     try {
-      return JSON.parse(text) as {
-        body: string;
-        attachmentsSessionKey?: string;
-      };
+      const parsed = JSON.parse(text) as {
+        body?: unknown;
+        attachmentsSessionKey?: unknown;
+      };
+      if (typeof parsed.body !== 'string') {
+        throw new Error('missing body');
+      }
+      return parsed as { body: string; attachmentsSessionKey?: string };
     } catch {
       throw new BadRequestException(
         'Encrypted payload is not a valid body envelope',
       );
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/modules/email/email.service.ts` around lines 244 - 266, Update
decryptPayloadForExternalDelivery to validate the parsed JSON envelope before
returning it: require a string body and, when present, a string
attachmentsSessionKey. Treat missing or incorrectly typed fields like JSON parse
failures by throwing BadRequestException, preventing encrypted sends from
falling back to an empty body.
src/modules/email/email.service.spec.ts (1)

130-164: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test override no longer exercises what it's testing.

envelope overrides body-level wrappedKeys with two entries, but the assertion at Line 159 checks envelope.previewWrappedKeys (the fixture's single default entry). The override is now dead for this test's purpose — the multi-key preview-enrichment scenario this test appears to intend to cover isn't actually exercised.

♻️ Suggested fix
-      const envelope = newEncryptionBlock({
-        wrappedKeys: [newEncryptedWrappedKey(), newEncryptedWrappedKey()],
-      });
+      const envelope = newEncryptionBlock({
+        previewWrappedKeys: [newEncryptedWrappedKey(), newEncryptedWrappedKey()],
+      });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/modules/email/email.service.spec.ts` around lines 130 - 164, Update the
encrypted-row fixture in the test “when page has encrypted rows, then it
enriches those with the preview and wrapped keys” so the preview-level wrapped
keys contain multiple entries, then keep the encryption assertion aligned with
that configured preview data. Ensure the test actually exercises multi-key
preview enrichment rather than overriding only the unused body-level
wrappedKeys.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/modules/email/email.service.spec.ts`:
- Around line 130-164: Update the encrypted-row fixture in the test “when page
has encrypted rows, then it enriches those with the preview and wrapped keys” so
the preview-level wrapped keys contain multiple entries, then keep the
encryption assertion aligned with that configured preview data. Ensure the test
actually exercises multi-key preview enrichment rather than overriding only the
unused body-level wrappedKeys.

In `@src/modules/email/email.service.ts`:
- Around line 244-266: Update decryptPayloadForExternalDelivery to validate the
parsed JSON envelope before returning it: require a string body and, when
present, a string attachmentsSessionKey. Treat missing or incorrectly typed
fields like JSON parse failures by throwing BadRequestException, preventing
encrypted sends from falling back to an empty body.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 96e24394-1c75-415f-9f86-4ecca11c411a

📥 Commits

Reviewing files that changed from the base of the PR and between 9b4db20 and 9cc90f2.

📒 Files selected for processing (9)
  • src/modules/email/email-encryption.spec.ts
  • src/modules/email/email-encryption.ts
  • src/modules/email/email.dto.ts
  • src/modules/email/email.service.spec.ts
  • src/modules/email/email.service.ts
  • src/modules/email/email.types.ts
  • src/modules/email/server-crypto.spec.ts
  • src/modules/email/server-crypto.ts
  • test/fixtures.ts

@xabg2 xabg2 merged commit d16e478 into master Jul 15, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants