CVE-2023-29518: Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') (CWE-74)
value: XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. Any user with view rights can execute arbitrary Groovy, Python or Velocity code in XWiki leading to full access to the XWiki installation. The root cause is improper escaping of `Invitation.InvitationCommon`. This page is installed by default. The vulnerability has been patched in XWiki 15.0-rc-1, 14.10.1, 14.4.8, and 13.10.11. Users are advised to upgrade. There are no known workarounds for this issue.
CWE description: The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
CVSS v3 base score: 8.8
Published: 2023-04-19T00:15Z
Repository: https://github.com/xwiki/xwiki-platform
Language: XML
Files changed: xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/pom.xml, xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/main/resources/Invitation/InvitationCommon.xml, xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/test/java/org/xwiki/invitation/InvitationCommonPageTest.java
Commit date: 2022-12-08 10:35:10 +0100
Commit message: XWIKI-20283: Improved escaping on Invitation.InvitationCommon

Diff: diff --git a/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/pom.xml b/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/pom.xml
index 3fdfff370154b..d809fedcd9cff 100644
--- a/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/pom.xml
+++ b/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/pom.xml
@@ -42,7 +42,40 @@
       <artifactId>xwiki-platform-administration-ui</artifactId>
       <version>${project.version}</version>
       <type>xar</type>
       <scope>runtime</scope>
     </dependency>
+    <dependency>
+      <groupId>org.xwiki.platform</groupId>
+      <artifactId>xwiki-platform-rendering-xwiki</artifactId>
+      <version>${project.version}</version>
+      <scope>runtime</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.xwiki.platform</groupId>
+      <artifactId>xwiki-platform-user-default</artifactId>
+      <version>${project.version}</version>
+      <scope>runtime</scope>
+    </dependency>
+    <!-- Test dependencies. -->
+    <dependency>
+      <groupId>org.xwiki.platform</groupId>
+      <artifactId>xwiki-platform-test-page</artifactId>
+      <version>${project.version}</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.xwiki.platform</groupId>
+      <artifactId>xwiki-platform-rendering-xwiki</artifactId>
+      <version>${project.version}</version>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.xwiki.platform</groupId>
+      <artifactId>xwiki-platform-user-default</artifactId>
+      <version>${project.version}</version>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 </project>
diff --git a/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/main/resources/Invitation/InvitationCommon.xml b/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/main/resources/Invitation/InvitationCommon.xml
index 6473c94a1be10..1807432252467 100644
--- a/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/main/resources/Invitation/InvitationCommon.xml
+++ b/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/main/resources/Invitation/InvitationCommon.xml
@@ -18,11 +18,11 @@
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 -->
 
-<xwikidoc version="1.3" reference="Invitation.InvitationCommon" locale="">
+<xwikidoc version="1.4" reference="Invitation.InvitationCommon" locale="">
   <web>Invitation</web>
   <name>InvitationCommon</name>
   <language/>
   <defaultLanguage/>
   <translation>0</translation>
@@ -32,11 +32,11 @@
   <contentAuthor>xwiki:XWiki.Admin</contentAuthor>
   <version>1.1</version>
   <title/>
   <comment/>
   <minorEdit>false</minorEdit>
-  <syntaxId>xwiki/2.0</syntaxId>
+  <syntaxId>xwiki/2.1</syntaxId>
   <hidden>true</hidden>
   <content>{{velocity}}
 #*
  * Invitation Application
  * This document contains common macros used by all documents in the Invitation Application.
@@ -78,11 +78,11 @@
  *###
 #macro(displayMessage, $mail, $recipients, $invalidAddresses)
 
   {{html wiki=false clean=false}}
   &lt;div id="invitation-displaymessage" class="invitation"&gt;
-   &lt;strong&gt;$services.localization.render('xe.invitation.previewLabel')&lt;/strong&gt;
+   &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.previewLabel'))&lt;/strong&gt;
    &lt;div class="invitation invitation-preview"&gt;
     #set($recips = [])
     #set($invalid = [])
     ## get the lists of valid and invalid email addresses.
     #if("$!invalidAddresses" == '')
@@ -97,11 +97,11 @@
       #set($discard = $recips.addAll($recipients))
       #set($discard = $invalid.addAll($invalidAddresses))
     #end
     ## Print the email addresses to be sent to.
     ## To:
-    &lt;strong&gt;$services.localization.render('xe.invitation.toLabel')&lt;/strong&gt;
+    &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.toLabel'))&lt;/strong&gt;
     &lt;div id="preview-to-field" class="invitation-preview field"&gt;
      #foreach($recip in $recips)
        #if($invalid.contains($recip))
          &lt;span class="invalid-address"&gt;$!escapetool.xml($!recip)&lt;/span&gt; ##
          #set($discard = $invalid.remove($recip))
@@ -118,28 +118,28 @@
     #if($invalidAddresses &amp;&amp; $invalidAddresses.size() &gt; 0)
       &lt;p class="invalid-address-message"&gt;
        &lt;span class="errormessage"&gt;
         #if($recips.size() == 1)
           ## The email address given is invalid and will not be sent to.
-          $services.localization.render('xe.invitation.displayMessage.theAddressIsInvalid')
+          $escapetool.xml($services.localization.render('xe.invitation.displayMessage.theAddressIsInvalid'))
         #else
           #if($invalid.size() &gt; 1)
-            $services.localization.render('xe.invitation.displayMessage.someAddressesAreInvalid', [$invalidAddresses.size()])
+            $escapetool.xml($services.localization.render('xe.invitation.displayMessage.someAddressesAreInvalid', [$invalidAddresses.size()]))
           #else
-            $services.localization.render('xe.invitation.displayMessage.anAddressesIsInvalid')
+            $escapetool.xml($services.localization.render('xe.invitation.displayMessage.anAddressesIsInvalid'))
           #end
         #end
        &lt;/span&gt;
       &lt;/p&gt;
     #end
      ## Subject:
-     &lt;strong&gt;$services.localization.render('xe.invitation.subjectLabel')&lt;/strong&gt;
+     &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.subjectLabel'))&lt;/strong&gt;
     &lt;div id="preview-subjectline-field" class="invitation-preview field"&gt;
      $escapetool.xml($mail.getProperty('subjectLine').getValue())
     &lt;/div&gt;
     ## Message:
-    &lt;strong&gt;$services.localization.render('xe.invitation.contentLabel')&lt;/strong&gt;
+    &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.contentLabel'))&lt;/strong&gt;
     &lt;div id="preview-messagebody-field" class="invitation-preview field"&gt;
      $mail.getProperty('messageBody').getValue()
     &lt;/div&gt;
    &lt;/div&gt;
   &lt;/div&gt;
@@ -230,11 +230,12 @@
   #if(!$configDoc.isNew())
     $configDoc.deleteAsAuthor()
   #end
   #set($configClass = $xwiki.getDocumentAsAuthor("${doc.getSpace()}.WebHome"))
   #if($configClass.isNew())
-    {{error}}Class document [[${doc.getSpace()}.WebHome]] not found. can't run test.{{/error}}
+    #set ($classDocumentLink = $services.rendering.escape("${doc.getSpace()}.WebHome", 'xwiki/2.1'))
+    {{error}}Class document [[$classDocumentLink]] not found. can't run test.{{/error}}
   #else
     #set($config = {})
     #loadInvitationConfig($config, 'HopefullyNonexistantSpace')
     #if($config.size() &lt; 9)
       {{error}}Config map too small{{/error}}
@@ -494,14 +495,14 @@
         <multiSelect>0</multiSelect>
         <name>emailClass</name>
         <number>5</number>
         <picker>1</picker>
         <prettyName>Email message XClass</prettyName>
-        <size>30</size>
         <relationalStorage>0</relationalStorage>
         <separator> </separator>
         <separators/>
+        <size>30</size>
         <sort>none</sort>
         <sql/>
         <unmodifiable>0</unmodifiable>
         <validationMessage/>
         <validationRegExp/>
@@ -519,14 +520,14 @@
         <multiSelect>0</multiSelect>
         <name>emailContainer</name>
         <number>9</number>
         <picker>1</picker>
         <prettyName>Document containing email XObjects</prettyName>
-        <size>30</size>
         <relationalStorage>0</relationalStorage>
         <separator> </separator>
         <separators/>
+        <size>30</size>
         <sort>none</sort>
         <sql/>
         <unmodifiable>0</unmodifiable>
         <validationMessage/>
         <validationRegExp/>
@@ -841,41 +842,48 @@
       <defaultWeb/>
       <nameField/>
       <validationScript/>
       <cache>
         <cache>0</cache>
+        <defaultValue>long</defaultValue>
         <disabled>0</disabled>
         <displayType>select</displayType>
+        <freeText>forbidden</freeText>
+        <largeStorage>0</largeStorage>
         <multiSelect>0</multiSelect>
         <name>cache</name>
-        <number>6</number>
+        <number>5</number>
         <prettyName>Caching policy</prettyName>
         <relationalStorage>0</relationalStorage>
         <separator> </separator>
         <separators>|, </separators>
         <size>1</size>
         <unmodifiable>0</unmodifiable>
         <values>long|short|default|forbid</values>
         <classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
       </cache>
       <code>
+        <contenttype>PureText</contenttype>
         <disabled>0</disabled>
+        <editor>PureText</editor>
         <name>code</name>
-        <number>3</number>
+        <number>2</number>
         <prettyName>Code</prettyName>
         <rows>20</rows>
         <size>50</size>
         <unmodifiable>0</unmodifiable>
         <classType>com.xpn.xwiki.objects.classes.TextAreaClass</classType>
       </code>
       <contentType>
         <cache>0</cache>
         <disabled>0</disabled>
         <displayType>select</displayType>
+        <freeText>forbidden</freeText>
+        <largeStorage>0</largeStorage>
         <multiSelect>0</multiSelect>
         <name>contentType</name>
-        <number>1</number>
+        <number>6</number>
         <prettyName>Content Type</prettyName>
         <relationalStorage>0</relationalStorage>
         <separator> </separator>
         <separators>|, </separators>
         <size>1</size>
@@ -884,33 +892,35 @@
         <classType>com.xpn.xwiki.objects.classes.StaticListClass</classType>
       </contentType>
       <name>
         <disabled>0</disabled>
         <name>name</name>
-        <number>2</number>
+        <number>1</number>
         <prettyName>Name</prettyName>
         <size>30</size>
         <unmodifiable>0</unmodifiable>
         <classType>com.xpn.xwiki.objects.classes.StringClass</classType>
       </name>
       <parse>
         <disabled>0</disabled>
         <displayFormType>select</displayFormType>
         <displayType>yesno</displayType>
         <name>parse</name>
-        <number>5</number>
+        <number>4</number>
         <prettyName>Parse content</prettyName>
         <unmodifiable>0</unmodifiable>
         <classType>com.xpn.xwiki.objects.classes.BooleanClass</classType>
       </parse>
       <use>
         <cache>0</cache>
         <disabled>0</disabled>
         <displayType>select</displayType>
+        <freeText>forbidden</freeText>
+        <largeStorage>0</largeStorage>
         <multiSelect>0</multiSelect>
         <name>use</name>
-        <number>4</number>
+        <number>3</number>
         <prettyName>Use this extension</prettyName>
         <relationalStorage>0</relationalStorage>
         <separator> </separator>
         <separators>|, </separators>
         <size>1</size>
diff --git a/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/test/java/org/xwiki/invitation/InvitationCommonPageTest.java b/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/test/java/org/xwiki/invitation/InvitationCommonPageTest.java
new file mode 100644
index 0000000000000..56fa49d8e3959
--- /dev/null
+++ b/xwiki-platform-core/xwiki-platform-invitation/xwiki-platform-invitation-ui/src/test/java/org/xwiki/invitation/InvitationCommonPageTest.java
@@ -0,0 +1,269 @@
+/*
+ * See the NOTICE file distributed with this work for additional
+ * information regarding copyright ownership.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.xwiki.invitation;
+
+import java.util.stream.IntStream;
+
+import javax.script.ScriptContext;
+
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.xwiki.model.reference.DocumentReference;
+import org.xwiki.rendering.RenderingScriptServiceComponentList;
+import org.xwiki.rendering.internal.configuration.DefaultExtendedRenderingConfiguration;
+import org.xwiki.rendering.internal.configuration.RenderingConfigClassDocumentConfigurationSource;
+import org.xwiki.rendering.internal.macro.message.ErrorMessageMacro;
+import org.xwiki.rendering.internal.macro.message.InfoMessageMacro;
+import org.xwiki.rendering.syntax.Syntax;
+import org.xwiki.script.ScriptContextManager;
+import org.xwiki.security.authorization.AuthorizationManager;
+import org.xwiki.test.annotation.ComponentList;
+import org.xwiki.test.page.HTML50ComponentList;
+import org.xwiki.test.page.PageTest;
+import org.xwiki.test.page.TestNoScriptMacro;
+import org.xwiki.test.page.XWikiSyntax21ComponentList;
+import org.xwiki.user.UserReferenceComponentList;
+
+import com.xpn.xwiki.api.Object;
+import com.xpn.xwiki.doc.XWikiDocument;
+import com.xpn.xwiki.objects.BaseObject;
+
+import static javax.script.ScriptContext.GLOBAL_SCOPE;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test of {@code Invitation.InvitationCommon}.
+ *
+ * @version $Id$
+ * @since 15.0RC1
+ * @since 14.10.1
+ * @since 14.4.8
+ * @since 13.10.11
+ */
+@HTML50ComponentList
+@XWikiSyntax21ComponentList
+@RenderingScriptServiceComponentList
+@UserReferenceComponentList
+@ComponentList({
+    InfoMessageMacro.class,
+    ErrorMessageMacro.class,
+    // Start - Required in addition of RenderingScriptServiceComponentList
+    DefaultExtendedRenderingConfiguration.class,
+    RenderingConfigClassDocumentConfigurationSource.class,
+    // End - Required in additional of RenderingScriptServiceComponentList
+    TestNoScriptMacro.class
+})
+class InvitationCommonPageTest extends PageTest
+{
+    private ScriptContext scriptContext;
+
+    @BeforeEach
+    void setUp() throws Exception
+    {
+        AuthorizationManager authorizationManager = this.componentManager.getInstance(AuthorizationManager.class);
+        // Allow everything by default.
+        when(authorizationManager.hasAccess(any(), any(), any())).thenReturn(true);
+        this.scriptContext = this.oldcore.getMocker().<ScriptContextManager>getInstance(ScriptContextManager.class)
+            .getCurrentScriptContext();
+    }
+
+    @Test
+    void testEq0() throws Exception
+    {
+        this.context.setDoc(this.xwiki.getDocument(
+            new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon"), this.context));
+
+        DocumentReference invitationCommonReference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
+        Document document = Jsoup.parse(loadPage(invitationCommonReference).getRenderedContent(this.context));
+        assertEquals("xe.invitation.internalDocument [<script>console\\.log</script>.WebHome]",
+            document.selectFirst(".infomessage").text());
+    }
+
+    @Test
+    void testEq1ConfigClassIsNew() throws Exception
+    {
+        String spaceName = "<script>console.log</script>]]{{noscript/}}";
+        DocumentReference invitationCommonReference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
+
+        XWikiDocument doc =
+            this.xwiki.getDocument(new DocumentReference("xwiki", spaceName, "InvitationCommon"), this.context);
+        this.xwiki.saveDocument(doc, this.context);
+        this.context.setDoc(doc);
+
+        this.request.put("test", "1");
+
+        Document document = Jsoup.parse(loadPage(invitationCommonReference).getRenderedContent(this.context));
+
+        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
+        Element errorMessage = document.selectFirst(".errormessage");
+        assertEquals("Class document <script>console\\.log</script>]]{{noscript/}}.WebHome not found. "
+            + "can't run test.", errorMessage.text());
+        Element errorLink = errorMessage.selectFirst("a");
+        assertEquals("<script>console\\.log</script>]]{{noscript/}}.WebHome", errorLink.text());
+        assertEquals("<script>console\\.log</script>]]{{noscript/}}.WebHome", errorLink.attr("href"));
+    }
+
+    @Test
+    void testEq1ConfigClassExistsInvalidFromAddress() throws Exception
+    {
+        // Create an InvitationCommon file.
+        DocumentReference documentReference =
+            new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon");
+        XWikiDocument doc = this.xwiki.getDocument(documentReference, this.context);
+        this.xwiki.saveDocument(doc, this.context);
+        this.context.setDoc(doc);
+
+        // Create a WebHome file in the same space as InvitationCommon, with an XClass containing the expected fields.
+        DocumentReference configDocumentReference =
+            new DocumentReference("xwiki", "<script>console.log</script>", "WebHome");
+        XWikiDocument configDoc = this.xwiki.getDocument(configDocumentReference, this.context);
+        configDoc.getXClass().addTextField("from_address", "From Address", 30);
+        this.xwiki.saveDocument(configDoc, this.context);
+
+        // Initialize the document in the same space as InvitationCommon, containing an XObject with a WebHome XObject.
+        XWikiDocument hopefullyNonExistantSpaceDoc = this.xwiki.getDocument(
+            new DocumentReference("xwiki", "<script>console.log</script>", "HopefullyNonexistantSpace"), this.context);
+        BaseObject invitationConfigXObject =
+            hopefullyNonExistantSpaceDoc.newXObject(configDocumentReference, this.context);
+        invitationConfigXObject.set("from_address", "<script>console.log('from_address')</script>", this.context);
+        this.xwiki.saveDocument(hopefullyNonExistantSpaceDoc, this.context);
+
+        this.request.put("test", "1");
+
+        XWikiDocument invitationCommonDoc = loadPage(new DocumentReference("xwiki", "Invitation", "InvitationCommon"));
+        Document document = Jsoup.parse(invitationCommonDoc.getRenderedContent(this.context));
+
+        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
+        Element firstErrorMessage = document.selectFirst(".errormessage");
+        assertEquals("Config map too small", firstErrorMessage.text());
+        Element secondErrorMessage = document.select(".errormessage").get(1);
+        assertEquals("form_address incorrect, expecting \"no-reply@localhost.localdomain\" "
+            + "got \"<script>console.log('from_address')</script>\"", secondErrorMessage.text());
+    }
+
+    @Test
+    void testEq1ConfigClassExistsConfigMapTooSmall() throws Exception
+    {
+        // Create an InvitationCommon file.
+        XWikiDocument doc = this.xwiki
+            .getDocument(new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon"),
+                this.context);
+        this.xwiki.saveDocument(doc, this.context);
+        this.context.setDoc(doc);
+
+        // Create a WebHome file in the same space as InvitationCommon, with an XClass containing the expected fields.
+        DocumentReference configDocumentReference =
+            new DocumentReference("xwiki", "<script>console.log</script>", "WebHome");
+        XWikiDocument configDoc = this.xwiki.getDocument(configDocumentReference, this.context);
+        configDoc.getXClass().addTextField("from_address", "From Address", 30);
+
+        this.xwiki.saveDocument(configDoc, this.context);
+
+        // Initialize the document in the same space as InvitationCommon, containing an XObject with a WebHome XObject.
+        XWikiDocument hopefullyNonExistantSpaceDoc = this.xwiki.getDocument(
+            new DocumentReference("xwiki", "<script>console.log</script>", "HopefullyNonexistantSpace"), this.context);
+        BaseObject invitationConfigXObject =
+            hopefullyNonExistantSpaceDoc.newXObject(configDocumentReference, this.context);
+        invitationConfigXObject.set("from_address", "no-reply@localhost.localdomain", this.context);
+        this.xwiki.saveDocument(hopefullyNonExistantSpaceDoc, this.context);
+
+        this.request.put("test", "1");
+
+        DocumentReference reference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
+        XWikiDocument invitationCommonDoc = loadPage(reference);
+        Document document = Jsoup.parse(invitationCommonDoc.getRenderedContent(this.context));
+
+        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
+        Element firstErrorMessage = document.selectFirst(".errormessage");
+        assertEquals("Config map too small", firstErrorMessage.text());
+        Element secondErrorMessage = document.select(".errormessage").get(1);
+        assertEquals("Config document not created", secondErrorMessage.text());
+    }
+
+    @Test
+    void testEq1ConfigClassExistsNewInvitationConfig() throws Exception
+    {
+        // Create an InvitationCommon file.
+        XWikiDocument doc = this.xwiki.getDocument(
+            new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon"), this.context);
+        this.xwiki.saveDocument(doc, this.context);
+        this.context.setDoc(doc);
+
+        // Create a WebHome file in the same space as InvitationCommon, with an XClass containing the expected fields.
+        DocumentReference configDocumentReference =
+            new DocumentReference("xwiki", "<script>console.log</script>", "WebHome");
+        XWikiDocument configDoc = this.xwiki.getDocument(configDocumentReference, this.context);
+        configDoc.getXClass().addTextField("from_address", "From Address", 30);
+        // Initialize 8 fields, because that's the only check performed in the document currently.
+        IntStream.range(0, 8)
+            .forEach(value -> configDoc.getXClass().addTextField("field" + value, "Field " + value, 30));
+        this.xwiki.saveDocument(configDoc, this.context);
+
+        // Initialize the document in the same space as InvitationCommon, containing an XObject with a WebHome XObject.
+        XWikiDocument hopefullyNonExistantSpaceDoc = this.xwiki.getDocument(
+            new DocumentReference("xwiki", "<script>console.log</script>", "HopefullyNonexistantSpace"), this.context);
+        BaseObject invitationConfigXObject =
+            hopefullyNonExistantSpaceDoc.newXObject(configDocumentReference, this.context);
+        invitationConfigXObject.set("from_address", "no-reply@localhost.localdomain", this.context);
+        IntStream.range(0, 8)
+            .forEach(value -> invitationConfigXObject.set("field" + value, "value " + value, this.context));
+        this.xwiki.saveDocument(hopefullyNonExistantSpaceDoc, this.context);
+
+        this.request.put("test", "1");
+
+        DocumentReference reference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
+        XWikiDocument invitationCommonDoc = loadPage(reference);
+        Document document = Jsoup.parse(invitationCommonDoc.getRenderedContent(this.context));
+
+        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
+        Element firstErrorMessage = document.selectFirst(".errormessage");
+        assertEquals("Config document not created", firstErrorMessage.text());
+    }
+
+    @Test
+    void displayMessageVelocityMacro() throws Exception
+    {
+        loadPage(new DocumentReference("xwiki", "Invitation", "InvitationCommon"));
+        DocumentReference invitationMailClassDocumentReference =
+            new DocumentReference("xwiki", "Invitation", "InvitationMailClass");
+        loadPage(invitationMailClassDocumentReference);
+
+        XWikiDocument page = this.xwiki.getDocument(new DocumentReference("xwiki", "Space", "Page"), this.context);
+        BaseObject invitationMailXObject = page.newXObject(invitationMailClassDocumentReference, this.context);
+        invitationMailXObject.set("messageBody", "<strong>message body</strong>", this.context);
+        page.setSyntax(Syntax.XWIKI_2_1);
+        page.setContent("{{include reference=\"Invitation.InvitationCommon\"/}}\n"
+            + "\n"
+            + "{{velocity}}\n"
+            + "$mail.class\n"
+            + "#displayMessage($mail)\n"
+            + "{{/velocity}}");
+
+        this.scriptContext.setAttribute("mail", new Object(invitationMailXObject, this.context), GLOBAL_SCOPE);
+
+        Document document = renderHTMLPage(page);
+        assertEquals("<strong>message body</strong>", document.selectFirst("#preview-messagebody-field").html());
+    }
+}

Vulnerable code: <xwikidoc version="1.3" reference="Invitation.InvitationCommon" locale="">
  <syntaxId>xwiki/2.0</syntaxId>
   &lt;strong&gt;$services.localization.render('xe.invitation.previewLabel')&lt;/strong&gt;
    &lt;strong&gt;$services.localization.render('xe.invitation.toLabel')&lt;/strong&gt;
          $services.localization.render('xe.invitation.displayMessage.theAddressIsInvalid')
            $services.localization.render('xe.invitation.displayMessage.someAddressesAreInvalid', [$invalidAddresses.size()])
            $services.localization.render('xe.invitation.displayMessage.anAddressesIsInvalid')
     &lt;strong&gt;$services.localization.render('xe.invitation.subjectLabel')&lt;/strong&gt;
    &lt;strong&gt;$services.localization.render('xe.invitation.contentLabel')&lt;/strong&gt;
    {{error}}Class document [[${doc.getSpace()}.WebHome]] not found. can't run test.{{/error}}
        <size>30</size>
        <size>30</size>
        <number>6</number>
        <number>3</number>
        <number>1</number>
        <number>2</number>
        <number>5</number>
        <number>4</number>
Fixed code:     <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-rendering-xwiki</artifactId>
      <version>${project.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-user-default</artifactId>
      <version>${project.version}</version>
      <scope>runtime</scope>
    </dependency>
    <!-- Test dependencies. -->
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-test-page</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-rendering-xwiki</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.xwiki.platform</groupId>
      <artifactId>xwiki-platform-user-default</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
<xwikidoc version="1.4" reference="Invitation.InvitationCommon" locale="">
  <syntaxId>xwiki/2.1</syntaxId>
   &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.previewLabel'))&lt;/strong&gt;
    &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.toLabel'))&lt;/strong&gt;
          $escapetool.xml($services.localization.render('xe.invitation.displayMessage.theAddressIsInvalid'))
            $escapetool.xml($services.localization.render('xe.invitation.displayMessage.someAddressesAreInvalid', [$invalidAddresses.size()]))
            $escapetool.xml($services.localization.render('xe.invitation.displayMessage.anAddressesIsInvalid'))
     &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.subjectLabel'))&lt;/strong&gt;
    &lt;strong&gt;$escapetool.xml($services.localization.render('xe.invitation.contentLabel'))&lt;/strong&gt;
    #set ($classDocumentLink = $services.rendering.escape("${doc.getSpace()}.WebHome", 'xwiki/2.1'))
    {{error}}Class document [[$classDocumentLink]] not found. can't run test.{{/error}}
        <size>30</size>
        <size>30</size>
        <defaultValue>long</defaultValue>
        <freeText>forbidden</freeText>
        <largeStorage>0</largeStorage>
        <number>5</number>
        <contenttype>PureText</contenttype>
        <editor>PureText</editor>
        <number>2</number>
        <freeText>forbidden</freeText>
        <largeStorage>0</largeStorage>
        <number>6</number>
        <number>1</number>
        <number>4</number>
        <freeText>forbidden</freeText>
        <largeStorage>0</largeStorage>
        <number>3</number>
/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.invitation;

import java.util.stream.IntStream;

import javax.script.ScriptContext;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.rendering.RenderingScriptServiceComponentList;
import org.xwiki.rendering.internal.configuration.DefaultExtendedRenderingConfiguration;
import org.xwiki.rendering.internal.configuration.RenderingConfigClassDocumentConfigurationSource;
import org.xwiki.rendering.internal.macro.message.ErrorMessageMacro;
import org.xwiki.rendering.internal.macro.message.InfoMessageMacro;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.script.ScriptContextManager;
import org.xwiki.security.authorization.AuthorizationManager;
import org.xwiki.test.annotation.ComponentList;
import org.xwiki.test.page.HTML50ComponentList;
import org.xwiki.test.page.PageTest;
import org.xwiki.test.page.TestNoScriptMacro;
import org.xwiki.test.page.XWikiSyntax21ComponentList;
import org.xwiki.user.UserReferenceComponentList;

import com.xpn.xwiki.api.Object;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;

import static javax.script.ScriptContext.GLOBAL_SCOPE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

/**
 * Test of {@code Invitation.InvitationCommon}.
 *
 * @version $Id$
 * @since 15.0RC1
 * @since 14.10.1
 * @since 14.4.8
 * @since 13.10.11
 */
@HTML50ComponentList
@XWikiSyntax21ComponentList
@RenderingScriptServiceComponentList
@UserReferenceComponentList
@ComponentList({
    InfoMessageMacro.class,
    ErrorMessageMacro.class,
    // Start - Required in addition of RenderingScriptServiceComponentList
    DefaultExtendedRenderingConfiguration.class,
    RenderingConfigClassDocumentConfigurationSource.class,
    // End - Required in additional of RenderingScriptServiceComponentList
    TestNoScriptMacro.class
})
class InvitationCommonPageTest extends PageTest
{
    private ScriptContext scriptContext;

    @BeforeEach
    void setUp() throws Exception
    {
        AuthorizationManager authorizationManager = this.componentManager.getInstance(AuthorizationManager.class);
        // Allow everything by default.
        when(authorizationManager.hasAccess(any(), any(), any())).thenReturn(true);
        this.scriptContext = this.oldcore.getMocker().<ScriptContextManager>getInstance(ScriptContextManager.class)
            .getCurrentScriptContext();
    }

    @Test
    void testEq0() throws Exception
    {
        this.context.setDoc(this.xwiki.getDocument(
            new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon"), this.context));

        DocumentReference invitationCommonReference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
        Document document = Jsoup.parse(loadPage(invitationCommonReference).getRenderedContent(this.context));
        assertEquals("xe.invitation.internalDocument [<script>console\\.log</script>.WebHome]",
            document.selectFirst(".infomessage").text());
    }

    @Test
    void testEq1ConfigClassIsNew() throws Exception
    {
        String spaceName = "<script>console.log</script>]]{{noscript/}}";
        DocumentReference invitationCommonReference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");

        XWikiDocument doc =
            this.xwiki.getDocument(new DocumentReference("xwiki", spaceName, "InvitationCommon"), this.context);
        this.xwiki.saveDocument(doc, this.context);
        this.context.setDoc(doc);

        this.request.put("test", "1");

        Document document = Jsoup.parse(loadPage(invitationCommonReference).getRenderedContent(this.context));

        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
        Element errorMessage = document.selectFirst(".errormessage");
        assertEquals("Class document <script>console\\.log</script>]]{{noscript/}}.WebHome not found. "
            + "can't run test.", errorMessage.text());
        Element errorLink = errorMessage.selectFirst("a");
        assertEquals("<script>console\\.log</script>]]{{noscript/}}.WebHome", errorLink.text());
        assertEquals("<script>console\\.log</script>]]{{noscript/}}.WebHome", errorLink.attr("href"));
    }

    @Test
    void testEq1ConfigClassExistsInvalidFromAddress() throws Exception
    {
        // Create an InvitationCommon file.
        DocumentReference documentReference =
            new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon");
        XWikiDocument doc = this.xwiki.getDocument(documentReference, this.context);
        this.xwiki.saveDocument(doc, this.context);
        this.context.setDoc(doc);

        // Create a WebHome file in the same space as InvitationCommon, with an XClass containing the expected fields.
        DocumentReference configDocumentReference =
            new DocumentReference("xwiki", "<script>console.log</script>", "WebHome");
        XWikiDocument configDoc = this.xwiki.getDocument(configDocumentReference, this.context);
        configDoc.getXClass().addTextField("from_address", "From Address", 30);
        this.xwiki.saveDocument(configDoc, this.context);

        // Initialize the document in the same space as InvitationCommon, containing an XObject with a WebHome XObject.
        XWikiDocument hopefullyNonExistantSpaceDoc = this.xwiki.getDocument(
            new DocumentReference("xwiki", "<script>console.log</script>", "HopefullyNonexistantSpace"), this.context);
        BaseObject invitationConfigXObject =
            hopefullyNonExistantSpaceDoc.newXObject(configDocumentReference, this.context);
        invitationConfigXObject.set("from_address", "<script>console.log('from_address')</script>", this.context);
        this.xwiki.saveDocument(hopefullyNonExistantSpaceDoc, this.context);

        this.request.put("test", "1");

        XWikiDocument invitationCommonDoc = loadPage(new DocumentReference("xwiki", "Invitation", "InvitationCommon"));
        Document document = Jsoup.parse(invitationCommonDoc.getRenderedContent(this.context));

        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
        Element firstErrorMessage = document.selectFirst(".errormessage");
        assertEquals("Config map too small", firstErrorMessage.text());
        Element secondErrorMessage = document.select(".errormessage").get(1);
        assertEquals("form_address incorrect, expecting \"no-reply@localhost.localdomain\" "
            + "got \"<script>console.log('from_address')</script>\"", secondErrorMessage.text());
    }

    @Test
    void testEq1ConfigClassExistsConfigMapTooSmall() throws Exception
    {
        // Create an InvitationCommon file.
        XWikiDocument doc = this.xwiki
            .getDocument(new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon"),
                this.context);
        this.xwiki.saveDocument(doc, this.context);
        this.context.setDoc(doc);

        // Create a WebHome file in the same space as InvitationCommon, with an XClass containing the expected fields.
        DocumentReference configDocumentReference =
            new DocumentReference("xwiki", "<script>console.log</script>", "WebHome");
        XWikiDocument configDoc = this.xwiki.getDocument(configDocumentReference, this.context);
        configDoc.getXClass().addTextField("from_address", "From Address", 30);

        this.xwiki.saveDocument(configDoc, this.context);

        // Initialize the document in the same space as InvitationCommon, containing an XObject with a WebHome XObject.
        XWikiDocument hopefullyNonExistantSpaceDoc = this.xwiki.getDocument(
            new DocumentReference("xwiki", "<script>console.log</script>", "HopefullyNonexistantSpace"), this.context);
        BaseObject invitationConfigXObject =
            hopefullyNonExistantSpaceDoc.newXObject(configDocumentReference, this.context);
        invitationConfigXObject.set("from_address", "no-reply@localhost.localdomain", this.context);
        this.xwiki.saveDocument(hopefullyNonExistantSpaceDoc, this.context);

        this.request.put("test", "1");

        DocumentReference reference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
        XWikiDocument invitationCommonDoc = loadPage(reference);
        Document document = Jsoup.parse(invitationCommonDoc.getRenderedContent(this.context));

        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
        Element firstErrorMessage = document.selectFirst(".errormessage");
        assertEquals("Config map too small", firstErrorMessage.text());
        Element secondErrorMessage = document.select(".errormessage").get(1);
        assertEquals("Config document not created", secondErrorMessage.text());
    }

    @Test
    void testEq1ConfigClassExistsNewInvitationConfig() throws Exception
    {
        // Create an InvitationCommon file.
        XWikiDocument doc = this.xwiki.getDocument(
            new DocumentReference("xwiki", "<script>console.log</script>", "InvitationCommon"), this.context);
        this.xwiki.saveDocument(doc, this.context);
        this.context.setDoc(doc);

        // Create a WebHome file in the same space as InvitationCommon, with an XClass containing the expected fields.
        DocumentReference configDocumentReference =
            new DocumentReference("xwiki", "<script>console.log</script>", "WebHome");
        XWikiDocument configDoc = this.xwiki.getDocument(configDocumentReference, this.context);
        configDoc.getXClass().addTextField("from_address", "From Address", 30);
        // Initialize 8 fields, because that's the only check performed in the document currently.
        IntStream.range(0, 8)
            .forEach(value -> configDoc.getXClass().addTextField("field" + value, "Field " + value, 30));
        this.xwiki.saveDocument(configDoc, this.context);

        // Initialize the document in the same space as InvitationCommon, containing an XObject with a WebHome XObject.
        XWikiDocument hopefullyNonExistantSpaceDoc = this.xwiki.getDocument(
            new DocumentReference("xwiki", "<script>console.log</script>", "HopefullyNonexistantSpace"), this.context);
        BaseObject invitationConfigXObject =
            hopefullyNonExistantSpaceDoc.newXObject(configDocumentReference, this.context);
        invitationConfigXObject.set("from_address", "no-reply@localhost.localdomain", this.context);
        IntStream.range(0, 8)
            .forEach(value -> invitationConfigXObject.set("field" + value, "value " + value, this.context));
        this.xwiki.saveDocument(hopefullyNonExistantSpaceDoc, this.context);

        this.request.put("test", "1");

        DocumentReference reference = new DocumentReference("xwiki", "Invitation", "InvitationCommon");
        XWikiDocument invitationCommonDoc = loadPage(reference);
        Document document = Jsoup.parse(invitationCommonDoc.getRenderedContent(this.context));

        assertEquals("testLoadInvitationConfig", document.selectFirst(".infomessage").text());
        Element firstErrorMessage = document.selectFirst(".errormessage");
        assertEquals("Config document not created", firstErrorMessage.text());
    }

    @Test
    void displayMessageVelocityMacro() throws Exception
    {
        loadPage(new DocumentReference("xwiki", "Invitation", "InvitationCommon"));
        DocumentReference invitationMailClassDocumentReference =
            new DocumentReference("xwiki", "Invitation", "InvitationMailClass");
        loadPage(invitationMailClassDocumentReference);

        XWikiDocument page = this.xwiki.getDocument(new DocumentReference("xwiki", "Space", "Page"), this.context);
        BaseObject invitationMailXObject = page.newXObject(invitationMailClassDocumentReference, this.context);
        invitationMailXObject.set("messageBody", "<strong>message body</strong>", this.context);
        page.setSyntax(Syntax.XWIKI_2_1);
        page.setContent("{{include reference=\"Invitation.InvitationCommon\"/}}\n"
            + "\n"
            + "{{velocity}}\n"
            + "$mail.class\n"
            + "#displayMessage($mail)\n"
            + "{{/velocity}}");

        this.scriptContext.setAttribute("mail", new Object(invitationMailXObject, this.context), GLOBAL_SCOPE);

        Document document = renderHTMLPage(page);
        assertEquals("<strong>message body</strong>", document.selectFirst("#preview-messagebody-field").html());
    }
}