Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,8 +415,9 @@ A `SignedXml` object provides the following methods:

To sign xml documents:

- `addReference({ xpath, transforms, digestAlgorithm, id, type, isEmptyUri, inclusiveNamespacesPrefixList })` - adds a reference to a xml element where:
- `addReference({ xpath, select, transforms, digestAlgorithm, id, type, isEmptyUri, inclusiveNamespacesPrefixList })` - adds a reference to a xml element where:
- `xpath` - a string containing a XPath expression referencing a xml element
- `select` - instead of `xpath`, a function that is given the parsed document being signed and returns an array of the elements to reference. When none of them is in the input, it is called again after the signature is inserted, to find content in the signature's `Object` elements. Pass either `xpath` or `select`, not both
- `transforms` - an array of [transform algorithms](#canonicalization-and-transformation-algorithms), the referenced element will be transformed for each value in the array
- `digestAlgorithm` - one of the supported [hashing algorithms](#hashing-algorithms)
- `id` - an optional `Id` attribute to add to the reference element
Expand All @@ -428,7 +429,7 @@ To sign xml documents:
- `options` - an object with the following properties:
- `prefix` - adds this value as a prefix for the generated signature tags
- `attrs` - a hash of attributes and values `attrName: value` to add to the signature root node
- `location` - customize the location of the signature, pass an object with a `reference` key which should contain a XPath expression to a reference node, an `action` key which should contain one of the following values: `append`, `prepend`, `before`, `after`
- `location` - customize the location of the signature, pass an object with a `reference` key which should contain a XPath expression to a reference node (or a function that is given the parsed document being signed and returns that node), an `action` key which should contain one of the following values: `append`, `prepend`, `before`, `after`
- `existingPrefixes` - A hash of prefixes and namespaces `prefix: namespace` that shouldn't be in the signature because they already exist in the xml
- `computeSignatureAsync(xml, [options])` - `computeSignature` for a signature algorithm that signs asynchronously; returns a promise for the `SignedXml` instance. See [Asynchronous signing and verification](#asynchronous-signing-and-verification)
- `getSignedXml()` - returns the original xml document with the signature in it, **must be called only after `computeSignature`**
Expand Down Expand Up @@ -855,8 +856,9 @@ sig.computeSignature(xml, {
### how to specify the location of the signature

Use the `location` option when calling `computeSignature` to move the signature around. Set
`reference` to an XPath expression that selects a node (default `/*`, the document element), and
`action` to one of the following:
`reference` to an XPath expression that selects a node (default `/*`, the document element), or to
a function that is given the parsed document and returns that node, and `action` to one of the
following:

- `append` (default) - insert the signature as the last child of the `reference` node
- `prepend` - insert the signature as the first child of the `reference` node
Expand Down
11 changes: 3 additions & 8 deletions src/enveloped-signature.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import * as xpath from "xpath";
import * as isDomNode from "@xmldom/is-dom-node";
import { isDescendantOf } from "./utils";
import { isDescendantOf, isSignatureElement } from "./utils";

import type {
CanonicalizationOrTransformationAlgorithm,
Expand All @@ -17,11 +15,8 @@ export class EnvelopedSignature implements CanonicalizationOrTransformationAlgor

process(node: Node, options: CanonicalizationOrTransformationAlgorithmProcessOptions): Node {
if (null == options.signatureNode) {
const signature = xpath.select1(
"./*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']",
node,
);
if (isDomNode.isNodeLike(signature) && signature.parentNode) {
const signature = Array.from(node.childNodes ?? []).find(isSignatureElement);
if (signature?.parentNode) {
signature.parentNode.removeChild(signature);
}
return node;
Expand Down
147 changes: 99 additions & 48 deletions src/signed-xml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,39 @@ type C14nOptionsWithXmlAttributes = CanonicalizationOrTransformationAlgorithmPro
};

function findSignatureElements(node: Node): Element[] {
const signatures = xpath.select(
".//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']",
node,
);
isDomNode.assertIsArrayOfNodes(signatures);
return signatures.filter(isDomNode.isElementNode);
return utils.findDescendants(node).filter(utils.isSignatureElement);
}

// An absolute XPath location path starts from the document, even for a detached node.
function findRoot(node: Node): Node {
if (isDomNode.isDocumentNode(node)) {
return node;
}
if (node.ownerDocument != null) {
return node.ownerDocument;
}
let root = node;
while (root.parentNode != null) {
root = root.parentNode;
}
return root;
}

// The first `Algorithm` attribute without a namespace, on any descendant named `localName`. The
// name is matched case-insensitively, as xpath did: xmldom reports the HTML feature, so xpath treats
// every xmldom document as HTML.
function findAlgorithmAttribute(node: Node, localName: string): Attr | undefined {
for (const descendant of utils.findDescendants(node)) {
if (isDomNode.isElementNode(descendant) && utils.localNameOf(descendant) === localName) {
const algorithm = Array.from(descendant.attributes).find(
(attr) => !attr.namespaceURI && utils.localNameOf(attr).toLowerCase() === "algorithm",
);
if (algorithm != null) {
return algorithm;
}
}
}
return undefined;
}

// SignatureValue is base64Binary, so whitespace in it carries no value:
Expand Down Expand Up @@ -337,8 +364,13 @@ export class SignedXml {
*/
static getCertFromKeyInfo(keyInfo?: Node | null): string | null {
if (keyInfo != null) {
const cert = xpath.select1(".//*[local-name(.)='X509Certificate']", keyInfo);
if (isDomNode.isElementNode(cert)) {
const cert = utils
.findDescendants(keyInfo)
.find(
(node): node is Element =>
isDomNode.isElementNode(node) && utils.localNameOf(node) === "X509Certificate",
);
if (cert != null) {
return utils.toPem(cert.textContent, "CERTIFICATE");
}
}
Expand Down Expand Up @@ -611,12 +643,17 @@ export class SignedXml {
};
}

private getCanonReferenceXml(doc: Document, ref: Reference, node: Node) {
private getCanonReferenceXml(
doc: Document,
ref: Reference,
node: Node,
docSubset: string | Element | undefined,
) {
/**
* Search for ancestor namespaces before canonicalization.
*/
if (Array.isArray(ref.transforms)) {
ref.ancestorNamespaces = utils.findAncestorNs(doc, ref.xpath, this.namespaceResolver);
ref.ancestorNamespaces = utils.findAncestorNs(doc, docSubset, this.namespaceResolver);
}

const c14nOptions = {
Expand Down Expand Up @@ -736,7 +773,7 @@ export class SignedXml {
}
}

const canonXml = this.getCanonReferenceXml(doc, ref, elem);
const canonXml = this.getCanonReferenceXml(doc, ref, elem, ref.xpath);
const hash = this.findHashAlgorithm(ref.digestAlgorithm);
const digest = hash.getHash(canonXml);

Expand All @@ -750,7 +787,7 @@ export class SignedXml {

private validateReference(ref: Reference, doc: Document): string | undefined {
const uri = ref.uri?.[0] === "#" ? ref.uri.substring(1) : ref.uri;
let elem: xpath.SelectSingleReturnType = null;
let elem: Node | null = null;

// Only an empty URI and a fragment are same-document references:
// https://www.w3.org/TR/xmldsig-core1/#sec-ReferenceProcessingModel
Expand All @@ -759,15 +796,21 @@ export class SignedXml {
}

if (uri === "") {
elem = utils.hasDocumentLevelProcessingInstruction(doc) ? doc : xpath.select1("//*", doc);
elem = utils.hasDocumentLevelProcessingInstruction(doc) ? doc : doc.documentElement;
} else if (uri?.indexOf("'") !== -1) {
// xpath injection
throw new Error("Cannot validate a uri with quotes inside it");
} else {
let num_elements_for_id = 0;
const elements = utils.findDescendants(doc).filter(isDomNode.isElementNode);
for (const attr of this.idAttributes) {
const tmp_elemXpath = `//*[@*[local-name(.)='${attr}']='${uri}']`;
const tmp_elem = xpath.select(tmp_elemXpath, doc);
// Same match as tmp_elemXpath: an attribute of that local name, in any namespace.
const tmp_elem = elements.filter((element) =>
Array.from(element.attributes).some(
(attribute) => utils.localNameOf(attribute) === attr && attribute.value === uri,
),
);
if (utils.isArrayHasLength(tmp_elem)) {
num_elements_for_id += tmp_elem.length;

Expand Down Expand Up @@ -802,7 +845,9 @@ export class SignedXml {
return undefined;
}

const canonXml = this.getCanonReferenceXml(doc, ref, elem);
// An ID match is the only element its generated ref.xpath selects, so no need to evaluate it.
const docSubset = uri === "" || !isDomNode.isElementNode(elem) ? ref.xpath : elem;
const canonXml = this.getCanonReferenceXml(doc, ref, elem, docSubset);
const hash = this.findHashAlgorithm(ref.digestAlgorithm);
const digest = hash.getHash(canonXml);

Expand All @@ -819,12 +864,7 @@ export class SignedXml {
}

findSignatures(doc: Node): Node[] {
const nodes = xpath.select(
"//*[local-name(.)='Signature' and namespace-uri(.)='http://www.w3.org/2000/09/xmldsig#']",
doc,
);

return isDomNode.isArrayOfNodes(nodes) ? nodes : [];
return findSignatureElements(findRoot(doc));
}

/**
Expand All @@ -841,24 +881,14 @@ export class SignedXml {

this.signatureXml = signatureNode.toString();

const node = xpath.select1(
".//*[local-name(.)='CanonicalizationMethod']/@Algorithm",
signatureNode,
);
if (!isDomNode.isNodeLike(node)) {
const node = findAlgorithmAttribute(signatureNode, "CanonicalizationMethod");
if (node == null) {
throw new Error("could not find CanonicalizationMethod/@Algorithm element");
}
this.canonicalizationAlgorithm = node.value as CanonicalizationAlgorithmType;

if (isDomNode.isAttributeNode(node)) {
this.canonicalizationAlgorithm = node.value as CanonicalizationAlgorithmType;
}

const signatureAlgorithm = xpath.select1(
".//*[local-name(.)='SignatureMethod']/@Algorithm",
signatureNode,
);

if (isDomNode.isAttributeNode(signatureAlgorithm)) {
const signatureAlgorithm = findAlgorithmAttribute(signatureNode, "SignatureMethod");
if (signatureAlgorithm != null) {
this.signatureAlgorithm = signatureAlgorithm.value as SignatureAlgorithmType;
}

Expand Down Expand Up @@ -1019,6 +1049,7 @@ export class SignedXml {
* Adds a reference to the signature.
*
* @param xpath The XPath expression to select the XML nodes to be referenced.
* @param select A function that selects the XML elements to be referenced, instead of `xpath`.
* @param transforms An array of transform algorithms to be applied to the selected nodes.
* @param digestAlgorithm The digest algorithm to use for computing the digest value.
* @param uri The URI identifier for the reference. If empty, an empty URI will be used.
Expand All @@ -1030,6 +1061,7 @@ export class SignedXml {
*/
addReference({
xpath,
select,
transforms,
digestAlgorithm,
uri = "",
Expand All @@ -1047,8 +1079,13 @@ export class SignedXml {
throw new Error("transforms must contain at least one transform algorithm");
}

if (xpath != null && select != null) {
throw new Error("a reference takes either xpath or select, not both");
}

this.references.push({
xpath,
select,
transforms,
digestAlgorithm,
uri,
Expand Down Expand Up @@ -1247,8 +1284,7 @@ export class SignedXml {

const referenceTargets = new Map<Reference, SigningReferenceTarget[]>();
for (const ref of this.getReferences()) {
const nodes = xpath.selectWithResolver(ref.xpath ?? "", doc, this.namespaceResolver);
isDomNode.assertIsArrayOfNodes(nodes);
const nodes = this.selectReferenceNodes(ref, doc);
const targets = nodes.map((node) => {
isDomNode.assertIsElementNode(node);
return { node };
Expand Down Expand Up @@ -1299,11 +1335,16 @@ export class SignedXml {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const signatureElem = nodeXml.documentElement.firstChild! as Element;

const referenceNode = xpath.select1(location.reference, doc);
const referenceNode =
typeof location.reference === "function"
? location.reference(doc)
: xpath.select1(location.reference, doc);

if (!isDomNode.isNodeLike(referenceNode)) {
const err2 = new Error(
`the following xpath cannot be used because it was not found: ${location.reference}`,
typeof location.reference === "function"
? "the location.reference function did not return a node"
: `the following xpath cannot be used because it was not found: ${location.reference}`,
);
if (!callback) {
throw err2;
Expand Down Expand Up @@ -1407,14 +1448,21 @@ export class SignedXml {
return this.findHashAlgorithm(ref.digestAlgorithm).getHash(canonXml);
}

private selectReferenceNodes(ref: Reference, doc: Document): Node[] {
const nodes =
ref.select != null
? ref.select(doc)
: xpath.selectWithResolver(ref.xpath ?? "", doc, this.namespaceResolver);
isDomNode.assertIsArrayOfNodes(nodes);
return nodes;
}

private findSignatureContentTargets(
ref: Reference,
doc: Document,
signatureElem: Element,
): SigningReferenceTarget[] {
const nodes = xpath.selectWithResolver(ref.xpath ?? "", doc, this.namespaceResolver);
isDomNode.assertIsArrayOfNodes(nodes);
return nodes
return this.selectReferenceNodes(ref, doc)
.filter((node) => node === signatureElem || utils.isDescendantOf(node, signatureElem))
.map((node) => {
isDomNode.assertIsElementNode(node);
Expand All @@ -1436,7 +1484,9 @@ export class SignedXml {
const signatureNamespace = "http://www.w3.org/2000/09/xmldsig#";

// Find the SignedInfo element to append to
const signedInfoNode = xpath.select1(`./*[local-name(.)='SignedInfo']`, signatureElem);
const signedInfoNode = Array.from(signatureElem.childNodes).find(
(node) => isDomNode.isElementNode(node) && utils.localNameOf(node) === "SignedInfo",
);
isDomNode.assertIsElementNode(signedInfoNode); // Type-safe assertion

// Signature document is technically the same document as the one we are signing,
Expand All @@ -1456,7 +1506,9 @@ export class SignedXml {

if (!utils.isArrayHasLength(targets)) {
throw new Error(
`the following xpath cannot be signed because it was not found: ${ref.xpath}`,
ref.select != null
? "the reference's select function found nothing to sign"
: `the following xpath cannot be signed because it was not found: ${ref.xpath}`,
);
}

Expand All @@ -1468,7 +1520,7 @@ export class SignedXml {
utils.isDescendantOf(node, signedInfoNode)
) {
throw new Error(
`Cannot sign a reference to the Signature or SignedInfo element itself: ${ref.xpath}`,
`Cannot sign a reference to the Signature or SignedInfo element itself: ${ref.xpath ?? "select"}`,
);
}

Expand Down Expand Up @@ -1646,8 +1698,7 @@ export class SignedXml {
}
}
if (discardComments) {
const comments = xpath.select(".//comment()", canonXml);
isDomNode.assertIsArrayOfNodes(comments);
const comments = utils.findDescendants(canonXml).filter(isDomNode.isCommentNode);
comments.forEach((comment) => comment.parentNode?.removeChild(comment));
}
let transformedXml: Node | string = canonXml;
Expand Down
17 changes: 14 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,11 @@ export interface CanonicalizationOrTransformationAlgorithmProcessOptions {
}

export interface ComputeSignatureOptionsLocation {
reference?: string;
/**
* An XPath expression, or a function given the parsed document being signed, that selects the
* node to place the signature relative to. Defaults to `/*`.
*/
reference?: string | ((doc: Document) => Node | null);
action?: "append" | "prepend" | "before" | "after";
}

Expand All @@ -123,10 +127,10 @@ export interface ComputeSignatureOptionsLocation {
*
* - `prefix` {String} Adds a prefix for the generated signature tags
* - `attrs` {Object} A hash of attributes and values `attrName: value` to add to the signature root node
* - `location` {{ reference: String, action: String }}
* - `location` {{ reference: String | Function, action: String }}
* - `existingPrefixes` {Object} A hash of prefixes and namespaces `prefix: namespace` already in the xml
* An object with a `reference` key which should
* contain a XPath expression, an `action` key which
* contain a XPath expression or a function that returns a node, an `action` key which
* should contain one of the following values:
* `append`, `prepend`, `before`, `after`
*/
Expand All @@ -144,6 +148,13 @@ export interface Reference {
// The XPath expression that selects the data to be signed.
xpath?: string;

/**
* Selects the elements to be signed, instead of `xpath`. It is given the parsed document being
* signed, and is called again after the signature is inserted to find content in its `Object`
* elements when nothing in the input matched.
*/
select?: (doc: Document) => Element[];

// An array of transforms to be applied to the data before signing.
transforms: ReadonlyArray<CanonicalizationOrTransformAlgorithmType>;

Expand Down
Loading