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

gnodet pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/maven-4.0.x by this push:
     new 73fae427a9 [Backport maven-4.0.x] #13882: Reject unknown root 
namespaces when strictly reading POMs (#14034)
73fae427a9 is described below

commit 73fae427a9524383d6621a9d75a51e36b342d45a
Author: Guillaume Nodet <[email protected]>
AuthorDate: Tue Nov 17 08:31:13 2026 +0100

    [Backport maven-4.0.x] #13882: Reject unknown root namespaces when strictly 
reading POMs (#14034)
    
    Backport of #13882 to `maven-4.0.x`.
    
    The generated MavenStaxReader verified that child elements share the root
    element's namespace, but never validated the root namespace itself, so
    `<project xmlns="https://ff.com";>` was accepted.
    
    When the existing (previously unused) `enforceNamespace` template parameter
    is set, reader-stax.vm now emits the list of accepted root namespaces,
    derived from the model's XmlModelMetadata for every model version between
    `minimalVersion` and the generated version.
    
    In strict mode, a root element in any other namespace is rejected;
    no namespace remains allowed.
    
    4.0.x adaptations:
    - Remove 4.2.0 namespace from accepted namespaces test (not a valid POM
      namespace on the 4.0.x branch)
    - Add missing imports (ModelBuilderException, assertThrows) to
      DefaultModelBuilderTest — these were already on master but absent on 4.0.x
    
    Cherry-picked from 68efb356909488888a672fd1808abf54ecdebda2
    
    Co-authored-by: Vincent Potuček <[email protected]>
---
 .../maven/impl/model/DefaultModelBuilderTest.java  | 47 ++++++++++++++
 .../resources/poms/factory/random-namespace.xml    | 26 ++++++++
 impl/maven-support/pom.xml                         |  5 ++
 .../apache/maven/model/v4/MavenStaxReaderTest.java | 61 +++++++++++++++++++
 src/mdo/reader-stax.vm                             | 71 ++++++++++++++++++++++
 5 files changed, 210 insertions(+)

diff --git 
a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java
 
b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java
index ccaf10f8a9..a7f6ac01ba 100644
--- 
a/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java
+++ 
b/impl/maven-impl/src/test/java/org/apache/maven/impl/model/DefaultModelBuilderTest.java
@@ -44,6 +44,7 @@
 import org.apache.maven.api.model.Repository;
 import org.apache.maven.api.services.BuilderProblem;
 import org.apache.maven.api.services.ModelBuilder;
+import org.apache.maven.api.services.ModelBuilderException;
 import org.apache.maven.api.services.ModelBuilderRequest;
 import org.apache.maven.api.services.ModelBuilderResult;
 import org.apache.maven.api.services.ModelProblem;
@@ -65,6 +66,7 @@
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /**
@@ -122,6 +124,51 @@ public void testPropertiesAndProfiles() {
         assertEquals("21", 
result.getEffectiveModel().getProperties().get("maven.compiler.release"));
     }
 
+    /**
+     * A project POM whose root element is in an unknown namespace must fail 
the build
+     * (<a href="https://github.com/apache/maven/issues/10985";>#10985</a>).
+     */
+    @Test
+    void testRandomNamespaceIsRejectedForProjectBuild() {
+        ModelBuilderRequest request = ModelBuilderRequest.builder()
+                .session(session)
+                .requestType(ModelBuilderRequest.RequestType.BUILD_PROJECT)
+                .source(Sources.buildSource(getPom("random-namespace")))
+                .build();
+
+        ModelBuilderException e = assertThrows(
+                ModelBuilderException.class, () -> 
builder.newSession().build(request));
+        assertTrue(
+                e.getProblemCollector()
+                        .problems()
+                        .anyMatch(p -> p.getSeverity() == 
BuilderProblem.Severity.ERROR
+                                && p.getMessage().contains("Unrecognized 
namespace 'https://ff.com'")),
+                () -> "Expected an error about the unrecognized namespace, 
got: "
+                        + e.getProblemCollector().problems().toList());
+    }
+
+    /**
+     * POMs consumed from repositories are parsed leniently: an unknown root 
namespace must not
+     * break the resolution of existing artifacts.
+     */
+    @Test
+    void testRandomNamespaceIsToleratedForDependencyModel() {
+        ModelBuilderRequest request = ModelBuilderRequest.builder()
+                .session(session)
+                
.requestType(ModelBuilderRequest.RequestType.CONSUMER_DEPENDENCY)
+                .source(Sources.buildSource(getPom("random-namespace")))
+                .build();
+
+        ModelBuilderResult result = builder.newSession().build(request);
+
+        assertEquals("random-namespace", 
result.getEffectiveModel().getArtifactId());
+        assertTrue(
+                result.getProblemCollector().problems().noneMatch(p -> 
p.getMessage()
+                        .contains("Unrecognized namespace")),
+                () -> "Unexpected namespace problem: "
+                        + result.getProblemCollector().problems().toList());
+    }
+
     /**
      * Models built at {@link 
ModelBuilderRequest.RequestType#CONSUMER_DEPENDENCY} come from a
      * dependency POM resolved from a repository. Their file, property, and 
condition activators
diff --git 
a/impl/maven-impl/src/test/resources/poms/factory/random-namespace.xml 
b/impl/maven-impl/src/test/resources/poms/factory/random-namespace.xml
new file mode 100644
index 0000000000..975eb62dc7
--- /dev/null
+++ b/impl/maven-impl/src/test/resources/poms/factory/random-namespace.xml
@@ -0,0 +1,26 @@
+<?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.
+-->
+<!-- https://github.com/apache/maven/issues/10985: the root namespace is 
neither empty nor a POM namespace -->
+<project xmlns="https://ff.com";>
+  <modelVersion>4.0.0</modelVersion>
+
+  <groupId>org.apache.maven.its</groupId>
+  <artifactId>random-namespace</artifactId>
+  <version>1.0-SNAPSHOT</version>
+  <packaging>pom</packaging>
+</project>
diff --git a/impl/maven-support/pom.xml b/impl/maven-support/pom.xml
index 1b84d69d7a..3d106a5308 100644
--- a/impl/maven-support/pom.xml
+++ b/impl/maven-support/pom.xml
@@ -61,6 +61,11 @@ under the License.
       <artifactId>junit-jupiter-api</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter-params</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 
   <build>
diff --git 
a/impl/maven-support/src/test/java/org/apache/maven/model/v4/MavenStaxReaderTest.java
 
b/impl/maven-support/src/test/java/org/apache/maven/model/v4/MavenStaxReaderTest.java
index b8cf040603..0b5b64fd99 100644
--- 
a/impl/maven-support/src/test/java/org/apache/maven/model/v4/MavenStaxReaderTest.java
+++ 
b/impl/maven-support/src/test/java/org/apache/maven/model/v4/MavenStaxReaderTest.java
@@ -27,6 +27,8 @@
 import org.apache.maven.api.model.InputSource;
 import org.apache.maven.api.model.Model;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -281,6 +283,65 @@ void testLocationReportingForListElements() throws 
Exception {
         assertEquals(5, module3Location.getColumnNumber(), "Module 3 should 
start at column 5");
     }
 
+    @Test
+    void testRandomRootNamespaceIsRejectedInStrictMode() {
+        // https://github.com/apache/maven/issues/10985
+        String xml = pomWithNamespace("https://ff.com";);
+
+        XMLStreamException ex = assertThrows(XMLStreamException.class, () -> 
fromXml(xml));
+        assertTrue(
+                ex.getMessage().contains("Unrecognized namespace 
'https://ff.com' for root element 'project'"),
+                ex.getMessage());
+        
assertTrue(ex.getMessage().contains("http://maven.apache.org/POM/4.0.0";), 
ex.getMessage());
+        assertNotNull(ex.getLocation());
+        assertEquals(1, ex.getLocation().getLineNumber());
+    }
+
+    @ParameterizedTest
+    // only exact matches are accepted, no prefix matching
+    @ValueSource(
+            strings = {
+                "http://maven.apache.org/POM/";,
+                "http://maven.apache.org/POM/4.0";,
+                "http://maven.apache.org/POM/4.0.0/";,
+                "http://maven.apache.org/POM/9.9.9";,
+                // namespaces are case-sensitive and the scheme is part of the 
namespace name
+                "https://maven.apache.org/POM/4.0.0";,
+                "http://maven.apache.org/pom/4.0.0";,
+                // namespaces of other Maven models are not valid for a POM
+                "http://maven.apache.org/METADATA/1.1.0";,
+                "http://maven.apache.org/SETTINGS/1.0.0";
+            })
+    void testUnknownRootNamespacesAreRejectedInStrictMode(String ns) {
+        XMLStreamException ex = assertThrows(XMLStreamException.class, () -> 
fromXml(pomWithNamespace(ns)), ns);
+        assertTrue(ex.getMessage().contains("Unrecognized namespace '" + ns + 
"'"), ex.getMessage());
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"http://maven.apache.org/POM/4.0.0";, 
"http://maven.apache.org/POM/4.1.0"})
+    void testKnownRootNamespacesAreAcceptedInStrictMode(String ns) throws 
XMLStreamException {
+        assertEquals(ns, fromXml(pomWithNamespace(ns)).getNamespaceUri(), ns);
+    }
+
+    @Test
+    void testRandomRootNamespaceIsAcceptedInLenientMode() throws 
XMLStreamException {
+        // POMs consumed from repositories are read leniently and must keep 
working
+        Model model = new MavenStaxReader().read(new 
StringReader(pomWithNamespace("https://ff.com";)), false, null);
+
+        assertEquals("https://ff.com";, model.getNamespaceUri());
+        assertEquals("unrecognized-namespace", model.getArtifactId());
+    }
+
+    private static String pomWithNamespace(String namespace) {
+        return "<project xmlns=\"" + namespace + "\">\n"
+                + "  <modelVersion>4.0.0</modelVersion>\n"
+                + "  <groupId>org.apache.maven.its</groupId>\n"
+                + "  <artifactId>unrecognized-namespace</artifactId>\n"
+                + "  <version>1.0-SNAPSHOT</version>\n"
+                + "  <packaging>pom</packaging>\n"
+                + "</project>";
+    }
+
     private Model fromXml(String xml) throws XMLStreamException {
         MavenStaxReader reader = new MavenStaxReader();
         return reader.read(new StringReader(xml), true, null);
diff --git a/src/mdo/reader-stax.vm b/src/mdo/reader-stax.vm
index 73cd2b38c9..fd4dc20f5a 100644
--- a/src/mdo/reader-stax.vm
+++ b/src/mdo/reader-stax.vm
@@ -27,6 +27,36 @@
 #set ( $rootUcapName = $Helper.capitalise( $root.name ) )
 #set ( $rootLcapName = $Helper.uncapitalise( $root.name ) )
 #
+#if ( $enforceNamespace )
+  ## Compute the root namespaces this reader accepts: one per model version 
supported by the
+  ## reader, derived from the XML namespace declared in the .mdo file (never 
hardcoded here).
+  ## The set of versions is collected the same way as in model-version.vm.
+  #set ( $xmlModelMetadata = $model.getMetadata( 
"org.codehaus.modello.plugins.xml.metadata.XmlModelMetadata" ) )
+  #set ( $String = $model.getClass().forName( "java.lang.String" ) )
+  #set ( $TreeSet = $model.getClass().forName( "java.util.TreeSet" ) )
+  #set ( $Version = $model.getClass().forName( 
"org.codehaus.modello.model.Version" ) )
+  #set ( $nsVersions = $TreeSet.newInstance() )
+  #foreach ( $class in $model.allClasses )
+    #set ( $dummy = $nsVersions.add( $class.versionRange.fromVersion ) )
+    #foreach ( $field in $class.allFields )
+      #if ( ! $Helper.xmlFieldMetadata( $field ).transient )
+        #set ( $dummy = $nsVersions.add( $field.versionRange.fromVersion ) )
+      #end
+    #end
+  #end
+  #set ( $dummy = $nsVersions.add( $version ) )
+  #set ( $dummy = $nsVersions.remove( $Version.getConstructor( $String 
).newInstance( "0.0.0" ) ) )
+  #if ( $minimalVersion )
+    #set ( $minimalNsVersion = $Version.getConstructor( $String ).newInstance( 
$minimalVersion ) )
+    #set ( $dummy = $nsVersions.add( $minimalNsVersion ) )
+    #set ( $nsVersions = $nsVersions.tailSet( $minimalNsVersion, true ) )
+  #end
+  #set ( $nsVersions = $nsVersions.headSet( $version, true ) )
+  #set ( $allowedNamespaces = [] )
+  #foreach ( $nsVersion in $nsVersions )
+    #set ( $dummy = $allowedNamespaces.add( $xmlModelMetadata.getNamespace( 
$nsVersion ) ) )
+  #end
+#end
 #set ( $needXmlContext = false )
 #foreach ( $class in $model.allClasses )
   #set ( $allFields = $Helper.xmlFields( $class ) )
@@ -86,6 +116,21 @@ import static java.util.Map.entry;
 
 @Generated
 public class ${className} {
+#if ( $enforceNamespace )
+
+    /**
+     * The XML namespaces accepted on the root element {@code <${rootTag}>} 
when reading in strict mode,
+     * in addition to no namespace at all.
+     */
+    private static final List<String> ALLOWED_NAMESPACES = List.of(
+#foreach ( $allowedNamespace in $allowedNamespaces )
+#if ( $foreach.hasNext )
+            "${allowedNamespace}",
+#else
+            "${allowedNamespace}");
+#end
+#end
+#end
 
     public static interface ContentTransformer {
         /**
@@ -276,6 +321,11 @@ public class ${className} {
                     // fallback, already expected a XMLStreamException due to 
invalid XML
                     throw new XMLStreamException("Duplicated tag: 
'${rootTag}'", parser.getLocation(), null);
                 }
+#if ( $enforceNamespace )
+                if (strict) {
+                    checkRootNamespace(parser);
+                }
+#end
 #if ( $locationTracking )
                 $rootLcapName = parse${rootUcapName}(parser, strict, 
parser.getNamespaceURI(), inputSrc);
 #elseif ( $needXmlContext )
@@ -514,6 +564,27 @@ public class ${className} {
  #end
 #end
 
+#if ( $enforceNamespace )
+    /**
+     * Ensures the root element is either in no namespace or in one of the 
{@link #ALLOWED_NAMESPACES}.
+     *
+     * @param parser the parser, positioned on the root element
+     * @throws XMLStreamException if the root element namespace is not 
recognized
+     */
+    private static void checkRootNamespace(XMLStreamReader parser) throws 
XMLStreamException {
+        String ns = parser.getNamespaceURI();
+        if (ns != null && !ns.isEmpty() && !ALLOWED_NAMESPACES.contains(ns)) {
+            throw new XMLStreamException(
+                    String.format("Unrecognized namespace '%s' for root 
element '%s': expected no namespace or one of %s",
+                        ns,
+                        parser.getLocalName(),
+                        ALLOWED_NAMESPACES),
+                    parser.getLocation(),
+                    null);
+        }
+    }
+
+#end
     private void checkNamespace(XMLStreamReader parser, boolean strict, String 
namespace) throws XMLStreamException {
         if (strict) {
             String ns = parser.getNamespaceURI();

Reply via email to