Skip to content

feat(xmlsec1): add keys, KeyInfo, templates and signature transforms on the owned tree - #464

Closed
polaz wants to merge 3 commits into
feat/#451-core-keys-treefrom
feat/#451-xmlsec1-keys
Closed

polaz wants to merge 3 commits into
feat/#451-core-keys-treefrom
feat/#451-xmlsec1-keys

Conversation

@polaz

@polaz polaz commented Nov 14, 2026

Copy link
Copy Markdown
Member

Summary

Changes

  • Tree layer: the library policy is published as one verification and signing pair, both admitting the external reference URIs the caller's callbacks resolve, replaced as a whole by one republishing caller at a time.
  • One policy revision per operation: a KeyInfo read pins it in its context and hands it, with the read's resource budget and the URI classes admitted for each key reference, to the transform chains its references run; a run of a transform context pins its own. A chain whose transforms sign reads the signing snapshot for its shared work (transform count, reference URIs, budgets, parsing, C14N, XPath, Relationship), any other chain the verification snapshot. Key reads enforce the verification policy's key sources, key-retrieval URI classes and depth, and one key-candidate allowance shared by every key value decoded and every key-store entry inspected, through a key manager's lax search too; a key value the context's requirements refuse is not installed, and every key value (symmetric, DER, RSA, DSA, EC, or raw binary bytes) is bounded by the per-resource limit before it is decoded or copied. Digest, HMAC and signature transforms admit their method and key under the operation's policy before taking input; a caller-supplied key without expected targets goes through VerificationPolicy::check_supplied_key_verification.
  • xmltree.h, templates.h, keys.h, keysdata.h (binary value, symmetric and RSA/DSA/EC/DEREncodedKeyValue klasses), keyinfo.h (KeyName, KeyValue, RetrievalMethod, KeyInfoReference), keysmngr.h (manager, store protocol, simple store), digest/HMAC/signature klasses in the built-in crypto table, xmlSecCryptoAppKeyLoadMemory. MD5 and RIPEMD-160 klasses come with the legacy-algorithms feature. Template functions fail when the tree refuses an attribute they were asked to set.
  • A buffer that grows moves its contents to a new block and wipes the old one; key material is wiped in writes the compiler keeps, and the block ciphers wipe their key schedules.
  • Functions that read or write a file themselves are not offered: xmlSecKeyReadBinaryFile, xmlSecSimpleKeysStoreLoad, xmlSecSimpleKeysStoreLoad_ex, xmlSecSimpleKeysStoreSave; the headers say so and point to the memory entry points. Templates are built in the document they belong to.

Testing

Every C program under crates/xml-sec-xmlsec1/tests/c prints the same as the libxmlsec1 oracle, a 1.3.13 pre-release snapshot (capi --xmlsec1); tests (with the xmlsec1 oracle and SoftHSM), clippy with all features, the alloc-only build, formatting, the header check and the clean C API check pass locally on macOS; CI runs the full matrix.

Related

Closes #458
Part of #451

The libxmlsec1-compatible library and the tree library link, load and
call no C library besides the platform's C runtime. Documents are the
core's trees behind opaque handles, read and changed through our own
tree functions shaped like libxml2's.

- core: OwnedTree, a Rust-owned mutable document over the xmloxide
  arena, parsed under the policy with its limits enforced while parsing,
  implementing the external-tree contract; XmlDocument lends it to an
  operation (from_owned_tree, into_owned_tree) or reads a snapshot of it
  (snapshot_of_external_tree); its ID table is xml:id and the IDs a
  caller registers
- xml-sec-libxml2: the handle table (documents, nodes, attributes,
  namespace declarations and XPath namespace nodes, node sets) with
  handles from a counter that never repeats, validated on every use; the
  xs* tree functions and xs_tree.h with incomplete types; output and
  input buffers over the caller's callbacks or memory; the heap released
  with xsFree; the generic error channel; xs_tree_document, a clean C
  API document over a tree document that reads the tree at every
  operation
- xml-sec-xmlsec1: every tree access goes through the handles; node
  sets, buffers and parsing are the library's own; read-only transforms
  read a snapshot so C callbacks still see the live tree; the headers
  are libxmlsec1's with xs_tree.h in place of libxml2's, generated and
  checked by xmlsec1-headers, and leave out the functions that read a
  file or install an entity loader
- the C test programs use the tree functions; capi --xmlsec1 builds each
  against the libxmlsec1 oracle with the tree calls mapped onto libxml2
  and against the library, and both print the same; the library's own
  round trips link nothing else, on every platform

BREAKING CHANGE: xs_libxml2_document is replaced by xs_tree_document over
a tree document of xs_tree.h; xmlSecParseFile, xmlSecBufferReadFile,
xmlSecParsePrepareCtxt and xmlSecSetExternalEntityLoader are not offered.

Part of #451
Core owned tree:
- refuse a DOCTYPE the policy forbids before its internal subset is read,
  through the lexical scan every other parse runs, which also bounds
  entity expansion
- report the byte ceiling as the typed policy violation
- project the parsed children of an entity reference, so replacement
  markup is markup (XML 1.0 section 4.4.2)
- normalize xml:id values before registering them and keep the normalized
  value (xml:id 1.0 section 4); register inserted xml:id attributes in the
  tree's own ID table after the edit, journaled for rollback
- an ordinary attribute no longer matches a namespace declaration of the
  same local name; an empty namespace URI is no namespace
- release the payload of freed nodes
- serialize with a UTF-8 declaration, matching the bytes
- parse bytes in the encoding a byte-order mark or declaration selects,
  UTF-16 included, and refuse parts too large together before joining them
- a snapshot of an external tree refuses every mutation with
  ReadOnlySnapshot instead of splicing into an empty serialization

Tree library:
- document slots come from the never-repeating handle counter, so a freed
  document's slot never names a later document
- an edit prunes only the name-keyed handles of its own document
- a panic inside an operation returns the lent tree to its slot
- a refused link or replacement leaves the node where it was
- xsSearchNsByHref passes a shadowed prefix and keeps searching
- a short write callback is offered the rest; no progress fails the buffer

libxmlsec1 surface:
- a namespace node matches an element's namespace node only with the same
  URI
- xmlSecParseMemoryExt checks the combined size before joining the chunks

Each defect carries a regression test that failed before its fix, except
the chunk size check, whose effect is the allocation it avoids.

Part of #451
The slot number a clean C API document keeps is never reused, so a freed
document's slot is refused on every access.

Part of #451
@coderabbitai

coderabbitai Bot commented Nov 14, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • 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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T11:36:03.107074Z 742fac7 PR opened
ℹ️ 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.

@polaz

polaz commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

Opened from a stale branch by mistake; superseded by the PR that follows.

@polaz polaz closed this Nov 14, 2026

@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: 742fac7714

ℹ️ 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 on lines +746 to +747
self.put_attribute(id, local_name, prefix, namespace, value);
Ok(())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Update the ID index when an ID attribute changes

After parsing <r xml:id="old"/>, calling xsSetProp(root, "xml:id", "new") changes the attribute but leaves self.ids untouched: xsGetID(doc, "old") still returns the root, while xsGetID(doc, "new") returns null. Adding an xml:id through this setter likewise never registers it. This makes ID-based selection disagree with the document's current attributes and regresses the corresponding libxml2 setter behavior, which I checked against the installed library. Keep the ID index synchronized when ID attributes are added, replaced, or removed.

Useful? React with 👍 / 👎.

Comment on lines +635 to +637
self.element(element)?;
self.ids.insert(String::from(value), element);
Ok(())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject duplicate explicit ID registrations

When callers use xsAddID to register attributes on two different elements with the same value, this unconditional insertion silently replaces the first element and reports success for both registrations. Subsequent xsGetID calls therefore select whichever element was registered last, rather than exposing the duplicate to the caller. I checked the installed libxml2 implementation: its second xmlAddID call fails and preserves the first entry. Refuse registration when the value already belongs to another live element instead of overwriting it.

Useful? React with 👍 / 👎.

Comment on lines +636 to +637
pub fn set_content(node: *mut Node, content: &str) -> Result<(), HandleError> {
handles::edit(handle_of(node), |tree, node| tree.set_text(node, content))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Support attribute handles in the node-content setter

For an ordinary attribute returned by xsHasProp or an XPath attribute selection, xsNodeSetContent((xmlNodePtr)attr, "new") always fails: handles::edit resolves only Target::Node and rejects Target::Attribute with WrongKind. Thus generic node-editing code cannot update attribute values even though xsNodeGetContent supports those same handles. This contradicts the tree surface's stated libxml2-compatible semantics; I verified that the installed libxml2's xmlNodeSetContent successfully updates an attribute. Handle attribute targets separately and update their owning element's attribute.

Useful? React with 👍 / 👎.

Comment on lines +14 to +15
/// The handler a caller installed, with its context's address.
static HANDLER: Mutex<Option<(GenericErrorFunc, usize)>> = Mutex::new(None);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep generic error handlers local to the calling thread

In multithreaded applications that install a per-request error handler, this process-wide singleton lets one thread overwrite another thread's handler and context. xmlSecErrorsDefaultCallback then sends errors to the wrong request's callback, and resetting the handler on one thread disables reporting for the others. The previous implementation read libxml2's calling-thread handler through its accessor; I also verified with the installed libxml2 that two threads retain independent xmlSetGenericErrorFunc contexts. Store this handler in thread-local state rather than a process-global mutex to preserve that behavior.

Useful? React with 👍 / 👎.

@polaz
polaz deleted the feat/#451-xmlsec1-keys branch November 14, 2026 12:02
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