Skip to content

Avoid cloning the AAD header buffer in SelfEncrypt::seal - #220

Merged
larseggert merged 1 commit into
mainfrom
selfencrypt-seal-no-clone
Sep 14, 2026
Merged

larseggert merged 1 commit into
mainfrom
selfencrypt-seal-no-clone

Conversation

@larseggert

Copy link
Copy Markdown
Collaborator

Build extended_aad directly with Vec::with_capacity and write the
header once, mirroring the approach already used in open(), instead
of cloning the header Vec to extend it with the AAD.

Copilot AI balanced review requested due to automatic review settings September 13, 2026 12:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The refactor preserves encryption format and behavior while eliminating the unnecessary clone.

Pull request overview

Optimizes SelfEncrypt::seal by constructing the encryption header once and avoiding a cloned buffer.

Changes:

  • Introduces a shared header-length constant and fixed-size header.
  • Preallocates AAD and output buffers, then copies the header into each.
File summaries
File Description
src/selfencrypt.rs Refactors header and buffer construction in seal.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 0
  • Review effort level: Balanced

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the refactor of SelfEncrypt::seal. The rewritten header construction is byte-for-byte equivalent to the old one (VERSION, key_id, 16-byte salt; encoded_len unchanged), the AAD still covers header-then-caller-AAD exactly as open() reconstructs it, and output[HEADER_LEN..] is the same destination slice as the old output[offset..]. Allocation count for the AAD buffer goes from two (the clone() produced a Vec with capacity == len, so write_all(aad) always reallocated) to one. No correctness or security concerns; no public API change. Only cleanup comments inline.

Two related observations that apply beyond the individual lines:

  • Style drift between the two halves. seal now uses extend_from_slice, while open() still uses write_all(...).unwrap_or_else(|_| unreachable!(...)). Converting those two calls the same way removes six lines of infallible-IO boilerplate and lets use std::io::Write as _ drop out of the imports (only fmt::Write would remain). Worth folding into this PR since it's the same idea applied to the mirror function.
  • The tests don't really guard this code. assert_bad_data is an if let Err(..), so it passes silently on Ok — damage_salt, damage_ciphertext, damage_auth_tag, and truncate would all pass even if open() accepted tampered input. A let Err(Error::Nss { name, .. }) = res else { panic!(...) } would make them meaningful. Header-layout regressions in this diff are caught indirectly (seal_open + damage_version), so I don't think new tests are needed, but tightening that helper is cheap.

No benchmark seems warranted — the win is a couple of small allocations per seal, and there's no existing benches/ dir to extend.

Comment thread src/selfencrypt.rs Resolved
Comment thread src/selfencrypt.rs Resolved
@codecov-commenter

codecov-commenter commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.83333% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 73.71%. Comparing base (95cbf42) to head (8026ff1).

Files with missing lines Patch % Lines
src/selfencrypt.rs 95.83% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #220      +/-   ##
==========================================
+ Coverage   73.57%   73.71%   +0.14%     
==========================================
  Files          28       28              
  Lines        3315     3318       +3     
  Branches     3315     3318       +3     
==========================================
+ Hits         2439     2446       +7     
- Misses        662      663       +1     
+ Partials      214      209       -5     
Flag Coverage Δ
freebsd 73.71% <95.83%> (+0.14%) ⬆️
linux 73.71% <95.83%> (+0.14%) ⬆️
macos 73.71% <95.83%> (+0.14%) ⬆️
windows 73.71% <95.83%> (+0.14%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Build extended_aad directly with Vec::with_capacity and write the
header once, mirroring the approach already used in open(), instead
of cloning the header Vec to extend it with the AAD.
Copilot AI review requested due to automatic review settings September 13, 2026 17:29
@larseggert
larseggert force-pushed the selfencrypt-seal-no-clone branch from 71dfea9 to 8026ff1 Compare September 13, 2026 17:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

The refactor preserves existing behavior while eliminating the unnecessary clone.

Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pure refactor of SelfEncrypt::seal/open with no wire-format or cryptographic change: the header bytes (version ‖ key_id ‖ salt) are now written once into extended_aad and the prefix copied into output, replacing the enc.clone(). AAD construction, nonce (counter 0 over a fresh 16-byte random salt) and output layout are byte-identical to before, so the format stays compatible. Both of my earlier comments on the previous push are addressed: HEADER_LEN is hoisted to an associated const and used on both sides, and the header scratch array is gone.

Two residual observations that apply to the file as a whole rather than a single line:

  • The zero-fill in output.resize(encoded_len, 0) still memsets plaintext.len() + expansion() bytes that cipher.encrypt overwrites immediately. Eliminating it needs spare_capacity_mut + set_len (i.e. unsafe), which is probably not worth it here — but it is the larger remaining cost in seal, bigger than the clone this PR removes. If these paths are considered hot (session-ticket seal/open), a small Criterion benchmark would make that trade-off measurable instead of inferred.
  • assert_bad_data in tests/selfencrypt.rs silently passes when res is Ok, so the damage_* and truncate tests would not fail if a future refactor accidentally made corrupted input decrypt successfully. Pre-existing and out of scope here, but worth tightening (e.g. assert!(matches!(res, Err(Error::Nss { ref name, .. }) if name == "SEC_ERROR_BAD_DATA"))) given this PR touches exactly the offset arithmetic those tests guard.

Comment thread src/selfencrypt.rs Resolved
Comment thread src/selfencrypt.rs Resolved

@martinthomson martinthomson 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.

Avoids reallocation and copying of the AAD.

@larseggert
larseggert added this pull request to the merge queue Sep 14, 2026
Merged via the queue into main with commit 5e221c6 Sep 14, 2026
53 of 57 checks passed
@larseggert
larseggert deleted the selfencrypt-seal-no-clone branch September 25, 2026 07:31
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.

4 participants