You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by en...@apache.org on 2023/03/14 19:27:17 UTC
[sling-org-apache-sling-starter-content] branch master updated: SLING-11674 update the acl/ace pages for new SLING-11243 features (#7)
This is an automated email from the ASF dual-hosted git repository.
enorman pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-starter-content.git
The following commit(s) were added to refs/heads/master by this push:
new 93bbcbd SLING-11674 update the acl/ace pages for new SLING-11243 features (#7)
93bbcbd is described below
commit 93bbcbdcbbc39d310f1be53b7e521a48c8e15031
Author: Eric Norman <en...@apache.org>
AuthorDate: Tue Mar 14 12:27:11 2023 -0700
SLING-11674 update the acl/ace pages for new SLING-11243 features (#7)
---
bnd.bnd | 3 +
pom.xml | 171 +++++-
.../starter/access/models/AccessFormPage.java | 100 ++++
.../apache/sling/starter/access/models/Ace.java | 658 +++++++++++++++++++++
.../sling/starter/access/models/AceUtils.java | 71 +++
.../apache/sling/starter/access/models/Acl.java | 79 +++
.../starter/access/models/PrincipalPrivilege.java | 74 +++
.../sling/starter/access/models/PrivilegeItem.java | 186 ++++++
.../access/models/RestrictionDefinitionInfo.java | 51 ++
.../starter/access/models/RestrictionItem.java | 123 ++++
.../sling/starter/access/models/package-info.java | 21 +
.../apps/sling/servlet/default/ace.html | 172 ++++++
.../apps/sling/servlet/default/ace.html.esp | 127 ----
.../apps/sling/servlet/default/acl.html | 107 ++++
.../apps/sling/servlet/default/acl.html.esp | 109 ----
.../initial-content/content/starter/access/ace.css | 161 +++++
.../initial-content/content/starter/access/ace.js | 375 ++++++++++++
.../initial-content/content/starter/access/acl.css | 51 ++
.../initial-content/content/starter/access/acl.js | 33 ++
.../starter/access/models/AccessFormPageTest.java | 106 ++++
.../sling/starter/access/models/AceTest.java | 594 +++++++++++++++++++
.../sling/starter/access/models/AceUtilsTest.java | 82 +++
.../sling/starter/access/models/AclTest.java | 129 ++++
.../access/models/PrincipalPrivilegeTest.java | 110 ++++
.../starter/access/models/PrivilegeItemTest.java | 292 +++++++++
.../models/RestrictionDefinitionInfoTest.java | 89 +++
.../starter/access/models/RestrictionItemTest.java | 174 ++++++
.../starter/access/models/TestGroupPrincipal.java | 47 ++
28 files changed, 4027 insertions(+), 268 deletions(-)
diff --git a/bnd.bnd b/bnd.bnd
index 5ee3783..1da995d 100644
--- a/bnd.bnd
+++ b/bnd.bnd
@@ -1,3 +1,6 @@
Sling-Initial-Content: initial-content
-includeresource: target/frontend/dist
+
+# scan for any sling models
+-plugin.sling.models: org.apache.sling.bnd.models.ModelsScannerPlugin
diff --git a/pom.xml b/pom.xml
index c56d374..f1d3af4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -44,8 +44,10 @@
</scm>
<properties>
- <frontend.target>target/frontend</frontend.target>
+ <frontend.target>target/frontend</frontend.target>
<project.build.outputTimestamp>1646405911</project.build.outputTimestamp>
+ <oak.version>1.16.0</oak.version>
+ <junit-jupiter.version>5.9.1</junit-jupiter.version>
</properties>
<build>
@@ -54,6 +56,13 @@
<plugin>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.bnd.models</artifactId>
+ <version>1.0.0</version>
+ </dependency>
+ </dependencies>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
@@ -66,12 +75,12 @@
</goals>
<configuration>
<outputDirectory>${basedir}/${frontend.target}</outputDirectory>
- <resources>
+ <resources>
<resource>
<directory>src/main/frontend</directory>
</resource>
- </resources>
- </configuration>
+ </resources>
+ </configuration>
</execution>
</executions>
</plugin>
@@ -81,36 +90,36 @@
<artifactId>frontend-maven-plugin</artifactId>
<version>1.12.1</version>
<configuration>
- <installDirectory>${frontend.target}</installDirectory>
- <workingDirectory>${frontend.target}</workingDirectory>
+ <installDirectory>${frontend.target}</installDirectory>
+ <workingDirectory>${frontend.target}</workingDirectory>
</configuration>
<executions>
- <execution>
- <id>install node and npm</id>
- <goals>
- <goal>install-node-and-npm</goal>
- </goals>
- <configuration>
- <nodeVersion>v6.11.0</nodeVersion>
- <npmVersion>3.10.10</npmVersion>
- </configuration>
- </execution>
- <execution>
- <id>npm install</id>
- <goals>
- <goal>npm</goal>
- </goals>
- <configuration>
- <arguments>install</arguments>
- </configuration>
- </execution>
- <execution>
- <id>gulp build</id>
- <goals>
- <goal>gulp</goal>
- </goals>
- </execution>
- </executions>
+ <execution>
+ <id>install node and npm</id>
+ <goals>
+ <goal>install-node-and-npm</goal>
+ </goals>
+ <configuration>
+ <nodeVersion>v6.11.0</nodeVersion>
+ <npmVersion>3.10.10</npmVersion>
+ </configuration>
+ </execution>
+ <execution>
+ <id>npm install</id>
+ <goals>
+ <goal>npm</goal>
+ </goals>
+ <configuration>
+ <arguments>install</arguments>
+ </configuration>
+ </execution>
+ <execution>
+ <id>gulp build</id>
+ <goals>
+ <goal>gulp</goal>
+ </goals>
+ </execution>
+ </executions>
</plugin>
</plugins>
</build>
@@ -128,4 +137,102 @@
</plugin>
</plugins>
</reporting>
+ <dependencies>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.annotation.versioning</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains</groupId>
+ <artifactId>annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-annotation_1.3_spec</artifactId>
+ <version>1.3</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-json_1.1_spec</artifactId>
+ <version>1.5</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.jcr</groupId>
+ <artifactId>jcr</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.api</artifactId>
+ <version>2.27.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.models.api</artifactId>
+ <version>1.4.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.servlets.post</artifactId>
+ <version>2.5.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>oak-api</artifactId>
+ <version>${oak.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>oak-jackrabbit-api</artifactId>
+ <version>${oak.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>oak-security-spi</artifactId>
+ <version>${oak.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.jcr.jackrabbit.accessmanager</artifactId>
+ <version>3.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>4.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <version>${junit-jupiter.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <version>${junit-jupiter.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.johnzon</groupId>
+ <artifactId>johnzon-core</artifactId>
+ <version>1.2.19</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-jcr-commons</artifactId>
+ <version>2.18.2</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
</project>
diff --git a/src/main/java/org/apache/sling/starter/access/models/AccessFormPage.java b/src/main/java/org/apache/sling/starter/access/models/AccessFormPage.java
new file mode 100644
index 0000000..80d6136
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/AccessFormPage.java
@@ -0,0 +1,100 @@
+/*
+ * 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.starter.access.models;
+
+import java.io.IOException;
+
+import javax.annotation.PostConstruct;
+import javax.jcr.Node;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.SlingHttpServletResponse;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.jcr.jackrabbit.accessmanager.PrivilegesInfo;
+import org.apache.sling.models.annotations.injectorspecific.ScriptVariable;
+
+/**
+ * Base class for common ACL/ACE functionality
+ */
+public abstract class AccessFormPage {
+ protected PrivilegesInfo privilegesInfo = null;
+
+ @ScriptVariable
+ protected SlingHttpServletRequest request;
+
+ @ScriptVariable
+ protected SlingHttpServletResponse response;
+
+ @ScriptVariable
+ protected Resource resource;
+
+ /**
+ * Instantiates the model.
+ */
+ @PostConstruct
+ protected void init() throws IOException {
+ if (!getCanReadAccessControl()) {
+ if (request.getRemoteUser() == null) {
+ // 404 for anonymous
+ response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ } else {
+ // 403 for logged in user
+ response.sendError(HttpServletResponse.SC_FORBIDDEN);
+ }
+ }
+ }
+
+ /**
+ * Lazy create the PrivilegesInfo field the first time it is used.
+ */
+ protected PrivilegesInfo getPrivilegesInfo() {
+ if (privilegesInfo == null) {
+ privilegesInfo = new PrivilegesInfo();
+ }
+ return privilegesInfo;
+ }
+
+ /**
+ * Checks whether the current user has been granted privileges
+ * to modify the access control of the current node.
+ *
+ * @return true if the current user has the privileges, false otherwise
+ */
+ public boolean getCanReadAccessControl() {
+ return getPrivilegesInfo().canReadAccessControl(resource.adaptTo(Node.class));
+ }
+
+ /**
+ * Checks whether the current user has been granted privileges
+ * to modify the access control of the current node.
+ *
+ * @return true if the current user has the privileges, false otherwise
+ */
+ public boolean getCanModifyAccessControl() {
+ return getPrivilegesInfo().canModifyAccessControl(resource.adaptTo(Node.class));
+ }
+
+ public String getLocation() {
+ String location = null;
+ if (resource != null) {
+ location = resource.getResourceResolver().map(resource.getPath());
+ }
+ return location;
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/Ace.java b/src/main/java/org/apache/sling/starter/access/models/Ace.java
new file mode 100644
index 0000000..a50e90a
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/Ace.java
@@ -0,0 +1,658 @@
+/*
+ * 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.starter.access.models;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+import javax.annotation.PostConstruct;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.Workspace;
+import javax.jcr.security.AccessControlManager;
+import javax.jcr.security.Privilege;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonArrayBuilder;
+import javax.json.JsonBuilderFactory;
+import javax.json.JsonObject;
+import javax.json.JsonObjectBuilder;
+import javax.json.JsonString;
+import javax.json.JsonValue;
+
+import org.apache.jackrabbit.api.JackrabbitSession;
+import org.apache.jackrabbit.api.JackrabbitWorkspace;
+import org.apache.jackrabbit.api.security.authorization.PrivilegeManager;
+import org.apache.jackrabbit.api.security.principal.PrincipalManager;
+import org.apache.jackrabbit.api.security.user.Authorizable;
+import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider;
+import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.request.RequestParameter;
+import org.apache.sling.api.request.RequestParameterMap;
+import org.apache.sling.api.resource.ResourceNotFoundException;
+import org.apache.sling.api.resource.ResourceUtil;
+import org.apache.sling.jcr.jackrabbit.accessmanager.GetAce;
+import org.apache.sling.jcr.jackrabbit.accessmanager.GetAcl;
+import org.apache.sling.models.annotations.Model;
+import org.apache.sling.models.annotations.injectorspecific.OSGiService;
+import org.apache.sling.servlets.post.SlingPostConstants;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * The ace page options.
+ */
+@Model(adaptables=SlingHttpServletRequest.class)
+public class Ace extends AccessFormPage {
+ // for principal ace
+ protected static final String PATH_REPOSITORY = "/:repository";
+
+ // for matching restriction request parameters
+ protected static final Pattern RESTRICTION_PATTERN = Pattern.compile("^restriction@([^@]+)@([^@]+)@(Allow|Deny)$");
+ protected static final Pattern RESTRICTION_PATTERN_DELETE = Pattern.compile(String.format("^restriction@([^@]+)@([^@]+)%s$",
+ SlingPostConstants.SUFFIX_DELETE));
+
+ // use these hints to influence the order that the privileges are displayed
+ protected static final Map<String, Integer> privilegesPriority = createPrivilegesPriorityMap();
+ protected static Map<String, Integer> createPrivilegesPriorityMap() {
+ Map<String, Integer> myMap = new HashMap<>();
+ myMap.put(PrivilegeConstants.JCR_READ, 1);
+ myMap.put(PrivilegeConstants.REP_WRITE, 2);
+ myMap.put(PrivilegeConstants.JCR_READ_ACCESS_CONTROL, 3);
+ myMap.put(PrivilegeConstants.JCR_MODIFY_ACCESS_CONTROL, 4);
+
+ myMap.put(PrivilegeConstants.JCR_WRITE, 1);
+ myMap.put(PrivilegeConstants.JCR_NODE_TYPE_MANAGEMENT, 2);
+ return myMap;
+ }
+
+ protected String principalId;
+ protected Map<Privilege, PrivilegeItem> persistedPrivilegesMap = null;
+ private boolean aceExists;
+
+ @OSGiService
+ protected List<RestrictionProvider> restrictionProviders = null;
+
+ @OSGiService
+ public GetAce getAce = null;
+
+ @OSGiService
+ public GetAcl getAcl = null;
+
+ /**
+ * Instantiates the model.
+ */
+ @Override
+ @PostConstruct
+ protected void init() throws IOException {
+ super.init();
+ principalId = request.getParameter("pid");
+ }
+
+ public String getPrincipalId() {
+ return principalId;
+ }
+
+ public boolean getIsInvalidPrincipal() throws RepositoryException {
+ boolean isInValidPrincipal = true;
+ if (principalId != null && !principalId.isEmpty()) {
+ Session session = request.getResourceResolver().adaptTo(Session.class);
+ if (session instanceof JackrabbitSession) {
+ UserManager userManager = ((JackrabbitSession)session).getUserManager();
+ if (userManager != null) {
+ Authorizable authorizable = userManager.getAuthorizable(principalId);
+ if (authorizable != null) {
+ isInValidPrincipal = false;
+ } else {
+ //no user/group matches the supplied principal id
+ }
+ }
+ }
+ }
+
+ return isInValidPrincipal;
+ }
+
+ protected String getAcePath() {
+ return resource.getPath();
+ }
+
+ public boolean isExists() {
+ return aceExists;
+ }
+
+ public Collection<PrivilegeItem> getPrivileges() throws RepositoryException {
+ Map<Privilege, PrivilegeItem> privilegesMap = getPersistedPrivilegesMap();
+ if (privilegesMap == null || privilegesMap.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ //make a temp map for quick lookup below
+ Set<RestrictionDefinition> supportedRestrictions = getSupportedRestrictions();
+ Map<String, RestrictionDefinition> srMap = toSrMap(supportedRestrictions);
+
+ Map<String, List<RestrictionItem>> postedAllowRestrictionsMap = new HashMap<>();
+ Map<String, List<RestrictionItem>> postedDenyRestrictionsMap = new HashMap<>();
+ Map<String, String[]> fieldValues = populateEntriesFromPreviousFailedPost(postedAllowRestrictionsMap, postedDenyRestrictionsMap, srMap);
+ Map<String, String[]> toDeleteFieldValues = getFieldValuesForPattern(RESTRICTION_PATTERN_DELETE);
+ //entries from the previous failed POST.
+ for (PrivilegeItem entry : privilegesMap.values()) {
+ String privilegeName = entry.getName();
+ // check for any submitted form fields in case of error and redisplay of the page
+ String paramValue = request.getParameter(String.format("privilege@%s", privilegeName));
+ if (paramValue != null) {
+ //req param was here from a failed post?
+ if ("granted".equals(paramValue)) {
+ entry.setGranted(true);
+ } else if ("denied".equals(paramValue)) {
+ entry.setDenied(true);
+ }
+ } else {
+ // check for delete existing param
+ String paramDeleteValue = request.getParameter(String.format("privilege@%s@Delete", privilegeName));
+ if (paramDeleteValue != null) {
+ //req param was here from a failed post?
+ if ("granted".equals(paramDeleteValue)) {
+ entry.setGranted(false);
+ } else if ("denied".equals(paramDeleteValue)) {
+ entry.setDenied(false);
+ }
+ }
+ }
+
+ for (boolean forAllow : new boolean [] {true, false}) {
+ // first add items for any posted fields
+ Map<String, List<RestrictionItem>> postedRestrictionsMap = forAllow ? postedAllowRestrictionsMap : postedDenyRestrictionsMap;
+ List<RestrictionItem> newRestrictionsList = postedRestrictionsMap.computeIfAbsent(privilegeName, pn -> new ArrayList<>());
+ //now merge in any declared restrictions that were not posted
+ List<RestrictionItem> declaredRestrictions = forAllow ? entry.getAllowRestrictions() : entry.getDenyRestrictions();
+ if (declaredRestrictions != null && !declaredRestrictions.isEmpty()) {
+ for (RestrictionItem ri : declaredRestrictions) {
+ String restrictionName = ri.getName();
+
+ boolean addIt = true;
+ String fieldKeyPrefix = String.format("restriction@%s@%s", privilegeName, restrictionName);
+ String fieldKey = String.format("%s@%s", fieldKeyPrefix, (forAllow ? "Allow" : "Deny"));
+ // skip it if it was requested to be deleted in the previous POST attempt
+ // or already handled above
+ if (toDeleteFieldValues.containsKey(String.format("%s%s", fieldKeyPrefix, SlingPostConstants.SUFFIX_DELETE))) {
+ addIt = false;
+ } else if (fieldValues.containsKey(fieldKey)) {
+ // mark the form posted item as exists since it also
+ // had a persisted value
+ newRestrictionsList.stream()
+ .filter(list -> list.getName().equals(restrictionName))
+ .forEach(item -> item.setExists(true));
+ addIt = false;
+ }
+
+ if (addIt) {
+ newRestrictionsList.add(ri);
+ }
+ }
+ }
+
+ // check if we are missing an item for any mandatory restrictions
+ populateEntriesForMissingMandatoryRestrictions(newRestrictionsList, supportedRestrictions);
+
+ // and apply it
+ if (forAllow) {
+ entry.setAllowRestrictions(newRestrictionsList);
+ } else {
+ entry.setDenyRestrictions(newRestrictionsList);
+ }
+
+ // populate restrictions to delete here.
+ toDeleteFieldValues.keySet().stream()
+ .filter(key -> RESTRICTION_PATTERN_DELETE.matcher(key).matches())
+ .forEach(key -> {
+ Matcher matcher = RESTRICTION_PATTERN_DELETE.matcher(key);
+ if (matcher.matches()) {
+ String restrictionName = matcher.group(2);
+ if (forAllow) {
+ entry.addAllowRestrictionToDelete(restrictionName);
+ } else {
+ entry.addDenyRestrictionToDelete(restrictionName);
+ }
+ }
+ });
+ }
+ }
+
+ List<PrivilegeItem> list = new ArrayList<>(privilegesMap.values());
+ list.sort((p1, p2) -> {
+ String longestPath1 = p1.getLongestPath();
+ String[] segments1 = longestPath1.split("/");
+ String longestPath2 = p2.getLongestPath();
+ String[] segments2 = longestPath2.split("/");
+
+ for (int i = 0; i < segments1.length; i++) {
+ Integer priority1 = privilegesPriority.getOrDefault(segments1[i], 1000);
+ if (segments2.length <= i) {
+ return longestPath1.compareTo(longestPath2);
+ }
+ Integer priority2 = privilegesPriority.getOrDefault(segments2[i], 1000);
+ int cmp = priority1.compareTo(priority2);
+ if (cmp != 0) {
+ return cmp;
+ }
+ }
+ if (segments1.length == segments2.length) {
+ // natural sort of the namespace-free last segment of each path
+ String lastSegment1 = segments1[segments1.length - 1];
+ String lastSegment2 = segments2[segments2.length - 1];
+ lastSegment1 = lastSegment1.substring(lastSegment1.indexOf(':'));
+ lastSegment2 = lastSegment2.substring(lastSegment2.indexOf(':'));
+ return lastSegment1.compareTo(lastSegment2);
+ }
+ return longestPath1.compareTo(longestPath2);
+ });
+
+ // loop through one more time to annotate the items with
+ // extra css markers to help render a tree-ish view
+ boolean lastBranch = true;
+ for (int i = list.size() - 1; i > 0; i--) {
+ PrivilegeItem item = list.get(i);
+ if (lastBranch) {
+ item.addExtraCssClass("lastBranch");
+ }
+ if (lastBranch && item.getDepth() == 1) {
+ lastBranch = false;
+ }
+ if (i == list.size() - 1) {
+ item.addExtraCssClass("lastSibling");
+ } else {
+ boolean lastSibling = true;
+ // if the there remains another item that has the same depth as this
+ // then this is not the last sibling
+ for (int j = i + 1; j < list.size(); j++) {
+ PrivilegeItem nextItem = list.get(j);
+ if (nextItem.getDepth() == item.getDepth()) {
+ String nextItemParentPath = ResourceUtil.getParent(nextItem.getLongestPath());
+ String itemParentPath = ResourceUtil.getParent(item.getLongestPath());
+ if (nextItemParentPath != null && nextItemParentPath.equals(itemParentPath)) {
+ lastSibling = false;
+ break;
+ }
+ }
+ }
+ if (lastSibling) {
+ item.addExtraCssClass("lastSibling");
+ }
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Populate the restriction item list from data from a previously failed POST request
+ * @param list the list of restriction items
+ * @param srMap map where the key is the restriction name and the value is the restriction definition
+ * @return map of field values that were found in the form context
+ */
+ protected Map<String, String[]> populateEntriesFromPreviousFailedPost(Map<String, List<RestrictionItem>> allowMap,
+ Map<String, List<RestrictionItem>> denyMap,
+ Map<String, RestrictionDefinition> srMap) {
+ Map<String, String[]> toDeleteFieldValues = getFieldValuesForPattern(RESTRICTION_PATTERN_DELETE);
+ Map<String, String[]> fieldValues = getFieldValuesForPattern(RESTRICTION_PATTERN);
+ Set<Entry<String, String[]>> fieldValuesEntrySet = fieldValues.entrySet();
+ for (Entry<String, String[]> entry : fieldValuesEntrySet) {
+ String deleteKey = String.format("%s%s", entry.getKey(), SlingPostConstants.SUFFIX_DELETE);
+ if (toDeleteFieldValues.containsKey(deleteKey)) {
+ //it was requested to be deleted in the previous POST attempt
+ continue;
+ }
+
+ Matcher matcher = RESTRICTION_PATTERN.matcher(entry.getKey());
+ if (matcher.matches()) {
+ String privilegeName = matcher.group(1);
+ String restrictionName = matcher.group(2);
+ boolean isAllow = "Allow".equals(matcher.group(3));
+
+ RestrictionDefinition rd = srMap.get(restrictionName);
+ if (rd != null) {
+ Object value = entry.getValue();
+ String[] strings = entry.getValue();
+ if (rd.getRequiredType().isArray()) {
+ value = strings;
+ } else if (strings.length > 0) {
+ //use the first one?
+ value = strings[0];
+ }
+
+ RestrictionItem ri = new RestrictionItem(rd, value, false);
+ Map<String, List<RestrictionItem>> map = isAllow ? allowMap : denyMap;
+ List<RestrictionItem> list = map.computeIfAbsent(privilegeName, n -> new ArrayList<>());
+ list.add(ri);
+ }
+ }
+ }
+ return fieldValues;
+ }
+
+ /**
+ * Populate restriction item entries for any restriction definitions that are
+ * mandatory and not already declared.
+ * @param list the list of restriction items
+ * @param supportedRestrictions supported restrictions set
+ */
+ protected void populateEntriesForMissingMandatoryRestrictions(List<RestrictionItem> list,
+ Set<RestrictionDefinition> supportedRestrictions) {
+ if (supportedRestrictions != null) {
+ for (RestrictionDefinition rd : supportedRestrictions) {
+ if (rd.isMandatory() && list.stream().noneMatch(item -> item.getName().equals(rd.getName()))) {
+ //missing it, so add an item to the list
+ RestrictionItem ri = new RestrictionItem(rd, null, false);
+ list.add(ri);
+ }
+ }
+ }
+ }
+
+ /**
+ * Convert the supported restrictions to a map for quick lookup later
+ * @param supportedRestrictions the supported restrictions
+ * @return a map where the key is the restriction name and the value is the restriction definition
+ */
+ protected Map<String, RestrictionDefinition> toSrMap(Set<RestrictionDefinition> supportedRestrictions) {
+ Map<String, RestrictionDefinition> srMap = new HashMap<>();
+ for (RestrictionDefinition restrictionDefinition : supportedRestrictions) {
+ srMap.put(restrictionDefinition.getName(), restrictionDefinition);
+ }
+ return srMap;
+ }
+
+ /**
+ * Calculates the supported privileges in the resource path exists, or the registered
+ * privileges if the resource path does not exist
+ *
+ * @param jcrSession the current session
+ * @param resourcePath the resource path to consider
+ * @return
+ * @throws RepositoryException
+ */
+ protected @NotNull Privilege[] getSupportedOrRegisteredPrivileges(@NotNull Session jcrSession, @Nullable String resourcePath)
+ throws RepositoryException {
+ Privilege[] supportedPrivileges = null;
+ if (resourcePath != null && jcrSession.nodeExists(resourcePath)) {
+ supportedPrivileges = jcrSession.getAccessControlManager().getSupportedPrivileges(resourcePath);
+ } else {
+ // non-existing path. We can't determine what is supported there, so consider all registered privileges
+ Workspace workspace = jcrSession.getWorkspace();
+ if (workspace instanceof JackrabbitWorkspace) {
+ PrivilegeManager privilegeManager = ((JackrabbitWorkspace)workspace).getPrivilegeManager();
+ supportedPrivileges = privilegeManager.getRegisteredPrivileges();
+ }
+ }
+ return supportedPrivileges == null ? new Privilege[0] : supportedPrivileges;
+ }
+
+ protected Map<Privilege, PrivilegeItem> initialPrivilegesMap(
+ Map<Privilege, String> privilegeToLongestPath, String acePath) {
+ Map<Privilege, PrivilegeItem> newMap = new HashMap<>();
+ Privilege[] supportedPrivileges = null;
+ try {
+ Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
+ supportedPrivileges = getSupportedOrRegisteredPrivileges(jcrSession,
+ PATH_REPOSITORY.equals(acePath) ? null : acePath );
+ } catch (RepositoryException e) {
+ //ignore
+ supportedPrivileges = null;
+ }
+ if (supportedPrivileges != null) {
+ for (Privilege privilege : supportedPrivileges) {
+ PrivilegeItem p1 = new PrivilegeItem(privilege.getName(), false, false, privilegeToLongestPath.get(privilege));
+ newMap.put(privilege, p1);
+ }
+ }
+ return newMap;
+ }
+
+ protected Map<Privilege, PrivilegeItem> getPersistedPrivilegesMap() throws RepositoryException {
+ if (persistedPrivilegesMap == null) {
+ Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
+ Map<Privilege, String> privilegeToLongestPath = AceUtils.getPrivilegeLongestPathMap(jcrSession);
+ String acePath = getAcePath();
+ persistedPrivilegesMap = initialPrivilegesMap(privilegeToLongestPath, acePath);
+
+ JsonObject ace;
+ try {
+ ace = getAce.getAce(jcrSession, acePath, getPrincipalId());
+ } catch (ResourceNotFoundException rnfe) {
+ // no ACE exists yet?
+ ace = null;
+ }
+ if (ace != null) {
+ aceExists = true;
+ AccessControlManager acm = jcrSession.getAccessControlManager();
+
+ //make a temp map for quick lookup below
+ Set<RestrictionDefinition> supportedRestrictions = getSupportedRestrictions();
+ Map<String, RestrictionDefinition> srMap = toSrMap(supportedRestrictions);
+
+ JsonObject privileges = ace.getJsonObject("privileges");
+ for (String pn : privileges.keySet()) {
+ Privilege p = acm.privilegeFromName(pn);
+ PrivilegeItem privilegeItem = persistedPrivilegesMap.computeIfAbsent(p, key -> new PrivilegeItem(key.getName(), false, false, privilegeToLongestPath.get(key)));
+
+ JsonObject privilegeObj = privileges.getJsonObject(pn);
+ JsonValue allowJsonValue = privilegeObj.get("allow");
+ if (allowJsonValue != null) {
+ privilegeItem.setAllowExists(true);
+ privilegeItem.setGranted(true);
+ if (allowJsonValue instanceof JsonObject) {
+ List<RestrictionItem> restrictionItems = jsonToRestrictionItems(srMap, (JsonObject)allowJsonValue);
+ privilegeItem.setAllowRestrictions(restrictionItems);
+ }
+ }
+ JsonValue denyJsonValue = privilegeObj.get("deny");
+ if (denyJsonValue != null) {
+ privilegeItem.setDenyExists(true);
+ privilegeItem.setDenied(true);
+ if (denyJsonValue instanceof JsonObject) {
+ List<RestrictionItem> restrictionItems = jsonToRestrictionItems(srMap, (JsonObject)denyJsonValue);
+ privilegeItem.setDenyRestrictions(restrictionItems);
+ }
+ }
+ }
+ }
+ }
+ return persistedPrivilegesMap;
+ }
+
+ protected List<RestrictionItem> jsonToRestrictionItems(Map<String, RestrictionDefinition> srMap,
+ JsonObject restrictionsObj) {
+ List<RestrictionItem> restrictionItems = new ArrayList<>();
+ for (Entry<String, JsonValue> entry : restrictionsObj.entrySet()) {
+ String rn = entry.getKey();
+ RestrictionDefinition rd = srMap.get(rn);
+ if (rd != null) {
+ Object value = null;
+ JsonValue jsonValue = entry.getValue();
+ if (jsonValue instanceof JsonArray) {
+ JsonArray jsonArray = (JsonArray)jsonValue;
+ String [] values = new String[jsonArray.size()];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = jsonArray.getString(i);
+ }
+ value = values;
+ } else if (jsonValue instanceof JsonString) {
+ value = ((JsonString)jsonValue).getString();
+ }
+ restrictionItems.add(new RestrictionItem(rd, value, true));
+ }
+ }
+ return restrictionItems;
+ }
+
+ public Set<RestrictionDefinition> getSupportedRestrictions() {
+ Set<RestrictionDefinition> supportedRestrictions = new HashSet<>();
+ for (RestrictionProvider rp : restrictionProviders) {
+ supportedRestrictions.addAll(rp.getSupportedRestrictions(resource.getPath()));
+ }
+ return supportedRestrictions;
+ }
+
+ public List<RestrictionDefinitionInfo> getSupportedRestrictionsInfo() {
+ return getSupportedRestrictions().stream()
+ .map(rd -> new RestrictionDefinitionInfo(rd.getName(), rd))
+ .sorted(Comparator.comparing(RestrictionDefinitionInfo::getDisplayName))
+ .collect(Collectors.toList());
+ }
+
+ /**
+ * Returns a structure with the aggregate privilege relationships that can
+ * be used on the client side UI.
+ * @return JSON representation of the privilege aggregations
+ * @throws RepositoryException
+ */
+ public String getPrivilegeAggregationsAsJSON() throws RepositoryException {
+ JsonBuilderFactory factory = Json.createBuilderFactory(Collections.emptyMap());
+ JsonObjectBuilder builder = factory.createObjectBuilder();
+
+ Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
+ Map<Privilege, String> privilegeToLongestPath = AceUtils.getPrivilegeLongestPathMap(jcrSession);
+ Privilege[] supported = getSupportedOrRegisteredPrivileges(jcrSession, resource.getPath());
+ for (Privilege privilege : supported) {
+ Privilege[] aggregatePrivileges = privilege.getAggregatePrivileges();
+ if (aggregatePrivileges != null && aggregatePrivileges.length > 0) {
+ // order these so the client side iteration will process from the top down
+ List<Privilege> list = new ArrayList<>(Arrays.asList(aggregatePrivileges));
+ list.sort((Privilege o1, Privilege o2) -> privilegeToLongestPath.get(o1).compareTo(privilegeToLongestPath.get(o2)));
+
+ JsonArrayBuilder aggregateArray = factory.createArrayBuilder();
+
+ for (Privilege privilege2 : list) {
+ aggregateArray.add(privilege2.getName());
+ }
+
+ builder.add(privilege.getName(), aggregateArray);
+ }
+ }
+
+ JsonObject jsonObj = builder.build();
+ return jsonObj.toString();
+ }
+
+ public String getExistingRestrictionNamesAsJSON() throws RepositoryException {
+ JsonObjectBuilder jsonObjBuilder = Json.createObjectBuilder();
+ for (boolean forAllow : new boolean[] {true, false}) {
+ JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
+ Set<String> alreadyProcessed = new HashSet<>();
+ for (PrivilegeItem pi : getPrivileges()) {
+ if ((forAllow && pi.getGranted()) ||
+ (!forAllow && pi.getDenied())) {
+ List<RestrictionItem> restrictions = forAllow ? pi.getAllowRestrictions() : pi.getDenyRestrictions();
+ for (RestrictionItem ri : restrictions) {
+ if (ri.isExists()) {
+ String name = String.format("%s@%s", pi.getName(), ri.getName());
+ if (!alreadyProcessed.contains(name)) {
+ jsonArrayBuilder.add(name);
+ alreadyProcessed.add(name);
+ }
+ }
+ }
+ }
+ }
+ jsonObjBuilder.add(forAllow ? "allow" : "deny", jsonArrayBuilder);
+ }
+ return jsonObjBuilder.build().toString();
+ }
+
+ public String getOrderValue() {
+ String parameter = request.getParameter("order");
+ return parameter == null ? "" : parameter;
+ }
+
+ public Collection<PrincipalPrivilege> getOrderList() throws RepositoryException {
+ List<PrincipalPrivilege> list = new ArrayList<>();
+ Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
+ PrincipalManager principalManager = ((JackrabbitSession)jcrSession).getPrincipalManager();
+ String pid = getPrincipalId();
+ JsonObject acl = getAcl.getAcl(jcrSession, getAcePath());
+ for (String uid : acl.keySet()) {
+ if (pid != null && pid.equals(uid)) {
+ //skip it
+ continue;
+ }
+ Principal principal = principalManager.getPrincipal(uid);
+ if (principal != null) {
+ PrincipalPrivilege pi = new PrincipalPrivilege(principal);
+ list.add(pi);
+ }
+ }
+ return list;
+ }
+
+ protected String [] fieldValuesFromReqParams(RequestParameter[] paramValues) {
+ String[] fieldValues = null;
+ fieldValues = new String[paramValues.length];
+ for (int i=0; i < paramValues.length; i++) {
+ fieldValues[i] = paramValues[i].getString();
+ }
+ return fieldValues;
+ }
+
+ /**
+ * Gets the values of the specified field from the request. If not
+ * supplied the values from the supplied resource are returned.
+ *
+ * @param keyPattern the regular expression to used to match against the field keys
+ * @return the values of the field or empty map if not available
+ */
+ protected Map<String, String[]> getFieldValuesForPattern(Pattern keyPattern) {
+ Map<String, String[]> resultMap = new HashMap<>();
+
+ @NotNull
+ RequestParameterMap requestParameterMap = request.getRequestParameterMap();
+ Set<Entry<String, RequestParameter[]>> entrySet2 = requestParameterMap.entrySet();
+ for (Entry<String, RequestParameter[]> entry : entrySet2) {
+ String key2 = entry.getKey();
+ if (!resultMap.containsKey(key2)) {
+ Matcher matcher = keyPattern.matcher(key2);
+ if (matcher.matches()) {
+ //just use the original request value
+ RequestParameter[] paramValues = entry.getValue();
+ if (paramValues != null) {
+ String[] fieldValues = fieldValuesFromReqParams(paramValues);
+ resultMap.put(key2, fieldValues);
+ }
+ }
+ }
+ }
+
+ return resultMap;
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/AceUtils.java b/src/main/java/org/apache/sling/starter/access/models/AceUtils.java
new file mode 100644
index 0000000..56384a8
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/AceUtils.java
@@ -0,0 +1,71 @@
+/*
+ * 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.starter.access.models;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.security.AccessControlManager;
+import javax.jcr.security.Privilege;
+
+import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;
+
+/**
+ * Utility for helping to sort and order privileges by their longest aggregate depth
+ */
+public class AceUtils {
+
+ private AceUtils() {
+ // private constructor to hide the implicit public one
+ }
+
+ /**
+ * If the privilege is contained in multiple aggregate privileges, then
+ * calculate the instance with the greatest depth.
+ */
+ private static void toLongestPath(String prefix, Privilege parentPrivilege, Map<Privilege, String> privilegeToLongestPath) {
+ Privilege[] declaredAggregatePrivileges = parentPrivilege.getDeclaredAggregatePrivileges();
+ for (Privilege privilege : declaredAggregatePrivileges) {
+ String candidatePath = String.format("%s/%s", prefix, privilege.getName());
+ String oldValue = privilegeToLongestPath.get(privilege);
+ if (oldValue == null || oldValue.length() < candidatePath.length()) {
+ privilegeToLongestPath.put(privilege, candidatePath);
+
+ // continue drilling down to the leaf privileges
+ toLongestPath(candidatePath, privilege, privilegeToLongestPath);
+ }
+ }
+ }
+
+ /**
+ * Calculate the longest path for each of the possible privileges
+ * @param jcrSession the current users JCR session
+ * @return map where the key is the privilege and the value is the longest path
+ */
+ public static Map<Privilege, String> getPrivilegeLongestPathMap(Session jcrSession) throws RepositoryException {
+ AccessControlManager accessControlManager = jcrSession.getAccessControlManager();
+ Privilege jcrAll = accessControlManager.privilegeFromName(PrivilegeConstants.JCR_ALL);
+
+ Map<Privilege, String> privilegeToLongestPath = new HashMap<>();
+ privilegeToLongestPath.put(jcrAll, jcrAll.getName());
+ toLongestPath(jcrAll.getName(), jcrAll, privilegeToLongestPath);
+ return privilegeToLongestPath;
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/Acl.java b/src/main/java/org/apache/sling/starter/access/models/Acl.java
new file mode 100644
index 0000000..0bb4846
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/Acl.java
@@ -0,0 +1,79 @@
+/*
+ * 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.starter.access.models;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.json.JsonObject;
+import javax.json.JsonValue;
+
+import org.apache.jackrabbit.api.JackrabbitSession;
+import org.apache.jackrabbit.api.security.principal.PrincipalManager;
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.jcr.jackrabbit.accessmanager.GetAcl;
+import org.apache.sling.models.annotations.Model;
+import org.apache.sling.models.annotations.injectorspecific.OSGiService;
+
+@Model(adaptables=SlingHttpServletRequest.class)
+public class Acl extends AccessFormPage {
+ private List<PrincipalPrivilege> principalPrivilegeList;
+
+ @OSGiService
+ public GetAcl getAcl = null;
+
+ public Collection<PrincipalPrivilege> getPrincipals() throws RepositoryException {
+ if (principalPrivilegeList == null) {
+ principalPrivilegeList = new ArrayList<>();
+
+ Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
+ PrincipalManager principalManager = ((JackrabbitSession)jcrSession).getPrincipalManager();
+ JsonObject acl = getAcl.getAcl(jcrSession, resource.getPath());
+ for (Entry<String, JsonValue> entry : acl.entrySet()) {
+ String uid = entry.getKey();
+ Principal principal = principalManager.getPrincipal(uid);
+ if (principal != null) {
+ PrincipalPrivilege pi = new PrincipalPrivilege(principal);
+ AtomicBoolean allow = new AtomicBoolean(false);
+ AtomicBoolean deny = new AtomicBoolean(false);
+ JsonObject privilegesObj = ((JsonObject)entry.getValue()).getJsonObject("privileges");
+ privilegesObj.values().stream()
+ .forEach(item -> {
+ allow.set(allow.get() || ((JsonObject)item).containsKey("allow"));
+ deny.set(deny.get() || ((JsonObject)item).containsKey("deny"));
+ });
+ if (allow.get()) {
+ pi.setAllow(true);
+ }
+ if (deny.get()) {
+ pi.setDeny(true);
+ }
+ principalPrivilegeList.add(pi);
+ }
+ }
+ }
+
+ return principalPrivilegeList;
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/PrincipalPrivilege.java b/src/main/java/org/apache/sling/starter/access/models/PrincipalPrivilege.java
new file mode 100644
index 0000000..8fe31e1
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/PrincipalPrivilege.java
@@ -0,0 +1,74 @@
+/*
+ * 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.starter.access.models;
+
+import java.security.Principal;
+
+import org.apache.jackrabbit.api.security.principal.GroupPrincipal;
+import org.jetbrains.annotations.NotNull;
+
+public class PrincipalPrivilege {
+ private String principalName;
+ private boolean isAllow;
+ private boolean isDeny;
+ private boolean isGroup;
+
+ public PrincipalPrivilege(@NotNull Principal principal) {
+ super();
+ this.principalName = principal.getName();
+ this.isGroup = principal instanceof GroupPrincipal;
+ }
+
+ public String getName() {
+ return principalName;
+ }
+
+ public String getPrivilegesDisplayName() {
+ StringBuilder buffer = new StringBuilder();
+ if (isAllow) {
+ buffer.append("allow");
+ }
+ if (isDeny) {
+ if (buffer.length() > 0) {
+ buffer.append(" / ");
+ }
+ buffer.append("deny");
+ }
+ return buffer.toString();
+ }
+
+ public boolean isAllow() {
+ return isAllow;
+ }
+
+ public void setAllow(boolean isAllow) {
+ this.isAllow = isAllow;
+ }
+
+ public boolean isDeny() {
+ return isDeny;
+ }
+
+ public void setDeny(boolean isDeny) {
+ this.isDeny = isDeny;
+ }
+
+ public boolean getIsGroup() {
+ return isGroup;
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/PrivilegeItem.java b/src/main/java/org/apache/sling/starter/access/models/PrivilegeItem.java
new file mode 100644
index 0000000..50a872b
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/PrivilegeItem.java
@@ -0,0 +1,186 @@
+/*
+ * 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.starter.access.models;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class PrivilegeItem {
+ private String name;
+ private boolean granted;
+ private boolean denied;
+ private String longestPath;
+ private long depth;
+ private String extraCssClasses;
+ private List<RestrictionItem> allowRestrictions;
+ private List<RestrictionItem> denyRestrictions;
+ private Set<String> allowRestrictionsToDelete;
+ private Set<String> denyRestrictionsToDelete;
+ private boolean allowExists = false;
+ private boolean denyExists = false;
+
+ public PrivilegeItem(String name, boolean granted, boolean denied, String longestPath) {
+ this(name, granted, denied, longestPath, Collections.emptyList(), Collections.emptyList());
+ }
+ public PrivilegeItem(String name, boolean granted, boolean denied, String longestPath,
+ List<RestrictionItem> allowRestrictions, List<RestrictionItem> denyRestrictions) {
+ super();
+ this.name = name;
+ this.granted = granted;
+ this.denied = denied;
+ this.longestPath = longestPath;
+ this.depth = longestPath.chars().filter(ch -> ch == '/').count();
+ this.allowRestrictions = allowRestrictions;
+ this.denyRestrictions = denyRestrictions;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getNone() {
+ return !granted && !denied;
+ }
+
+ public boolean getGranted() {
+ return granted;
+ }
+
+ public boolean getDenied() {
+ return denied;
+ }
+
+ public void setGranted(boolean granted) {
+ this.granted = granted;
+ }
+
+ public void setDenied(boolean denied) {
+ this.denied = denied;
+ }
+
+ public boolean isAllowExists() {
+ return allowExists;
+ }
+
+ public void setAllowExists(boolean allowExists) {
+ this.allowExists = allowExists;
+ }
+
+ public boolean isDenyExists() {
+ return denyExists;
+ }
+
+ public void setDenyExists(boolean denyExists) {
+ this.denyExists = denyExists;
+ }
+
+ public String getLongestPath() {
+ return longestPath;
+ }
+
+ public void addExtraCssClass(String addClass) {
+ if (this.extraCssClasses == null) {
+ this.extraCssClasses = addClass;
+ } else {
+ this.extraCssClasses = String.format("%s %s", this.extraCssClasses, addClass);
+ }
+ }
+
+ public String getDepthCss() {
+ String css;
+ if (extraCssClasses != null) {
+ css = String.format("depth%d %s", this.depth, extraCssClasses);
+ } else {
+ css = String.format("depth%d", this.depth);
+ }
+ return css;
+ }
+
+ public long getDepth() {
+ return depth;
+ }
+
+ public List<RestrictionItem> getAllowRestrictions() {
+ return allowRestrictions;
+ }
+
+ public List<RestrictionItem> getDenyRestrictions() {
+ return denyRestrictions;
+ }
+
+ public void setAllowRestrictions(List<RestrictionItem> restrictions) {
+ this.allowRestrictions = restrictions;
+ }
+ public void setDenyRestrictions(List<RestrictionItem> restrictions) {
+ this.denyRestrictions = restrictions;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("PrivilegeItem [name=");
+ builder.append(name);
+ builder.append(", granted=");
+ builder.append(granted);
+ builder.append(", denied=");
+ builder.append(denied);
+ builder.append(", longestPath=");
+ builder.append(longestPath);
+ builder.append(", depth=");
+ builder.append(depth);
+ builder.append(", extraCssClasses=");
+ builder.append(extraCssClasses);
+ builder.append(", allowRestrictions=");
+ builder.append(allowRestrictions);
+ builder.append(", denyRestrictions=");
+ builder.append(denyRestrictions);
+ builder.append("]");
+ return builder.toString();
+ }
+
+ public void addAllowRestrictionToDelete(String restrictionName) {
+ if (allowRestrictionsToDelete == null) {
+ allowRestrictionsToDelete = new HashSet<>();
+ }
+ allowRestrictionsToDelete.add(restrictionName);
+ }
+
+ public Collection<String> getAllowRestrictionsToDelete() {
+ if (allowRestrictionsToDelete != null) {
+ return allowRestrictionsToDelete;
+ }
+ return Collections.emptySet();
+ }
+
+ public void addDenyRestrictionToDelete(String restrictionName) {
+ if (denyRestrictionsToDelete == null) {
+ denyRestrictionsToDelete = new HashSet<>();
+ }
+ denyRestrictionsToDelete.add(restrictionName);
+ }
+
+ public Collection<String> getDenyRestrictionsToDelete() {
+ if (denyRestrictionsToDelete != null) {
+ return denyRestrictionsToDelete;
+ }
+ return Collections.emptySet();
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/RestrictionDefinitionInfo.java b/src/main/java/org/apache/sling/starter/access/models/RestrictionDefinitionInfo.java
new file mode 100644
index 0000000..35896ae
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/RestrictionDefinitionInfo.java
@@ -0,0 +1,51 @@
+/*
+ * 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.starter.access.models;
+
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+import org.jetbrains.annotations.NotNull;
+import org.apache.jackrabbit.oak.api.Type;
+
+public class RestrictionDefinitionInfo implements RestrictionDefinition {
+ private String displayName;
+ private RestrictionDefinition rd;
+
+ public RestrictionDefinitionInfo(String displayName, RestrictionDefinition rd) {
+ this.displayName = displayName;
+ this.rd = rd;
+ }
+
+ public String getDisplayName() {
+ return displayName;
+ }
+
+ @Override
+ public @NotNull String getName() {
+ return rd.getName();
+ }
+
+ @Override
+ public @NotNull Type<?> getRequiredType() {
+ return rd.getRequiredType();
+ }
+
+ @Override
+ public boolean isMandatory() {
+ return rd.isMandatory();
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/RestrictionItem.java b/src/main/java/org/apache/sling/starter/access/models/RestrictionItem.java
new file mode 100644
index 0000000..7c35675
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/RestrictionItem.java
@@ -0,0 +1,123 @@
+/*
+ * 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.starter.access.models;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Value;
+
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+
+public class RestrictionItem {
+ private RestrictionDefinition rd;
+ private Object value;
+ private boolean exists;
+
+ public RestrictionItem(RestrictionDefinition rd, Object value, boolean exists) {
+ super();
+ this.rd = rd;
+ this.value = value;
+ this.exists = exists;
+ }
+
+ public String getName() {
+ return rd.getName();
+ }
+
+ public boolean isMultiValue() {
+ return rd.getRequiredType().isArray();
+ }
+
+ public String getValue() throws RepositoryException {
+ String v = null;
+ if (value instanceof Value) {
+ v = ((Value)value).getString();
+ } else if (value instanceof Value[]) {
+ Value[] va = (Value[])value;
+ if (va.length > 0) {
+ v = va[0].getString();
+ }
+ } else if (value instanceof String) {
+ v = (String)value;
+ } else if (value instanceof String[]) {
+ String[] values = (String[])value;
+ if (values.length > 0) {
+ v = values[0];
+ }
+ }
+
+ if (v == null) {
+ //empty string if no values yet
+ v = "";
+ }
+ return v;
+ }
+
+ public List<String> getValues() throws RepositoryException {
+ List<String> values = new ArrayList<>();
+ if (value instanceof Value) {
+ values.add(((Value)value).getString());
+ } else if (value instanceof Value[]) {
+ Value[] va = (Value[])value;
+ for (Value v : va) {
+ values.add(v.getString());
+ }
+ } else if (value instanceof String) {
+ values.add((String)value);
+ } else if (value instanceof String[]) {
+ values.addAll(Arrays.asList((String[])value));
+ }
+ if (values.isEmpty()) {
+ //empty string if no values yet
+ values.add("");
+ }
+ return values;
+ }
+
+ public boolean isExists() {
+ return exists;
+ }
+
+ public void setExists(boolean exists) {
+ this.exists = exists;
+ }
+
+ public boolean isMandatory() {
+ return rd.isMandatory();
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("RestrictionItem [name=");
+ builder.append(rd.getName());
+ builder.append(", value=");
+ try {
+ builder.append(getValues());
+ } catch (RepositoryException e) {
+ // ignore
+ }
+ builder.append(", exists=");
+ builder.append(exists);
+ builder.append("]");
+ return builder.toString();
+ }
+
+}
diff --git a/src/main/java/org/apache/sling/starter/access/models/package-info.java b/src/main/java/org/apache/sling/starter/access/models/package-info.java
new file mode 100644
index 0000000..ef7e797
--- /dev/null
+++ b/src/main/java/org/apache/sling/starter/access/models/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+@org.osgi.annotation.versioning.Version("1.0.0")
+package org.apache.sling.starter.access.models;
diff --git a/src/main/resources/initial-content/apps/sling/servlet/default/ace.html b/src/main/resources/initial-content/apps/sling/servlet/default/ace.html
new file mode 100644
index 0000000..7eedec9
--- /dev/null
+++ b/src/main/resources/initial-content/apps/sling/servlet/default/ace.html
@@ -0,0 +1,172 @@
+<sly data-sly-use.p="org.apache.sling.starter.access.models.Ace" data-sly-set.canModify="${p.canModifyAccessControl}">
+</sly><!DOCTYPE html>
+<html lang="en">
+<!--/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ ~ 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.
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/-->
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Access Control Entry : ${resource.name}</title>
+ <meta name="theme-color" content="#00678c">
+ <link href="${request.contextPath}/starter/css/bundle.css" rel="stylesheet" />
+ <link rel="stylesheet" type="text/css" href="${request.contextPath}/starter/access/ace.css" />
+</head>
+<body>
+ <div class="Grid Fit-Medium Home-Grid">
+ <div class="Gradient"></div>
+ <header class="Cell Medium-35 Large-25 Align-Center Logos">
+ <a href="http://sling.apache.org" target="_blank" rel="noopener" id="sling-logo" title="Visit the Apache Sling website">
+ <img src="${request.contextPath}/starter/img/sling-logo.svg" alt="Apache Sling Logo"/>
+ </a>
+ <a href="http://apache.org" target="_blank" rel="noopener" id="asf-logo" title="Visit the Apache Software Foundation website">
+ <img src="${request.contextPath}/starter/img/asf-logo.svg" alt="Apache Software Foundation Logo"/>
+ </a>
+ </header>
+ <div class="Cell Align-Center Main-Content">
+ <div class="Grid">
+ <section class="Cell Large-70">
+ <p data-sly-test.isInvalid="${p.isInvalidPrincipal}" class="notice error">Invalid principal name: ${p.principalId}</p>
+
+ <h1 data-sly-test="${!isInvalid}">${canModify ? "Modify" : "View"} ACE on ${p.location} for: ${p.principalId}</h1>
+
+ <form data-sly-test="${!isInvalid}" id="modifyAceForm" method="POST" action="${request.contextPath}${p.location}.modifyAce.html" autocomplete="off" >
+ <input type="hidden" name=":redirect" value="${request.contextPath}${p.location}.acl.html" />
+ <input id="principalId" type="hidden" name="principalId" value="${p.principalId}" />
+
+ <fieldset id="ace-privileges">
+ <legend><label>Declared Privileges</label></legend>
+
+ <table id="privileges">
+ <caption>Declared Privileges</caption>
+ <thead>
+ <tr>
+ <th scope="col" style="text-align:left;">Name</th>
+ <th scope="col" style="text-align:left;width:25%">Allow</th>
+ <th scope="col" style="text-align:left;width:25%">Deny</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr data-sly-repeat.pi="${p.privileges}" data-privilege="${pi.name}">
+ <td class="${pi.depthCss @ context='attribute'}" style="text-align:left">
+ <div class="ellipsis">
+ <label>${pi.name}</label>
+ </div>
+ </td>
+ <td style="text-align:left" data-sly-set.checked="${pi.granted}" data-sly-set.restrictions="${pi.allowRestrictions}" >
+ <div class="ellipsis">
+ <label><input type="checkbox" class="granted_or_denied" name="privilege@${pi.name}" value="allow" data-sly-attribute.checked="${checked}" data-sly-attribute.disabled="${!canModify}"/></label>
+ <input data-sly-test="${canModify && pi.allowExists}" type="hidden" class="delete" name="privilege@${pi.name}@Delete" value="allow" data-sly-attribute.disabled="${checked}" />
+ <span class="editRestrictions" style="${checked ? null : 'display:none' @ context='attribute'}">
+ <a href="javascript:void(0)" id="edit-allow-restriction@${pi.name}" title="Edit Restrictions">
+ <span class="restriction-details">
+ <sly data-sly-test="${!restrictions}">No Restrictions</sly>
+ <sly data-sly-repeat.restriction="${restrictions}"><sly data-sly-test="${!restrictionList.first}">, </sly>${restriction.name}</sly>
+ </span>
+ </a>
+ <span class="restriction-state">
+ <sly data-sly-repeat.restriction="${restrictions}" >
+ <input data-sly-repeat.value="${restriction.values}" type="hidden" name="restriction@${pi.name}@${restriction.name}@Allow" value="${value}" data-sly-attribute.disabled="${!canModify}" />
+ </sly>
+ <input data-sly-test="${canModify}" data-sly-repeat.restriction="${pi.allowRestrictionsToDelete}" type="hidden" name="restriction@${pi.name}@${restriction}@Delete" value="allow" />
+ </span>
+ </span>
+ </div>
+ </td>
+ <td style="text-align:left" data-sly-set.checked="${pi.denied}" data-sly-set.restrictions="${pi.denyRestrictions}" >
+ <div class="ellipsis">
+ <label><input type="checkbox" class="granted_or_denied" name="privilege@${pi.name}" value="deny" data-sly-attribute.checked="${checked}" data-sly-attribute.disabled="${!canModify}"/></label>
+ <input data-sly-test="${canModify && pi.denyExists}" type="hidden" class="delete" name="privilege@${pi.name}@Delete" value="deny" data-sly-attribute.disabled="${checked}" />
+ <span class="editRestrictions" style="${checked ? null : 'display:none' @ context='attribute'}">
+ <a href="javascript:void(0)" id="edit-deny-restriction@${pi.name}" title="Edit Restrictions">
+ <span class="restriction-details">
+ <sly data-sly-test="${!restrictions}">No Restrictions</sly>
+ <sly data-sly-repeat.restriction="${restrictions}"><sly data-sly-test="${!restrictionList.first}">, </sly>${restriction.name}</sly>
+ </span>
+ </a>
+ <span class="restriction-state">
+ <sly data-sly-repeat.restriction="${restrictions}" >
+ <input data-sly-repeat.value="${restriction.values}" type="hidden" name="restriction@${pi.name}@${restriction.name}@Deny" value="${value}" data-sly-attribute.disabled="${!canModify}" />
+ </sly>
+ <input data-sly-test="${canModify}" data-sly-repeat.restriction="${pi.denyRestrictionsToDelete}" type="hidden" name="restriction@${pi.name}@${restriction}@Delete" value="deny" />
+ </span>
+ </span>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </fieldset>
+
+ <div data-sly-test="${canModify}">
+ <label for="order">Order</label>
+ <select id="order" name="order">
+ <option data-sly-attribute.selected="${p.orderValue == ''}" value="">Default</option>
+ <option data-sly-attribute.selected="${p.orderValue == 'first'}" value="first">First</option>
+ <option data-sly-repeat.principal="${p.orderList}" value="before ${principal.name}">Before ${principal.name}</option>
+ <option data-sly-attribute.selected="${p.orderValue == 'last'}" value="last">Last</option>
+ </select>
+ </div>
+
+ <div class="form-buttons" data-sly-test="${canModify}">
+ <button id="applyButton" type="submit" class="button-primary">Apply</button>
+ <button data-sly-test="${p.exists}" id="deleteButton" type="button">Delete</button>
+ </div>
+ </form>
+
+ <form data-sly-test="${!isInvalid && p.exists}" id="deleteAceForm" method="POST" action="${request.contextPath}${p.location}.deleteAce.html" autocomplete="off" >
+ <input type="hidden" name=":redirect" value="${request.contextPath}${p.location}.acl.html" />
+ <input type="hidden" name=":applyTo" value="${p.principalId}" />
+ </form>
+
+ <dialog data-sly-test="${!isInvalid}" id="restrictionsDialog">
+ <form id="modifyAceRestrictionsForm" method="dialog"
+ data-for-privilege-allow="" data-canModify="${canModify ? 'true' : 'false'}" autocomplete="off" >
+ <h3>
+ Restrictions For Privilege: <label><span id="for-privilege"></span></label>
+ </h3>
+
+ <p data-sly-repeat.ri="${p.supportedRestrictionsInfo}" data-restriction="${ri.name}" data-multival="${ri.requiredType.array ? 'true' : 'false'}" class="restriction-row">
+ <label><input class="declare-restriction" type="checkbox" data-sly-attribute.checked="${ri.manditory}"
+ data-sly-attribute.readonly="${ri.manditory}" data-sly-attribute.disabled="${!canModify}" /> ${ri.name} </label>
+ </p>
+
+ <div class="form-buttons" style="margin-top: 20px; text-align: right;">
+ <button id="dlgOk" data-sly-attribute.disabled="${!canModify}">Ok</button>
+ <button id="dlgCancel">Cancel</button>
+ </div>
+ </form>
+ </dialog>
+ </section>
+ <div class="Cell Large-5"><!--/* Give the columns a bit of space between them. */--></div>
+ <section class="Cell Large-25">
+ <h1>Session</h1>
+ <h2 id="login-signedin" style="display: block;"><a href="${request.contextPath}/system/sling/logout" title="Logout of Apache Sling">Logout</a> <span id="user">${request.remoteUser}</span></h2>
+ </section>
+ </div>
+ </div>
+ </div>
+ <script data-sly-test="${!isInvalid}" type="text/javascript">
+ // holds the details for all supported aggregate privileges
+ const aggregates = ${p.privilegeAggregationsAsJSON @ context='unsafe'};
+
+ // holds the names of the already existing restrictions
+ const existingRestrictionNames = ${p.existingRestrictionNamesAsJSON @ context='unsafe'};
+ </script>
+ <script data-sly-test="${!isInvalid}" type="text/javascript" src="${request.contextPath}/starter/access/ace.js"></script>
+</body>
+</html>
diff --git a/src/main/resources/initial-content/apps/sling/servlet/default/ace.html.esp b/src/main/resources/initial-content/apps/sling/servlet/default/ace.html.esp
deleted file mode 100644
index 8ff8584..0000000
--- a/src/main/resources/initial-content/apps/sling/servlet/default/ace.html.esp
+++ /dev/null
@@ -1,127 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<!--
- 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.
--->
- <%
- var privilegesInfo = new Packages.org.apache.sling.jcr.jackrabbit.accessmanager.PrivilegesInfo();
- if (!privilegesInfo.canReadAccessControl(currentNode)) {
- //no rights to view the access control of the node, so just return a 404 status
- response.sendError(404);
- } else {
- var principalId = request.getParameter("pid");
- var isValidPrincipal = false;
- if (principalId != null && principalId != "") {
- var userManager = Packages.org.apache.sling.jcr.base.util.AccessControlUtil.getUserManager(currentNode.session);
- if (userManager != null) {
- var authorizable = userManager.getAuthorizable(principalId);
- if (authorizable != null) {
- isValidPrincipal = true;
- } else {
- //no user/group matches the supplied principal id
- }
- }
- }
-%>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8" />
- <title>Access Control Entry : <%=currentNode.name%></title>
-
- <style TYPE="text/css">
- <!--
- ul.error-msg {
- list-style-position: inside;
- list-style-type: none;
- }
- li.error-msg {
- color: #c00;
- background-color: #fee;
- border: 1px solid #c00;
- margin: 3px;
- padding: 4px;
- line-height: 18px;
- font-weight: bold;
- }
- -->
- </style>
-</head>
-<body>
- <%
- if (!isValidPrincipal) {
- %>
- <ul class="error-msg">
- <li class="error-msg">Invalid principal name: "<%=principalId%>"</li>
- </ul>
- <%
- } else {
- //principal is valid
- var accessRights = privilegesInfo.getDeclaredAccessRightsForPrincipal(currentNode, principalId);
- var granted = accessRights.getGranted();
- var denied = accessRights.getDenied();
- var supported = privilegesInfo.getSupportedPrivileges(currentNode);
- var canModify = privilegesInfo.canModifyAccessControl(currentNode);
- %>
-
- <h1>Modify Access Control Entry For: <%=principalId%></h1>
-
- <form method="POST" action="<%=request.contextPath%><%=currentNode.path%>.modifyAce.html" >
- <input type="hidden" name=":redirect" value="<%=request.contextPath%><%=currentNode.path%>.acl.html" />
- <input type="hidden" name="principalId" value="<%=principalId%>" />
-
- <table width="100%">
- <thead>
- <tr>
- <th align="left" width="55%">Privilege</th>
- <th align="center" width="15%">Ignored</th>
- <th align="center" width="15%">Granted</th>
- <th align="center" width="15%">Denied</th>
- </tr>
- </thead>
- <tbody>
- <%
- for (i=0; i < supported.length; i++) {
- var p = supported[i];
- %>
- <tr>
- <td align="left" width="55%"><%=p.getName()%></td>
- <td align="center" width="15%"><input type="radio" name="privilege@<%=p.getName()%>" value="none" <%=granted.contains(p) || denied.contains(p) ? "" : "checked"%> /></td>
- <td align="center" width="15%"><input type="radio" name="privilege@<%=p.getName()%>" value="granted" <%=granted.contains(p) ? "checked" : ""%> /></td>
- <td align="center" width="15%"><input type="radio" name="privilege@<%=p.getName()%>" value="denied" <%=denied.contains(p) ? "checked" : ""%> /></td>
- </tr>
- <%
- }
- %>
- </tbody>
- <tfoot>
- <tr>
- <td colspan="3"></td>
- <td align="center" width="15%">
- <button accesskey="a" id="applyButton" class="form-button" type="submit">Apply</button>
- </td>
- </tr>
- </tfoot>
- </table>
- </form>
- <%
- } //end-if isValidPrincipal
- %>
-</body>
-</html>
-<%
- }
-%>
\ No newline at end of file
diff --git a/src/main/resources/initial-content/apps/sling/servlet/default/acl.html b/src/main/resources/initial-content/apps/sling/servlet/default/acl.html
new file mode 100644
index 0000000..e4b72aa
--- /dev/null
+++ b/src/main/resources/initial-content/apps/sling/servlet/default/acl.html
@@ -0,0 +1,107 @@
+<sly data-sly-use.p="org.apache.sling.starter.access.models.Acl" data-sly-set.canModify="${p.canModifyAccessControl}">
+</sly><!DOCTYPE html>
+<html lang="en">
+<!--/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ ~ 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.
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/-->
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Access Control List : ${resource.name}</title>
+ <meta name="theme-color" content="#00678c">
+ <link href="${request.contextPath}/starter/css/bundle.css" rel="stylesheet" />
+ <link rel="stylesheet" type="text/css" href="${request.contextPath}/starter/access/acl.css" />
+</head>
+<body>
+ <div class="Grid Fit-Medium Home-Grid">
+ <div class="Gradient"></div>
+ <header class="Cell Medium-35 Large-25 Align-Center Logos">
+ <a href="http://sling.apache.org" target="_blank" rel="noopener" id="sling-logo" title="Visit the Apache Sling website">
+ <img src="${request.contextPath}/starter/img/sling-logo.svg" alt="Apache Sling Logo"/>
+ </a>
+ <a href="http://apache.org" target="_blank" rel="noopener" id="asf-logo" title="Visit the Apache Software Foundation website">
+ <img src="${request.contextPath}/starter/img/asf-logo.svg" alt="Apache Software Foundation Logo"/>
+ </a>
+ </header>
+ <div class="Cell Align-Center Main-Content">
+ <div class="Grid">
+ <section class="Cell Large-70">
+ <h1>${canModify ? "Modify" : "View"} ACL on: ${p.location}</h1>
+
+ <fieldset data-sly-test="${canModify}">
+ <legend>Add an entry for a user or group</legend>
+ <form id="addAceForm" data-sly-test.canModify="${canModify}" method="GET" action="${request.contextPath}${p.location}.ace.html">
+ <input id="addPid" type="text" name="pid" value="" placeholder='User or group name' required="required" />
+ <button id="addAce" type="submit" class="button-primary">Add Entry</button>
+ </form>
+ </fieldset>
+ <fieldset data-sly-set.list="${p.principals}">
+ <legend>Current access control entries</legend>
+
+ <p data-sly-test="${list.empty}" class="notice info"><span>No access control entries have been declared.</span></p>
+ <form method="POST" action="${request.contextPath}${p.location}.deleteAce.html"
+ data-sly-test="${!list.empty}" >
+ <input type="hidden" name=":redirect" value="${request.contextPath}${p.location}.acl.html" />
+ <table id="aces">
+ <caption>Access Control Entries</caption>
+ <thead>
+ <tr>
+ <th scope="col" style="text-align: left;">Principal</th>
+ <th scope="col" style="text-align: center;">Privileges</th>
+ <th data-sly-test="${canModify}" scope="col" style="text-align: center;"><sly data-sly-test="${canModify}">Remove</sly></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr data-sly-repeat.pi="${list}">
+ <td style="text-align: left;">
+ <div class="ellipsis">
+ <a href="${request.contextPath}${p.location}.ace.html?pid=${pi.name}">
+ ${pi.name}
+ </a>
+ </div>
+ </td>
+ <td style="text-align: center;">
+ <div class="ellipsis">
+ ${pi.privilegesDisplayName}
+ </div>
+ </td>
+ <td data-sly-test="${canModify}" style="text-align: center;">
+ <input class="delete" type="checkbox" name=":applyTo" value="${pi.name}" />
+ </td>
+ </tr>
+ </tbody>
+ <tfoot data-sly-test="${canModify}">
+ <tr>
+ <td colspan="2"></td>
+ <td style="text-align: center;"><button id="removeButton" type="submit" disabled="disabled">Remove Selected</button></td>
+ </tr>
+ </tfoot>
+ </table>
+ </form>
+ </fieldset>
+ </section>
+ <div class="Cell Large-5"><!--/* Give the columns a bit of space between them. */--></div>
+ <section class="Cell Large-25">
+ <h1>Session</h1>
+ <h2 id="login-signedin" style="display: block;"><a href="${request.contextPath}/system/sling/logout" title="Logout of Apache Sling">Logout</a> <span id="user">${request.remoteUser}</span></h2>
+ </section>
+ </div>
+ </div>
+ </div>
+ <script data-sly-test="${canModify}" type="text/javascript" src="${request.contextPath}/starter/access/acl.js"></script>
+</body>
+</html>
diff --git a/src/main/resources/initial-content/apps/sling/servlet/default/acl.html.esp b/src/main/resources/initial-content/apps/sling/servlet/default/acl.html.esp
deleted file mode 100644
index d2d16bb..0000000
--- a/src/main/resources/initial-content/apps/sling/servlet/default/acl.html.esp
+++ /dev/null
@@ -1,109 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<!--
- 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.
--->
- <%
- var privilegesInfo = new Packages.org.apache.sling.jcr.jackrabbit.accessmanager.PrivilegesInfo();
- if (!privilegesInfo.canReadAccessControl(currentNode)) {
- //no rights to view the access control of the node, so just return a 404 status
- response.sendError(404);
- } else {
- var canModify = privilegesInfo.canModifyAccessControl(currentNode);
-%>
-<head>
- <meta http-equiv="content-type" content="text/html; charset=utf-8" />
- <title>Access Control List : <%=currentNode.name%></title>
-</head>
-
-<body>
-
- <h1>Manage Access Control For: <%=currentNode.path%></h1>
-
- <% if (canModify) { %>
- <fieldset>
- <legend>Add an entry for a user or group</legend>
- <form method="GET" action="<%=request.contextPath%><%=currentNode.path%>.ace.html">
- <label for="addpid">Principal Name:</label>
- <input id="addpid" type="text" name="pid" value="" />
- <input type="submit" value="Add"/>
- </form>
- </fieldset>
- <% } %>
-
- <fieldset>
- <legend>Current access control entries</legend>
-
- <form method="POST" action="<%=request.contextPath%><%=currentNode.path%>.deleteAce.html" >
- <input type="hidden" name=":redirect" value="<%=request.contextPath%>" />
-
- <table width="100%">
- <thead>
- <tr>
- <th align="left" width="60%">Principal</th>
- <th align="center" width="25%">Privileges</th>
- <th align="center" width="15%"><% if (canModify) { %>Remove<% } %></th>
- </tr>
- </thead>
- <tbody>
- <%
- var accessMap = privilegesInfo.getDeclaredAccessRights(currentNode);
- var entrySet = accessMap.entrySet();
- var iterator = entrySet.iterator();
- while (iterator.hasNext()) {
- var entry = iterator.next();
- var principal = entry.getKey();
- var accessrights = entry.getValue();
- %>
- <tr>
- <td align="left" width="60%" >
- <% if (canModify) { %>
- <a href="<%=request.contextPath%><%=currentNode.path%>.ace.html?pid=<%=principal.getName()%>">
- <%=principal.getName()%>
- </a>
- <% } else { %>
- <%=principal.getName()%>
- <% } %>
- </td>
- <td align="center" width="25%" >
- <%=accessrights.getPrivilegeSetDisplayName(request.locale)%>
- </td>
- <td align="center" width="15%">
- <% if (canModify) { %>
- <input type="checkbox" name=":applyTo" value="<%=principal.getName()%>" />
- <% } %>
- </td>
- </tr>
- <%
- }
- %>
- </tbody>
- <tfoot>
- <tr>
- <td colspan="2"></td>
- <td align="center"><input type="submit" value="Remove Selected" /></td>
- </tr>
- </tfoot>
- </table>
- </form>
- </fieldset>
-</body>
-</html>
-<%
- }
-%>
diff --git a/src/main/resources/initial-content/content/starter/access/ace.css b/src/main/resources/initial-content/content/starter/access/ace.css
new file mode 100644
index 0000000..d42e311
--- /dev/null
+++ b/src/main/resources/initial-content/content/starter/access/ace.css
@@ -0,0 +1,161 @@
+/*
+ * 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.
+ */
+
+.notice.error {
+ color: #c00;
+ background-color: #fee;
+ border: 1px solid #c00;
+ margin: 3px;
+ padding: 4px;
+ line-height: 18px;
+ font-weight: bold;
+}
+
+table#privileges {
+ width: 100%;
+}
+table#restrictions caption,
+table#privileges caption {
+ display: none;
+}
+
+table#privileges .ellipsis {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+table#privileges tbody tr:nth-child(odd) {
+ background-color: aliceblue;
+}
+
+table#privileges td.depth1 label:before {
+ content: "\0000a0┣━ ";
+ font-family: monospace;
+ color: gray;
+}
+table#privileges td.depth1.lastBranch label:before,
+table#privileges td.depth1.lastSibling label:before {
+ content: "\0000a0┗━ ";
+}
+
+table#privileges td.depth2 label:before {
+ content: "\0000a0┃\0000a0\0000a0\0000a0┣━ ";
+ font-family: monospace;
+ color: gray;
+}
+table#privileges td.depth2.lastSibling label:before {
+ content: "\0000a0┃\0000a0\0000a0\0000a0┗━ ";
+}
+table#privileges td.depth2.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0┣━ ";
+}
+table#privileges td.depth2.lastSibling.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0┗━ ";
+}
+
+table#privileges td.depth3 label:before {
+ content: "\0000a0┃\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┣━ ";
+ font-family: monospace;
+ color: gray;
+}
+table#privileges td.depth3.lastSibling label:before {
+ content: "\0000a0┃\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┗━ ";
+}
+table#privileges td.depth3.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0┣━ ";
+}
+table#privileges td.depth3.lastSibling.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0┗━ ";
+}
+
+table#privileges td.depth4 label:before {
+ content: "\0000a0┃\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┣━ ";
+ font-family: monospace;
+ color: gray;
+}
+table#privileges td.depth4.lastSibling label:before {
+ content: "\0000a0┃\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┗━ ";
+}
+table#privileges td.depth4.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┣━ ";
+}
+table#privileges td.depth4.lastSibling.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0┃\0000a0\0000a0\0000a0┗━ ";
+}
+table#privileges td.depth4.restriction.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0┣━ ";
+}
+table#privileges td.depth4.restriction.lastSibling.lastBranch label:before {
+ content: "\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0\0000a0┗━ ";
+}
+
+.restriction-row input,
+table#privileges input {
+ width: auto;
+ margin-bottom: revert;
+}
+
+fieldset#ace-privileges {
+ margin-bottom: 20px;
+}
+
+form#modifyAceForm > div label {
+ display: block;
+}
+form#modifyAceForm div select {
+ width: 100%;
+}
+
+form#modifyAceForm div.form-buttons {
+ margin-top: 20px;
+ margin-bottom: 20px;
+}
+
+dialog#restrictionsDialog {
+ min-width: 400px;
+ max-width: 70%;
+ max-height: 70%;
+ overflow:auto;
+}
+dialog#restrictionsDialog h3 {
+ margin-block-start: 0px;
+}
+
+p.restriction-row label {
+ display: block;
+}
+p.restriction-row span.restriction-values,
+p.restriction-row span.restriction-value {
+ display: block;
+ margin-left: 25px;
+}
+p.restriction-row span.restriction-values input[type='text'] {
+ width: calc(100% - 100px);
+}
+p.restriction-row span.restriction-value input[type='text'] {
+ width: calc(100% - 40px);
+}
+p.restriction-row button {
+ width: 25px;
+ padding: 0.5em 0.6em;
+ vertical-align: top;
+}
+#modifyAceRestrictionsForm button:disabled {
+ background-color: revert;
+ color: revert;
+}
diff --git a/src/main/resources/initial-content/content/starter/access/ace.js b/src/main/resources/initial-content/content/starter/access/ace.js
new file mode 100644
index 0000000..e30fb63
--- /dev/null
+++ b/src/main/resources/initial-content/content/starter/access/ace.js
@@ -0,0 +1,375 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// NOTE: this code expects 'aggregates' and 'existingRestrictionNames' variables
+// to be defined before this is script is invoked
+if (typeof aggregates == 'undefined') {
+ console.error("Expected 'aggregates' variable to be defined");
+}
+if (typeof existingRestrictionNames == 'undefined') {
+ console.error("Expected 'existingRestrictionNames' variable to be defined");
+}
+
+/**
+ * attach click handler for delete ACE button
+ */
+const deleteButton = document.getElementById("deleteButton");
+if (deleteButton) {
+ deleteButton.addEventListener('click', (e) => {
+ e.preventDefault();
+ document.getElementById("deleteAceForm").submit();
+ });
+}
+
+/** reference to the dialog */
+const restrictionsDialog = document.getElementById('restrictionsDialog');
+
+/**
+ * populate the specified restriction state in the restrictions dialog
+ * @param rname the restriction name
+ * @param rvalues the restriction values array
+ */
+const addRestrictionForPrivilege = (rname, rvalues) => {
+ restrictionsDialog.querySelectorAll('p[data-restriction="' + rname + '"] input.declare-restriction').forEach((input) => {
+ input.checked = true;
+ // manually trigger the change handler
+ input.dispatchEvent(new Event("change"));
+
+ const p = input.closest("p");
+ // remove the old rows
+ p.querySelectorAll("span.restriction-value, span.restriction-values").forEach((span) => {
+ span.remove();
+ });
+ // iterate rvalues to add new rows
+ rvalues.forEach((rvalue) => {
+ addRestrictionValueRowFn({ target: p }, rvalue);
+ });
+ });
+};
+
+/**
+ * handler for links that open the restrictions modal dialog
+ */
+const showRestrictionsDialog = (e) => {
+ e.preventDefault();
+ if (typeof restrictionsDialog.showModal === "function") {
+ // populate the dialog with the current state
+ const c = e.target;
+ const privilegeName = c.closest("tr").getAttribute('data-privilege');
+ document.getElementById("for-privilege").textContent = privilegeName;
+
+ const td = c.closest("td");
+ const isAllow = "allow" == td.querySelector("input.granted_or_denied").value;
+ const form = document.getElementById("modifyAceRestrictionsForm");
+ form.setAttribute("data-privilege", privilegeName);
+ form.setAttribute("data-for-privilege-allow", isAllow);
+
+ // clear out the old dialog state
+ restrictionsDialog.querySelectorAll('p.restriction-row').forEach((row) => {
+ // uncheck it
+ const checkbox = row.querySelector("input.declare-restriction");
+ if (checkbox.checked) {
+ checkbox.checked = false;
+ // manually trigger the change handler
+ checkbox.dispatchEvent(new Event("change"));
+ }
+
+ // reset the value rows back to a neutral state
+ row.querySelectorAll("span.restriction-value, span.restriction-values").forEach((span) => {
+ span.remove();
+ });
+ addRestrictionValueRowFn({ target: row }, "");
+ });
+
+ // fill in the current restriction details to a temp obj
+ const rvaluesMap = {};
+ // loop through once to collect all the current values
+ td.querySelectorAll("span.restriction-state input").forEach((input) => {
+ const restrictionRegex = /^restriction@([^@]+)@([^@]+)(@(Allow|Deny))?$/;
+ const matches = restrictionRegex.exec(input.getAttribute("name"));
+ if (matches) {
+ const restrictionName = matches[2];
+ if (restrictionName) {
+ const value = input.value;
+ if (value) {
+ if (!rvaluesMap[restrictionName]) {
+ rvaluesMap[restrictionName] = {
+ values: []
+ };
+ }
+ if (value) {
+ rvaluesMap[restrictionName]["values"].push(value);
+ }
+ }
+ }
+ }
+ });
+
+ // now loop through the collected items to do the work
+ Object.keys(rvaluesMap).forEach((rname) => {
+ const robj = rvaluesMap[rname];
+ addRestrictionForPrivilege(rname, robj["values"]);
+ });
+
+ restrictionsDialog.showModal();
+ } else {
+ alert("Sorry, the <dialog> API is not supported by this browser.");
+ }
+};
+
+/**
+ * Attach the click handler to all the edit restrictions links
+ */
+document.querySelectorAll('span.editRestrictions a').forEach((link) => {
+ link.addEventListener('click', showRestrictionsDialog);
+});
+
+
+/**
+ * Attach click handler to the restrictions dialog ok button
+ */
+restrictionsDialog.querySelector("button#dlgOk").addEventListener("click", (e) => {
+ e.preventDefault();
+
+ const form = document.getElementById("modifyAceRestrictionsForm");
+ if (form.reportValidity()) {
+ // copy the dialog state to the restriction-state elements
+ const privilegeName = form.getAttribute('data-privilege');
+ // determine which column is being updated
+ const tdIdx = form.getAttribute('data-for-privilege-allow') == "true" ? 2 : 3;
+ const restrictionState = document.querySelector("table#privileges tr[data-privilege='" + privilegeName + "'] td:nth-of-type(" + tdIdx + ") span.restriction-state");
+ // clear the old state
+ restrictionState.replaceChildren();
+
+ // fill in the current restriction details to a temp obj
+ const rnames = new Set();
+ // inject the new state
+ restrictionsDialog.querySelectorAll("input").forEach((input) => {
+ // if unchecked restriction is one that was existing before, then add
+ // a hidden field to remove the restriction
+ if (input.classList.contains("declare-restriction") && !input.checked) {
+ const restrictionName = input.parentElement.innerText.trim();
+ const prname = privilegeName + "@" + restrictionName;
+ const key = tdIdx == 2 ? "allow" : "deny";
+ if (existingRestrictionNames[key].includes(prname)) {
+ //add a hidden input to remove the existing restriction
+ restrictionState.insertAdjacentHTML("beforeend", "<input type='hidden' name='restriction@" + prname + "@Delete' value='" + ("allow" == key ? 'allow' : 'deny') + "'/>");
+ }
+ }
+ if (!input.disabled && input.name) {
+ const clone = input.cloneNode();
+ clone.type = "hidden";
+ restrictionState.appendChild(clone);
+
+ // keep track of the names for use later
+ const restrictionRegex = /^restriction@([^@]+)@([^@]+)(@(Delete|Allow|Deny))?$/;
+ const matches = restrictionRegex.exec(input.getAttribute("name"));
+ const restrictionName = matches[2];
+ if (restrictionName) {
+ rnames.add(restrictionName);
+ }
+ }
+ });
+
+ // now update the label of the corresponding 'edit restrictions' link'
+ const restrictionDetails = document.querySelector("table#privileges tr[data-privilege='" + privilegeName + "'] td:nth-of-type(" + tdIdx + ") span.editRestrictions span.restriction-details");
+ // clear out the old value
+ restrictionDetails.replaceChildren();
+ // insert the new value
+ if (rnames.size == 0) {
+ restrictionDetails.insertAdjacentText("beforeend", "No Restrictions");
+ } else {
+ restrictionDetails.insertAdjacentText("beforeend", Array.from(rnames).join(", "));
+ }
+
+ // all done, so close the dialog
+ restrictionsDialog.close();
+ }
+});
+
+/**
+ * Attach click handler to the restrictions dialog cancel button
+ */
+restrictionsDialog.querySelector("button#dlgCancel").addEventListener("click", (e) => {
+ e.preventDefault();
+ restrictionsDialog.close();
+});
+
+/**
+ * function that toggle the display of the restriction value input rows
+ */
+const applyRestrictionFn = (e) => {
+ e.preventDefault();
+ const c = e.target;
+ const p = c.closest("p");
+ p.querySelectorAll("input[type='text']").forEach((input) => {
+ input.disabled = !c.checked;
+ });
+ p.querySelectorAll("span").forEach((span) => {
+ span.style.display = c.checked ? '' : 'none';
+ });
+};
+
+/**
+ * Attach change handler to the restriction checkboxes
+ */
+document.querySelectorAll('input.declare-restriction').forEach((checkbox) => {
+ checkbox.addEventListener('change', applyRestrictionFn);
+});
+
+/**
+ * Helper to disable the delete restriction value row button if there is only one left
+ */
+const maybeDisableDeleteMultivalue = (p) => {
+ // disable the delete button if there is only one row left
+ const buttons = p.querySelectorAll("button.delete-multivalue");
+ const form = document.getElementById("modifyAceRestrictionsForm");
+ const canModify = form.getAttribute("data-canModify") == "true";
+ buttons.forEach((button) => {
+ button.disabled = !canModify || buttons.length == 1;
+ });
+};
+
+/**
+ * function that removes the restriction value row
+ */
+const removeRestrictionValueRowFn = (e) => {
+ if (typeof e.preventDefault === "function") {
+ e.preventDefault();
+ }
+ const c = e.target;
+ const p = c.closest("p");
+ if (p.querySelectorAll("span").length > 1) {
+ c.closest("span").remove();
+ maybeDisableDeleteMultivalue(p);
+ } else {
+ alert("Sorry, the last row can not be removed.");
+ }
+}
+
+/**
+ * function that adds a new restriction value row
+ * @param e the triggering event
+ * @param value (optional) the initial value of the new text input
+ */
+const addRestrictionValueRowFn = (e, value) => {
+ if (typeof e.preventDefault === "function") {
+ e.preventDefault();
+ }
+ const c = e.target;
+ const p = c.closest("p");
+ const form = c.closest("form");
+ const canModify = form.getAttribute("data-canModify") == "true";
+ const privilegeName = form.getAttribute('data-privilege');
+ const suffix = form.getAttribute('data-for-privilege-allow') == "true" ? "Allow" : "Deny";
+ const restrictionName = p.getAttribute('data-restriction');
+ const multival = p.getAttribute("data-multival") == "true";
+ const checked = p.querySelector("input.declare-restriction").checked;
+ let row = '<span class="restriction-value' + (multival ? 's' : '') + '"' + (checked ? '' : ' style="display: none;"') + '>' +
+ '<input type="text" name="restriction@' + privilegeName + '@' + restrictionName + '@' + suffix + '" value="' + (value || '').replaceAll('"', '"') + '" required="required"' + (canModify && checked ? '' : ' disabled="disabled"') + ' /> ';
+ if (multival) {
+ row += '<button type="button" class="add-multivalue"' + (canModify ? '' : ' disabled="disabled"') + '>+</button> ' +
+ '<button type="button" class="delete-multivalue">-</button>';
+ }
+ row += '</span>';
+ p.insertAdjacentHTML("beforeend", row);
+ if (multival) {
+ const newRow = p.lastElementChild;
+ newRow.querySelector("button.add-multivalue")
+ .addEventListener('click', addRestrictionValueRowFn);
+ newRow.querySelector("button.delete-multivalue")
+ .addEventListener('click', removeRestrictionValueRowFn);
+ maybeDisableDeleteMultivalue(p);
+ }
+}
+
+/**
+ * toggle the restrictions links when permission checkbox changes
+ */
+const setAggregatePrivilege = (privilegeName, val, checked) => {
+ const btn = document.querySelector("input[name='privilege@" + privilegeName + "'][type=checkbox][value='" + val + "']");
+ if ((checked && !btn.checked) ||
+ (!checked && btn.disabled)) {
+ let ancestorChecked = false;
+ if (!checked) {
+ // check if any ancestor checkboxes are still checked
+ Object.keys(aggregates).every((pname) => {
+ const pobj = aggregates[pname];
+ if (pobj.includes(privilegeName)) {
+ ancestorChecked = document.querySelector("input[name='privilege@" + pname + "'][type=checkbox][value='" + val + "']").checked;
+ }
+ return !ancestorChecked;
+ });
+ }
+ if (!ancestorChecked) {
+ btn.checked = checked;
+ btn.disabled = checked;
+
+ const td = btn.closest("td");
+ td.querySelectorAll("input.delete").forEach((input) => {
+ input.disabled = checked;
+ });
+ td.querySelectorAll(".restriction-state input").forEach((input) => {
+ input.disabled = !checked;
+ });
+ td.querySelector(".editRestrictions").style.display = checked ? '' : 'none';
+ }
+ }
+};
+
+/**
+ * handler for changes to allow/deny privilege checkboxes
+ */
+const applyAggregatePrivilegeFn = (e) => {
+ if (typeof e.preventDefault === "function") {
+ e.preventDefault();
+ }
+ const c = e.target;
+ const div = c.parentElement.parentElement;
+ // toggle the disabled state of the hidden "delete" input (if any)
+ div.querySelectorAll("input.delete").forEach((input) => {
+ input.disabled = c.checked;
+ });
+
+ // toggle the disabled state of any restriction state inputs
+ div.querySelectorAll(".restriction-state input").forEach((input) => {
+ input.disabled = !c.checked;
+ });
+
+ // toggle the visibility of the edit restrictions link
+ div.querySelector("span.editRestrictions").style.display = c.checked ? '' : 'none';
+
+ // set/unset any affected aggregate privileges
+ const privilegeName = c.closest("tr").getAttribute('data-privilege');
+ const a = aggregates[privilegeName];
+ if (a) {
+ a.forEach((name) => {
+ setAggregatePrivilege(name, c.value, c.checked);
+ });
+ }
+};
+
+/**
+ * Attach the change handler to all the allow/deny privilege checkboxes
+ */
+document.querySelectorAll('input.granted_or_denied').forEach((checkbox) => {
+ checkbox.addEventListener('change', applyAggregatePrivilegeFn);
+ if (checkbox.checked) {
+ // pre-process any checkboxes that are already checked
+ applyAggregatePrivilegeFn({ target: checkbox });
+ }
+});
diff --git a/src/main/resources/initial-content/content/starter/access/acl.css b/src/main/resources/initial-content/content/starter/access/acl.css
new file mode 100644
index 0000000..c3aab72
--- /dev/null
+++ b/src/main/resources/initial-content/content/starter/access/acl.css
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+.notice.info {
+ margin: 3px;
+ padding: 4px;
+ line-height: 18px;
+ font-weight: bold;
+}
+
+table#aces {
+ width: 100%;
+}
+table#aces caption {
+ display: none;
+}
+table#aces .ellipsis {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+table#aces tbody tr:nth-child(odd) {
+ background-color: aliceblue;
+}
+input#addPid {
+ width: 100%;
+}
+
+table#aces button,
+table#aces input {
+ width: auto;
+ margin-bottom: revert;
+}
+table#aces button:disabled {
+ background-color: revert;
+ color: revert;
+}
diff --git a/src/main/resources/initial-content/content/starter/access/acl.js b/src/main/resources/initial-content/content/starter/access/acl.js
new file mode 100644
index 0000000..ad483b3
--- /dev/null
+++ b/src/main/resources/initial-content/content/starter/access/acl.js
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+/**
+ * Attach the change handler to all the select ACE checkboxes
+ */
+const selectedChangedFn = () => {
+ // enable the removeButton if any checkboxes are checked
+ let disable = true;
+ document.querySelectorAll('input.delete').forEach((input) => {
+ if (input.checked) {
+ disable = false;
+ }
+ });
+ document.getElementById("removeButton").disabled = disable;
+};
+document.querySelectorAll('input.delete').forEach((input) => {
+ input.addEventListener('change', selectedChangedFn);
+});
diff --git a/src/test/java/org/apache/sling/starter/access/models/AccessFormPageTest.java b/src/test/java/org/apache/sling/starter/access/models/AccessFormPageTest.java
new file mode 100644
index 0000000..8adbaa9
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/AccessFormPageTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.SlingHttpServletResponse;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.jcr.jackrabbit.accessmanager.PrivilegesInfo;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+abstract class AccessFormPageTest {
+ protected AccessFormPage page;
+ protected Node currentNode;
+ protected ResourceResolver rr;
+ protected abstract AccessFormPage createPageModel();
+
+ @BeforeEach
+ void beforeEach() throws RepositoryException {
+ page = createPageModel();
+ page.privilegesInfo = Mockito.mock(PrivilegesInfo.class);
+ page.resource = Mockito.mock(Resource.class);
+ page.request = Mockito.mock(SlingHttpServletRequest.class);
+ page.response = Mockito.mock(SlingHttpServletResponse.class);
+
+ rr = Mockito.mock(ResourceResolver.class);
+ currentNode = Mockito.mock(Node.class);
+ Mockito.when(page.resource.adaptTo(Node.class)).thenReturn(currentNode);
+ Mockito.when(page.resource.getPath()).thenReturn("/content/test1");
+ Mockito.when(page.resource.getResourceResolver()).thenReturn(rr);
+ Mockito.when(page.request.getResourceResolver()).thenReturn(rr);
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.AccessFormPage#init()}.
+ */
+ @Test
+ void testInit() {
+ Assertions.assertDoesNotThrow(() -> page.init());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.AccessFormPage#getPrivilegesInfo()}.
+ */
+ @Test
+ void testGetPrivilegesInfo() {
+ assertNotNull(page.getPrivilegesInfo());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.AccessFormPage#getCanReadAccessControl()}.
+ */
+ @Test
+ void testGetCanReadAccessControl() {
+ Mockito.when(page.privilegesInfo.canReadAccessControl(currentNode)).thenReturn(true);
+ assertTrue(page.getCanReadAccessControl());
+ Mockito.when(page.privilegesInfo.canReadAccessControl(currentNode)).thenReturn(false);
+ assertFalse(page.getCanReadAccessControl());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.AccessFormPage#getCanModifyAccessControl()}.
+ */
+ @Test
+ void testGetCanModifyAccessControl() {
+ Mockito.when(page.privilegesInfo.canModifyAccessControl(currentNode)).thenReturn(true);
+ assertTrue(page.getCanModifyAccessControl());
+ Mockito.when(page.privilegesInfo.canModifyAccessControl(currentNode)).thenReturn(false);
+ assertFalse(page.getCanModifyAccessControl());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.AccessFormPage#getLocation()}.
+ */
+ @Test
+ void testGetLocation() {
+ Mockito.when(rr.map(page.resource.getPath())).thenReturn("/test1");
+ assertEquals("/test1", page.getLocation());
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/AceTest.java b/src/test/java/org/apache/sling/starter/access/models/AceTest.java
new file mode 100644
index 0000000..19b23d1
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/AceTest.java
@@ -0,0 +1,594 @@
+/*
+ * 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.starter.access.models;
+
+import static org.apache.sling.starter.access.models.AceUtilsTest.createMockPrivilege;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+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.assertTrue;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.Workspace;
+import javax.jcr.security.AccessControlManager;
+import javax.jcr.security.Privilege;
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+import javax.json.JsonValue;
+
+import org.apache.jackrabbit.api.JackrabbitSession;
+import org.apache.jackrabbit.api.JackrabbitWorkspace;
+import org.apache.jackrabbit.api.security.authorization.PrivilegeManager;
+import org.apache.jackrabbit.api.security.principal.PrincipalManager;
+import org.apache.jackrabbit.api.security.user.User;
+import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.jackrabbit.oak.api.Type;
+import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinitionImpl;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider;
+import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;
+import org.apache.sling.api.request.RequestParameter;
+import org.apache.sling.api.request.RequestParameterMap;
+import org.apache.sling.api.request.builder.impl.RequestParameterImpl;
+import org.apache.sling.api.request.builder.impl.RequestParameterMapImpl;
+import org.apache.sling.jcr.jackrabbit.accessmanager.GetAce;
+import org.apache.sling.jcr.jackrabbit.accessmanager.GetAcl;
+import org.jetbrains.annotations.NotNull;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class AceTest extends AccessFormPageTest {
+ private static final String ACE_JSON = "{\n"
+ + " \"principal\":\"testUser1\",\n"
+ + " \"order\":0,\n"
+ + " \"privileges\":{\n"
+ + " \"jcr:read\":{\n"
+ + " \"allow\":true\n"
+ + " },\n"
+ + " \"jcr:write\":{\n"
+ + " \"allow\":true\n"
+ + " }\n"
+ + " }\n"
+ + "}";
+ private static final String ACE_JSON_WITH_RESTRICTIONS = "{\n"
+ + " \"principal\":\"testUser1\",\n"
+ + " \"order\":0,\n"
+ + " \"privileges\":{\n"
+ + " \"jcr:read\":{\n"
+ + " \"allow\":{\n"
+ + " \"rep:ntNames\":[\n"
+ + " \"name1\",\n"
+ + " \"name2\"\n"
+ + " ]\n"
+ + " }\n"
+ + " },\n"
+ + " \"jcr:write\":{\n"
+ + " \"deny\":{\n"
+ + " \"rep:glob\":\"glob1\"\n"
+ + " }\n"
+ + " }\n"
+ + " }\n"
+ + "}";
+ private static final String RESTRICTIONS_JSON = "{\n"
+ + " \"rep:ntNames\":[\n"
+ + " \"name1\",\n"
+ + " \"name2\"\n"
+ + " ],\n"
+ + " \"rep:glob\":\"glob1\"\n"
+ + " }";
+
+ private Ace acePage = null;
+
+ private RestrictionDefinition repGlobDef;
+ private RestrictionDefinition repNtNamesDef;
+
+ private Session jcrSession;
+
+ private Privilege jcrRead;
+
+ private Privilege jcrWrite;
+
+ @Override
+ protected AccessFormPage createPageModel() {
+ acePage = new Ace();
+ return acePage;
+ }
+
+ @Override
+ @BeforeEach
+ void beforeEach() throws RepositoryException {
+ super.beforeEach();
+
+ Mockito.when(acePage.request.getParameter("pid")).thenReturn("testUser1");
+
+ acePage.getAcl = Mockito.mock(GetAcl.class);
+ acePage.getAce = Mockito.mock(GetAce.class);
+
+ jcrSession = Mockito.mock(JackrabbitSession.class);
+ Mockito.when(acePage.request.getResourceResolver().adaptTo(Session.class)).thenReturn(jcrSession);
+
+ mockPrivilegeLookup();
+ mockAuthorizableLookup();
+ mockRestrictionProvider(false);
+ mockPrincipalManager();
+ }
+
+ protected void mockPrincipalManager() throws RepositoryException {
+ // mock principalMgr
+ PrincipalManager principalMgr = Mockito.mock(PrincipalManager.class);
+ Mockito.when(((JackrabbitSession)jcrSession).getPrincipalManager()).thenReturn(principalMgr);
+ Mockito.when(principalMgr.getPrincipal("testUser1")).thenReturn(() -> "testUser1");
+ Mockito.when(principalMgr.getPrincipal("testGroup1")).thenReturn(new TestGroupPrincipal("testGroup1"));
+ }
+
+ protected void mockRestrictionProvider(boolean isManditory) {
+ // mock the restriction provider calls
+ RestrictionProvider restrictionProvider = Mockito.mock(RestrictionProvider.class);
+ acePage.restrictionProviders = Collections.singletonList(restrictionProvider);
+ repGlobDef = new RestrictionDefinitionImpl(AccessControlConstants.REP_GLOB, Type.STRING, isManditory);
+ repNtNamesDef = new RestrictionDefinitionImpl(AccessControlConstants.REP_NT_NAMES, Type.STRINGS, isManditory);
+ Mockito.when(restrictionProvider.getSupportedRestrictions(acePage.resource.getPath()))
+ .thenReturn(new HashSet<>(Arrays.asList(repGlobDef, repNtNamesDef)));
+ }
+
+ protected void mockAuthorizableLookup() throws RepositoryException {
+ // mock the authorizable lookup path
+ UserManager userMgr = Mockito.mock(UserManager.class);
+ Mockito.when(acePage.request.getResourceResolver().adaptTo(Session.class)).thenReturn(jcrSession);
+ Mockito.when(((JackrabbitSession)jcrSession).getUserManager()).thenReturn(userMgr);
+ User userAuthorizable = Mockito.mock(User.class);
+ Mockito.when(userMgr.getAuthorizable("testUser1")).thenReturn(userAuthorizable);
+ }
+
+ protected void mockPrivilegeLookup() throws RepositoryException {
+ // mock the privilege lookup
+ AccessControlManager acm = Mockito.mock(AccessControlManager.class);
+ Mockito.when(jcrSession.getAccessControlManager()).thenReturn(acm);
+
+ Privilege repReadNodes = createMockPrivilege(PrivilegeConstants.REP_READ_NODES, new Privilege[0]);
+ Privilege repReadProperties = createMockPrivilege(PrivilegeConstants.REP_READ_PROPERTIES, new Privilege[0]);
+ jcrRead = createMockPrivilege(PrivilegeConstants.JCR_READ, new Privilege[] {
+ repReadNodes,
+ repReadProperties
+ });
+ jcrWrite = createMockPrivilege(PrivilegeConstants.JCR_WRITE, new Privilege[0]);
+
+ Privilege all = createMockPrivilege(PrivilegeConstants.JCR_ALL, new Privilege[] {
+ jcrRead,
+ jcrWrite
+ });
+ Mockito.when(acm.privilegeFromName(PrivilegeConstants.JCR_ALL)).thenReturn(all);
+ Mockito.when(acm.privilegeFromName(PrivilegeConstants.REP_READ_NODES)).thenReturn(repReadNodes);
+ Mockito.when(acm.privilegeFromName(PrivilegeConstants.REP_READ_PROPERTIES)).thenReturn(repReadProperties);
+ Mockito.when(acm.privilegeFromName(PrivilegeConstants.JCR_READ)).thenReturn(jcrRead);
+ Mockito.when(acm.privilegeFromName(PrivilegeConstants.JCR_WRITE)).thenReturn(jcrWrite);
+
+ Mockito.when(acm.getSupportedPrivileges(acePage.getAcePath())).thenReturn(new Privilege[] {
+ all,
+ jcrRead,
+ repReadNodes,
+ repReadNodes,
+ jcrWrite
+ });
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#init()}.
+ */
+ @Test
+ void testInit() {
+ super.testInit();
+ assertEquals("testUser1", acePage.getPrincipalId());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#createPrivilegesPriorityMap()}.
+ */
+ @Test
+ void testCreatePrivilegesPriorityMap() {
+ assertNotNull(Ace.createPrivilegesPriorityMap());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getPrincipalId()}.
+ */
+ @Test
+ void testGetPrincipalId() {
+ assertNull(acePage.getPrincipalId());
+ super.testInit();
+ assertEquals("testUser1", acePage.getPrincipalId());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getIsInvalidPrincipal()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetIsInvalidPrincipal() throws RepositoryException {
+ assertTrue(acePage.getIsInvalidPrincipal());
+ super.testInit();
+ assertFalse(acePage.getIsInvalidPrincipal());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getAcePath()}.
+ */
+ @Test
+ void testGetAcePath() {
+ assertEquals("/content/test1", acePage.getAcePath());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#isExists()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testIsExists() throws RepositoryException {
+ assertFalse(acePage.isExists());
+
+ // exists calculation happens in here
+ testGetPersistedPrivilegesMap();
+
+ assertTrue(acePage.isExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getPrivileges()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetPrivileges() throws RepositoryException {
+ mockPersistedPrivileges(ACE_JSON);
+
+ Collection<PrivilegeItem> privileges = acePage.getPrivileges();
+ assertNotNull(privileges);
+ assertEquals(2, privileges.size());
+ assertTrue(privileges.stream().anyMatch(p -> jcrRead.getName().equals(p.getName())));
+ assertTrue(privileges.stream().anyMatch(p -> jcrWrite.getName().equals(p.getName())));
+ }
+
+ protected void mockPersistedPrivileges(String ace) throws RepositoryException {
+ Assertions.assertDoesNotThrow(() -> page.init());
+
+ JsonObject aceJson;
+ try (StringReader strReader = new StringReader(ace);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ aceJson = jsonReader.readObject();
+ }
+ Mockito.when(acePage.getAce.getAce(jcrSession, acePage.resource.getPath(), "testUser1"))
+ .thenReturn(aceJson);
+
+ Map<String, String[]> rawReqParams = new HashMap<>();
+ RequestParameterMap requestParameterMap = new RequestParameterMapImpl(rawReqParams);
+ Mockito.when(acePage.request.getRequestParameterMap()).thenReturn(requestParameterMap);
+
+ // clear this out from any previous call so it is calculated again
+ acePage.persistedPrivilegesMap = null;
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#populateEntriesFromPreviousFailedPost(java.util.Map, java.util.Map, java.util.Map)}.
+ */
+ @Test
+ void testPopulateEntriesFromPreviousFailedPost() {
+ // mock the request parameters map
+ Map<String, String[]> rawReqParams = new HashMap<>();
+ rawReqParams.put("restriction@jcr:read@rep:glob@Allow", new String[] {"glob1"});
+ rawReqParams.put("restriction@jcr:write@rep:ntNames@Deny", new String[] {"ntNames1", "ntNames2"});
+ rawReqParams.put("key1", new String[] {"value2"});
+ RequestParameterMap requestParameterMap = new RequestParameterMapImpl(rawReqParams);
+ Mockito.when(acePage.request.getRequestParameterMap()).thenReturn(requestParameterMap);
+
+ Map<String, List<RestrictionItem>> postedAllowRestrictionsMap = new HashMap<>();
+ Map<String, List<RestrictionItem>> postedDenyRestrictionsMap = new HashMap<>();
+ Map<String, String[]> entriesMap = acePage.populateEntriesFromPreviousFailedPost(postedAllowRestrictionsMap,
+ postedDenyRestrictionsMap, acePage.toSrMap(acePage.getSupportedRestrictions()));
+ assertNotNull(entriesMap);
+ assertEquals(2, entriesMap.size());
+ assertArrayEquals(new String[] {"glob1"}, entriesMap.get("restriction@jcr:read@rep:glob@Allow"));
+ assertArrayEquals(new String[] {"ntNames1", "ntNames2"}, entriesMap.get("restriction@jcr:write@rep:ntNames@Deny"));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#populateEntriesForMissingMandatoryRestrictions(java.util.List, java.util.Set)}.
+ */
+ @Test
+ void testPopulateEntriesForMissingMandatoryRestrictions() {
+ // test when no restrictions are mandatory
+ List<RestrictionItem> newRestrictionsList = new ArrayList<>();
+ acePage.populateEntriesForMissingMandatoryRestrictions(newRestrictionsList, acePage.getSupportedRestrictions());
+ assertEquals(0, newRestrictionsList.size());
+
+ // mock a restriction being mandatory
+ mockRestrictionProvider(true);
+ acePage.populateEntriesForMissingMandatoryRestrictions(newRestrictionsList, acePage.getSupportedRestrictions());
+ assertEquals(2, newRestrictionsList.size());
+ assertTrue(newRestrictionsList.stream().anyMatch(p -> p.getName().equals(AccessControlConstants.REP_GLOB)));
+ assertTrue(newRestrictionsList.stream().anyMatch(p -> p.getName().equals(AccessControlConstants.REP_NT_NAMES)));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#toSrMap(java.util.Set)}.
+ */
+ @Test
+ void testToSrMap() {
+ Map<String, RestrictionDefinition> srMap = acePage.toSrMap(acePage.getSupportedRestrictions());
+ assertNotNull(srMap);
+ assertEquals(2, srMap.size());
+ assertTrue(srMap.containsKey(repGlobDef.getName()));
+ assertTrue(srMap.containsKey(repNtNamesDef.getName()));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getSupportedOrRegisteredPrivileges(javax.jcr.Session, java.lang.String)}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetSupportedOrRegisteredPrivileges() throws RepositoryException {
+ // mock that the resource does exist
+ Mockito.when(jcrSession.nodeExists(acePage.getAcePath())).thenReturn(true);
+ @NotNull
+ Privilege[] supportedOrRegisteredPrivileges = acePage.getSupportedOrRegisteredPrivileges(jcrSession, acePage.getAcePath());
+ assertNotNull(supportedOrRegisteredPrivileges);
+ assertEquals(5, supportedOrRegisteredPrivileges.length);
+ assertTrue(Stream.of(supportedOrRegisteredPrivileges).anyMatch(p -> jcrRead.equals(p)));
+ assertTrue(Stream.of(supportedOrRegisteredPrivileges).anyMatch(p -> jcrWrite.equals(p)));
+
+ // mock that the resource does not exist
+ Mockito.when(jcrSession.nodeExists(Ace.PATH_REPOSITORY)).thenReturn(false);
+ Workspace workspace = Mockito.mock(JackrabbitWorkspace.class);
+ Mockito.when(jcrSession.getWorkspace()).thenReturn(workspace);
+ PrivilegeManager privilegeManager = Mockito.mock(PrivilegeManager.class);
+ Mockito.when(((JackrabbitWorkspace)workspace).getPrivilegeManager()).thenReturn(privilegeManager);
+ Mockito.when(privilegeManager.getRegisteredPrivileges()).thenReturn(new Privilege[] {
+ jcrRead,
+ jcrWrite
+ });
+ supportedOrRegisteredPrivileges = acePage.getSupportedOrRegisteredPrivileges(jcrSession, Ace.PATH_REPOSITORY);
+ assertNotNull(supportedOrRegisteredPrivileges);
+ assertEquals(2, supportedOrRegisteredPrivileges.length);
+ assertTrue(Stream.of(supportedOrRegisteredPrivileges).anyMatch(p -> jcrRead.equals(p)));
+ assertTrue(Stream.of(supportedOrRegisteredPrivileges).anyMatch(p -> jcrWrite.equals(p)));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#initialPrivilegesMap(java.util.Map, java.lang.String)}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testInitialPrivilegesMap() throws RepositoryException {
+ Map<Privilege, String> privilegeLongestPathMap = AceUtils.getPrivilegeLongestPathMap(jcrSession);
+ // mock that the resource does exist
+ Mockito.when(jcrSession.nodeExists(acePage.getAcePath())).thenReturn(true);
+ Map<Privilege, PrivilegeItem> initialPrivilegesMap = acePage.initialPrivilegesMap(privilegeLongestPathMap, acePage.getAcePath());
+ assertNotNull(initialPrivilegesMap);
+ assertEquals(4, initialPrivilegesMap.size());
+ assertTrue(initialPrivilegesMap.containsKey(jcrRead));
+ assertTrue(initialPrivilegesMap.containsKey(jcrWrite));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getPersistedPrivilegesMap()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetPersistedPrivilegesMap() throws RepositoryException {
+ Assertions.assertDoesNotThrow(() -> page.init());
+
+ JsonObject aceJson;
+ try (StringReader strReader = new StringReader(ACE_JSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ aceJson = jsonReader.readObject();
+ }
+ Mockito.when(acePage.getAce.getAce(jcrSession, acePage.resource.getPath(), "testUser1"))
+ .thenReturn(aceJson);
+
+ Map<Privilege, PrivilegeItem> persistedPrivilegesMap = acePage.getPersistedPrivilegesMap();
+ assertNotNull(persistedPrivilegesMap);
+ assertEquals(2, persistedPrivilegesMap.size());
+ assertTrue(persistedPrivilegesMap.containsKey(jcrRead));
+ assertTrue(persistedPrivilegesMap.containsKey(jcrWrite));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#jsonToRestrictionItems(java.util.Map, javax.json.JsonObject)}.
+ */
+ @Test
+ void testJsonToRestrictionItems() {
+ JsonObject restrictionsJson;
+ try (StringReader strReader = new StringReader(RESTRICTIONS_JSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ restrictionsJson = jsonReader.readObject();
+ }
+ List<RestrictionItem> jsonToRestrictionItems = acePage.jsonToRestrictionItems(acePage.toSrMap(acePage.getSupportedRestrictions()), restrictionsJson);
+ assertNotNull(jsonToRestrictionItems);
+ assertEquals(2, jsonToRestrictionItems.size());
+ assertTrue(jsonToRestrictionItems.stream().anyMatch(p -> repGlobDef.getName().equals(p.getName())));
+ assertTrue(jsonToRestrictionItems.stream().anyMatch(p -> repNtNamesDef.getName().equals(p.getName())));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getSupportedRestrictions()}.
+ */
+ @Test
+ void testGetSupportedRestrictions() {
+ Set<RestrictionDefinition> supportedRestrictions = acePage.getSupportedRestrictions();
+ assertNotNull(supportedRestrictions);
+ assertEquals(2, supportedRestrictions.size());
+ assertTrue(supportedRestrictions.contains(repGlobDef));
+ assertTrue(supportedRestrictions.contains(repNtNamesDef));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getSupportedRestrictionsInfo()}.
+ */
+ @Test
+ void testGetSupportedRestrictionsInfo() {
+ List<RestrictionDefinitionInfo> supportedRestrictionsInfo = acePage.getSupportedRestrictionsInfo();
+ assertNotNull(supportedRestrictionsInfo);
+ assertEquals(2, supportedRestrictionsInfo.size());
+ assertEquals(repGlobDef.getName(), supportedRestrictionsInfo.get(0).getName());
+ assertEquals(repNtNamesDef.getName(), supportedRestrictionsInfo.get(1).getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getPrivilegeAggregationsAsJSON()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetPrivilegeAggregationsAsJSON() throws RepositoryException {
+ // mock that the resource does exist
+ Mockito.when(jcrSession.nodeExists(acePage.getAcePath())).thenReturn(true);
+ String privilegeAggregationsAsJSON = acePage.getPrivilegeAggregationsAsJSON();
+ assertNotNull(privilegeAggregationsAsJSON);
+ JsonObject json;
+ try (StringReader strReader = new StringReader(privilegeAggregationsAsJSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ json = jsonReader.readObject();
+ }
+ assertEquals(2, json.size());
+ assertTrue(json.containsKey(PrivilegeConstants.JCR_ALL));
+ assertTrue(json.containsKey(PrivilegeConstants.JCR_READ));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getExistingRestrictionNamesAsJSON()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetExistingRestrictionNamesAsJSON() throws RepositoryException {
+ // try again with no existing restrictions
+ mockPersistedPrivileges(ACE_JSON);
+ String existingRestrictionNamesAsJSON = acePage.getExistingRestrictionNamesAsJSON();
+ assertNotNull(existingRestrictionNamesAsJSON);
+ JsonObject restrictionNamesJson;
+ try (StringReader strReader = new StringReader(existingRestrictionNamesAsJSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ restrictionNamesJson = jsonReader.readObject();
+ }
+ assertNotNull(restrictionNamesJson);
+ JsonValue allow = restrictionNamesJson.get("allow");
+ assertTrue(allow instanceof JsonArray);
+ assertEquals(0, ((JsonArray)allow).size());
+ JsonValue deny = restrictionNamesJson.get("deny");
+ assertTrue(deny instanceof JsonArray);
+ assertEquals(0, ((JsonArray)deny).size());
+
+ // try again with existing restrictions
+ mockPersistedPrivileges(ACE_JSON_WITH_RESTRICTIONS);
+ existingRestrictionNamesAsJSON = acePage.getExistingRestrictionNamesAsJSON();
+ assertNotNull(existingRestrictionNamesAsJSON);
+ try (StringReader strReader = new StringReader(existingRestrictionNamesAsJSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ restrictionNamesJson = jsonReader.readObject();
+ }
+ assertNotNull(restrictionNamesJson);
+ allow = restrictionNamesJson.get("allow");
+ assertTrue(allow instanceof JsonArray);
+ assertEquals(1, ((JsonArray)allow).size());
+ assertEquals("jcr:read@rep:ntNames", ((JsonArray)allow).getString(0));
+ deny = restrictionNamesJson.get("deny");
+ assertTrue(deny instanceof JsonArray);
+ assertEquals(1, ((JsonArray)deny).size());
+ assertEquals("jcr:write@rep:glob", ((JsonArray)deny).getString(0));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getOrderValue()}.
+ */
+ @Test
+ void testGetOrderValue() {
+ assertEquals("", acePage.getOrderValue());
+ Mockito.when(acePage.request.getParameter("order")).thenReturn("first");
+ assertEquals("first", acePage.getOrderValue());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getOrderList()}.
+ * @throws RepositoryException
+ */
+ @Test
+ void testGetOrderList() throws RepositoryException {
+ JsonObject aclJson;
+ try (StringReader strReader = new StringReader(AclTest.ACL_JSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ aclJson = jsonReader.readObject();
+ }
+ Mockito.when(acePage.getAcl.getAcl(jcrSession, acePage.resource.getPath()))
+ .thenReturn(aclJson);
+
+ Collection<PrincipalPrivilege> orderList = acePage.getOrderList();
+ assertNotNull(orderList);
+ assertEquals(2, orderList.size());
+ PrincipalPrivilege[] array = orderList.toArray(new PrincipalPrivilege[orderList.size()]);
+ assertEquals("testUser1", array[0].getName());
+ assertEquals("testGroup1", array[1].getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#fieldValuesFromReqParams(org.apache.sling.api.request.RequestParameter[])}.
+ */
+ @Test
+ void testFieldValuesFromReqParams() {
+ RequestParameter [] paramValues = new RequestParameter[] {
+ new RequestParameterImpl("key1", "value1"),
+ new RequestParameterImpl("key1", "value2"),
+ };
+ assertArrayEquals(new String[] {"value1", "value2"},
+ acePage.fieldValuesFromReqParams(paramValues));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Ace#getFieldValuesForPattern(java.util.regex.Pattern)}.
+ */
+ @Test
+ void testGetFieldValuesForPattern() {
+ Map<String, String[]> rawReqParams = new HashMap<>();
+ rawReqParams.put("restriction@jcr:read@rep:glob@Allow", new String[] {"glob1"});
+ rawReqParams.put("restriction@jcr:write@rep:ntNames@Deny", new String[] {"ntNames1", "ntNames2"});
+ rawReqParams.put("key1", new String[] {"value2"});
+ RequestParameterMap requestParameterMap = new RequestParameterMapImpl(rawReqParams);
+ Mockito.when(acePage.request.getRequestParameterMap()).thenReturn(requestParameterMap);
+
+ Map<String, String[]> fieldValuesForPattern = acePage.getFieldValuesForPattern(Ace.RESTRICTION_PATTERN);
+ assertNotNull(fieldValuesForPattern);
+ assertEquals(2, fieldValuesForPattern.size());
+ assertArrayEquals(new String[] {"glob1"}, fieldValuesForPattern.get("restriction@jcr:read@rep:glob@Allow"));
+ assertArrayEquals(new String[] {"ntNames1", "ntNames2"}, fieldValuesForPattern.get("restriction@jcr:write@rep:ntNames@Deny"));
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/AceUtilsTest.java b/src/test/java/org/apache/sling/starter/access/models/AceUtilsTest.java
new file mode 100644
index 0000000..64712d9
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/AceUtilsTest.java
@@ -0,0 +1,82 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.util.Map;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.security.AccessControlManager;
+import javax.jcr.security.Privilege;
+
+import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class AceUtilsTest {
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.AceUtils#getPrivilegeLongestPathMap(javax.jcr.Session)}.
+ */
+ @Test
+ void testGetPrivilegeLongestPathMap() throws RepositoryException {
+ Session session = Mockito.mock(Session.class);
+ AccessControlManager acm = Mockito.mock(AccessControlManager.class);
+ Mockito.when(session.getAccessControlManager()).thenReturn(acm);
+
+ Privilege repReadNodes = createMockPrivilege(PrivilegeConstants.REP_READ_NODES, new Privilege[0]);
+ Privilege repReadProperties = createMockPrivilege(PrivilegeConstants.REP_READ_PROPERTIES, new Privilege[0]);
+ Privilege jcrRead = createMockPrivilege(PrivilegeConstants.JCR_READ, new Privilege[] {
+ repReadNodes,
+ repReadProperties
+ });
+ Privilege jcrReadAccessControl = createMockPrivilege(PrivilegeConstants.JCR_READ_ACCESS_CONTROL, new Privilege[0]);
+
+ Privilege all = createMockPrivilege(PrivilegeConstants.JCR_ALL, new Privilege[] {
+ jcrRead,
+ jcrReadAccessControl
+ });
+ Mockito.when(acm.privilegeFromName(PrivilegeConstants.JCR_ALL)).thenReturn(all);
+
+ Map<Privilege, String> privilegeLongestPathMap = AceUtils.getPrivilegeLongestPathMap(session);
+ assertNotNull(privilegeLongestPathMap);
+ assertEquals(PrivilegeConstants.JCR_ALL, privilegeLongestPathMap.get(all));
+ assertEquals(String.format("%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ),
+ privilegeLongestPathMap.get(jcrRead));
+ assertEquals(String.format("%s/%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ, PrivilegeConstants.REP_READ_NODES),
+ privilegeLongestPathMap.get(repReadNodes));
+ assertEquals(String.format("%s/%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ, PrivilegeConstants.REP_READ_PROPERTIES),
+ privilegeLongestPathMap.get(repReadProperties));
+ assertEquals(String.format("%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ_ACCESS_CONTROL),
+ privilegeLongestPathMap.get(jcrReadAccessControl));
+ }
+
+ protected static Privilege createMockPrivilege(String name, Privilege[] dap) {
+ Privilege p = Mockito.mock(Privilege.class);
+ Mockito.when(p.getName()).thenReturn(name);
+ Mockito.when(p.getDeclaredAggregatePrivileges()).thenReturn(dap);
+ Mockito.when(p.getAggregatePrivileges()).thenReturn(dap);
+ if (dap != null && dap.length > 0) {
+ Mockito.when(p.isAggregate()).thenReturn(true);
+ }
+ return p;
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/AclTest.java b/src/test/java/org/apache/sling/starter/access/models/AclTest.java
new file mode 100644
index 0000000..4811339
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/AclTest.java
@@ -0,0 +1,129 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.StringReader;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.json.Json;
+import javax.json.JsonObject;
+import javax.json.JsonReader;
+
+import org.apache.jackrabbit.api.JackrabbitSession;
+import org.apache.jackrabbit.api.security.principal.PrincipalManager;
+import org.apache.sling.jcr.jackrabbit.accessmanager.GetAcl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class AclTest extends AccessFormPageTest {
+ static final String ACL_JSON = "{\n"
+ + " \"testUser1\":{\n"
+ + " \"principal\":\"testUser1\",\n"
+ + " \"order\":0,\n"
+ + " \"privileges\":{\n"
+ + " \"jcr:read\":{\n"
+ + " \"allow\":true\n"
+ + " },\n"
+ + " \"rep:write\":{\n"
+ + " \"allow\":true\n"
+ + " }\n"
+ + " }\n"
+ + " },\n"
+ + " \"testGroup1\":{\n"
+ + " \"principal\":\"testGroup1\",\n"
+ + " \"order\":0,\n"
+ + " \"privileges\":{\n"
+ + " \"jcr:read\":{\n"
+ + " \"allow\":true\n"
+ + " },\n"
+ + " \"rep:write\":{\n"
+ + " \"deny\":true\n"
+ + " }\n"
+ + " }\n"
+ + " }\n"
+ + "}";
+
+ protected Session jcrSession;
+
+ private Acl aclPage = null;
+
+ @Override
+ protected AccessFormPage createPageModel() {
+ aclPage = new Acl();
+ return aclPage;
+ }
+
+ @Override
+ @BeforeEach
+ void beforeEach() throws RepositoryException {
+ super.beforeEach();
+
+ aclPage.getAcl = Mockito.mock(GetAcl.class);
+ jcrSession = Mockito.mock(JackrabbitSession.class);
+ Mockito.when(aclPage.request.getResourceResolver().adaptTo(Session.class)).thenReturn(jcrSession);
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.Acl#getPrincipals()}.
+ */
+ @Test
+ void testGetPrincipals() throws RepositoryException {
+ PrincipalManager principalMgr = Mockito.mock(PrincipalManager.class);
+ Mockito.when(((JackrabbitSession)jcrSession).getPrincipalManager()).thenReturn(principalMgr);
+ Mockito.when(principalMgr.getPrincipal("testUser1")).thenReturn(() -> "testUser1");
+ Mockito.when(principalMgr.getPrincipal("testGroup1")).thenReturn(new TestGroupPrincipal("testGroup1"));
+
+ JsonObject aclJson;
+ try (StringReader strReader = new StringReader(ACL_JSON);
+ JsonReader jsonReader = Json.createReader(strReader)) {
+ aclJson = jsonReader.readObject();
+ }
+ Mockito.when(aclPage.getAcl.getAcl(jcrSession, aclPage.resource.getPath()))
+ .thenReturn(aclJson);
+
+ Collection<PrincipalPrivilege> principals = aclPage.getPrincipals();
+ assertNotNull(principals);
+ assertEquals(2, principals.size());
+ Map<String, PrincipalPrivilege> asMap = new HashMap<>();
+ principals.stream().forEach(item -> asMap.put(item.getName(), item));
+
+ PrincipalPrivilege candidateUser = asMap.get("testUser1");
+ assertNotNull(candidateUser);
+ assertEquals("testUser1", candidateUser.getName());
+ assertTrue(candidateUser.isAllow());
+ assertFalse(candidateUser.isDeny());
+ assertFalse(candidateUser.getIsGroup());
+
+ PrincipalPrivilege candidateGroup = asMap.get("testGroup1");
+ assertNotNull(candidateGroup);
+ assertEquals("testGroup1", candidateGroup.getName());
+ assertTrue(candidateGroup.isAllow());
+ assertTrue(candidateGroup.isDeny());
+ assertTrue(candidateGroup.getIsGroup());
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/PrincipalPrivilegeTest.java b/src/test/java/org/apache/sling/starter/access/models/PrincipalPrivilegeTest.java
new file mode 100644
index 0000000..5680556
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/PrincipalPrivilegeTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class PrincipalPrivilegeTest {
+
+ private PrincipalPrivilege pp;
+
+ @BeforeEach
+ void beforeEach() {
+ pp = new PrincipalPrivilege(() -> "testUser1");
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#getName()}.
+ */
+ @Test
+ void testGetName() {
+ assertEquals("testUser1", pp.getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#getPrivilegesDisplayName()}.
+ */
+ @Test
+ void testGetPrivilegesDisplayName() {
+ assertEquals("", pp.getPrivilegesDisplayName());
+ pp.setAllow(true);
+ assertEquals("allow", pp.getPrivilegesDisplayName());
+ pp.setDeny(true);
+ assertEquals("allow / deny", pp.getPrivilegesDisplayName());
+ pp.setAllow(false);
+ assertEquals("deny", pp.getPrivilegesDisplayName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#isAllow()}.
+ */
+ @Test
+ void testIsAllow() {
+ assertFalse(pp.isAllow());
+ pp.setAllow(true);
+ assertTrue(pp.isAllow());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#setAllow(boolean)}.
+ */
+ @Test
+ void testSetAllow() {
+ pp.setAllow(true);
+ assertTrue(pp.isAllow());
+ pp.setAllow(false);
+ assertFalse(pp.isAllow());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#isDeny()}.
+ */
+ @Test
+ void testIsDeny() {
+ assertFalse(pp.isDeny());
+ pp.setDeny(true);
+ assertTrue(pp.isDeny());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#setDeny(boolean)}.
+ */
+ @Test
+ void testSetDeny() {
+ pp.setDeny(true);
+ assertTrue(pp.isDeny());
+ pp.setDeny(false);
+ assertFalse(pp.isDeny());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrincipalPrivilege#getIsGroup()}.
+ */
+ @Test
+ void testGetIsGroup() {
+ assertFalse(pp.getIsGroup());
+
+ PrincipalPrivilege gp = new PrincipalPrivilege(new TestGroupPrincipal("testGroup1"));
+ assertTrue(gp.getIsGroup());
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/PrivilegeItemTest.java b/src/test/java/org/apache/sling/starter/access/models/PrivilegeItemTest.java
new file mode 100644
index 0000000..83974e3
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/PrivilegeItemTest.java
@@ -0,0 +1,292 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class PrivilegeItemTest {
+ private PrivilegeItem jcrReadPi;
+ private PrivilegeItem jcrReadNodesPiWithRestrictions;
+
+ protected RestrictionItem createSingleValueRestrictionItem(String name, Object value, boolean exists) {
+ RestrictionDefinition rd = Mockito.mock(RestrictionDefinition.class);
+ Mockito.when(rd.getName()).thenReturn(name);
+ return new RestrictionItem(rd, value, exists);
+ }
+
+ @BeforeEach
+ void beforeEach() {
+ jcrReadPi = new PrivilegeItem(PrivilegeConstants.JCR_READ, false, false,
+ String.format("%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ));
+
+ jcrReadNodesPiWithRestrictions = new PrivilegeItem(PrivilegeConstants.REP_READ_NODES, false, false,
+ String.format("%s/%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ, PrivilegeConstants.REP_READ_NODES),
+ // allowRestrictions
+ Collections.singletonList(createSingleValueRestrictionItem(AccessControlConstants.REP_GLOB, "glob1", true)),
+ // denyRestrictions
+ Collections.singletonList(createSingleValueRestrictionItem(AccessControlConstants.REP_ITEM_NAMES,
+ new String[] {"name1", "name2"}, true)));
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getName()}.
+ */
+ @Test
+ void testGetName() {
+ assertEquals(PrivilegeConstants.JCR_READ, jcrReadPi.getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getNone()}.
+ */
+ @Test
+ void testGetNone() {
+ assertTrue(jcrReadPi.getNone());
+ jcrReadPi.setGranted(true);
+ assertFalse(jcrReadPi.getNone());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getGranted()}.
+ */
+ @Test
+ void testGetGranted() {
+ assertFalse(jcrReadPi.getGranted());
+ jcrReadPi.setGranted(true);
+ assertTrue(jcrReadPi.getGranted());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getDenied()}.
+ */
+ @Test
+ void testGetDenied() {
+ assertFalse(jcrReadPi.getDenied());
+ jcrReadPi.setDenied(true);
+ assertTrue(jcrReadPi.getDenied());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#setGranted(boolean)}.
+ */
+ @Test
+ void testSetGranted() {
+ jcrReadPi.setGranted(true);
+ assertTrue(jcrReadPi.getGranted());
+ jcrReadPi.setGranted(false);
+ assertFalse(jcrReadPi.getGranted());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#setDenied(boolean)}.
+ */
+ @Test
+ void testSetDenied() {
+ jcrReadPi.setDenied(true);
+ assertTrue(jcrReadPi.getDenied());
+ jcrReadPi.setDenied(false);
+ assertFalse(jcrReadPi.getDenied());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#isAllowExists()}.
+ */
+ @Test
+ void testIsAllowExists() {
+ assertFalse(jcrReadPi.isAllowExists());
+ jcrReadPi.setAllowExists(true);
+ assertTrue(jcrReadPi.isAllowExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#setAllowExists(boolean)}.
+ */
+ @Test
+ void testSetAllowExists() {
+ jcrReadPi.setAllowExists(true);
+ assertTrue(jcrReadPi.isAllowExists());
+ jcrReadPi.setAllowExists(false);
+ assertFalse(jcrReadPi.isAllowExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#isDenyExists()}.
+ */
+ @Test
+ void testIsDenyExists() {
+ assertFalse(jcrReadPi.isDenyExists());
+ jcrReadPi.setDenyExists(true);
+ assertTrue(jcrReadPi.isDenyExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#setDenyExists(boolean)}.
+ */
+ @Test
+ void testSetDenyExists() {
+ jcrReadPi.setDenyExists(true);
+ assertTrue(jcrReadPi.isDenyExists());
+ jcrReadPi.setDenyExists(false);
+ assertFalse(jcrReadPi.isDenyExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getLongestPath()}.
+ */
+ @Test
+ void testGetLongestPath() {
+ assertEquals(String.format("%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ),
+ jcrReadPi.getLongestPath());
+ assertEquals(String.format("%s/%s/%s", PrivilegeConstants.JCR_ALL, PrivilegeConstants.JCR_READ, PrivilegeConstants.REP_READ_NODES),
+ jcrReadNodesPiWithRestrictions.getLongestPath());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#addExtraCssClass(java.lang.String)}.
+ */
+ @Test
+ void testAddExtraCssClass() {
+ assertEquals("depth1", jcrReadPi.getDepthCss());
+ jcrReadPi.addExtraCssClass("extra1");
+ assertEquals("depth1 extra1", jcrReadPi.getDepthCss());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getDepthCss()}.
+ */
+ @Test
+ void testGetDepthCss() {
+ assertEquals("depth1", jcrReadPi.getDepthCss());
+ assertEquals("depth2", jcrReadNodesPiWithRestrictions.getDepthCss());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getDepth()}.
+ */
+ @Test
+ void testGetDepth() {
+ assertEquals(1, jcrReadPi.getDepth());
+ assertEquals(2, jcrReadNodesPiWithRestrictions.getDepth());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getAllowRestrictions()}.
+ */
+ @Test
+ void testGetAllowRestrictions() {
+ assertTrue(jcrReadPi.getAllowRestrictions().isEmpty());
+
+ List<RestrictionItem> allowRestrictions = jcrReadNodesPiWithRestrictions.getAllowRestrictions();
+ assertEquals(1, allowRestrictions.size());
+ assertEquals(AccessControlConstants.REP_GLOB, allowRestrictions.get(0).getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getDenyRestrictions()}.
+ */
+ @Test
+ void testGetDenyRestrictions() {
+ assertTrue(jcrReadPi.getDenyRestrictions().isEmpty());
+
+ List<RestrictionItem> denyRestrictions = jcrReadNodesPiWithRestrictions.getDenyRestrictions();
+ assertEquals(1, denyRestrictions.size());
+ assertEquals(AccessControlConstants.REP_ITEM_NAMES, denyRestrictions.get(0).getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#setAllowRestrictions(java.util.List)}.
+ */
+ @Test
+ void testSetAllowRestrictions() {
+ assertEquals(Collections.emptyList(), jcrReadPi.getAllowRestrictions());
+ List<RestrictionItem> newRestrictions = Collections.singletonList(createSingleValueRestrictionItem(AccessControlConstants.REP_GLOB, "glob1", false));
+ jcrReadPi.setAllowRestrictions(newRestrictions);
+ assertEquals(newRestrictions, jcrReadPi.getAllowRestrictions());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#setDenyRestrictions(java.util.List)}.
+ */
+ @Test
+ void testSetDenyRestrictions() {
+ assertEquals(Collections.emptyList(), jcrReadPi.getDenyRestrictions());
+ List<RestrictionItem> newRestrictions = Collections.singletonList(createSingleValueRestrictionItem(AccessControlConstants.REP_GLOB, "glob1", false));
+ jcrReadPi.setDenyRestrictions(newRestrictions);
+ assertEquals(newRestrictions, jcrReadPi.getDenyRestrictions());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#toString()}.
+ */
+ @Test
+ void testToString() {
+ assertNotNull(jcrReadPi.toString());
+ assertNotNull(jcrReadNodesPiWithRestrictions.toString());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#addAllowRestrictionToDelete(java.lang.String)}.
+ */
+ @Test
+ void testAddAllowRestrictionToDelete() {
+ jcrReadPi.addAllowRestrictionToDelete(AccessControlConstants.REP_ITEM_NAMES);
+ assertEquals(Collections.singleton(AccessControlConstants.REP_ITEM_NAMES), jcrReadPi.getAllowRestrictionsToDelete());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getAllowRestrictionsToDelete()}.
+ */
+ @Test
+ void testGetAllowRestrictionsToDelete() {
+ assertEquals(Collections.emptySet(), jcrReadPi.getAllowRestrictionsToDelete());
+ jcrReadPi.addAllowRestrictionToDelete(AccessControlConstants.REP_GLOB);
+ assertEquals(Collections.singleton(AccessControlConstants.REP_GLOB), jcrReadPi.getAllowRestrictionsToDelete());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#addDenyRestrictionToDelete(java.lang.String)}.
+ */
+ @Test
+ void testAddDenyRestrictionToDelete() {
+ jcrReadPi.addDenyRestrictionToDelete(AccessControlConstants.REP_NT_NAMES);
+ assertEquals(Collections.singleton(AccessControlConstants.REP_NT_NAMES), jcrReadPi.getDenyRestrictionsToDelete());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.PrivilegeItem#getDenyRestrictionsToDelete()}.
+ */
+ @Test
+ void testGetDenyRestrictionsToDelete() {
+ assertEquals(Collections.emptySet(), jcrReadPi.getDenyRestrictionsToDelete());
+ jcrReadPi.addDenyRestrictionToDelete(AccessControlConstants.REP_PREFIXES);
+ assertEquals(Collections.singleton(AccessControlConstants.REP_PREFIXES), jcrReadPi.getDenyRestrictionsToDelete());
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/RestrictionDefinitionInfoTest.java b/src/test/java/org/apache/sling/starter/access/models/RestrictionDefinitionInfoTest.java
new file mode 100644
index 0000000..457c289
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/RestrictionDefinitionInfoTest.java
@@ -0,0 +1,89 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.apache.jackrabbit.oak.api.Type;
+import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+class RestrictionDefinitionInfoTest {
+ private RestrictionDefinitionInfo rdInfo;
+
+ @BeforeEach
+ void beforeEach() {
+ RestrictionDefinition rd = createMockRestrictionDefintion();
+ rdInfo = new RestrictionDefinitionInfo(AccessControlConstants.REP_ITEM_NAMES + " DisplayName", rd);
+ }
+
+ protected RestrictionDefinition createMockRestrictionDefintion() {
+ RestrictionDefinition rd = Mockito.mock(RestrictionDefinition.class);
+ Mockito.when(rd.getName()).thenReturn(AccessControlConstants.REP_ITEM_NAMES);
+ Mockito.when(rd.getRequiredType()).thenAnswer(new Answer<Type<?>>() {
+ @Override
+ public Type<?> answer(InvocationOnMock invocation) throws Throwable {
+ return Type.STRINGS;
+ }
+ });
+ return rd;
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionDefinitionInfo#getDisplayName()}.
+ */
+ @Test
+ void testGetDisplayName() {
+ assertEquals(AccessControlConstants.REP_ITEM_NAMES + " DisplayName", rdInfo.getDisplayName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionDefinitionInfo#getName()}.
+ */
+ @Test
+ void testGetName() {
+ assertEquals(AccessControlConstants.REP_ITEM_NAMES, rdInfo.getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionDefinitionInfo#getRequiredType()}.
+ */
+ @Test
+ void testGetRequiredType() {
+ assertEquals(Type.STRINGS, rdInfo.getRequiredType());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionDefinitionInfo#isMandatory()}.
+ */
+ @Test
+ void testIsMandatory() {
+ assertFalse(rdInfo.isMandatory());
+
+ // also try a manditory one
+ RestrictionDefinition manditoryRd = createMockRestrictionDefintion();
+ Mockito.when(manditoryRd.isMandatory()).thenReturn(true);
+ RestrictionDefinitionInfo manditoryRdInfo = new RestrictionDefinitionInfo(AccessControlConstants.REP_ITEM_NAMES + " DisplayName", manditoryRd);
+ assertTrue(manditoryRdInfo.isMandatory());
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/RestrictionItemTest.java b/src/test/java/org/apache/sling/starter/access/models/RestrictionItemTest.java
new file mode 100644
index 0000000..4e7b83d
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/RestrictionItemTest.java
@@ -0,0 +1,174 @@
+/*
+ * 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.starter.access.models;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.Value;
+import javax.jcr.ValueFactory;
+
+import org.apache.jackrabbit.oak.api.Type;
+import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants;
+import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionDefinition;
+import org.apache.jackrabbit.value.ValueFactoryImpl;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+class RestrictionItemTest {
+
+ private RestrictionItem itemNamesRi;
+
+ protected RestrictionItem createRestrictionItem(String name, Type<?> type, Object value) {
+ return createRestrictionItem(name, type, value, false);
+ }
+ protected RestrictionItem createRestrictionItem(String name, Type<?> type, Object value, boolean isManditory) {
+ RestrictionDefinition globRd = Mockito.mock(RestrictionDefinition.class);
+ Mockito.when(globRd.getName()).thenReturn(name);
+ Mockito.when(globRd.getRequiredType())
+ .thenAnswer(new Answer<Type<?>>() {
+ @Override
+ public Type<?> answer(InvocationOnMock invocation) throws Throwable {
+ return type;
+ }
+ });
+ if (isManditory) {
+ Mockito.when(globRd.isMandatory()).thenReturn(isManditory);
+ }
+ return new RestrictionItem(globRd, value, false);
+ }
+
+ @BeforeEach
+ void beforeEach() {
+ itemNamesRi = createRestrictionItem(AccessControlConstants.REP_ITEM_NAMES, Type.STRINGS, new String[] {"name1", "name2"});
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#getName()}.
+ */
+ @Test
+ void testGetName() {
+ assertEquals(AccessControlConstants.REP_ITEM_NAMES, itemNamesRi.getName());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#isMultiValue()}.
+ */
+ @Test
+ void testIsMultiValue() {
+ assertTrue(itemNamesRi.isMultiValue());
+
+ // also a non-multivalue one
+ RestrictionItem globRi = createRestrictionItem(AccessControlConstants.REP_GLOB, Type.STRING, "glob1");
+ assertFalse(globRi.isMultiValue());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#getValue()}.
+ */
+ @Test
+ void testGetValue() throws RepositoryException {
+ assertEquals("name1", itemNamesRi.getValue());
+
+ // also a non-multivalue one
+ RestrictionItem globRi = createRestrictionItem(AccessControlConstants.REP_GLOB, Type.STRING, "glob1");
+ assertEquals("glob1", globRi.getValue());
+
+ // also a Value instead of String
+ ValueFactory vf = ValueFactoryImpl.getInstance();
+ globRi = createRestrictionItem(AccessControlConstants.REP_GLOB, Type.STRING, vf.createValue("glob1"));
+ assertEquals("glob1", globRi.getValue());
+
+ // also a Value[] instead of String[]
+ itemNamesRi = createRestrictionItem(AccessControlConstants.REP_ITEM_NAMES, Type.STRINGS,
+ new Value[] {vf.createValue("name1"), vf.createValue("name2")});
+ assertEquals("name1", itemNamesRi.getValue());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#getValues()}.
+ */
+ @Test
+ void testGetValues() throws RepositoryException {
+ assertEquals(Arrays.asList("name1", "name2"), itemNamesRi.getValues());
+
+ // also a non-multivalue one
+ RestrictionItem globRi = createRestrictionItem(AccessControlConstants.REP_GLOB, Type.STRING, "glob1");
+ assertEquals(Collections.singletonList("glob1"), globRi.getValues());
+
+ // also a Value instead of String
+ ValueFactory vf = ValueFactoryImpl.getInstance();
+ globRi = createRestrictionItem(AccessControlConstants.REP_GLOB, Type.STRING, vf.createValue("glob1"));
+ assertEquals(Collections.singletonList("glob1"), globRi.getValues());
+
+ // also a Value[] instead of String[]
+ itemNamesRi = createRestrictionItem(AccessControlConstants.REP_ITEM_NAMES, Type.STRINGS,
+ new Value[] {vf.createValue("name1"), vf.createValue("name2")});
+ assertEquals(Arrays.asList("name1", "name2"), itemNamesRi.getValues());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#isExists()}.
+ */
+ @Test
+ void testIsExists() {
+ assertFalse(itemNamesRi.isExists());
+ itemNamesRi.setExists(true);
+ assertTrue(itemNamesRi.isExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#setExists(boolean)}.
+ */
+ @Test
+ void testSetExists() {
+ itemNamesRi.setExists(true);
+ assertTrue(itemNamesRi.isExists());
+ itemNamesRi.setExists(false);
+ assertFalse(itemNamesRi.isExists());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#isMandatory()}.
+ */
+ @Test
+ void testIsMandatory() {
+ assertFalse(itemNamesRi.isMandatory());
+
+ // also a mandatory one
+ RestrictionItem globRi = createRestrictionItem(AccessControlConstants.REP_GLOB, Type.STRING, "glob1", true);
+ assertTrue(globRi.isMandatory());
+ }
+
+ /**
+ * Test method for {@link org.apache.sling.starter.access.models.RestrictionItem#toString()}.
+ */
+ @Test
+ void testToString() {
+ assertNotNull(itemNamesRi.toString());
+ }
+
+}
diff --git a/src/test/java/org/apache/sling/starter/access/models/TestGroupPrincipal.java b/src/test/java/org/apache/sling/starter/access/models/TestGroupPrincipal.java
new file mode 100644
index 0000000..7930988
--- /dev/null
+++ b/src/test/java/org/apache/sling/starter/access/models/TestGroupPrincipal.java
@@ -0,0 +1,47 @@
+/*
+ * 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.starter.access.models;
+
+import java.security.Principal;
+import java.util.Collections;
+import java.util.Enumeration;
+
+import org.apache.jackrabbit.api.security.principal.GroupPrincipal;
+
+class TestGroupPrincipal implements GroupPrincipal {
+ private String name;
+
+ TestGroupPrincipal(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public boolean isMember(Principal member) {
+ return false;
+ }
+
+ @Override
+ public Enumeration<? extends Principal> members() {
+ return Collections.emptyEnumeration();
+ }
+
+}
\ No newline at end of file