Skip to content

perf(xmldsig): sign without reparsing each step - #305

Merged
polaz merged 3 commits into
mainfrom
perf/#304-sign-reparse
Oct 25, 2026
Merged

polaz merged 3 commits into
mainfrom
perf/#304-sign-reparse

Conversation

@polaz

@polaz polaz commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Template signing parsed the whole document eight times. It now parses twice: once for the input and once for the KeyInfo commit.

  • KeyInfo merge reads the current parsed view. It no longer runs its own validation parse, because the commit parse validates under the same settings.
  • Dependency analysis reads the current tree when every transform is enveloped-signature, XPath exclusion of signatures or canonicalization. These transforms keep or drop whole subtrees, so a mutable DigestValue or SignatureValue is covered exactly when its future text is. This holds only while every value holds text alone; a value with element content, and every other transform chain, keeps the placeholder analysis.
  • Deferred digests: when the plan has a single dependency level and every DigestValue is empty, the digests are computed from the current generation. They are inserted into the canonical SignedInfo at each DigestValue end tag, instead of being committed to an intermediate generation. C14N writes an empty element as a start/end pair and escapes < in attribute values. Base64 needs no escaping (C14N 1.0 §5.2), so the result is the canonical form of the filled element.
  • String entry points (sign_template, sign_with_builder) serialize the final generation directly. They check the projected size and node count that the commit parse would have enforced.
  • Retained-document entry points still commit a validated generation. The output mode is a type parameter, so no path has to unwrap an Option.

Performance

1.69 MB enveloped SAML response, 16384 attributes, RSA-SHA256, exclusive C14N, X509 KeyInfo writer (macOS, release, median of 15, both runs back to back in one session):

sign
main 385 ms
this PR 117 ms

On every measured size the output is byte-identical to the previous implementation.

Behaviour notes

  • Every refusal is unchanged: policy, dependency cycles, structure, document size and node limits.
  • A single-level template now parses XPath expressions one fewer time, so it consumes less of the shared expression budget. The two budget tests now use the new count and still prove that the final SignedInfo parse and builder validation charge the same allowance.

Testing

  • cargo fmt --check.
  • cargo clippy --workspace --all-targets --all-features -D warnings on stable.
  • check-features.sh lint for the dsig, xmlenc and c14n profiles on 1.92.
  • cargo nextest run --workspace --all-features with the xmlsec1 oracle and SoftHSM: 5641 passed.
  • cargo doc -D warnings and cargo test --doc.
  • New tests in src/xmldsig/sign/deferred_commit_tests.rs:
    • text projection output equals the committed document for the exclusive, inclusive, XPath, nested-Manifest and pre-filled templates;
    • the canonical SignedInfo handed to the key equals an independent canonicalization of the emitted document;
    • the projection and the commit parse refuse at the same node-limit boundary;
    • a Reference to element content of SignatureValue is refused;
    • a DigestValue of references to an empty entity (roxmltree, internal DTD), whose replacement shrinks the document, signs.

Closes #304

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T20:52:37.593777Z 9da0fc0 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 25, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 10 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between d235f07 and c56421a.

Files selected for processing: 9
  • src/c14n/mod.rs
  • src/document.rs
  • src/operation.rs
  • src/xmldsig/mutation.rs
  • src/xmldsig/parse.rs
  • src/xmldsig/sign.rs
  • src/xmldsig/sign/deferred_commit_tests.rs
  • src/xmldsig/sign/error_conversion_tests.rs
  • tests/signing_digest.rs

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 8c75f14 and d235f07.

Files selected for processing: 9
  • src/c14n/mod.rs
  • src/document.rs
  • src/operation.rs
  • src/xmldsig/mutation.rs
  • src/xmldsig/parse.rs
  • src/xmldsig/sign.rs
  • src/xmldsig/sign/deferred_commit_tests.rs
  • src/xmldsig/sign/error_conversion_tests.rs
  • tests/signing_digest.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

Signing defers digest replacements for eligible single-level reference plans. It uses pending digest values when parsing and canonicalizing SignedInfo, then finalizes output as a document commit or text projection. KeyInfo merging can reuse an existing parsed document.

Changes: XML signature signing

Layer / File(s) Summary
Document-aware output and KeyInfo merging
src/document.rs, src/operation.rs, src/xmldsig/mutation.rs, src/xmldsig/sign.rs
Added bounded text projection and document batch/projection execution paths. KeyInfo merging accepts a parsed document, and signing selects document commit or text projection output.
Deferred digest calculation and SignedInfo canonicalization
src/c14n/mod.rs, src/xmldsig/parse.rs, src/xmldsig/sign.rs, src/xmldsig/sign/deferred_commit_tests.rs, src/xmldsig/sign/error_conversion_tests.rs, tests/signing_digest.rs
Eligible single-level plans compute pending digest values without an intermediate document transition. SignedInfo parsing and canonicalization use those values. Tests cover output equivalence, canonical SignedInfo, node limits, and updated XPath budget counts.

Priority: Normal

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

Change: Refactor · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant ReferenceFilling
  participant SignedInfoParser
  participant SignedInfoCanonicalizer
  participant SigningKey
  participant SignedOutput
  ReferenceFilling->>SignedInfoParser: pending DigestValue identities and values
  SignedInfoParser->>SignedInfoCanonicalizer: parsed SignedInfo with pending values
  SignedInfoCanonicalizer->>SigningKey: canonical SignedInfo bytes
  SigningKey->>SignedOutput: signature value
  SignedOutput->>SignedOutput: commit document or project text output
Loading
Merge Risk: Minimal · up to d235f

This change speeds up XML signing by avoiding repeated document parses. The supplied evidence shows no concrete defect in the output or in the refusal behavior. The PR states that output is byte-identical and the tests cover the deferred path, so merge risk is minimal.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 27.59% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 58 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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 and concisely describes the main change: reducing reparsing during XML signature signing.
Linked Issues check Passed Directly linked issue #304 has four coding objectives. (1) KeyInfo merge reads the current parsed view and drops its validation parse. The summary of src/xmldsig/mutation.rs and src/xmldsig/sign.rs co…
Out of Scope Changes check Passed The changed files support the fast paths in #304. src/c14n/mod.rs adds a crate-private bounded canonicalization entry point that returns tracked start-tag positions for deferred digest insertion. src/…
Full details: Linked Issues check

Explanation

Directly linked issue #304 has four coding objectives. (1) KeyInfo merge reads the current parsed view and drops its validation parse. The summary of src/xmldsig/mutation.rs and src/xmldsig/sign.rs confirms this. (2) String entry points (sign_template, sign_with_builder) serialize the final generation without a reparse. Retained-document entry points still commit a validated generation. The summary of src/xmldsig/sign.rs confirms this. (3) Dependency analysis uses the current tree for enveloped-signature, XPath exclude-signatures and canonicalization transform chains. Other chains keep placeholder analysis, as #304 allows. (4) With one dependency level and empty DigestValues, digests fill the canonical SignedInfo through src/xmldsig/parse.rs and sign.rs. No intermediate reparse occurs. Acceptance evidence: src/xmldsig/sign/deferred_commit_tests.rs (read at head) compares text output with committed-document output for exclusive, inclusive, XPath, nested-Manifest and pre-filled templates. It checks the canonical SignedInfo passed to the key against an independent canonicalization. It checks node-limit parity between projection and commit parse. The PR reports byte-identical output on measured sizes, a 414 ms to 108–112 ms timing, a full test run of 5641 passed, and refusal behavior unchanged. The eight-to-two parse count is supported by the code summary and the adjusted budget tests (tests/signing_digest.rs and src/xmldsig/sign/error_conversion_tests.rs). It is not measured directly by a parse counter in the diff. I did not rerun the reported timings or the test suite.

Full details: Out of Scope Changes check

Explanation

The changed files support the fast paths in #304. src/c14n/mod.rs adds a crate-private bounded canonicalization entry point that returns tracked start-tag positions for deferred digest insertion. src/document.rs adds project_base64_commit, which projects the node count and output without parsing. This serves the node-limit parity requirement. src/operation.rs adds run_document_batch_with_budgets and run_document_projection. The PR reports clippy with -D warnings passing, so these methods are used and are not dead code. src/xmldsig/parse.rs adds a SignedInfo parse path that accepts pending DigestValue text. The existing parsers delegate with an empty list, so their behavior is unchanged. src/xmldsig/mutation.rs separates standalone and in-document KeyInfo merging. Test updates in src/xmldsig/sign/error_conversion_tests.rs and tests/signing_digest.rs change XPath expression budget counts. The PR discloses this as a consequence of one fewer XPath parse on the single-level path. Changes are gated to xmldsig where the summaries state so. No change was found that is unrelated to #304.

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.

@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: d235f07dbc

ℹ️ 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/xmldsig/sign.rs Resolved
Comment thread src/xmldsig/sign.rs Resolved
polaz added 2 commits October 25, 2026 22:50
Signing a template parsed the whole document eight times; on a 1.7 MB
SAML response the parses took about 92% of the operation. Signing now
parses the input and the KeyInfo commit only:

- Merge KeyInfo sources against the current parsed view and rely on the
  commit parse for validation instead of a separate validation parse.
- Derive the Reference dependency plan from the current tree when every
  transform is enveloped-signature, XPath exclusion of signatures or
  canonicalization: these keep or drop whole subtrees, so a mutable
  DigestValue or SignatureValue is covered exactly when its future text
  is. Other chains keep the placeholder analysis.
- When no Reference depends on another digest and every DigestValue is
  empty, compute the digests from the current generation and splice them
  into the canonical SignedInfo at the end tag of each DigestValue,
  instead of committing an intermediate generation.
- String entry points serialize the final generation directly, checking
  the projected size and node count the commit parse would enforce.
  Retained-document entry points still commit a validated generation.
  The output mode is a type parameter, so no path unwraps an option.

Output is byte-identical to the previous implementation. XPath
expressions in a single-level template are parsed once less, so the
operation consumes less of the shared expression budget; the budget
tests use the new count.

1.69 MB enveloped SAML response with X509 KeyInfo: 414 ms -> 108 ms.

Closes #304
- Dependency analysis on the current tree assumed that filling a value
  removes only text. A SignatureValue or DigestValue holding elements
  loses them when filled, so a Reference to such an element was signed
  although the emitted document no longer contains it. The current tree
  is now used only when every value holds text alone; otherwise the
  placeholder analysis reports the missing target as before.
- Admitting deferred digests assumed each replacement grows the
  document. A DigestValue of references to an empty entity has no
  semantic children but more source bytes than its digest, and the
  subtraction overflowed. The total now adds each projected length and
  subtracts the unchanged base.

Regression tests: signing_refuses_a_reference_to_content_the_signature_value_replaces
and deferred_digest_may_replace_longer_lexical_content.
@polaz
polaz force-pushed the perf/#304-sign-reparse branch from 2d39128 to 9da0fc0 Compare October 25, 2026 20:50
@polaz
polaz enabled auto-merge (squash) October 25, 2026 21:30
@polaz
polaz merged commit bfa636c into main Oct 25, 2026
30 checks passed
@polaz
polaz deleted the perf/#304-sign-reparse branch October 25, 2026 23:11
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.

perf(xmldsig): sign without reparsing after each step

1 participant