This is an automated email from the ASF dual-hosted git repository.
cziegeler pushed a commit to branch SLING-120744
in repository
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-scripting-core.git
The following commit(s) were added to refs/heads/SLING-120744 by this push:
new b04647e Remove special get servlet and check for resource resolver in
web console plugin
b04647e is described below
commit b04647e188f5b015d768b1f144b4fc8566eca94d
Author: Carsten Ziegeler <[email protected]>
AuthorDate: Thu Oct 5 07:49:46 2023 +0200
Remove special get servlet and check for resource resolver in web console
plugin
---
.gitignore | 1 +
pom.xml | 26 +-
.../core/impl/ScriptingVariablesConsolePlugin.java | 137 ++++++++
.../SlingBindingsVariablesListJsonServlet.java | 198 ------------
.../core/impl/helper/ProtectedBindings.java | 2 +-
.../scriptingvariables/ui/scriptingvariables.js | 7 +-
.../sling/scripting/core/it/HtmlScriptingIT.java | 4 +-
.../sling/scripting/core/it/SLING_10147IT.java | 352 ---------------------
.../core/it/ScriptingCoreTestSupport.java | 6 +-
9 files changed, 166 insertions(+), 567 deletions(-)
diff --git a/.gitignore b/.gitignore
index 5b783ed..d4bfe7c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+.vscode
/target
.idea
.classpath
diff --git a/pom.xml b/pom.xml
index bfe9b9f..6be6407 100644
--- a/pom.xml
+++ b/pom.xml
@@ -103,13 +103,13 @@
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.api</artifactId>
- <version>2.23.4</version>
+ <version>2.27.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.commons.mime</artifactId>
- <version>2.0.2-incubator</version>
+ <version>2.2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -174,7 +174,7 @@
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.testing.paxexam</artifactId>
- <version>3.1.0</version>
+ <version>4.0.0</version>
<scope>test</scope>
</dependency>
<!-- OSGi -->
@@ -236,7 +236,7 @@
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.framework</artifactId>
- <version>6.0.3</version>
+ <version>7.0.5</version>
<scope>test</scope>
</dependency>
@@ -337,19 +337,31 @@
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.resourceresolver</artifactId>
- <version>1.6.16</version>
+ <version>1.11.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.servlets.resolver</artifactId>
- <version>2.8.2</version>
+ <version>2.9.14</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.engine</artifactId>
+ <version>2.15.6</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.auth.core</artifactId>
+ <version>1.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.commons.johnzon</artifactId>
- <version>1.2.6</version>
+ <version>1.2.16</version>
<scope>test</scope>
</dependency>
<dependency>
diff --git
a/src/main/java/org/apache/sling/scripting/core/impl/ScriptingVariablesConsolePlugin.java
b/src/main/java/org/apache/sling/scripting/core/impl/ScriptingVariablesConsolePlugin.java
index 89dca2d..688fc35 100644
---
a/src/main/java/org/apache/sling/scripting/core/impl/ScriptingVariablesConsolePlugin.java
+++
b/src/main/java/org/apache/sling/scripting/core/impl/ScriptingVariablesConsolePlugin.java
@@ -18,7 +18,11 @@ package org.apache.sling.scripting.core.impl;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
+import java.util.Collection;
+import java.util.Map;
+import javax.script.Bindings;
+import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.servlet.Servlet;
@@ -26,9 +30,21 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.felix.utils.json.JSONWriter;
import org.apache.felix.webconsole.AbstractWebConsolePlugin;
import org.apache.felix.webconsole.WebConsoleConstants;
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.request.builder.Builders;
+import org.apache.sling.api.resource.NonExistingResource;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.scripting.SlingBindings;
+import org.apache.sling.api.scripting.SlingScriptConstants;
+import org.apache.sling.scripting.api.BindingsValuesProvider;
+import org.apache.sling.scripting.api.BindingsValuesProvidersByContext;
+import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
+import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
@@ -48,6 +64,13 @@ public class ScriptingVariablesConsolePlugin extends
AbstractWebConsolePlugin {
protected static final String LABEL = "scriptingvariables";
protected static final String TITLE = "Scripting Variables";
+ protected static final String FORWARD_PATH = "/" + LABEL + "/show";
+
+ private static final String PARAMETER_EXTENSION = "extension";
+ private static final String PARAMETER_PATH = "path";
+
+ protected static final String REQUEST_ATTR =
ScriptingVariablesConsolePlugin.class.getName() + ".auth";
+
/**
*
*/
@@ -61,6 +84,19 @@ public class ScriptingVariablesConsolePlugin extends
AbstractWebConsolePlugin {
@Reference
private ScriptEngineManager scriptEngineManager;
+ /**
+ * The BindingsValuesProviderTracker
+ */
+ @Reference
+ private BindingsValuesProvidersByContext bindingsValuesProviderTracker;
+
+ private BundleContext bundleContext;
+
+ @Activate
+ protected void init(final BundleContext context) {
+ bundleContext = context;
+ }
+
/**
* Automatically called from
* <a
href="https://github.com/apache/felix/blob/4a60744d0f88f351551e4cb4673eb60b8fbd21d3/webconsole/src/main/java/org/apache/felix/webconsole/AbstractWebConsolePlugin.java#L510">AbstractWebConsolePlugin#spoolResource</a>
@@ -85,6 +121,33 @@ public class ScriptingVariablesConsolePlugin extends
AbstractWebConsolePlugin {
return TITLE;
}
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse
response)
+ throws ServletException, IOException {
+ final String path = request.getPathInfo();
+ if ( FORWARD_PATH.equals(path)) {
+ final ResourceResolver resolver = (ResourceResolver)
request.getAttribute("org.apache.sling.auth.core.ResourceResolver");
+ if ( resolver == null ) {
+ log("Access forbidden as the request was not authenticated
through the web console");
+ if (!response.isCommitted()) {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN);
+ }
+ return;
+ }
+ final String resourcePath = request.getParameter(PARAMETER_PATH);
+ final String extension = request.getParameter(PARAMETER_EXTENSION);
+ // resolve is used to get non existing resources as well
+ final Resource resource = resolver.resolve(resourcePath);
+ final SlingHttpServletRequest slingRequest =
Builders.newRequestBuilder(resource)
+ .useServletContextFrom(request)
+ .useAttributesFrom(request)
+ .build();
+ this.showBindings(slingRequest, response, extension);
+ return;
+ }
+ super.doGet(request, response);
+ }
+
@Override
protected void renderContent(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
@@ -111,4 +174,78 @@ public class ScriptingVariablesConsolePlugin extends
AbstractWebConsolePlugin {
pw.append("<button type='button' id='submitButton'> Retrieve Variables
</button></td></tr></table>");
pw.append("<div id='response'></div>");
}
+
+ protected void showBindings(SlingHttpServletRequest request,
HttpServletResponse response, final String requestedExtension)
+ throws ServletException, IOException {
+ response.setContentType("application/json");
+ JSONWriter jsonWriter = new JSONWriter(response.getWriter());
+ jsonWriter.array();
+ // get filter by engine selector
+ if (requestedExtension != null && !requestedExtension.isEmpty() ) {
+ ScriptEngine selectedScriptEngine =
scriptEngineManager.getEngineByExtension(requestedExtension);
+ if (selectedScriptEngine == null) {
+ throw new IllegalArgumentException("Invalid extension
requested: "+requestedExtension);
+ } else {
+ writeBindingsToJsonWriter(jsonWriter,
selectedScriptEngine.getFactory(), request);
+ }
+ } else {
+ for (ScriptEngineFactory engineFactory :
scriptEngineManager.getEngineFactories()) {
+ writeBindingsToJsonWriter(jsonWriter, engineFactory, request);
+ }
+ }
+ jsonWriter.endArray();
+ }
+
+ private void writeBindingsToJsonWriter(JSONWriter jsonWriter,
ScriptEngineFactory engineFactory, SlingHttpServletRequest request) throws
IOException {
+ jsonWriter.object();
+ jsonWriter.key("engine");
+ jsonWriter.value(engineFactory.getEngineName());
+ jsonWriter.key("extensions");
+ jsonWriter.value(engineFactory.getExtensions());
+ Bindings bindings = getBindingsByEngine(engineFactory, request);
+ jsonWriter.key("bindings");
+ jsonWriter.array();
+ for (Map.Entry<String, Object> entry : bindings.entrySet()) {
+ jsonWriter.object();
+ jsonWriter.key("name");
+ jsonWriter.value(entry.getKey());
+ jsonWriter.key("class");
+ jsonWriter.value(entry.getValue() == null ? "<NO VALUE>" :
entry.getValue().getClass().getName());
+ jsonWriter.endObject();
+ }
+ jsonWriter.endArray();
+ jsonWriter.endObject();
+ }
+
+ /**
+ * Gets the {@link Bindings} object for the given {@link
ScriptEngineFactory}.
+ * It only considers the default context "request".
+ *
+ * @see <a href="https://issues.apache.org/jira/browse/SLING-3038">binding
contexts(SLING-3083)</a>
+ *
+ * @param scriptEngineFactory the factory of the script engine, for which
to retrieve the bindings
+ * @param request the current request (necessary to create the bindings)
+ * @param response the current response (necessary to create the bindings)
+ * @return the bindings (list of key/value pairs) as defined by {@link
Bindings} for the given script engine.
+ * @throws IOException
+ */
+ private Bindings getBindingsByEngine(ScriptEngineFactory
scriptEngineFactory, SlingHttpServletRequest request) throws IOException {
+ String context = SlingScriptAdapterFactory.BINDINGS_CONTEXT; // use
default context only
+ final Collection<BindingsValuesProvider> bindingsValuesProviders =
+
bindingsValuesProviderTracker.getBindingsValuesProviders(scriptEngineFactory,
context);
+
+ Resource invalidScriptResource = new
NonExistingResource(request.getResourceResolver(), "some/invalid/scriptpath");
+ DefaultSlingScript defaultSlingScript = new
DefaultSlingScript(bundleContext, invalidScriptResource,
scriptEngineFactory.getScriptEngine(), bindingsValuesProviders, null, null);
+
+ // prepare the bindings (similar as in DefaultSlingScript#service)
+ final SlingBindings initalBindings = new SlingBindings();
+ initalBindings.setRequest(request);
+ initalBindings.setResponse(Builders.newResponseBuilder().build());
+ final Bindings bindings =
defaultSlingScript.verifySlingBindings(initalBindings);
+
+ // only thing being added in {DefaultSlingScript#call(...)} is
resource resolver
+ bindings.put(SlingScriptConstants.ATTR_SCRIPT_RESOURCE_RESOLVER,
request.getResourceResolver());
+
+ return bindings;
+ }
}
diff --git
a/src/main/java/org/apache/sling/scripting/core/impl/SlingBindingsVariablesListJsonServlet.java
b/src/main/java/org/apache/sling/scripting/core/impl/SlingBindingsVariablesListJsonServlet.java
deleted file mode 100644
index 76ca403..0000000
---
a/src/main/java/org/apache/sling/scripting/core/impl/SlingBindingsVariablesListJsonServlet.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * 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.sling.scripting.core.impl;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Map;
-
-import javax.script.Bindings;
-import javax.script.ScriptEngine;
-import javax.script.ScriptEngineFactory;
-import javax.script.ScriptEngineManager;
-import javax.servlet.Servlet;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.felix.utils.json.JSONWriter;
-import org.apache.felix.webconsole.WebConsoleSecurityProvider;
-import org.apache.felix.webconsole.WebConsoleSecurityProvider2;
-import org.apache.sling.api.SlingHttpServletRequest;
-import org.apache.sling.api.SlingHttpServletResponse;
-import org.apache.sling.api.resource.NonExistingResource;
-import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.scripting.SlingBindings;
-import org.apache.sling.api.scripting.SlingScriptConstants;
-import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
-import org.apache.sling.scripting.api.BindingsValuesProvider;
-import org.apache.sling.scripting.api.BindingsValuesProvidersByContext;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.Constants;
-import org.osgi.service.component.ComponentContext;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Reference;
-import org.osgi.service.component.annotations.ReferenceCardinality;
-import org.osgi.service.component.annotations.ReferencePolicyOption;
-
-/**
- * Return all scripting variables for all registered scripting languages for
the default context (=request).
- * This can only be achieved when a real Sling request and Sling response is
available.
- * Also the context (i.e. the resource on which the request is acting) is
important,
- * because the actual binding variables might differ depending on the context
- */
-@Component(
- service = Servlet.class,
- property = {
- Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
- "sling.servlet.resourceTypes=sling/servlet/default",
- "sling.servlet.selectors=SLING_availablebindings",
- "sling.servlet.methods=GET",
- "sling.servlet.extensions=json"
- }
-)
-public class SlingBindingsVariablesListJsonServlet extends
SlingSafeMethodsServlet {
-
- /**
- *
- */
- private static final long serialVersionUID = -6744726829737263875L;
-
- /**
- * The webconsole security provider
- */
- @Reference(cardinality = ReferenceCardinality.OPTIONAL, policyOption =
ReferencePolicyOption.GREEDY)
- private WebConsoleSecurityProvider webconsoleSecurity;
-
- /**
- * The script engine manager.
- */
- @Reference
- private ScriptEngineManager scriptEngineManager;
-
- /**
- * The BindingsValuesProviderTracker
- */
- @Reference
- private BindingsValuesProvidersByContext bindingsValuesProviderTracker;
-
- private BundleContext bundleContext;
-
- private static final String PARAMETER_EXTENSION = "extension";
-
- @Activate
- protected void activate(ComponentContext context) {
- bundleContext = context.getBundleContext();
- }
-
- @Override
- protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response)
- throws ServletException, IOException {
- boolean allowed = true;
- if (webconsoleSecurity == null) {
- log("Access forbidden as the WebConsoleSecurity reference is not
set");
- allowed = false;
- } else if (!(webconsoleSecurity instanceof
WebConsoleSecurityProvider2)) {
- log("Access forbidden as the WebConsoleSecurity reference does not
implement WebConsoleSecurityProvider2");
- allowed = false;
- } else if
(!((WebConsoleSecurityProvider2)webconsoleSecurity).authenticate(request,
response)) {
- log("Access forbidden as the WebConsoleSecurity component returned
false");
- // the request is terminated without any more response sent back
to the client.
- // The WebConsoleSecurityProvider2 implementation may have sent
auth challenge to the client
- // in the case of anonymous access.
- allowed = false;
- }
- if (!allowed) {
- if (!response.isCommitted()) {
- response.sendError(HttpServletResponse.SC_FORBIDDEN);
- }
- return;
- }
-
- response.setContentType("application/json");
- JSONWriter jsonWriter = new JSONWriter(response.getWriter());
- jsonWriter.array();
- // get filter by engine selector
- String requestedExtension = request.getParameter(PARAMETER_EXTENSION);
- if (requestedExtension != null && !requestedExtension.isEmpty() ) {
- ScriptEngine selectedScriptEngine =
scriptEngineManager.getEngineByExtension(requestedExtension);
- if (selectedScriptEngine == null) {
- throw new IllegalArgumentException("Invalid extension
requested: "+requestedExtension);
- } else {
- writeBindingsToJsonWriter(jsonWriter,
selectedScriptEngine.getFactory(), request, response);
- }
- } else {
- for (ScriptEngineFactory engineFactory :
scriptEngineManager.getEngineFactories()) {
- writeBindingsToJsonWriter(jsonWriter, engineFactory, request,
response);
- }
- }
- jsonWriter.endArray();
- }
-
- private void writeBindingsToJsonWriter(JSONWriter jsonWriter,
ScriptEngineFactory engineFactory, SlingHttpServletRequest request,
SlingHttpServletResponse response) throws IOException {
- jsonWriter.object();
- jsonWriter.key("engine");
- jsonWriter.value(engineFactory.getEngineName());
- jsonWriter.key("extensions");
- jsonWriter.value(engineFactory.getExtensions());
- Bindings bindings = getBindingsByEngine(engineFactory, request,
response);
- jsonWriter.key("bindings");
- jsonWriter.array();
- for (Map.Entry<String, Object> entry : bindings.entrySet()) {
- jsonWriter.object();
- jsonWriter.key("name");
- jsonWriter.value(entry.getKey());
- jsonWriter.key("class");
- jsonWriter.value(entry.getValue() == null ? "<NO VALUE>" :
entry.getValue().getClass().getName());
- jsonWriter.endObject();
- }
- jsonWriter.endArray();
- jsonWriter.endObject();
- }
-
- /**
- * Gets the {@link Bindings} object for the given {@link
ScriptEngineFactory}.
- * It only considers the default context "request".
- *
- * @see <a href="https://issues.apache.org/jira/browse/SLING-3038">binding
contexts(SLING-3083)</a>
- *
- * @param scriptEngineFactory the factory of the script engine, for which
to retrieve the bindings
- * @param request the current request (necessary to create the bindings)
- * @param response the current response (necessary to create the bindings)
- * @return the bindings (list of key/value pairs) as defined by {@link
Bindings} for the given script engine.
- * @throws IOException
- */
- private Bindings getBindingsByEngine(ScriptEngineFactory
scriptEngineFactory, SlingHttpServletRequest request, SlingHttpServletResponse
response) throws IOException {
- String context = SlingScriptAdapterFactory.BINDINGS_CONTEXT; // use
default context only
- final Collection<BindingsValuesProvider> bindingsValuesProviders =
-
bindingsValuesProviderTracker.getBindingsValuesProviders(scriptEngineFactory,
context);
-
- Resource invalidScriptResource = new
NonExistingResource(request.getResourceResolver(), "some/invalid/scriptpath");
- DefaultSlingScript defaultSlingScript = new
DefaultSlingScript(bundleContext, invalidScriptResource,
scriptEngineFactory.getScriptEngine(), bindingsValuesProviders, null, null);
-
- // prepare the bindings (similar as in DefaultSlingScript#service)
- final SlingBindings initalBindings = new SlingBindings();
- initalBindings.setRequest(request);
- initalBindings.setResponse(response);
- final Bindings bindings =
defaultSlingScript.verifySlingBindings(initalBindings);
-
- // only thing being added in {DefaultSlingScript#call(...)} is
resource resolver
- bindings.put(SlingScriptConstants.ATTR_SCRIPT_RESOURCE_RESOLVER,
request.getResourceResolver());
-
- return bindings;
- }
-}
diff --git
a/src/main/java/org/apache/sling/scripting/core/impl/helper/ProtectedBindings.java
b/src/main/java/org/apache/sling/scripting/core/impl/helper/ProtectedBindings.java
index a2f8790..02b8326 100644
---
a/src/main/java/org/apache/sling/scripting/core/impl/helper/ProtectedBindings.java
+++
b/src/main/java/org/apache/sling/scripting/core/impl/helper/ProtectedBindings.java
@@ -28,7 +28,7 @@ import javax.script.Bindings;
import org.apache.sling.api.scripting.LazyBindings;
import org.jetbrains.annotations.NotNull;
-public class ProtectedBindings extends LazyBindings implements Bindings {
+public class ProtectedBindings extends LazyBindings {
private static final long serialVersionUID = -5988579857015221345L;
diff --git a/src/main/resources/scriptingvariables/ui/scriptingvariables.js
b/src/main/resources/scriptingvariables/ui/scriptingvariables.js
index 5356fc0..4666e54 100644
--- a/src/main/resources/scriptingvariables/ui/scriptingvariables.js
+++ b/src/main/resources/scriptingvariables/ui/scriptingvariables.js
@@ -41,7 +41,7 @@
function lookupVariables(path, extension) {
if (/^\//.test(path)) {
- $.ajax(appendSelectorToPath(path) +
"?extension="+extension,
+ $.ajax("scriptingvariables/show?path=" +
encodeURIComponent(path) + "&extension="+encodeURIComponent(extension),
{
type: 'GET'
}
@@ -58,11 +58,6 @@
$('#response').html('Invalid path given.');
}
}
-
- function appendSelectorToPath(path) {
- return path + ".SLING_availablebindings.json";
- }
-
function produceTableRow(variable, i) {
return "<tr class='" + (i % 2 === 0 ? "even" : "odd") + "
ui-state-default'>"
diff --git
a/src/test/java/org/apache/sling/scripting/core/it/HtmlScriptingIT.java
b/src/test/java/org/apache/sling/scripting/core/it/HtmlScriptingIT.java
index 0fbcf17..45a30d5 100644
--- a/src/test/java/org/apache/sling/scripting/core/it/HtmlScriptingIT.java
+++ b/src/test/java/org/apache/sling/scripting/core/it/HtmlScriptingIT.java
@@ -19,7 +19,7 @@
package org.apache.sling.scripting.core.it;
import static
org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
-import static
org.apache.sling.testing.paxexam.SlingOptions.slingScriptingSightly;
+import static org.apache.sling.testing.paxexam.SlingOptions.slingScriptingHtl;
import static
org.apache.sling.testing.paxexam.SlingOptions.slingScriptingThymeleaf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@@ -90,7 +90,7 @@ public class HtmlScriptingIT extends ScriptingCoreTestSupport
{
return options(
composite(
super.baseConfiguration(),
- slingScriptingSightly(),
+ slingScriptingHtl(),
slingScriptingThymeleaf(),
slingQuickstartOakTar(workingDirectory, httpPort),
factoryConfiguration("org.apache.sling.resource.presence.internal.ResourcePresenter")
diff --git
a/src/test/java/org/apache/sling/scripting/core/it/SLING_10147IT.java
b/src/test/java/org/apache/sling/scripting/core/it/SLING_10147IT.java
deleted file mode 100644
index 4312e36..0000000
--- a/src/test/java/org/apache/sling/scripting/core/it/SLING_10147IT.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * 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.sling.scripting.core.it;
-
-import static org.apache.sling.testing.paxexam.SlingOptions.slingAuthForm;
-import static
org.apache.sling.testing.paxexam.SlingOptions.slingQuickstartOakTar;
-import static
org.apache.sling.testing.paxexam.SlingOptions.slingScriptingJavascript;
-import static org.apache.sling.testing.paxexam.SlingOptions.versionResolver;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.ops4j.pax.exam.CoreOptions.composite;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.vmOption;
-import static
org.ops4j.pax.exam.cm.ConfigurationAdminOptions.factoryConfiguration;
-
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.time.Duration;
-import java.util.concurrent.Callable;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.http.Header;
-import org.apache.http.HttpEntity;
-import org.apache.http.auth.AuthenticationException;
-import org.apache.http.auth.UsernamePasswordCredentials;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.auth.BasicScheme;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.LaxRedirectStrategy;
-import org.awaitility.Awaitility;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.runners.Enclosed;
-import org.junit.rules.TestRule;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.ops4j.pax.exam.options.ModifiableCompositeOption;
-import org.ops4j.pax.exam.options.extra.VMOption;
-import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
-import org.ops4j.pax.exam.spi.reactors.PerClass;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Tests for SLING-10147 - verify scripting variables implementation details
are not
- * exposed to not authorized users
- */
-@RunWith(Enclosed.class)
-public class SLING_10147IT {
-
- private SLING_10147IT() {
- // private constructor to hide the implicit public one
- }
-
- /**
- * Base class to share the common parts of LoadedIT and NotLoadedIT
- * tests
- */
- public abstract static class BaseIT extends ScriptingCoreTestSupport {
- protected final Logger logger = LoggerFactory.getLogger(getClass());
-
- protected CloseableHttpClient httpClient;
-
- @Rule
- public TestRule watcher = new TestWatcher() {
-
- /* (non-Javadoc)
- * @see
org.junit.rules.TestWatcher#starting(org.junit.runner.Description)
- */
- @Override
- protected void starting(Description description) {
- logger.info("Starting test: {}", description.getMethodName());
- }
-
- /* (non-Javadoc)
- * @see
org.junit.rules.TestWatcher#finished(org.junit.runner.Description)
- */
- @Override
- protected void finished(Description description) {
- logger.info("Finished test: {}", description.getMethodName());
- }
-
- };
-
- @Before
- public void before() {
- waitForServices();
-
- int timeout = 15; // seconds
- RequestConfig config = RequestConfig.custom()
- .setConnectTimeout(timeout * 1000)
- .setConnectionRequestTimeout(timeout * 1000)
- .setSocketTimeout(timeout * 1000).build();
-
- HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
- .setRedirectStrategy(new LaxRedirectStrategy())
- .setDefaultRequestConfig(config);
- httpClient = httpClientBuilder.build();
- }
-
- /**
- * Wait for services to be available
- */
- protected void waitForServices() {
- final BundleContext bundleContext =
FrameworkUtil.getBundle(SLING_10147IT.class).getBundleContext();
- Awaitility.await()
- .atMost(Duration.ofMinutes(5))
- .pollInterval(Duration.ofSeconds(5))
- .until(new Callable<Boolean>() {
-
- private String [] servicesLists = new String[] {
- "org.apache.sling.jcr.api.SlingRepository",
- "org.apache.sling.engine.auth.Authenticator",
-
"org.apache.sling.api.resource.ResourceResolverFactory",
- "org.apache.sling.api.servlets.ServletResolver",
- "javax.script.ScriptEngineManager"
- };
-
- @Override
- public Boolean call() throws Exception {
- boolean foundAllServices = true;
- for (String serviceClass : servicesLists) {
- ServiceReference<?> serviceReference =
bundleContext.getServiceReference(serviceClass);
- if (serviceReference == null) {
- foundAllServices = false;
- break;
- }
- }
- return foundAllServices;
- }
-
- });
- }
-
- @After
- public void after() throws IOException {
- if (httpClient != null) {
- httpClient.close();
- httpClient = null;
- }
- }
-
- @Configuration
- public Option[] configuration() {
- versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.api");
- versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.resourceresolver");
- versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.servlets.resolver");
- versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.scripting.api");
-
- final Option webconsolesecurityprovider =
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.extensions.webconsolesecurityprovider").versionAsInProject();
- return composite(
- slingQuickstartOakTar(String.format("target/%s",
getClass().getSimpleName()), httpPort),
- slingScriptingJavascript(),
- slingAuthForm(),
- baseConfiguration(),
-
mavenBundle().groupId("org.apache.httpcomponents").artifactId("httpcore-osgi").version(versionResolver),
-
mavenBundle().groupId("org.apache.httpcomponents").artifactId("httpclient-osgi").version(versionResolver),
- webconsolesecurityprovider,
- optionalRemoteDebug()
- ).remove(
- scriptingCore // remove the old version
- ).getOptions();
- }
-
- /**
- * Optionally configure remote debugging on the port supplied by the
"debugPort"
- * system property.
- */
- protected ModifiableCompositeOption optionalRemoteDebug() {
- VMOption option = null;
- String property = System.getProperty("debugPort");
- if (property != null) {
- option =
vmOption(String.format("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=%s",
property));
- }
- return composite(option);
- }
-
- protected void checkContentType(CloseableHttpResponse response ,String
expected) {
- // Remove whatever follows semicolon in content-type
- HttpEntity entity = response.getEntity();
- Header contentTypeHeader = entity.getContentType();
- String contentType = contentTypeHeader == null ? null :
contentTypeHeader.getValue();
- if (contentType != null) {
- contentType = contentType.split(";")[0].trim();
- }
- // check for match
- assertEquals(expected, contentType);
- }
-
- }
-
- /**
- * Verify that when authorized that the scripting variables is accessible
- */
- @RunWith(PaxExam.class)
- @ExamReactorStrategy(PerClass.class)
- public static class AuthorizedIT extends BaseIT {
-
- @Test
- public void testGetSlingBindingsVariablesListJsonWithAuthorizedUser()
throws IOException, AuthenticationException {
- // make GET request and verify it returned a 200 ok
- HttpGet request = new
HttpGet(String.format("http://localhost:%d/.SLING_availablebindings.json?extension=esp",
httpPort()));
- // pre-emptive basic authentication
- request.addHeader(new BasicScheme().authenticate(new
UsernamePasswordCredentials("admin", "admin"), request, null));
-
- if (logger.isInfoEnabled()) {
- logger.info("Executing GET Request to: {}", request.getURI());
- }
- try (CloseableHttpResponse response = httpClient.execute(request))
{
- if (logger.isInfoEnabled()) {
- logger.info("Response Content\r\n: {}",
IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
- }
- // should have passed all security checks and returned the
JSON payload
- assertEquals(HttpServletResponse.SC_OK,
response.getStatusLine().getStatusCode());
- checkContentType(response, "application/json");
- }
- }
- }
-
- /**
- * Verify that when not authorized that the scripting variables is not
accessible
- */
- @RunWith(PaxExam.class)
- @ExamReactorStrategy(PerClass.class)
- public static class NotAuthorizedIT extends BaseIT {
-
- @Configuration
- @Override
- public Option[] configuration() {
- return composite(super.configuration())
- .add(// testing - add a user to use to login and verify
-
factoryConfiguration("org.apache.sling.jcr.repoinit.RepositoryInitializer")
- .put("scripts", new String[] {
- "create user sling10147 with password
sling10147"
- })
- .asOption()
- )
- .getOptions();
- }
-
- @Test
- public void
testGetSlingBindingsVariablesListJsonWithNotAuthorizedUser() throws
IOException, AuthenticationException {
- // make GET request and verify it is denied for user without
sufficient rights
- HttpGet request = new
HttpGet(String.format("http://localhost:%d/.SLING_availablebindings.json?extension=esp",
httpPort()));
- // pre-emptive basic authentication
- request.addHeader(new BasicScheme().authenticate(new
UsernamePasswordCredentials("sling10147", "sling10147"), request, null));
-
- if (logger.isInfoEnabled()) {
- logger.info("Executing GET Request to: {}", request.getURI());
- }
- try (CloseableHttpResponse response = httpClient.execute(request))
{
- if (logger.isInfoEnabled()) {
- logger.info("Response Content\r\n: {}",
IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
- }
- // should have been denied access by
WebConsoleSecurityProvider2 service access not granted to the user
- assertEquals(HttpServletResponse.SC_FORBIDDEN,
response.getStatusLine().getStatusCode());
- checkContentType(response, "text/html");
- }
- }
-
- @Test
- public void testGetSlingBindingsVariablesListJsonWithAnonymousUser()
throws IOException, AuthenticationException {
- // make GET request and verify it returned a forms login page
challenge
- HttpGet request = new
HttpGet(String.format("http://localhost:%d/.SLING_availablebindings.json?extension=esp",
httpPort()));
-
- if (logger.isInfoEnabled()) {
- logger.info("Executing GET Request to: {}", request.getURI());
- }
- try (CloseableHttpResponse response = httpClient.execute(request))
{
- String content =
IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
- if (logger.isInfoEnabled()) {
- logger.info("Response Content\r\n: {}", content);
- }
- // should have been challenged for authentication by the
WebConsoleSecurity2#authenitcate call
- assertEquals(HttpServletResponse.SC_OK,
response.getStatusLine().getStatusCode());
- checkContentType(response, "text/html");
- assertTrue("Expected forms based login page",
content.contains("Login to Apache Sling"));
- }
- }
- }
-
- /**
- * Verify that when no WebConsoleSecurityProvider2 service is available
that
- * the scripting variables is not accessible
- */
- @RunWith(PaxExam.class)
- @ExamReactorStrategy(PerClass.class)
- public static class HasNoWebConsoleSecurityProvider2IT extends BaseIT {
-
- @Configuration
- @Override
- public Option[] configuration() {
- // remove the security provider bundle from the configuration
- final Option webconsolesecurityprovider =
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.extensions.webconsolesecurityprovider").versionAsInProject();
- return composite(super.configuration())
- .remove(webconsolesecurityprovider)
- .getOptions();
- }
-
- @Test
- public void
testGetSlingBindingsVariablesListJsonWithoutWebConsoleSecurityProvider2()
throws IOException, AuthenticationException {
- // make GET request and verify it returned a 403 error
- HttpGet request = new
HttpGet(String.format("http://localhost:%d/.SLING_availablebindings.json?extension=esp",
httpPort()));
- // pre-emptive basic authentication
- request.addHeader(new BasicScheme().authenticate(new
UsernamePasswordCredentials("admin", "admin"), request, null));
-
- if (logger.isInfoEnabled()) {
- logger.info("Executing GET Request to: {}", request.getURI());
- }
- try (CloseableHttpResponse response = httpClient.execute(request))
{
- if (logger.isInfoEnabled()) {
- logger.info("Response Content\r\n: {}",
IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
- }
- // should have failed fast due to the missing
WebConsoleSecurityProvider2 service
- assertEquals(HttpServletResponse.SC_FORBIDDEN,
response.getStatusLine().getStatusCode());
- checkContentType(response, "text/html");
- }
- }
-
- }
-
-}
diff --git
a/src/test/java/org/apache/sling/scripting/core/it/ScriptingCoreTestSupport.java
b/src/test/java/org/apache/sling/scripting/core/it/ScriptingCoreTestSupport.java
index 4b5156a..3c3d66a 100644
---
a/src/test/java/org/apache/sling/scripting/core/it/ScriptingCoreTestSupport.java
+++
b/src/test/java/org/apache/sling/scripting/core/it/ScriptingCoreTestSupport.java
@@ -46,8 +46,10 @@ public class ScriptingCoreTestSupport extends TestSupport {
public ModifiableCompositeOption baseConfiguration() {
versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.api");
versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.resourceresolver");
+ versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.engine");
versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.servlets.resolver");
versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.scripting.api");
+ versionResolver.setVersionFromProject("org.apache.sling",
"org.apache.sling.auth.core");
return composite(
super.baseConfiguration(),
// Sling Scripting
@@ -67,11 +69,13 @@ public class ScriptingCoreTestSupport extends TestSupport {
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.commons.compiler").versionAsInProject(),
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.commons.johnzon").versionAsInProject(),
mavenBundle().groupId("org.apache.sling").artifactId("org.apache.sling.scripting.spi").versionAsInProject(),
+
mavenBundle().groupId("commons-fileupload").artifactId("commons-fileupload").version("1.5"),
+
mavenBundle().groupId("commons-codec").artifactId("commons-codec").version("1.13"),
junitBundles(),
awaitility(),
jacoco() // remove with Testing PaxExam 4.0
).add(
-
mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.converter").version("1.0.12")
// new Sling API dependency
+
mavenBundle().groupId("org.osgi").artifactId("org.osgi.util.converter").version("1.0.9")
// new Sling API dependency
).remove(
scriptingCore
);