Skip to content

refactor(key-manager)!: read PKCS#12 with the shared reader - #323

Merged
polaz merged 4 commits into
mainfrom
refactor/#281-shared-pkcs12
Oct 27, 2026
Merged

polaz merged 4 commits into
mainfrom
refactor/#281-shared-pkcs12

Conversation

@polaz

@polaz polaz commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

PKCS#12 import reads the container with the published structured-cms personal reader instead of its own BER/TLV traversal. The shared reader owns PFX, AuthenticatedSafe, SafeContents and bag framing and authenticates the whole safe before any bag is extracted. This crate keeps the password, the MAC/KDF/cipher work (RustCrypto) and their admission under the compiled resource policy.

One pass, password on demand

  • The container is processed once. The password is requested when the MAC or the first decryption needs it, after that step's KDF work and output memory are admitted, so a refused step never prompts. A bundle without a MAC or encrypted content never calls the password callback; a password passed up front is used directly.
  • The MAC runs before any bag is read: an altered safe is an unauthenticated container before its parameters are used.
  • KDF work accumulates across imports and is not refunded when a later step is refused.

Decrypted keys are kept, not copied

  • A shrouded key whose PrivateKeyInfo is already DER is stored in its decryption buffer, which keeps its wiping and its import memory charge. A BER key gets a framing-only DER rewrite; algorithm parameters that are not already DER are refused rather than re-encoded.
  • StoredPrivateKey::pkcs8_der becomes a method returning the DER bytes; the field holding either form is private. KeyInventory and StoredPrivateKey remain Send + Sync.

Accounting

  • Reading work counts against ResourcePolicy::max_x509_work, the budget of the shared ASN.1 readers; buffers count against the aggregate live-byte limit. Inventory material accounting counts the stored key once.
  • Bags (nested or inside encrypted content) and decrypted safes share one candidate count.

Behavior

  • Public-key integrity, enveloped privacy and CRL, secret or SDSI bags are selection errors; PBMAC1 remains unsupported.
  • structured-asn1, -pkix, -cms, -ltv and -xades move to 0.16.0 across the workspace. structured-cms is a dependency of xmldsig-sign only; the verification-only graph is unchanged. The competitor lockfile follows the version bump and adds structured-cms.

Testing

  • cargo fmt --check; cargo clippy --workspace --all-targets --all-features -D warnings on stable and on 1.92.0 (with the libtest large_stack_arrays allowance CI uses there).
  • scripts/test-pkcs11.sh (SoftHSM) running cargo nextest run --workspace --all-features with the xmlsec1 1.3.13 oracle: 5676 passed, including the OpenSSL, Windows-export, merlin and interop-2012 .p12 corpus.
  • cargo test --doc --workspace --all-features; RUSTDOCFLAGS=-D warnings cargo doc --workspace --all-features.
  • scripts/check-features.sh for dsig-xmloxide and dsig-sign-xmloxide; check-shared-pkix.sh; check-pedantic-lints.mjs 1.92.0 stable.

BREAKING CHANGE: StoredPrivateKey::pkcs8_der is a method returning the PKCS#8 DER bytes, not a public field.

Closes #281

Summary by CodeRabbit

  • New Features
    • PKCS#12 imports support password-protected integrity checks and common encrypted-container formats, including PBES2 with AES and legacy 3DES protection.
    • Passwords are requested only when needed during import.
  • Bug Fixes
    • Imports enforce shared resource limits and authenticate the entire protected container before extracting keys or certificates.
    • Bundles without a private key or with multiple private keys are rejected.
  • Documentation
    • Clarified supported formats, import protections, password-callback timing, and resource accounting.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T19:19:27.255757Z 6cac6c2 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 12c20a3 and 6cac6c2.

Files selected for processing: 1
  • src/key_manager/pkcs12_import/tests.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Walkthrough

PKCS#12 import now uses the shared container reader and a single-pass importer. It applies work and memory limits, requests passwords only when needed, supports selected MAC and encryption schemes, and returns at most one private key with certificates. Private-key DER is accessed through an accessor and may remain in its decrypted buffer.

Changes: PKCS#12 import

Layer / File(s) Summary
Process and authenticate the container
Cargo.toml, src/key_manager/pkcs12_import.rs, src/hard_limits.rs, src/policy.rs
The signing feature enables structured-cms. The importer processes PFX data through the shared reader, maps reader refusals to import errors, accounts for work and memory, and authenticates the AuthenticatedSafe before extracting bags. It supports selected MAC, PBES2/PBKDF2, AES-CBC, and legacy Triple-DES schemes.
Decrypt and retain imported contents
src/key_manager/pkcs12_import.rs, src/key_manager.rs, tools/xmlsec1/src/commands.rs, tools/xmlsec1/src/key_material.rs
The adapter decrypts supported content, applies candidate limits, normalizes permitted BER key framing, and retains at most one private key and certificates. StoredPrivateKey uses private DER storage and exposes the bytes through pkcs8_der().
Wire and validate PKCS#12 import
src/key_manager/pkcs12_import/tests.rs, src/key_manager/tests.rs, docs/key-management.md, docs/crypto-providers.md, Cargo.toml, crates/xml-sec-xades/Cargo.toml, tools/xmlsec1/Cargo.toml, vendor/sxd-document-no-unsafe/Cargo.toml
The tests cover password timing, authentication, supported and unsupported protection, BER key framing, candidate limits, and memory and KDF work. The documentation describes the shared reader and provider boundary. Structured dependencies are updated to version 0.16.0.

Priority: Normal

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant KeyManager
  participant Import as pkcs12_import::import
  participant Reader as structured_cms::personal
  participant Adapter
  participant PasswordCallback
  KeyManager->>Import: Pass PFX, limits, work counter, and callback
  Import->>Reader: Process PFX with Adapter
  Reader->>Adapter: Authenticate AuthenticatedSafe
  Adapter->>PasswordCallback: Request password when MAC verification needs it
  Reader->>Adapter: Request decryption of protected content
  Adapter->>PasswordCallback: Request password when decryption needs it
  Reader-->>Import: Return processed contents
  Import-->>KeyManager: Return contents and updated KDF work
Loading

Possibly related PRs

Merge Risk: Minimal · up to 6cac6

No actionable issue remains in the reviewed change; it is mergeable after normal checks.

Pre-merge checks: Passed 3 · Failed 1 · Inconclusive 1

Failed Failed checks: 1 warning · 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 16.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check Inconclusive For #281, the reviewed changes use structured_cms::personal for PFX, safe, and bag processing. The adapter retains password handling, MAC/KDF/cipher work, resource admission, plaintext retention and… Provide reviewable CI or command results for the #281 alloc, embedded, and WASM matrices. The available evidence does not establish whether those required builds and tests pass.
Passed Passed checks: 3 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies the main change: replacing local PKCS#12 traversal with the shared reader. The breaking-change marker is appropriate because the public `StoredPrivateKey::pk…
Out of Scope Changes check Passed The dependency updates, documentation, StoredPrivateKey::pkcs8_der() API change, importer refactor, consumer updates, policy documentation, and tests support #281 or its required API and feature iso…
Full details: Title check

Explanation

The title clearly and concisely identifies the main change: replacing local PKCS#12 traversal with the shared reader. The breaking-change marker is appropriate because the public StoredPrivateKey::pkcs8_der field changed to an accessor.

Full details: Out of Scope Changes check

Explanation

The dependency updates, documentation, StoredPrivateKey::pkcs8_der() API change, importer refactor, consumer updates, policy documentation, and tests support #281 or its required API and feature isolation. No unrelated change is demonstrated.

Full details: Docstring Coverage

Explanation

Docstring coverage is 16.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 98 functions across 7 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Full details: Linked Issues check

Explanation

For #281, the reviewed changes use structured_cms::personal for PFX, safe, and bag processing. The adapter retains password handling, MAC/KDF/cipher work, resource admission, plaintext retention and wiping, and optional CMS feature isolation. The tests cover MAC and password behavior, nested and protected content, unsupported modes, rollback-related limits, BER key handling, and interoperability. The reported commands do not establish the required alloc, embedded, and WASM matrix results.

Resolution

Provide reviewable CI or command results for the #281 alloc, embedded, and WASM matrices. The available evidence does not establish whether those required builds and tests pass.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

polaz added 3 commits October 27, 2026 12:54
PKCS#12 import no longer has its own BER/TLV traversal. The PFX,
AuthenticatedSafe, SafeContents and bag framing comes from the
published structured-cms personal reader, which authenticates the
whole safe before any bag is extracted. This crate keeps the password,
the MAC/KDF/cipher work (RustCrypto) and their admission under the
compiled resource policy.

- Before the password: the MAC parameters, every protection visible
  outside encrypted safes, safe and bag counts and unsupported types
  are checked; oversized work still never prompts for a password.
- One parse serves both passes; the processing pass continues the safe
  count, so hidden bags share the same candidate allowance.
- Reading work counts against max_x509_work, the shared ASN.1 reader
  budget; buffers against the aggregate live-byte limit.
- A BER PrivateKeyInfo is stored as DER by rewriting framing only;
  algorithm parameters that are not already DER are refused.
- Public-key integrity, enveloped privacy and CRL, secret or SDSI bags
  are selection errors; PBMAC1 remains unsupported.
- structured-cms is a dependency of xmldsig-sign only; the
  verification-only graph is unchanged.

Closes #281
The import no longer walks the container once before the password and
again after it. The shared processor runs once and the password is
requested lazily, when the MAC or the first decryption needs it, after
that step's KDF work and output memory are admitted. A bundle without a
MAC or encrypted content never requests one.

- Candidates are the bags and the decrypted safes; an unencrypted safe
  is counted through its bags.
- Work spent before a later refusal is kept, as it was actually done.
- The MAC still runs before any bag is read, so an altered safe is an
  unauthenticated container before its parameters are used.
- Retained results move out without being re-collected; the single
  private key is an Option instead of a one-element Vec.

Part of #281
The shared PKCS#12 processor now hands the backend the decrypted buffer
of a shrouded key after inspection. A key whose PrivateKeyInfo is
already DER is stored in that buffer instead of being copied into a new
one; it keeps its wiping and its import memory charge. A BER key still
gets its framing-only DER rewrite and the buffer is released.

- Update structured-asn1, -pkix, -cms, -ltv and -xades to 0.16.0 across
  the workspace; the competitor lockfile follows.
- StoredPrivateKey::pkcs8_der is now a method returning the DER bytes;
  the field holds either form and is private.
- Inventory material accounting still counts the key once.
- KeyInventory and StoredPrivateKey stay Send + Sync, checked in tests.

BREAKING CHANGE: StoredPrivateKey::pkcs8_der is a method, not a field.

Part of #281
@polaz
polaz force-pushed the refactor/#281-shared-pkcs12 branch from 05d9044 to 12c20a3 Compare October 27, 2026 12:58
@polaz polaz changed the title refactor(key-manager): read PKCS#12 with the shared reader refactor(key-manager)!: read PKCS#12 with the shared reader Oct 27, 2026
@polaz

polaz commented Oct 27, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 12c20a332b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/key_manager/pkcs12_import.rs Resolved
Import a key-only bundle (a shrouded key inside an encrypted safe)
through KeyInventory::add_pkcs12_with_password_callback while varying
ResourcePolicy::max_x509_work. One unit below the smallest admitted
limit is a typed X509_WORK denial after the password, so the limit
reaches reading of decrypted content; a single unit is refused in the
outer container before any password.

Part of #281
@polaz
polaz enabled auto-merge (squash) October 27, 2026 19:51
@polaz
polaz merged commit 0d09614 into main Oct 27, 2026
31 checks passed
@polaz
polaz deleted the refactor/#281-shared-pkcs12 branch October 27, 2026 20:00
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.

refactor: migrate PKCS#12 to shared containers

1 participant