You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@santuario.apache.org by co...@apache.org on 2024/10/24 06:22:20 UTC

(santuario-xml-security-java) branch main updated: [SANTUARIO-623] fix the transformation XPATH2 filtering. (#389)

This is an automated email from the ASF dual-hosted git repository.

coheigea pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/santuario-xml-security-java.git


The following commit(s) were added to refs/heads/main by this push:
     new 7c90e224 [SANTUARIO-623] fix the transformation XPATH2 filtering. (#389)
7c90e224 is described below

commit 7c90e2245eac33e6d283f18f5cce1b76fed96029
Author: jrihtarsic <jr...@gmail.com>
AuthorDate: Thu Oct 24 08:22:16 2024 +0200

    [SANTUARIO-623] fix the transformation XPATH2 filtering. (#389)
    
    * [SANTUARIO-623] fix the transformation XPATH2 filtering.
    
    * [SANTUARIO-623] update the xml example and add missing license notice
    
    ---------
    
    Co-authored-by: RIHTARSIC Joze <jo...@ext.ec.europa.eu>
---
 .../security/signature/XMLSignatureByteInput.java  |  6 +-
 .../apache/xml/security/test/dom/TestUtils.java    | 41 ++++++++++
 .../test/dom/signature/SignatureReferenceTest.java | 67 +++++++++++++--
 .../implementations/Xpath2TransformationTest.java  | 94 +++++++++++++++++++++-
 .../apache/xml/security/testutils/Assertions.java  | 68 ++++++++++++++++
 .../javax/xml/crypto/dsig/input-santuario-623.xml  | 40 +++++++++
 6 files changed, 306 insertions(+), 10 deletions(-)

diff --git a/src/main/java/org/apache/xml/security/signature/XMLSignatureByteInput.java b/src/main/java/org/apache/xml/security/signature/XMLSignatureByteInput.java
index 0f99a799..0a3d3ede 100644
--- a/src/main/java/org/apache/xml/security/signature/XMLSignatureByteInput.java
+++ b/src/main/java/org/apache/xml/security/signature/XMLSignatureByteInput.java
@@ -67,7 +67,11 @@ public class XMLSignatureByteInput extends XMLSignatureInput {
 
     @Override
     public void write(OutputStream outputStream, boolean c14n11) throws CanonicalizationException, IOException {
-        if (bytes == null || outputStream == getOutputStream()) {
+        if (outputStream == getOutputStream()) {
+            return;
+        }
+        if (bytes == null) {
+            canonicalize(outputStream, c14n11);
             return;
         }
         outputStream.write(bytes);
diff --git a/src/test/java/org/apache/xml/security/test/dom/TestUtils.java b/src/test/java/org/apache/xml/security/test/dom/TestUtils.java
index b493b6fa..0fb4b8b9 100644
--- a/src/test/java/org/apache/xml/security/test/dom/TestUtils.java
+++ b/src/test/java/org/apache/xml/security/test/dom/TestUtils.java
@@ -21,14 +21,22 @@ package org.apache.xml.security.test.dom;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 
+import org.apache.xml.security.parser.XMLParserException;
 import org.apache.xml.security.utils.Constants;
+import org.apache.xml.security.utils.XMLUtils;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
 public class TestUtils {
 
     private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
     private static final boolean isJava11Compatible;
+    // The class-path to test resources
+    private static final String RESOURCE_PATH = "/org/apache/xml/security/test/javax/xml/crypto/dsig/";
 
     static {
         DBF.setNamespaceAware(true);
@@ -72,6 +80,39 @@ public class TestUtils {
         return DBF.newDocumentBuilder().newDocument();
     }
 
+    /**
+     * Create a test method to read input XML Fragment bytes and return a Document with root element "ROOT".
+     * The XML fragment are wrapped in a "ROOT" element to make it a valid XML document.
+     *
+     * @param xmlFragment the XML fragment bytes
+     *                    (e.g. "<a>text 2</a><a><b>text 2</b></a>".getBytes())
+     * @return the Document with root element "ROOT"
+     */
+    public static Document xmlFragmentToDocument(byte[] xmlFragment) throws XMLParserException, IOException {
+        if (xmlFragment == null || xmlFragment.length == 0) {
+            throw new IllegalArgumentException("XML fragment cannot be null or empty");
+        }
+
+        String xml = new String(xmlFragment, StandardCharsets.UTF_8);
+        String xmlDocument = "<ROOT>" + xml + "</ROOT>";
+
+        try (ByteArrayInputStream is = new ByteArrayInputStream(xmlDocument.getBytes(StandardCharsets.UTF_8))) {
+            return XMLUtils.read(is, true);
+        }
+    }
+
+    /**
+     * Get a test document from a classpath resource.
+     * @param fileName the file name of the resource
+     * @return the Document
+     * @throws XMLParserException if an error occurs while parsing the XML document
+     */
+    public static Document getTestDocumentFromResource(String fileName) throws XMLParserException {
+        // read document from classpath resource
+        return XMLUtils.read(TestUtils.class
+                .getResourceAsStream(RESOURCE_PATH + fileName), true);
+    }
+
     public static boolean isJava11Compatible() {
         return isJava11Compatible;
     }
diff --git a/src/test/java/org/apache/xml/security/test/dom/signature/SignatureReferenceTest.java b/src/test/java/org/apache/xml/security/test/dom/signature/SignatureReferenceTest.java
index 8cec8618..0c85da08 100644
--- a/src/test/java/org/apache/xml/security/test/dom/signature/SignatureReferenceTest.java
+++ b/src/test/java/org/apache/xml/security/test/dom/signature/SignatureReferenceTest.java
@@ -18,10 +18,10 @@
  */
 package org.apache.xml.security.test.dom.signature;
 
-
 import java.security.KeyStore;
 import java.security.PrivateKey;
 import java.security.PublicKey;
+import java.util.Base64;
 import java.util.Enumeration;
 import java.util.List;
 
@@ -32,6 +32,7 @@ import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathFactory;
 
 import org.apache.xml.security.Init;
+import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
 import org.apache.xml.security.exceptions.XMLSecurityException;
 import org.apache.xml.security.keys.KeyInfo;
 import org.apache.xml.security.signature.Manifest;
@@ -47,6 +48,7 @@ import org.apache.xml.security.test.XmlSecTestEnvironment;
 import org.apache.xml.security.test.dom.DSNamespaceContext;
 import org.apache.xml.security.test.dom.TestUtils;
 import org.apache.xml.security.transforms.Transforms;
+import org.apache.xml.security.transforms.params.XPath2FilterContainer;
 import org.apache.xml.security.utils.Constants;
 import org.apache.xml.security.utils.ElementProxy;
 import org.apache.xml.security.utils.XMLUtils;
@@ -55,6 +57,8 @@ import org.apache.xml.security.utils.resolver.ResourceResolverException;
 import org.apache.xml.security.utils.resolver.ResourceResolverSpi;
 import org.apache.xml.security.utils.resolver.implementations.ResolverXPointer;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -104,6 +108,43 @@ class SignatureReferenceTest {
         assertEquals(referenceElement, originalElement);
     }
 
+    /**
+     * Test signing and verifying a document with a reference to a specific XPath expression.
+     * For details see <a href="https://issues.apache.org/jira/browse/SANTUARIO-623">SANTUARIO-623</a> (Note the test file from the issue
+     * was replaced and hashes recalculated.)
+     * @param xpathValue the XPath expression  with the transformation <a href="http://www.w3.org/2002/06/xmldsig-filter2">mldsig-filter2</a>
+     * @param expectedDigest the expected digest value
+     * @throws Throwable if an error occurs
+     */
+    @ParameterizedTest
+    @CsvSource({
+        "//*[local-name()='ToBeSigned'], bZdn277uy+5m4tJ2xU03pY9dH11Hw9zrjp8M76rWdgU=",
+        "//*[local-name()='ReallyToBeSigned'], PiON4xCpziq9v0XlV9wrDCQk3mqkHpZWM6fKPiyUVEY="})
+    void testSigningTransformationReference(String xpathValue, String expectedDigest) throws Throwable {
+        // given
+        Document doc = TestUtils.getTestDocumentFromResource("input-santuario-623.xml");
+        // configure the transformations and sign the document
+        Transforms transforms = new Transforms(doc);
+        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
+        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
+        XPath2FilterContainer xpath = XPath2FilterContainer.newInstanceSubtract(doc, xpathValue);
+        transforms.addTransform(Transforms.TRANSFORM_XPATH2FILTER, xpath.getElementPlusReturns());
+
+        // when
+        XMLSignature signature = signDocument(doc, transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
+        // then
+        PublicKey pubKey = getPublicKey(XmlSecTestEnvironment.getTestKeyStore());
+        assertTrue(signature.checkSignatureValue(pubKey));
+
+        // Check the reference(s)
+        SignedInfo signedInfo = signature.getSignedInfo();
+        Reference reference = signedInfo.item(0);
+        String value = Base64.getEncoder().encodeToString(reference.getDigestValue());
+
+        assertEquals(1, signedInfo.getLength());
+        assertEquals(expectedDigest, value);
+    }
+
     // See SANTUARIO-465
     @Test
     void testNoReferenceChildren() throws ParserConfigurationException, XMLSecurityException {
@@ -218,16 +259,30 @@ class SignatureReferenceTest {
     }
 
     private XMLSignature signDocument(Document doc) throws Throwable {
+        Transforms transforms = new Transforms(doc);
+        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
+        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
+
+        return signDocument(doc, transforms, Constants.ALGO_ID_DIGEST_SHA1);
+    }
+
+    /**
+     * Sign the document with the given transforms and reference digest algorithm. The signature
+     * is created with a DSA key.
+     * @param doc the document to sign
+     * @param transforms the transforms to apply to the references before signing
+     * @param referenceDigestAlgorithm the digest algorithm to use for the references
+     * @return the signature object
+     * @throws Throwable if an error occurs
+     */
+    private XMLSignature signDocument(Document doc, Transforms transforms, String referenceDigestAlgorithm) throws Throwable {
         XMLSignature sig = new XMLSignature(doc, "", XMLSignature.ALGO_ID_SIGNATURE_DSA);
         Element root = doc.getDocumentElement();
         root.appendChild(sig.getElement());
 
         sig.getSignedInfo().addResourceResolver(new ResolverXPointer());
 
-        Transforms transforms = new Transforms(doc);
-        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
-        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
-        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
+        sig.addDocument("", transforms, referenceDigestAlgorithm);
         KeyStore keyStore = XmlSecTestEnvironment.getTestKeyStore();
         sig.addKeyInfo(getPublicKey(keyStore));
         sig.sign(getPrivateKey(keyStore));
@@ -259,4 +314,4 @@ class SignatureReferenceTest {
         }
 
     }
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/apache/xml/security/test/dom/transforms/implementations/Xpath2TransformationTest.java b/src/test/java/org/apache/xml/security/test/dom/transforms/implementations/Xpath2TransformationTest.java
index 160af6c3..d2a0971e 100644
--- a/src/test/java/org/apache/xml/security/test/dom/transforms/implementations/Xpath2TransformationTest.java
+++ b/src/test/java/org/apache/xml/security/test/dom/transforms/implementations/Xpath2TransformationTest.java
@@ -19,18 +19,39 @@
 package org.apache.xml.security.test.dom.transforms.implementations;
 
 
-import java.io.ByteArrayInputStream;
-
 import org.apache.xml.security.Init;
 import org.apache.xml.security.signature.XMLSignature;
+import org.apache.xml.security.signature.XMLSignatureInput;
+import org.apache.xml.security.signature.XMLSignatureNodeInput;
+import org.apache.xml.security.testutils.Assertions;
+import org.apache.xml.security.test.dom.TestUtils;
+import org.apache.xml.security.transforms.Transforms;
+import org.apache.xml.security.transforms.params.XPath2FilterContainer;
 import org.apache.xml.security.utils.Constants;
 import org.apache.xml.security.utils.XMLUtils;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.platform.commons.util.StringUtils;
+import org.w3c.dom.Document;
 import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.HashMap;
+import java.util.Map;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 
+/**
+ * Tests the XPath2Transformation implementation
+ *
+ * @see <A HREF="http://www.w3.org/TR/xmldsig-filter2/">XPath Filter v2.0 (TR)</A>
+ */
 class Xpath2TransformationTest {
+    private static final String TEST_PARAM_LIST_SEPARATOR = ";";
+    private static final String TEST_PARAM_VALUE_SEPARATOR = "::";
 
     static {
         Init.init();
@@ -157,4 +178,71 @@ class Xpath2TransformationTest {
         }
     }
 
-}
\ No newline at end of file
+    /**
+     * Test the XPath2FilterContainer implementation with the example from the specification
+     * <A HREF="https://www.w3.org/TR/xmldsig-filter2/#sec-Examples">4. Examples of Signature
+     * Filter Transform Processing</A>
+     *
+     * @param xPathFilter the filter configuration as a string. The parameter is a list of
+     *                    filters separated by ";" and each filter is a pair of filter type
+     *                    and xpath separated by "::"
+     * @param resultValidationXPath the expected nodes count for each xpath as a string.
+     *                              The parameter is a list of xpaths  separated by ";"
+     *                              and each xpath is a pair of xpath and expected
+     *                              node count separated by "::"
+     * @throws Exception if an error occurs while performing the transformation
+     */
+    @ParameterizedTest
+    @CsvSource({
+            "intersect:://ToBeSigned, //ToBeSigned::2;//Data::4",
+            "intersect:://ToBeSigned;subtract:://NotToBeSigned, //ToBeSigned::2;//Data::2;//NotToBeSigned::0;//ReallyToBeSigned::0",
+            "intersect:://ToBeSigned;subtract:://NotToBeSigned;union:://ReallyToBeSigned, //ToBeSigned::2;//Data::3;//NotToBeSigned::0;//ReallyToBeSigned::1",
+    })
+    void testXPath2TransformExample(String xPathFilter, String resultValidationXPath) throws Exception {
+        Map<String, String> filterConfiguration = convertStringToMap(xPathFilter);
+        Map<String, String> assertNodeCountByXPaths = convertStringToMap(resultValidationXPath);
+
+        Document testDocument =  TestUtils.getTestDocumentFromResource("input-santuario-623.xml");
+        // create Transform filter
+        // create string array of [][] of filterConfiguration
+        String[][] filterConfigurationArray = filterConfiguration.entrySet()
+                .stream()
+                .map(entry -> new String[]{entry.getKey(), entry.getValue()})
+                .toArray(String[][]::new);
+
+        NodeList xpathElements = XPath2FilterContainer.newInstances(testDocument, filterConfigurationArray);
+        Transforms transforms = new Transforms(testDocument);
+        transforms.addTransform(Transforms.TRANSFORM_XPATH2FILTER, xpathElements);
+
+        // when: perform transformation
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        XMLSignatureInput res = transforms.performTransforms(new XMLSignatureNodeInput(testDocument), os);
+
+        // then: validate the result
+        Document resultDocument = TestUtils.xmlFragmentToDocument(res.getBytes());
+        Assertions.assertNodeCountForXPath(resultDocument, assertNodeCountByXPaths);
+    }
+
+    /**
+     * Get map values from string where each entry is separated by "list separator" ';' and
+     * key and value are separated by "value separator": '::'
+     * @param input the input string to convert to map
+     *              (e.g. "intersect:://ToBeSigned;subtract:://NotToBeSigned")
+*    * @return the map of key value pairs.
+     */
+    private Map<String, String> convertStringToMap(String input) {
+        if (StringUtils.isBlank(input)) {
+            return Map.of();
+        }
+
+        String[] entries = input.split(TEST_PARAM_LIST_SEPARATOR);
+        Map<String, String> map = new HashMap<>();
+        for (String entry : entries) {
+            String[] parts = entry.split(TEST_PARAM_VALUE_SEPARATOR);
+            if (parts.length == 2) {
+                map.put(parts[0], parts[1]);
+            }
+        }
+        return map;
+    }
+}
diff --git a/src/test/java/org/apache/xml/security/testutils/Assertions.java b/src/test/java/org/apache/xml/security/testutils/Assertions.java
new file mode 100644
index 00000000..d309b077
--- /dev/null
+++ b/src/test/java/org/apache/xml/security/testutils/Assertions.java
@@ -0,0 +1,68 @@
+/* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.apache.xml.security.testutils;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * {@code Assertions} is a collection of utility methods that support asserting
+ * conditions in DOM structure testing.
+ */
+public class Assertions {
+
+    /**
+     * Asserts that document contains the expected number of nodes for the given XPaths.
+     * @param resultDocument the document to assert if it contains the expected number of nodes
+     * @param assertNodeCountByXPaths the map of XPaths as key  and the expected number of nodes as map value
+     * @throws XPathExpressionException if an error occurs while evaluating the XPath expression
+     * @throws AssertionError if the number of nodes for the given XPath does not match the expected number of nodes
+     */
+    public static void assertNodeCountForXPath(Document resultDocument, Map<String, String> assertNodeCountByXPaths) throws XPathExpressionException {
+
+        for (Map.Entry<String, String> entry : assertNodeCountByXPaths.entrySet()) {
+            String key = entry.getKey();
+            String value = entry.getValue();
+            assertNodeCountForXPath(resultDocument, key, Integer.parseInt(value));
+        }
+    }
+
+    //Method asserts that given XPATH returns the expected number of nodes
+
+    /**
+     * Asserts that the given document contains the expected number of nodes for the given XPath.
+     * @param doc the document to assert if it contains the expected number of nodes
+     * @param xpath the XPath string expression to evaluate
+     * @param expectedCount the expected number of nodes for the given XPath
+     * @throws XPathExpressionException if an error occurs while evaluating the XPath expression
+     * @throws AssertionError if the number of nodes for the given XPath does not match the expected number of nodes
+     */
+    public static void assertNodeCountForXPath(Document doc, String xpath, int expectedCount) throws XPathExpressionException {
+        XPath xPath = XPathFactory.newInstance().newXPath();
+        NodeList nodes = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
+        assertEquals(expectedCount, nodes.getLength(), "Node count for xpath [" + xpath + "] does not match");
+    }
+}
diff --git a/src/test/resources/org/apache/xml/security/test/javax/xml/crypto/dsig/input-santuario-623.xml b/src/test/resources/org/apache/xml/security/test/javax/xml/crypto/dsig/input-santuario-623.xml
new file mode 100644
index 00000000..e98d161d
--- /dev/null
+++ b/src/test/resources/org/apache/xml/security/test/javax/xml/crypto/dsig/input-santuario-623.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License. You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied. See the License for the
+  specific language governing permissions and limitations
+  under the License.
+-->
+<!-- Note: this file is used to test the Santuario XML Security library for the signature transformation
+ Example as defined in <A HREF="https://www.w3.org/TR/xmldsig-filter2/#sec-Examples">4. Examples of Signature Filter Transform Processing</A>
+-->
+<Document>
+    <ToBeSigned>
+        <!-- comment -->
+        <Data>Test data 1</Data>
+        <NotToBeSigned>
+            <ReallyToBeSigned>
+                <!-- comment -->
+                <Data>Test data 2</Data>
+            </ReallyToBeSigned>
+        </NotToBeSigned>
+    </ToBeSigned>
+    <ToBeSigned>
+        <Data>Test data 3</Data>
+        <NotToBeSigned>
+            <Data>Test data 4</Data>
+        </NotToBeSigned>
+    </ToBeSigned>
+</Document>