From ce8a2772967e8587c0e7266b90d2382086f02b2a Mon Sep 17 00:00:00 2001 From: Alex O'Ree Date: Mon, 15 Dec 2025 16:14:53 -0500 Subject: [PATCH 1/3] JSPWIKI-1210 Advanced ACL rules, now supports AND/OR and NOT operators, as well as parenthesis --- .../java/org/apache/wiki/api/core/Engine.java | 8 ++ .../main/java/org/apache/wiki/WikiEngine.java | 3 +- .../auth/DefaultAuthorizationManager.java | 34 ++++- .../wiki/auth/acl/DefaultAclManager.java | 52 ++++++- .../apache/wiki/auth/acl/adv/AdvancedAcl.java | 116 ++++++++++++++++ .../org/apache/wiki/auth/acl/adv/NotNode.java | 49 +++++++ .../wiki/auth/acl/adv/OperatorNode.java | 69 +++++++++ .../apache/wiki/auth/acl/adv/RoleNode.java | 63 +++++++++ .../apache/wiki/auth/acl/adv/RuleNode.java | 45 ++++++ .../apache/wiki/auth/acl/adv/RuleParser.java | 109 +++++++++++++++ .../wiki/auth/acl/DefaultAclManagerTest.java | 84 +++++++++++ .../wiki/auth/acl/adv/RuleParserTest.java | 131 ++++++++++++++++++ 12 files changed, 759 insertions(+), 4 deletions(-) create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java create mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java create mode 100644 jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java b/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java index 884b8a8f24..637d39dd3f 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java @@ -110,6 +110,14 @@ public interface Engine { /** The name of the property containing the ACLManager implementing class. The value is {@value}. */ String PROP_ACL_MANAGER_IMPL = "jspwiki.aclManager"; + + /** + * The name of the property containing the AuthorizationManager implementing + * class. The value is {@value}. + * + * @since 3.0.0 + */ + String PROP_AUTHZ_MANAGER_IMPL = "jspwiki.authZManager"; /** The name of the property containing the ReferenceManager implementing class. The value is {@value}. */ String PROP_REF_MANAGER_IMPL = "jspwiki.refManager"; diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java index 02cee01fc9..945d16095f 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java @@ -293,6 +293,7 @@ public void initialize( final Properties props ) throws WikiException { // try { final String aclClassName = m_properties.getProperty( PROP_ACL_MANAGER_IMPL, ClassUtil.getMappedClass( AclManager.class.getName() ).getName() ); + final String authClassName = m_properties.getProperty( PROP_AUTHZ_MANAGER_IMPL, ClassUtil.getMappedClass( AuthorizationManager.class.getName() ).getName() ); final String urlConstructorClassName = TextUtil.getStringProperty( props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor" ); final Class< URLConstructor > urlclass = ClassUtil.findClass( "org.apache.wiki.url", urlConstructorClassName ); @@ -306,7 +307,7 @@ public void initialize( final Properties props ) throws WikiException { initComponent( VariableManager.class, props ); initComponent( SearchManager.class, this, props ); initComponent( AuthenticationManager.class ); - initComponent( AuthorizationManager.class ); + initComponent( authClassName, AuthorizationManager.class ); initComponent( UserManager.class ); initComponent( GroupManager.class ); initComponent( EditorManager.class, this ); diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java index 296e2e3574..387a9e6df1 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java @@ -59,11 +59,15 @@ Licensed to the Apache Software Foundation (ASF) under one import java.security.cert.Certificate; import java.text.MessageFormat; import java.util.Arrays; +import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; +import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.locks.ReentrantLock; +import org.apache.wiki.auth.acl.adv.AdvancedAcl; +import org.apache.wiki.auth.acl.adv.RuleNode; /** @@ -84,7 +88,7 @@ public class DefaultAuthorizationManager implements AuthorizationManager { /** Cache for storing ProtectionDomains used to evaluate the local policy. */ private final Map< Principal, ProtectionDomain > m_cachedPds = new WeakHashMap<>(); - private Engine m_engine; + protected Engine m_engine; private LocalPolicy m_localPolicy; @@ -144,7 +148,35 @@ public boolean checkPermission( final Session session, final Permission permissi fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission ); return true; } + if (acl instanceof AdvancedAcl) { + AdvancedAcl a2 = (AdvancedAcl) acl; + Set roles = new HashSet<>(); + roles.add(session.getLoginPrincipal().getName()); + if (session.getRoles() != null) { + for (Principal p : session.getRoles()) { + roles.add(p.getName()); + } + } + RuleNode node = a2.getNode(permission); + if (node == null) { + fireEvent(WikiSecurityEvent.ACCESS_ALLOWED, user, permission); + return true; + } + Set potentialRoles = node.getAllRoles(); + for (String s : potentialRoles) { + if (hasRoleOrPrincipal(session, new WikiPrincipal(s))) { + roles.add(s); + } + } + if (node.evaluate(roles)) { + //granted.. + fireEvent(WikiSecurityEvent.ACCESS_ALLOWED, user, permission); + return true; + } + fireEvent( WikiSecurityEvent.ACCESS_DENIED, user, permission ); + return false; + } // Next, iterate through the Principal objects assigned this permission. If the context's subject possesses // any of these, the action is allowed. final Principal[] aclPrincipals = acl.findPrincipals( permission ); diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java index e31b8334a0..ded83ba095 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java @@ -51,6 +51,12 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.wiki.auth.acl.adv.AdvancedAcl; +import org.apache.wiki.auth.acl.adv.NotNode; +import org.apache.wiki.auth.acl.adv.OperatorNode; +import org.apache.wiki.auth.acl.adv.RoleNode; +import org.apache.wiki.auth.acl.adv.RuleNode; +import org.apache.wiki.auth.acl.adv.RuleParser; /** * Default implementation that parses Acls from wiki page markup. @@ -96,10 +102,40 @@ public void initialize( final Engine engine, final Properties props ) { public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurityException { Acl acl = page.getAcl(); if (acl == null) { - acl = Wiki.acls().acl(); + acl = Wiki.acls().acl(); } try { + if (ruleLine.contains(" AND ") + || ruleLine.contains(" NOT ") + || ruleLine.contains(" OR ")) { + try { + if (acl == null || !(acl instanceof AdvancedAcl)) { + acl = new AdvancedAcl(); + } + final StringTokenizer fieldToks = new StringTokenizer(ruleLine); + //burn off the allow tag + fieldToks.nextToken(); + //get the permission flag. i.e. edit, view, etc + final String actions = fieldToks.nextToken(); + StringBuilder sb = new StringBuilder(); + while (fieldToks.hasMoreTokens()) { + sb.append(fieldToks.nextToken() + " "); + } + RuleParser parser = new RuleParser(sb.toString()); + RuleNode node = parser.parse(); + ((AdvancedAcl) acl).addRuleNode(node, actions); + recursiveResolve(node); + page.setAcl(acl); + LOG.debug(acl.toString()); + return acl; + } catch (final NoSuchElementException nsee) { + LOG.warn("Invalid access rule: " + ruleLine + " - defaults will be used."); + throw new WikiSecurityException("Invalid access rule: " + ruleLine, nsee); + } catch (final IllegalArgumentException iae) { + throw new WikiSecurityException("Invalid permission type: " + ruleLine, iae); + } + } final StringTokenizer fieldToks = new StringTokenizer(ruleLine); fieldToks.nextToken(); final String actions = fieldToks.nextToken(); @@ -133,7 +169,19 @@ public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurit return acl; } - + private void recursiveResolve(RuleNode node) { + if (node == null) { + return; + } + if (node instanceof OperatorNode) { + recursiveResolve(((OperatorNode) node).getLeft()); + recursiveResolve(((OperatorNode) node).getRight()); + } else if (node instanceof NotNode) { + recursiveResolve(((NotNode) node).getChild()); + } else if (node instanceof RoleNode) { + ((RoleNode) node).setPrincipal(m_auth.resolvePrincipal(((RoleNode) node).getRole())); + } + } /** {@inheritDoc} */ @Override diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java new file mode 100644 index 0000000000..4d10ccb49d --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java @@ -0,0 +1,116 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.security.Permission; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import org.apache.wiki.api.core.AclEntry; +import org.apache.wiki.auth.acl.Acl; + +/** + * an extension to the base ACL classes that provides boolean logic, tyical use + * case is for role/group membership + * + * @since 3.0.0 + * @see AclEntry + * @see AclImpl + * @see DefaultAclManager + */ +public class AdvancedAcl implements org.apache.wiki.api.core.Acl, Acl { + + private Map nodes = new HashMap<>(); + + @Override + public boolean addEntry(AclEntry entry) { + if (entry instanceof AdvancedAcl e) { + this.nodes.putAll(e.nodes); + return true; + } + return false; + } + + @Override + public Enumeration aclEntries() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isEmpty() { + return nodes.isEmpty(); + } + + @Override + public Principal[] findPrincipals(Permission permission) { + final List< Principal> principals = new ArrayList<>(); + final Enumeration< AclEntry> entries = aclEntries(); + while (entries.hasMoreElements()) { + final AclEntry entry = entries.nextElement(); + final Enumeration< Permission> permissions = entry.permissions(); + while (permissions.hasMoreElements()) { + final Permission perm = permissions.nextElement(); + if (perm.implies(permission)) { + principals.add(entry.getPrincipal()); + } + } + } + return principals.toArray(new Principal[0]); + } + + @Override + public AclEntry getAclEntry(Principal principal) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean removeEntry(AclEntry entry) { + boolean success = false; + if (entry instanceof AdvancedAcl e) { + for (String s : e.nodes.keySet()) { + RuleNode remove = nodes.remove(s); + if (remove != null) { + success = true; + } + } + + } + return success; + } + + public void addRuleNode(RuleNode node, String actions) { + nodes.put(actions, node); + } + + public RuleNode getNode(Permission permission) { + return nodes.get(permission.getActions()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + for (Entry e : nodes.entrySet()) { + sb.append("[{ALLOW ").append(e.getKey()).append(" ").append(e.toString()).append("}]\n"); + } + return sb.toString(); + } + +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java new file mode 100644 index 0000000000..512070f7ce --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java @@ -0,0 +1,49 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.util.Set; + +/** + * + * @author AO + */ +public class NotNode extends RuleNode { + private final RuleNode child; + + public RuleNode getChild() { + return child; + } + + public NotNode(RuleNode child) { + this.child = child; + } + + @Override + public boolean evaluate(java.util.Set userRoles) { + return !child.evaluate(userRoles); + } + + @Override + public String toString() { + return "(NOT " + child + ")"; + } + + @Override + public Set getAllRoles() { + return child.getAllRoles(); + } +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java new file mode 100644 index 0000000000..d8501c076a --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java @@ -0,0 +1,69 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author AO + */ +public class OperatorNode extends RuleNode { + + @Override + public Set getAllRoles() { + Set set = new HashSet<>(); + set.addAll(left.getAllRoles()); + set.addAll(right.getAllRoles()); + return set; + } + public enum Operator { AND, OR } + + private final Operator operator; + private final RuleNode left, right; + + public Operator getOperator() { + return operator; + } + + public RuleNode getLeft() { + return left; + } + + public RuleNode getRight() { + return right; + } + + public OperatorNode(Operator operator, RuleNode left, RuleNode right) { + this.operator = operator; + this.left = left; + this.right = right; + } + + @Override + public boolean evaluate(java.util.Set userRoles) { + boolean l = left.evaluate(userRoles); + boolean r = right.evaluate(userRoles); + return operator == Operator.AND ? (l && r) : (l || r); + } + + @Override + public String toString() { + return "(" + left + " " + operator + " " + right + ")"; + } +} + diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java new file mode 100644 index 0000000000..d42053c290 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java @@ -0,0 +1,63 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.security.Principal; +import java.util.HashSet; +import java.util.Set; + +/** + * + * @author AO + */ +public class RoleNode extends RuleNode { + + private final String role; + + public String getRole() { + return role; + } + + public RoleNode(String role) { + this.role = role.trim(); + } + + @Override + public boolean evaluate(java.util.Set userRoles) { + return userRoles.contains(role); + } + + @Override + public String toString() { + return role; + } + protected Principal principal; + + public void setPrincipal(Principal principal) { + this.principal = principal; + } + + public Principal getPrincipal() { + return this.principal; + } + + @Override + public Set getAllRoles() { + Set set = new HashSet<>(); + set.add(role); + return set; + } +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java new file mode 100644 index 0000000000..c3243bea28 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java @@ -0,0 +1,45 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.util.Set; + +/** + * A rule node is a tree like representation of a boolean logic statement used + * for access controls on a wiki page. + * + * @author AO + * @since 3.0.0 + */ +public abstract class RuleNode { + + /** + * evaluates if a given user/request is allowed to a specific page given + * their roles/attributes etc + * + * @param userRoles + * @return true if allowed, false otherwise + */ + public abstract boolean evaluate(java.util.Set userRoles); + + /** + * gets the complete list of all roles defined within the ACL statement. + * + * @return set of roles/usernames/attributes etc + */ + public abstract Set getAllRoles(); + +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java new file mode 100644 index 0000000000..6f82a8b6c4 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java @@ -0,0 +1,109 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.util.*; + +/** + * + * @author AO + */ + +public class RuleParser { + private final List tokens; + private int pos = 0; + + public RuleParser(String expr) { + this.tokens = tokenize(expr); + } + + public RuleNode parse() { + RuleNode node = parseOr(); + if (pos < tokens.size()) { + throw new IllegalArgumentException("Unexpected token: " + tokens.get(pos)); + } + return node; + } + + // Lowest precedence + private RuleNode parseOr() { + RuleNode left = parseAnd(); + while (match("OR")) { + RuleNode right = parseAnd(); + left = new OperatorNode(OperatorNode.Operator.OR, left, right); + } + return left; + } + + // Next precedence + private RuleNode parseAnd() { + RuleNode left = parseNot(); + while (match("AND")) { + RuleNode right = parseNot(); + left = new OperatorNode(OperatorNode.Operator.AND, left, right); + } + return left; + } + + // Handles unary NOT + private RuleNode parseNot() { + if (match("NOT")) { + return new NotNode(parseNot()); + } + return parsePrimary(); + } + + // Handles parentheses and role identifiers + private RuleNode parsePrimary() { + if (match("(")) { + RuleNode expr = parseOr(); + expect(")"); + return expr; + } + return new RoleNode(expectIdentifier()); + } + + // --- Helpers --- + private boolean match(String token) { + if (pos < tokens.size() && tokens.get(pos).equalsIgnoreCase(token)) { + pos++; + return true; + } + return false; + } + + private void expect(String token) { + if (!match(token)) { + throw new IllegalArgumentException("Expected '" + token + "'"); + } + } + + private String expectIdentifier() { + if (pos < tokens.size()) { + String tok = tokens.get(pos++); + if (!tok.equalsIgnoreCase("AND") && !tok.equalsIgnoreCase("OR") + && !tok.equalsIgnoreCase("NOT") + && !tok.equals("(") && !tok.equals(")")) { + return tok; + } + } + throw new IllegalArgumentException("Expected identifier at position " + pos); + } + + private static List tokenize(String expr) { + return Arrays.asList(expr.replaceAll("([()])", " $1 ").trim().split("\\s+")); + } +} diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java index b953e84657..70785d7826 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java @@ -41,6 +41,9 @@ Licensed to the Apache Software Foundation (ASF) under one import java.security.Principal; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; +import org.apache.wiki.auth.acl.adv.AdvancedAcl; +import org.apache.wiki.auth.acl.adv.RuleNode; +import org.mockito.internal.util.collections.Sets; public class DefaultAclManagerTest { @@ -50,6 +53,12 @@ public class DefaultAclManagerTest public void setUp() throws Exception { m_engine.saveText( "TestDefaultPage", "Foo" ); m_engine.saveText( "TestAclPage", "Bar. [{ALLOW edit Charlie, Herman}] " ); + + m_engine.saveText("TestAdvAclPage", "Bar. [{ALLOW edit Charlie OR Herman}] [{ALLOW view Charlie OR Herman}] "); + + m_engine.saveText("TestAdvAclPage2", "Bar. [{ALLOW edit Charlie OR Admin OR NOT Accounting}] "); + m_engine.saveText("TestAdvAclPage3", "Bar. [{ALLOW edit Group1 AND (Group2 OR Group3)}] "); + } @AfterEach @@ -57,6 +66,11 @@ public void tearDown() { try { m_engine.getManager( PageManager.class ).deletePage( "TestDefaultPage" ); m_engine.getManager( PageManager.class ).deletePage( "TestAclPage" ); + m_engine.getManager( PageManager.class ).deletePage( "TestAdvAclPage" ); + m_engine.getManager( PageManager.class ).deletePage( "TestAdvAclPage2" ); + m_engine.getManager( PageManager.class ).deletePage( "TestAdvAclPage3" ); + + } catch ( final ProviderException e ) { } } @@ -124,7 +138,77 @@ public void testGetPermissions() p = acl.findPrincipals( PermissionFactory.getPagePermission(page, "delete") ); Assertions.assertEquals( 0, p.length ); } + + @Test + public void testGetPermissionsAdvancedAcl() { + Page page = m_engine.getManager(PageManager.class).getPage("TestDefaultPage"); + AclManager mgr = m_engine.getManager(AclManager.class); + + page = m_engine.getManager(PageManager.class).getPage("TestAdvAclPage"); + AdvancedAcl aacl = (AdvancedAcl) mgr.getPermissions(page); + Assertions.assertNotNull(page.getAcl()); + Assertions.assertFalse(page.getAcl().isEmpty()); + + // Charlie is an editor; reading is therefore implied + RuleNode node = aacl.getNode(PermissionFactory.getPagePermission(page, "view")); + Assertions.assertTrue(node.evaluate(Sets.newSet("Charlie"))); + Assertions.assertTrue(node.evaluate(Sets.newSet("Herman"))); + + // Charlie should not be able to delete this page + Assertions.assertTrue(node.evaluate(Sets.newSet("Herman"))); + + // Herman should be in the ACL as an editor + node = aacl.getNode(PermissionFactory.getPagePermission(page, "edit")); + Assertions.assertTrue(node.evaluate(Sets.newSet("Herman"))); + + } + + @Test + public void testGetPermissionsAdvancedAcl2() { + Page page = m_engine.getManager(PageManager.class).getPage("TestAdvAclPage2"); + Assertions.assertNotNull(page.getAcl()); + Assertions.assertFalse(page.getAcl().isEmpty()); + AclManager mgr = m_engine.getManager(AclManager.class); + + AdvancedAcl acl = (AdvancedAcl) mgr.getPermissions(page); + Assertions.assertNotNull(page.getAcl()); + Assertions.assertFalse(page.getAcl().isEmpty()); + + // Charlie is an editor; reading is therefore implied + RuleNode node = acl.getNode(PermissionFactory.getPagePermission(page, "edit")); + Assertions.assertTrue(node.evaluate(Sets.newSet("Charlie"))); + Assertions.assertTrue(node.evaluate(Sets.newSet("Admin"))); + Assertions.assertFalse(node.evaluate(Sets.newSet("Accounting"))); + + + } + + @Test + public void testGetPermissionsAdvancedAcl3() { + Page page = m_engine.getManager(PageManager.class).getPage("TestAdvAclPage3"); + Assertions.assertNotNull(page.getAcl()); + Assertions.assertFalse(page.getAcl().isEmpty()); + AclManager mgr = m_engine.getManager(AclManager.class); + + AdvancedAcl acl = (AdvancedAcl) mgr.getPermissions(page); + Assertions.assertNotNull(page.getAcl()); + Assertions.assertFalse(page.getAcl().isEmpty()); + + // Charlie is an editor; reading is therefore implied + RuleNode node = acl.getNode(PermissionFactory.getPagePermission(page, "edit")); + Assertions.assertFalse(node.evaluate(Sets.newSet("Group1"))); + Assertions.assertFalse(node.evaluate(Sets.newSet("Group2"))); + Assertions.assertFalse(node.evaluate(Sets.newSet("Group3"))); + Assertions.assertTrue(node.evaluate(Sets.newSet("Group1", "Group2"))); + Assertions.assertTrue(node.evaluate(Sets.newSet("Group1", "Group3"))); + Assertions.assertTrue(node.evaluate(Sets.newSet("Group1", "Group2", "Group3"))); + Assertions.assertFalse(node.evaluate(Sets.newSet("Admin"))); + Assertions.assertFalse(node.evaluate(Sets.newSet("Accounting"))); + + + } + @Test public void testAclRegex() { diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java new file mode 100644 index 0000000000..065e3a53a9 --- /dev/null +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2025 The Apache Software Foundation. + * + * Licensed 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.wiki.auth.acl.adv; + +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * tests the rule parser for the advanced acl tool chain + * + * @see AdvancedAcl + * @since 3.0.0 + + */ +public class RuleParserTest { + + public RuleParserTest() { + } + + @Test + public void simpleOrStatement() { + RuleParser instance = new RuleParser("bob or mary"); + RuleNode result = instance.parse(); + Assertions.assertEquals(2, result.getAllRoles().size()); + Assertions.assertTrue(result.evaluate(Set.of("bob"))); + Assertions.assertTrue(result.evaluate(Set.of("mary"))); + Assertions.assertFalse(result.evaluate(Set.of("john"))); + } + + @Test + public void simpleAndStatement() { + RuleParser instance = new RuleParser("accounting AND finance"); + RuleNode result = instance.parse(); + Assertions.assertEquals(2, result.getAllRoles().size()); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance"))); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "otherDepartment"))); + Assertions.assertFalse(result.evaluate(Set.of("accounting"))); + Assertions.assertFalse(result.evaluate(Set.of("finance"))); + Assertions.assertFalse(result.evaluate(Set.of("john"))); + } + + @Test + public void complexSetup() { + RuleParser instance = new RuleParser("accounting AND (finance OR admin)"); + RuleNode result = instance.parse(); + Assertions.assertEquals(3, result.getAllRoles().size()); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance"))); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "otherDepartment"))); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "admin"))); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "admin"))); + Assertions.assertFalse(result.evaluate(Set.of("accounting"))); + Assertions.assertFalse(result.evaluate(Set.of("finance"))); + Assertions.assertFalse(result.evaluate(Set.of("john"))); + } + + @Test + public void complexSetupNot() { + RuleParser instance = new RuleParser("accounting AND finance AND NOT(bob)"); + instance = new RuleParser("(accounting AND finance AND NOT(bob))"); + RuleNode result = instance.parse(); + Assertions.assertEquals(3, result.getAllRoles().size()); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance"))); + Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "otherDepartment"))); + Assertions.assertFalse(result.evaluate(Set.of("accounting", "finance", "bob"))); + Assertions.assertFalse(result.evaluate(Set.of("accounting", "admin"))); + Assertions.assertFalse(result.evaluate(Set.of("accounting"))); + Assertions.assertFalse(result.evaluate(Set.of("finance"))); + Assertions.assertFalse(result.evaluate(Set.of("john"))); + } + + @Test + public void mismatchedParan() { + Assertions.assertThrows(IllegalArgumentException.class, () -> { + RuleParser instance = new RuleParser("(accounting AND finance AND NOT(bob)"); + RuleNode parse = instance.parse(); + System.out.println(parse); + }); + + RuleParser instance = new RuleParser("(accounting AND finance AND NOT(bob))"); + instance.parse(); + + List invalidExprs = List.of( + "role1 AND", + "AND role1", + "role1 OR OR role2", + "role1 (role2 OR role3)", + "(role1 AND role2", + "role1 AND role2)", + "role1 AND NOT", + "NOT", + "role1 OR AND role2", + "()", + "( )", + "role1 AND (OR role2)", + "role1 AND (role2 OR)", + "role1 role2", + "role1 AND (NOT)", + "(role1 AND) OR role2", + "role1 AND ((role2)", + "role1 AND )role2(", + "role1 AND NOT ( )", + "NOT (role1 AND)" + ); + + for (String expr : invalidExprs) { + try { + RuleParser parser = new RuleParser(expr); + parser.parse(); + System.out.println("❌ Should have failed but parsed: " + expr); + } catch (Exception e) { + System.out.println("✅ Correctly failed: " + expr + " → " + e.getMessage()); + } + } + } + +} From e46cbfb24fbe8859fc3ef9afffd0d2e8f8568833 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Sat, 21 Nov 2026 17:13:32 +0100 Subject: [PATCH 2/3] JSPWIKI-1210 Keep the advanced access rules next to the simple ones The advanced rules are kept by the AclImpl of the page, together with its entries, instead of in a class that replaces the Acl. A page can mix simple and advanced rules in any order, and the rules of the same action add up, as the simple ones do. The AuthorizationManager grants a permission to the users that satisfy any rule that implies it, and denies it when no rule does, so a page with only an advanced rule for edit is not readable by anonymous users either. A name counts as held only when the user has the role, group or user principal, so a name that is only asserted does not satisfy a rule. AND, OR and NOT are read only in upper case, a comma cannot be mixed with them, and a rule that does not parse is reported as an invalid access rule. printAcl writes the advanced rules too. The jspwiki.authZManager property and the protected engine of the authorization manager are dropped, as nothing needs them now. --- ChangeLog.md | 5 + .../java/org/apache/wiki/api/Release.java | 2 +- .../java/org/apache/wiki/api/core/Engine.java | 8 - .../main/java/org/apache/wiki/WikiEngine.java | 3 +- .../auth/DefaultAuthorizationManager.java | 65 ++++--- .../org/apache/wiki/auth/acl/AclImpl.java | 66 ++++++- .../wiki/auth/acl/DefaultAclManager.java | 86 ++++----- .../apache/wiki/auth/acl/adv/AdvancedAcl.java | 116 ----------- .../org/apache/wiki/auth/acl/adv/NotNode.java | 62 ++++-- .../wiki/auth/acl/adv/OperatorNode.java | 93 ++++++--- .../apache/wiki/auth/acl/adv/RoleNode.java | 90 ++++++--- .../apache/wiki/auth/acl/adv/RuleNode.java | 66 ++++--- .../apache/wiki/auth/acl/adv/RuleParser.java | 121 +++++++----- .../acl/AdvancedAclAuthorizationTest.java | 181 ++++++++++++++++++ .../wiki/auth/acl/DefaultAclManagerTest.java | 168 ++++++++++------ .../wiki/auth/acl/adv/RuleParserTest.java | 152 +++++++-------- 16 files changed, 782 insertions(+), 502 deletions(-) delete mode 100644 jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java create mode 100644 jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java diff --git a/ChangeLog.md b/ChangeLog.md index 7f9a870113..0f129dbca9 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -16,6 +16,11 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> +**2026-11-21 Arturo Bernal (abernal AT apache DOT org)** +* _3.0.2-git-2_ + +* Fix for [JSPWIKI-1210](https://issues.apache.org/jira/browse/JSPWIKI-1210) Access rules can combine roles, groups and users with AND, OR, NOT and parentheses, as in `[{ALLOW edit Editors AND (Reviewers OR NOT Banned)}]`. An advanced rule grants its permission together with the other rules of the page, the operators are written in upper case, and a name with an operator word inside it, such as ANDY, is still a name. Based on the work of Alex O'Ree + **2026-11-19 Arturo Bernal (abernal AT apache DOT org)** * _3.0.2-git-1_ diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java index 26cb6a0efa..ad73c8ffa7 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/Release.java @@ -69,7 +69,7 @@ public final class Release { *

* If the build identifier is empty, it is not added. */ - public static final String BUILD = "1"; + public static final String BUILD = "2"; /** * This is the generic version string you should use when printing out the version. It is of diff --git a/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java b/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java index 637d39dd3f..884b8a8f24 100644 --- a/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java +++ b/jspwiki-api/src/main/java/org/apache/wiki/api/core/Engine.java @@ -110,14 +110,6 @@ public interface Engine { /** The name of the property containing the ACLManager implementing class. The value is {@value}. */ String PROP_ACL_MANAGER_IMPL = "jspwiki.aclManager"; - - /** - * The name of the property containing the AuthorizationManager implementing - * class. The value is {@value}. - * - * @since 3.0.0 - */ - String PROP_AUTHZ_MANAGER_IMPL = "jspwiki.authZManager"; /** The name of the property containing the ReferenceManager implementing class. The value is {@value}. */ String PROP_REF_MANAGER_IMPL = "jspwiki.refManager"; diff --git a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java index 945d16095f..02cee01fc9 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/WikiEngine.java @@ -293,7 +293,6 @@ public void initialize( final Properties props ) throws WikiException { // try { final String aclClassName = m_properties.getProperty( PROP_ACL_MANAGER_IMPL, ClassUtil.getMappedClass( AclManager.class.getName() ).getName() ); - final String authClassName = m_properties.getProperty( PROP_AUTHZ_MANAGER_IMPL, ClassUtil.getMappedClass( AuthorizationManager.class.getName() ).getName() ); final String urlConstructorClassName = TextUtil.getStringProperty( props, PROP_URLCONSTRUCTOR, "DefaultURLConstructor" ); final Class< URLConstructor > urlclass = ClassUtil.findClass( "org.apache.wiki.url", urlConstructorClassName ); @@ -307,7 +306,7 @@ public void initialize( final Properties props ) throws WikiException { initComponent( VariableManager.class, props ); initComponent( SearchManager.class, this, props ); initComponent( AuthenticationManager.class ); - initComponent( authClassName, AuthorizationManager.class ); + initComponent( AuthorizationManager.class ); initComponent( UserManager.class ); initComponent( GroupManager.class ); initComponent( EditorManager.class, this ); diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java index 387a9e6df1..83080914ec 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java @@ -30,8 +30,11 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.core.Session; import org.apache.wiki.api.exceptions.NoRequiredPropertyException; import org.apache.wiki.api.exceptions.WikiException; +import org.apache.wiki.auth.acl.AclImpl; import org.apache.wiki.auth.acl.AclManager; import org.apache.wiki.auth.acl.UnresolvedPrincipal; +import org.apache.wiki.auth.acl.adv.RoleNode; +import org.apache.wiki.auth.acl.adv.RuleNode; import org.apache.wiki.auth.authorize.GroupManager; import org.apache.wiki.auth.authorize.Role; import org.apache.wiki.auth.permissions.AllPermission; @@ -66,8 +69,6 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.locks.ReentrantLock; -import org.apache.wiki.auth.acl.adv.AdvancedAcl; -import org.apache.wiki.auth.acl.adv.RuleNode; /** @@ -88,7 +89,7 @@ public class DefaultAuthorizationManager implements AuthorizationManager { /** Cache for storing ProtectionDomains used to evaluate the local policy. */ private final Map< Principal, ProtectionDomain > m_cachedPds = new WeakHashMap<>(); - protected Engine m_engine; + private Engine m_engine; private LocalPolicy m_localPolicy; @@ -148,35 +149,7 @@ public boolean checkPermission( final Session session, final Permission permissi fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission ); return true; } - if (acl instanceof AdvancedAcl) { - AdvancedAcl a2 = (AdvancedAcl) acl; - Set roles = new HashSet<>(); - roles.add(session.getLoginPrincipal().getName()); - if (session.getRoles() != null) { - for (Principal p : session.getRoles()) { - roles.add(p.getName()); - } - } - RuleNode node = a2.getNode(permission); - if (node == null) { - fireEvent(WikiSecurityEvent.ACCESS_ALLOWED, user, permission); - return true; - } - Set potentialRoles = node.getAllRoles(); - for (String s : potentialRoles) { - if (hasRoleOrPrincipal(session, new WikiPrincipal(s))) { - roles.add(s); - } - } - if (node.evaluate(roles)) { - //granted.. - fireEvent(WikiSecurityEvent.ACCESS_ALLOWED, user, permission); - return true; - } - fireEvent( WikiSecurityEvent.ACCESS_DENIED, user, permission ); - return false; - } // Next, iterate through the Principal objects assigned this permission. If the context's subject possesses // any of these, the action is allowed. final Principal[] aclPrincipals = acl.findPrincipals( permission ); @@ -201,10 +174,40 @@ public boolean checkPermission( final Session session, final Permission permissi return true; } } + + // The advanced rules grant the permission as well, to the users that satisfy any of them. + if( acl instanceof AclImpl ) { + for( final RuleNode rule : ( ( AclImpl ) acl ).findRules( permission ) ) { + if( satisfies( session, rule ) ) { + fireEvent( WikiSecurityEvent.ACCESS_ALLOWED, user, permission ); + return true; + } + } + } fireEvent( WikiSecurityEvent.ACCESS_DENIED, user, permission ); return false; } + /** + * Tells if the user of a session satisfies an advanced rule. A name counts as held only if the user really has the role or is the + * logged in user, so a name that is only asserted does not. + */ + private boolean satisfies( final Session session, final RuleNode rule ) { + final Set< String > held = new HashSet<>(); + for( final RoleNode node : rule.getRoleNodes() ) { + Principal principal = node.getPrincipal(); + if( principal == null || principal instanceof UnresolvedPrincipal ) { + // Same as for the entries of an ACL: a group or user created after the page was read can be resolved now + principal = resolvePrincipal( node.getRole() ); + node.setPrincipal( principal ); + } + if( hasRoleOrPrincipal( session, principal ) ) { + held.add( node.getRole() ); + } + } + return rule.evaluate( held ); + } + /** {@inheritDoc} */ @Override public Authorizer getAuthorizer() throws WikiSecurityException { diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java index 1a203d2375..e0726f9de7 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java @@ -19,6 +19,7 @@ Licensed to the Apache Software Foundation (ASF) under one package org.apache.wiki.auth.acl; import org.apache.wiki.api.core.AclEntry; +import org.apache.wiki.auth.acl.adv.RuleNode; import org.apache.wiki.util.Synchronizer; import java.io.Serializable; @@ -28,6 +29,7 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.Collections; import java.util.Enumeration; import java.util.List; +import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.ReentrantLock; @@ -51,6 +53,65 @@ public class AclImpl implements Acl, Serializable { private static final long serialVersionUID = 1L; private final List< AclEntry > m_entries = new CopyOnWriteArrayList<>(); + private final List< AdvancedRule > m_rules = new CopyOnWriteArrayList<>(); + + /** An advanced rule and the permission it grants to the users that satisfy it. */ + private static final class AdvancedRule implements Serializable { + + private static final long serialVersionUID = 1L; + + private final Permission permission; + private final RuleNode rule; + + private AdvancedRule( final Permission permission, final RuleNode rule ) { + this.permission = permission; + this.rule = rule; + } + } + + /** + * Adds an advanced rule, which grants a permission to the users that satisfy an expression of roles, groups and users joined by + * AND, OR and NOT. A rule adds to the entries and to the other rules of the same permission: a user is granted the permission if + * any of them grants it. + * + * @param permission the permission the rule grants. + * @param rule the expression. + * @since 3.0.2 + */ + public void addRule( final Permission permission, final RuleNode rule ) { + m_rules.add( new AdvancedRule( permission, rule ) ); + } + + /** + * Returns the advanced rules that grant a permission, which are the ones of that permission and of the permissions that imply it. + * + * @param permission the permission asked for. + * @return the expressions of the rules, in the order they were added. + * @since 3.0.2 + */ + public List< RuleNode > findRules( final Permission permission ) { + final List< RuleNode > rules = new ArrayList<>(); + for( final AdvancedRule r : m_rules ) { + if( r.permission.implies( permission ) ) { + rules.add( r.rule ); + } + } + return rules; + } + + /** + * Returns the permissions that advanced rules grant, with the expressions of the rules, in the order they were added. + * + * @return one entry for each rule. + * @since 3.0.2 + */ + public List< Map.Entry< Permission, RuleNode > > getRules() { + final List< Map.Entry< Permission, RuleNode > > rules = new ArrayList<>(); + for( final AdvancedRule r : m_rules ) { + rules.add( Map.entry( r.permission, r.rule ) ); + } + return rules; + } /** {@inheritDoc} */ @Override @@ -131,7 +192,7 @@ public AclEntry getAclEntry( final Principal principal ) { /** {@inheritDoc} */ @Override public boolean isEmpty() { - return m_entries.isEmpty(); + return m_entries.isEmpty() && m_rules.isEmpty(); } /** {@inheritDoc} */ @@ -152,6 +213,9 @@ public String toString() { } sb.append( ")\n" ); } + for( final AdvancedRule r : m_rules ) { + sb.append( " rule = " ).append( r.rule ).append( ": (" ).append( r.permission ).append( ")\n" ); + } return sb.toString(); } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java index ded83ba095..6416cf9409 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java @@ -30,6 +30,9 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.spi.Wiki; import org.apache.wiki.auth.AuthorizationManager; import org.apache.wiki.auth.WikiSecurityException; +import org.apache.wiki.auth.acl.adv.RoleNode; +import org.apache.wiki.auth.acl.adv.RuleNode; +import org.apache.wiki.auth.acl.adv.RuleParser; import org.apache.wiki.auth.permissions.PagePermission; import org.apache.wiki.auth.permissions.PermissionFactory; import org.apache.wiki.pages.PageLock; @@ -51,12 +54,6 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.wiki.auth.acl.adv.AdvancedAcl; -import org.apache.wiki.auth.acl.adv.NotNode; -import org.apache.wiki.auth.acl.adv.OperatorNode; -import org.apache.wiki.auth.acl.adv.RoleNode; -import org.apache.wiki.auth.acl.adv.RuleNode; -import org.apache.wiki.auth.acl.adv.RuleParser; /** * Default implementation that parses Acls from wiki page markup. @@ -83,6 +80,12 @@ public class DefaultAclManager implements AclManager { ")"; private static final String ACL_REGEX = "\\[\\{\\s*ALLOW\\s+" + PERM_REGEX + "\\s*(.*?)\\s*\\}\\]"; + /** + * Identifies an advanced rule, which is a rule that has AND, OR or NOT written in upper case as a word of its own. A name that + * contains one of them has to be written without spaces around it, or in lower case, to be read as a name. + */ + private static final Pattern ADVANCED_RULE = Pattern.compile( "(?:^|[\\s(])(?:AND|OR|NOT)(?=[\\s(]|$)" ); + /** * Identifies ACL strings in wiki text; the first group is the action (view, edit) and * the second is the list of Principals separated by commas. The overall match is @@ -102,44 +105,22 @@ public void initialize( final Engine engine, final Properties props ) { public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurityException { Acl acl = page.getAcl(); if (acl == null) { - acl = Wiki.acls().acl(); + acl = Wiki.acls().acl(); } try { - if (ruleLine.contains(" AND ") - || ruleLine.contains(" NOT ") - || ruleLine.contains(" OR ")) { - try { - if (acl == null || !(acl instanceof AdvancedAcl)) { - acl = new AdvancedAcl(); - } - final StringTokenizer fieldToks = new StringTokenizer(ruleLine); - //burn off the allow tag - fieldToks.nextToken(); - //get the permission flag. i.e. edit, view, etc - final String actions = fieldToks.nextToken(); - StringBuilder sb = new StringBuilder(); - while (fieldToks.hasMoreTokens()) { - sb.append(fieldToks.nextToken() + " "); - } - RuleParser parser = new RuleParser(sb.toString()); - RuleNode node = parser.parse(); - ((AdvancedAcl) acl).addRuleNode(node, actions); - recursiveResolve(node); - page.setAcl(acl); - LOG.debug(acl.toString()); - return acl; - } catch (final NoSuchElementException nsee) { - LOG.warn("Invalid access rule: " + ruleLine + " - defaults will be used."); - throw new WikiSecurityException("Invalid access rule: " + ruleLine, nsee); - } catch (final IllegalArgumentException iae) { - throw new WikiSecurityException("Invalid permission type: " + ruleLine, iae); - } - } final StringTokenizer fieldToks = new StringTokenizer(ruleLine); fieldToks.nextToken(); final String actions = fieldToks.nextToken(); + final String expression = ruleLine.substring( ruleLine.indexOf( actions ) + actions.length() ).trim(); + if( ADVANCED_RULE.matcher( expression ).find() ) { + addAdvancedRule( acl, page, actions, expression, ruleLine ); + page.setAcl( acl ); + LOG.debug( acl.toString() ); + return acl; + } + while( fieldToks.hasMoreTokens() ) { final String principalName = fieldToks.nextToken(",").trim(); final Principal principal = m_auth.resolvePrincipal(principalName); @@ -169,18 +150,24 @@ public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurit return acl; } - private void recursiveResolve(RuleNode node) { - if (node == null) { - return; + /** + * Adds an advanced rule to an ACL. The ACL has to be one of the implementation of this manager, as that is the one that keeps rules. + */ + private void addAdvancedRule( final Acl acl, final Page page, final String actions, final String expression, final String ruleLine ) + throws WikiSecurityException { + if( !( acl instanceof AclImpl ) ) { + throw new WikiSecurityException( "Access rules with AND, OR or NOT are not supported by the ACL of this page: " + ruleLine ); } - if (node instanceof OperatorNode) { - recursiveResolve(((OperatorNode) node).getLeft()); - recursiveResolve(((OperatorNode) node).getRight()); - } else if (node instanceof NotNode) { - recursiveResolve(((NotNode) node).getChild()); - } else if (node instanceof RoleNode) { - ((RoleNode) node).setPrincipal(m_auth.resolvePrincipal(((RoleNode) node).getRole())); + final RuleNode rule; + try { + rule = new RuleParser( expression ).parse(); + } catch( final IllegalArgumentException iae ) { + throw new WikiSecurityException( "Invalid access rule: " + ruleLine + " (" + iae.getMessage() + ")", iae ); + } + for( final RoleNode role : rule.getRoleNodes() ) { + role.setPrincipal( m_auth.resolvePrincipal( role.getRole() ) ); } + ( ( AclImpl ) acl ).addRule( PermissionFactory.getPagePermission( page, actions ), rule ); } /** {@inheritDoc} */ @@ -289,6 +276,11 @@ protected static String printAcl( final Acl acl ) { } s.append( "}]\n" ); } + if( acl instanceof AclImpl ) { + for( final Map.Entry< Permission, RuleNode > rule : ( ( AclImpl ) acl ).getRules() ) { + s.append( "[{ALLOW " ).append( rule.getKey().getActions() ).append( " " ).append( rule.getValue() ).append( "}]\n" ); + } + } return s.toString(); } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java deleted file mode 100644 index 4d10ccb49d..0000000000 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/AdvancedAcl.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2025 The Apache Software Foundation. - * - * Licensed 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.wiki.auth.acl.adv; - -import java.security.Permission; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.apache.wiki.api.core.AclEntry; -import org.apache.wiki.auth.acl.Acl; - -/** - * an extension to the base ACL classes that provides boolean logic, tyical use - * case is for role/group membership - * - * @since 3.0.0 - * @see AclEntry - * @see AclImpl - * @see DefaultAclManager - */ -public class AdvancedAcl implements org.apache.wiki.api.core.Acl, Acl { - - private Map nodes = new HashMap<>(); - - @Override - public boolean addEntry(AclEntry entry) { - if (entry instanceof AdvancedAcl e) { - this.nodes.putAll(e.nodes); - return true; - } - return false; - } - - @Override - public Enumeration aclEntries() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isEmpty() { - return nodes.isEmpty(); - } - - @Override - public Principal[] findPrincipals(Permission permission) { - final List< Principal> principals = new ArrayList<>(); - final Enumeration< AclEntry> entries = aclEntries(); - while (entries.hasMoreElements()) { - final AclEntry entry = entries.nextElement(); - final Enumeration< Permission> permissions = entry.permissions(); - while (permissions.hasMoreElements()) { - final Permission perm = permissions.nextElement(); - if (perm.implies(permission)) { - principals.add(entry.getPrincipal()); - } - } - } - return principals.toArray(new Principal[0]); - } - - @Override - public AclEntry getAclEntry(Principal principal) { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean removeEntry(AclEntry entry) { - boolean success = false; - if (entry instanceof AdvancedAcl e) { - for (String s : e.nodes.keySet()) { - RuleNode remove = nodes.remove(s); - if (remove != null) { - success = true; - } - } - - } - return success; - } - - public void addRuleNode(RuleNode node, String actions) { - nodes.put(actions, node); - } - - public RuleNode getNode(Permission permission) { - return nodes.get(permission.getActions()); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - - for (Entry e : nodes.entrySet()) { - sb.append("[{ALLOW ").append(e.getKey()).append(" ").append(e.toString()).append("}]\n"); - } - return sb.toString(); - } - -} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java index 512070f7ce..e94d5ab117 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java @@ -1,49 +1,71 @@ /* - * Copyright 2025 The Apache Software Foundation. + * 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 * - * Licensed 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 * - * 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. + * 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.wiki.auth.acl.adv; +import java.util.List; import java.util.Set; /** + * Negates an expression. It is true for every user that does not satisfy the expression, including users that are not logged in. * - * @author AO + * @since 3.0.2 */ public class NotNode extends RuleNode { + + private static final long serialVersionUID = 1L; + private final RuleNode child; + /** + * Creates a negation. + * + * @param child the expression to negate. + */ + public NotNode( final RuleNode child ) { + this.child = child; + } + + /** + * Returns the negated expression. + * + * @return the expression. + */ public RuleNode getChild() { return child; } - public NotNode(RuleNode child) { - this.child = child; + /** {@inheritDoc} */ + @Override + public boolean evaluate( final Set< String > userRoles ) { + return !child.evaluate( userRoles ); } + /** {@inheritDoc} */ @Override - public boolean evaluate(java.util.Set userRoles) { - return !child.evaluate(userRoles); + public List< RoleNode > getRoleNodes() { + return child.getRoleNodes(); } + /** {@inheritDoc} */ @Override public String toString() { return "(NOT " + child + ")"; } - @Override - public Set getAllRoles() { - return child.getAllRoles(); - } } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java index d8501c076a..7deed76dc9 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java @@ -1,69 +1,102 @@ /* - * Copyright 2025 The Apache Software Foundation. + * 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 * - * Licensed 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 * - * 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. + * 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.wiki.auth.acl.adv; -import java.util.HashSet; +import java.util.ArrayList; +import java.util.List; import java.util.Set; /** + * Combines two expressions with AND or OR. * - * @author AO + * @since 3.0.2 */ public class OperatorNode extends RuleNode { - @Override - public Set getAllRoles() { - Set set = new HashSet<>(); - set.addAll(left.getAllRoles()); - set.addAll(right.getAllRoles()); - return set; - } + private static final long serialVersionUID = 1L; + + /** The operators of an advanced access rule. */ public enum Operator { AND, OR } private final Operator operator; - private final RuleNode left, right; + private final RuleNode left; + private final RuleNode right; + + /** + * Creates a node. + * + * @param operator how the two expressions are combined. + * @param left the left expression. + * @param right the right expression. + */ + public OperatorNode( final Operator operator, final RuleNode left, final RuleNode right ) { + this.operator = operator; + this.left = left; + this.right = right; + } + /** + * Returns the operator. + * + * @return the operator. + */ public Operator getOperator() { return operator; } + /** + * Returns the left expression. + * + * @return the expression. + */ public RuleNode getLeft() { return left; } + /** + * Returns the right expression. + * + * @return the expression. + */ public RuleNode getRight() { return right; } - public OperatorNode(Operator operator, RuleNode left, RuleNode right) { - this.operator = operator; - this.left = left; - this.right = right; + /** {@inheritDoc} */ + @Override + public boolean evaluate( final Set< String > userRoles ) { + return operator == Operator.AND ? left.evaluate( userRoles ) && right.evaluate( userRoles ) + : left.evaluate( userRoles ) || right.evaluate( userRoles ); } + /** {@inheritDoc} */ @Override - public boolean evaluate(java.util.Set userRoles) { - boolean l = left.evaluate(userRoles); - boolean r = right.evaluate(userRoles); - return operator == Operator.AND ? (l && r) : (l || r); + public List< RoleNode > getRoleNodes() { + final List< RoleNode > nodes = new ArrayList<>( left.getRoleNodes() ); + nodes.addAll( right.getRoleNodes() ); + return nodes; } + /** {@inheritDoc} */ @Override public String toString() { return "(" + left + " " + operator + " " + right + ")"; } -} +} diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java index d42053c290..1b0cb6c622 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java @@ -1,63 +1,91 @@ /* - * Copyright 2025 The Apache Software Foundation. + * 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 * - * Licensed 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 * - * 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. + * 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.wiki.auth.acl.adv; import java.security.Principal; -import java.util.HashSet; +import java.util.List; import java.util.Set; /** + * A role, group or user name in an advanced access rule. * - * @author AO + * @since 3.0.2 */ public class RoleNode extends RuleNode { + private static final long serialVersionUID = 1L; + private final String role; + private transient volatile Principal principal; + + /** + * Creates a node for a name. + * + * @param role the name of a role, group or user. + */ + public RoleNode( final String role ) { + this.role = role.trim(); + } + /** + * Returns the name this node stands for. + * + * @return the name. + */ public String getRole() { return role; } - public RoleNode(String role) { - this.role = role.trim(); + /** + * Sets the principal the name resolved to. + * + * @param principal the principal. + */ + public void setPrincipal( final Principal principal ) { + this.principal = principal; } - @Override - public boolean evaluate(java.util.Set userRoles) { - return userRoles.contains(role); + /** + * Returns the principal the name resolved to. + * + * @return the principal, or {@code null} if the name was not resolved yet. + */ + public Principal getPrincipal() { + return principal; } + /** {@inheritDoc} */ @Override - public String toString() { - return role; + public boolean evaluate( final Set< String > userRoles ) { + return userRoles.contains( role ); } - protected Principal principal; - public void setPrincipal(Principal principal) { - this.principal = principal; - } - - public Principal getPrincipal() { - return this.principal; + /** {@inheritDoc} */ + @Override + public List< RoleNode > getRoleNodes() { + return List.of( this ); } + /** {@inheritDoc} */ @Override - public Set getAllRoles() { - Set set = new HashSet<>(); - set.add(role); - return set; + public String toString() { + return role; } + } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java index c3243bea28..282996cfcb 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java @@ -1,45 +1,63 @@ /* - * Copyright 2025 The Apache Software Foundation. + * 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 * - * Licensed 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 * - * 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. + * 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.wiki.auth.acl.adv; +import java.io.Serializable; +import java.util.LinkedHashSet; +import java.util.List; import java.util.Set; /** - * A rule node is a tree like representation of a boolean logic statement used - * for access controls on a wiki page. + * A node of the expression tree of an advanced access rule, such as {@code Admin AND (Editors OR NOT Banned)}. * - * @author AO - * @since 3.0.0 + * @since 3.0.2 */ -public abstract class RuleNode { +public abstract class RuleNode implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * Evaluates this node against the names a user holds. + * + * @param userRoles the names of the roles, groups and users the current user holds. + * @return {@code true} if the user satisfies the rule. + */ + public abstract boolean evaluate( Set< String > userRoles ); /** - * evaluates if a given user/request is allowed to a specific page given - * their roles/attributes etc + * Returns the leaves of this expression, in the order they were written. * - * @param userRoles - * @return true if allowed, false otherwise + * @return the role nodes of this expression. */ - public abstract boolean evaluate(java.util.Set userRoles); + public abstract List< RoleNode > getRoleNodes(); /** - * gets the complete list of all roles defined within the ACL statement. + * Returns the names of all the roles, groups and users this expression mentions. * - * @return set of roles/usernames/attributes etc + * @return the names, without duplicates. */ - public abstract Set getAllRoles(); + public Set< String > getAllRoles() { + final Set< String > names = new LinkedHashSet<>(); + for( final RoleNode node : getRoleNodes() ) { + names.add( node.getRole() ); + } + return names; + } } diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java index 6f82a8b6c4..af0c867ea2 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java @@ -1,109 +1,126 @@ /* - * Copyright 2025 The Apache Software Foundation. + * 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 * - * Licensed 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 * - * 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. + * 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.wiki.auth.acl.adv; -import java.util.*; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; /** + * Parses the expression of an advanced access rule. The operators are {@code AND}, {@code OR} and {@code NOT}, written in upper + * case, and parentheses group. {@code NOT} binds tighter than {@code AND}, which binds tighter than {@code OR}. * - * @author AO + * @since 3.0.2 */ - public class RuleParser { - private final List tokens; - private int pos = 0; - public RuleParser(String expr) { - this.tokens = tokenize(expr); + private static final Pattern PARENTHESES = Pattern.compile( "([()])" ); + private static final Pattern WHITESPACE = Pattern.compile( "\\s+" ); + + private final List< String > tokens; + private int pos; + + /** + * Creates a parser. + * + * @param expr the expression, without the {@code ALLOW} keyword and the action. + */ + public RuleParser( final String expr ) { + tokens = Arrays.asList( WHITESPACE.split( PARENTHESES.matcher( expr ).replaceAll( " $1 " ).trim() ) ); } + /** + * Parses the expression. + * + * @return the root of the expression tree. + * @throws IllegalArgumentException if the expression is not valid. + */ public RuleNode parse() { - RuleNode node = parseOr(); - if (pos < tokens.size()) { - throw new IllegalArgumentException("Unexpected token: " + tokens.get(pos)); + final RuleNode node = parseOr(); + if( pos < tokens.size() ) { + throw new IllegalArgumentException( "Unexpected token: " + tokens.get( pos ) ); } return node; } - // Lowest precedence private RuleNode parseOr() { RuleNode left = parseAnd(); - while (match("OR")) { - RuleNode right = parseAnd(); - left = new OperatorNode(OperatorNode.Operator.OR, left, right); + while( match( "OR" ) ) { + left = new OperatorNode( OperatorNode.Operator.OR, left, parseAnd() ); } return left; } - // Next precedence private RuleNode parseAnd() { RuleNode left = parseNot(); - while (match("AND")) { - RuleNode right = parseNot(); - left = new OperatorNode(OperatorNode.Operator.AND, left, right); + while( match( "AND" ) ) { + left = new OperatorNode( OperatorNode.Operator.AND, left, parseNot() ); } return left; } - // Handles unary NOT private RuleNode parseNot() { - if (match("NOT")) { - return new NotNode(parseNot()); + if( match( "NOT" ) ) { + return new NotNode( parseNot() ); } return parsePrimary(); } - // Handles parentheses and role identifiers private RuleNode parsePrimary() { - if (match("(")) { - RuleNode expr = parseOr(); - expect(")"); + if( match( "(" ) ) { + final RuleNode expr = parseOr(); + expect( ")" ); return expr; } - return new RoleNode(expectIdentifier()); + return new RoleNode( expectIdentifier() ); } - // --- Helpers --- - private boolean match(String token) { - if (pos < tokens.size() && tokens.get(pos).equalsIgnoreCase(token)) { + private boolean match( final String token ) { + if( pos < tokens.size() && tokens.get( pos ).equals( token ) ) { pos++; return true; } return false; } - private void expect(String token) { - if (!match(token)) { - throw new IllegalArgumentException("Expected '" + token + "'"); + private void expect( final String token ) { + if( !match( token ) ) { + throw new IllegalArgumentException( "Expected '" + token + "'" ); } } private String expectIdentifier() { - if (pos < tokens.size()) { - String tok = tokens.get(pos++); - if (!tok.equalsIgnoreCase("AND") && !tok.equalsIgnoreCase("OR") - && !tok.equalsIgnoreCase("NOT") - && !tok.equals("(") && !tok.equals(")")) { - return tok; + if( pos < tokens.size() ) { + final String token = tokens.get( pos ); + if( !token.isEmpty() && !isReserved( token ) ) { + pos++; + if( token.indexOf( ',' ) >= 0 ) { + throw new IllegalArgumentException( "A comma cannot be used together with AND, OR or NOT: " + token ); + } + return token; } } - throw new IllegalArgumentException("Expected identifier at position " + pos); + throw new IllegalArgumentException( "Expected a name at position " + pos ); } - private static List tokenize(String expr) { - return Arrays.asList(expr.replaceAll("([()])", " $1 ").trim().split("\\s+")); + private static boolean isReserved( final String token ) { + return "AND".equals( token ) || "OR".equals( token ) || "NOT".equals( token ) || "(".equals( token ) || ")".equals( token ); } + } diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java new file mode 100644 index 0000000000..75c825adec --- /dev/null +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java @@ -0,0 +1,181 @@ +/* + * 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.wiki.auth.acl; + +import org.apache.wiki.TestEngine; +import org.apache.wiki.WikiSessionTest; +import org.apache.wiki.api.core.Session; +import org.apache.wiki.auth.AuthorizationManager; +import org.apache.wiki.auth.Users; +import org.apache.wiki.auth.WikiPrincipal; +import org.apache.wiki.auth.authorize.Group; +import org.apache.wiki.auth.authorize.GroupManager; +import org.apache.wiki.auth.permissions.PermissionFactory; +import org.apache.wiki.pages.PageManager; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Properties; + +/** + * Checks who an advanced access rule lets in, with sessions of anonymous, asserted and authenticated users. The wiki groups are + * Editors (Alice, Fred, Biff), Reviewers (Bob, Fred) and Banned (Charlie, Biff). + */ +public class AdvancedAclAuthorizationTest { + + private static final String PAGE = "AdvancedAclPage"; + private static final String[] GROUPS = { "Editors", "Reviewers", "Banned" }; + + private TestEngine engine; + private AuthorizationManager auth; + private GroupManager groups; + + @BeforeEach + public void setUp() throws Exception { + final Properties props = TestEngine.getTestProperties(); + props.put( AuthorizationManager.POLICY, AuthorizationManager.DEFAULT_POLICY ); + engine = new TestEngine( props ); + auth = engine.getManager( AuthorizationManager.class ); + groups = engine.getManager( GroupManager.class ); + group( "Editors", Users.ALICE, Users.FRED, Users.BIFF ); + group( "Reviewers", Users.BOB, Users.FRED ); + group( "Banned", Users.CHARLIE, Users.BIFF ); + } + + @AfterEach + public void tearDown() throws Exception { + engine.getManager( PageManager.class ).deletePage( PAGE ); + for( final String name : GROUPS ) { + groups.removeGroup( name ); + } + } + + private void group( final String name, final String... members ) throws Exception { + final Group group = groups.parseGroup( name, "", true ); + for( final String member : members ) { + group.add( new WikiPrincipal( member ) ); + } + groups.setGroup( WikiSessionTest.adminSession( engine ), group ); + } + + private boolean can( final Session session, final String action ) { + return auth.checkPermission( session, PermissionFactory.getPagePermission( engine.getManager( PageManager.class ).getPage( PAGE ), action ) ); + } + + private Session anonymous() throws Exception { + return WikiSessionTest.anonymousSession( engine ); + } + + private Session user( final String name ) throws Exception { + return WikiSessionTest.authenticatedSession( engine, name, "password" ); + } + + /** Restricting the editors with an advanced rule restricts the readers too, as a simple rule does. */ + @Test + public void testOnlyAnAdvancedRuleForEditRestrictsViewToo() throws Exception { + engine.saveText( PAGE, "Secret. [{ALLOW edit Editors OR Reviewers}]" ); + + Assertions.assertFalse( can( anonymous(), "view" ) ); + Assertions.assertFalse( can( anonymous(), "edit" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "view" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); + + for( final String name : new String[] { Users.ALICE, Users.BOB } ) { + Assertions.assertTrue( can( user( name ), "view" ), name ); + Assertions.assertTrue( can( user( name ), "edit" ), name ); + Assertions.assertFalse( can( user( name ), "delete" ), name ); + } + } + + @Test + public void testSimpleRuleBeforeAnAdvancedOneIsKept() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW view Authenticated}] [{ALLOW edit Editors OR Reviewers}]" ); + + Assertions.assertFalse( can( anonymous(), "view" ) ); + Assertions.assertTrue( can( user( Users.CHARLIE ), "view" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.ALICE ), "edit" ) ); + } + + @Test + public void testAdvancedRuleBeforeASimpleOneCanBeSaved() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW edit Editors OR Reviewers}] [{ALLOW view Authenticated}]" ); + + Assertions.assertTrue( engine.getManager( PageManager.class ).getPureText( PAGE, -1 ).contains( "Text." ) ); + Assertions.assertFalse( can( anonymous(), "view" ) ); + Assertions.assertTrue( can( user( Users.CHARLIE ), "view" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.ALICE ), "edit" ) ); + } + + @Test + public void testAdvancedAndSimpleRuleForTheSameActionAddUp() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW edit Charlie}] [{ALLOW edit Editors AND Reviewers}]" ); + + Assertions.assertTrue( can( user( Users.CHARLIE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.FRED ), "edit" ) ); + Assertions.assertFalse( can( user( Users.ALICE ), "edit" ) ); + Assertions.assertFalse( can( user( Users.BOB ), "edit" ) ); + } + + @Test + public void testNotAndAnd() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW edit Authenticated AND NOT Banned}]" ); + + Assertions.assertTrue( can( user( Users.ALICE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.BOB ), "edit" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); + Assertions.assertFalse( can( user( Users.BIFF ), "edit" ) ); + Assertions.assertFalse( can( anonymous(), "edit" ) ); + } + + /** A name that is only asserted, as in a cookie, must not satisfy a rule, as it does not satisfy a simple rule. */ + @Test + public void testAssertedNameDoesNotSatisfyARule() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW edit Alice OR Bob}]" ); + + Assertions.assertFalse( can( WikiSessionTest.assertedSession( engine, Users.ALICE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.ALICE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.BOB ), "edit" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); + } + + @Test + public void testParenthesesChangeTheMeaning() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW edit Editors AND (Reviewers OR Banned)}]" ); + + Assertions.assertFalse( can( user( Users.ALICE ), "edit" ) ); + Assertions.assertTrue( can( user( Users.FRED ), "edit" ) ); + Assertions.assertTrue( can( user( Users.BIFF ), "edit" ) ); + Assertions.assertFalse( can( user( Users.BOB ), "edit" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); + } + + @Test + public void testPageWithoutAdvancedRulesIsAsBefore() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW edit Alice, Bob}]" ); + + Assertions.assertTrue( can( user( Users.ALICE ), "edit" ) ); + Assertions.assertFalse( can( anonymous(), "view" ) ); + Assertions.assertFalse( can( user( Users.FRED ), "edit" ) ); + } + +} diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java index 70785d7826..556d0780e2 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java @@ -29,6 +29,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.spi.Wiki; import org.apache.wiki.auth.AuthorizationManager; import org.apache.wiki.auth.WikiPrincipal; +import org.apache.wiki.auth.WikiSecurityException; import org.apache.wiki.auth.permissions.PermissionFactory; import org.apache.wiki.filters.FilterManager; import org.apache.wiki.pages.PageManager; @@ -39,11 +40,11 @@ Licensed to the Apache Software Foundation (ASF) under one import org.junit.jupiter.api.Test; import java.security.Principal; +import java.util.List; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; -import org.apache.wiki.auth.acl.adv.AdvancedAcl; import org.apache.wiki.auth.acl.adv.RuleNode; -import org.mockito.internal.util.collections.Sets; public class DefaultAclManagerTest { @@ -139,73 +140,126 @@ public void testGetPermissions() Assertions.assertEquals( 0, p.length ); } + private static RuleNode onlyRule( final Acl acl, final Page page, final String action ) { + final List< RuleNode > rules = ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, action ) ); + Assertions.assertEquals( 1, rules.size() ); + return rules.get( 0 ); + } + @Test public void testGetPermissionsAdvancedAcl() { - Page page = m_engine.getManager(PageManager.class).getPage("TestDefaultPage"); - AclManager mgr = m_engine.getManager(AclManager.class); - - page = m_engine.getManager(PageManager.class).getPage("TestAdvAclPage"); - AdvancedAcl aacl = (AdvancedAcl) mgr.getPermissions(page); - Assertions.assertNotNull(page.getAcl()); - Assertions.assertFalse(page.getAcl().isEmpty()); - - // Charlie is an editor; reading is therefore implied - RuleNode node = aacl.getNode(PermissionFactory.getPagePermission(page, "view")); - Assertions.assertTrue(node.evaluate(Sets.newSet("Charlie"))); - Assertions.assertTrue(node.evaluate(Sets.newSet("Herman"))); - - // Charlie should not be able to delete this page - Assertions.assertTrue(node.evaluate(Sets.newSet("Herman"))); - - // Herman should be in the ACL as an editor - node = aacl.getNode(PermissionFactory.getPagePermission(page, "edit")); - Assertions.assertTrue(node.evaluate(Sets.newSet("Herman"))); - + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestAdvAclPage" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertFalse( acl.isEmpty() ); + + // The page has a rule for view and another for edit, and reading is implied by editing, so both grant it + final List< RuleNode > view = ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "view" ) ); + Assertions.assertEquals( 2, view.size() ); + Assertions.assertTrue( view.get( 0 ).evaluate( Set.of( "Charlie" ) ) ); + Assertions.assertTrue( view.get( 1 ).evaluate( Set.of( "Herman" ) ) ); + Assertions.assertFalse( view.get( 0 ).evaluate( Set.of( "Alice" ) ) ); + + final RuleNode edit = onlyRule( acl, page, "edit" ); + Assertions.assertTrue( edit.evaluate( Set.of( "Herman" ) ) ); + Assertions.assertFalse( edit.evaluate( Set.of( "Alice" ) ) ); + + // the rule does not grant what editing does not imply + Assertions.assertTrue( ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "delete" ) ).isEmpty() ); } - @Test + @Test public void testGetPermissionsAdvancedAcl2() { - Page page = m_engine.getManager(PageManager.class).getPage("TestAdvAclPage2"); - Assertions.assertNotNull(page.getAcl()); - Assertions.assertFalse(page.getAcl().isEmpty()); - AclManager mgr = m_engine.getManager(AclManager.class); - - AdvancedAcl acl = (AdvancedAcl) mgr.getPermissions(page); - Assertions.assertNotNull(page.getAcl()); - Assertions.assertFalse(page.getAcl().isEmpty()); - - // Charlie is an editor; reading is therefore implied - RuleNode node = acl.getNode(PermissionFactory.getPagePermission(page, "edit")); - Assertions.assertTrue(node.evaluate(Sets.newSet("Charlie"))); - Assertions.assertTrue(node.evaluate(Sets.newSet("Admin"))); - Assertions.assertFalse(node.evaluate(Sets.newSet("Accounting"))); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestAdvAclPage2" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertFalse( acl.isEmpty() ); + + final RuleNode node = onlyRule( acl, page, "edit" ); + Assertions.assertTrue( node.evaluate( Set.of( "Charlie" ) ) ); + Assertions.assertTrue( node.evaluate( Set.of( "Admin" ) ) ); + Assertions.assertFalse( node.evaluate( Set.of( "Accounting" ) ) ); + Assertions.assertTrue( node.evaluate( Set.of() ) ); + } + @Test + public void testGetPermissionsAdvancedAcl3() { + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestAdvAclPage3" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertFalse( acl.isEmpty() ); + + final RuleNode node = onlyRule( acl, page, "edit" ); + Assertions.assertFalse( node.evaluate( Set.of( "Group1" ) ) ); + Assertions.assertFalse( node.evaluate( Set.of( "Group2" ) ) ); + Assertions.assertFalse( node.evaluate( Set.of( "Group3" ) ) ); + Assertions.assertTrue( node.evaluate( Set.of( "Group1", "Group2" ) ) ); + Assertions.assertTrue( node.evaluate( Set.of( "Group1", "Group3" ) ) ); + Assertions.assertTrue( node.evaluate( Set.of( "Group1", "Group2", "Group3" ) ) ); + Assertions.assertFalse( node.evaluate( Set.of( "Admin" ) ) ); + } + /** A simple rule and an advanced one on the same page keep both, whatever their order. */ + @Test + public void testSimpleAndAdvancedRulesAreKept() throws Exception { + final AclManager mgr = m_engine.getManager( AclManager.class ); + for( final String text : new String[] { "[{ALLOW view Alice}] [{ALLOW edit Bob OR Charlie}]", + "[{ALLOW edit Bob OR Charlie}] [{ALLOW view Alice}]" } ) { + m_engine.saveText( "TestMixedAclPage", text ); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestMixedAclPage" ); + final Acl acl = mgr.getPermissions( page ); + final Principal[] viewers = acl.findPrincipals( PermissionFactory.getPagePermission( page, "view" ) ); + Assertions.assertEquals( 1, viewers.length, text ); + Assertions.assertEquals( "Alice", viewers[ 0 ].getName(), text ); + Assertions.assertEquals( 1, ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "edit" ) ).size(), text ); + m_engine.getManager( PageManager.class ).deletePage( "TestMixedAclPage" ); + } } - - @Test - public void testGetPermissionsAdvancedAcl3() { - Page page = m_engine.getManager(PageManager.class).getPage("TestAdvAclPage3"); - Assertions.assertNotNull(page.getAcl()); - Assertions.assertFalse(page.getAcl().isEmpty()); - AclManager mgr = m_engine.getManager(AclManager.class); - AdvancedAcl acl = (AdvancedAcl) mgr.getPermissions(page); - Assertions.assertNotNull(page.getAcl()); - Assertions.assertFalse(page.getAcl().isEmpty()); + /** Two advanced rules for the same action add up, as simple rules do. */ + @Test + public void testAdvancedRulesOfTheSameActionAddUp() throws Exception { + m_engine.saveText( "TestTwoRulesPage", "[{ALLOW edit Alice OR Bob}] [{ALLOW edit Charlie AND Herman}]" ); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestTwoRulesPage" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertEquals( 2, ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "edit" ) ).size() ); + m_engine.getManager( PageManager.class ).deletePage( "TestTwoRulesPage" ); + } - // Charlie is an editor; reading is therefore implied - RuleNode node = acl.getNode(PermissionFactory.getPagePermission(page, "edit")); - Assertions.assertFalse(node.evaluate(Sets.newSet("Group1"))); - Assertions.assertFalse(node.evaluate(Sets.newSet("Group2"))); - Assertions.assertFalse(node.evaluate(Sets.newSet("Group3"))); - Assertions.assertTrue(node.evaluate(Sets.newSet("Group1", "Group2"))); - Assertions.assertTrue(node.evaluate(Sets.newSet("Group1", "Group3"))); - Assertions.assertTrue(node.evaluate(Sets.newSet("Group1", "Group2", "Group3"))); - Assertions.assertFalse(node.evaluate(Sets.newSet("Admin"))); - Assertions.assertFalse(node.evaluate(Sets.newSet("Accounting"))); + @Test + public void testInvalidAdvancedRuleIsRejected() { + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestDefaultPage" ); + final AclManager mgr = m_engine.getManager( AclManager.class ); + for( final String rule : new String[] { "Alice AND", "(Alice OR Bob", "Alice OR Bob, Charlie", "NOT", "AND OR" } ) { + final WikiSecurityException e = Assertions.assertThrows( WikiSecurityException.class, + () -> mgr.parseAcl( page, "ALLOW edit " + rule ), rule ); + Assertions.assertTrue( e.getMessage().startsWith( "Invalid access rule: ALLOW edit " + rule ), e.getMessage() ); + } + Assertions.assertTrue( page.getAcl() == null || page.getAcl().isEmpty() ); + } + /** Names that only contain the words of the operators are names, and a lower case operator is a name too. */ + @Test + public void testOperatorWordsInsideNamesAreNames() throws Exception { + m_engine.saveText( "TestWordsPage", "[{ALLOW edit ANDY, ORACLE, NOTARY, order, Brand}]" ); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestWordsPage" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertEquals( 5, acl.findPrincipals( PermissionFactory.getPagePermission( page, "edit" ) ).length ); + Assertions.assertTrue( ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "edit" ) ).isEmpty() ); + m_engine.getManager( PageManager.class ).deletePage( "TestWordsPage" ); + } + @Test + public void testPrintAclKeepsAdvancedRules() throws Exception { + m_engine.saveText( "TestPrintPage", "[{ALLOW view Alice}] [{ALLOW edit Bob AND (Charlie OR NOT Herman)}]" ); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestPrintPage" ); + final String printed = DefaultAclManager.printAcl( m_engine.getManager( AclManager.class ).getPermissions( page ) ); + Assertions.assertTrue( printed.contains( "[{ALLOW view Alice}]" ), printed ); + Assertions.assertTrue( printed.contains( "[{ALLOW edit (Bob AND (Charlie OR (NOT Herman)))}]" ), printed ); + + // what is printed reads back as the same rule + m_engine.saveText( "TestPrintPage2", printed ); + final Page page2 = m_engine.getManager( PageManager.class ).getPage( "TestPrintPage2" ); + Assertions.assertEquals( printed, DefaultAclManager.printAcl( m_engine.getManager( AclManager.class ).getPermissions( page2 ) ) ); + m_engine.getManager( PageManager.class ).deletePage( "TestPrintPage" ); + m_engine.getManager( PageManager.class ).deletePage( "TestPrintPage2" ); } diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java index 065e3a53a9..356169f636 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java @@ -15,117 +15,105 @@ */ package org.apache.wiki.auth.acl.adv; -import java.util.List; -import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; -/** - * tests the rule parser for the advanced acl tool chain - * - * @see AdvancedAcl - * @since 3.0.0 +import java.util.Set; +/** + * Tests the parser of the expressions of advanced access rules. */ public class RuleParserTest { - public RuleParserTest() { + private static RuleNode parse( final String expression ) { + return new RuleParser( expression ).parse(); } @Test public void simpleOrStatement() { - RuleParser instance = new RuleParser("bob or mary"); - RuleNode result = instance.parse(); - Assertions.assertEquals(2, result.getAllRoles().size()); - Assertions.assertTrue(result.evaluate(Set.of("bob"))); - Assertions.assertTrue(result.evaluate(Set.of("mary"))); - Assertions.assertFalse(result.evaluate(Set.of("john"))); + final RuleNode result = parse( "bob OR mary" ); + Assertions.assertEquals( 2, result.getAllRoles().size() ); + Assertions.assertTrue( result.evaluate( Set.of( "bob" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "mary" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "john" ) ) ); } @Test public void simpleAndStatement() { - RuleParser instance = new RuleParser("accounting AND finance"); - RuleNode result = instance.parse(); - Assertions.assertEquals(2, result.getAllRoles().size()); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance"))); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "otherDepartment"))); - Assertions.assertFalse(result.evaluate(Set.of("accounting"))); - Assertions.assertFalse(result.evaluate(Set.of("finance"))); - Assertions.assertFalse(result.evaluate(Set.of("john"))); + final RuleNode result = parse( "accounting AND finance" ); + Assertions.assertEquals( 2, result.getAllRoles().size() ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance", "otherDepartment" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "accounting" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "finance" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "john" ) ) ); } @Test public void complexSetup() { - RuleParser instance = new RuleParser("accounting AND (finance OR admin)"); - RuleNode result = instance.parse(); - Assertions.assertEquals(3, result.getAllRoles().size()); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance"))); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "otherDepartment"))); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "admin"))); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "admin"))); - Assertions.assertFalse(result.evaluate(Set.of("accounting"))); - Assertions.assertFalse(result.evaluate(Set.of("finance"))); - Assertions.assertFalse(result.evaluate(Set.of("john"))); + final RuleNode result = parse( "accounting AND (finance OR admin)" ); + Assertions.assertEquals( 3, result.getAllRoles().size() ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance", "otherDepartment" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance", "admin" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "admin" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "accounting" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "finance" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "john" ) ) ); } @Test public void complexSetupNot() { - RuleParser instance = new RuleParser("accounting AND finance AND NOT(bob)"); - instance = new RuleParser("(accounting AND finance AND NOT(bob))"); - RuleNode result = instance.parse(); - Assertions.assertEquals(3, result.getAllRoles().size()); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance"))); - Assertions.assertTrue(result.evaluate(Set.of("accounting", "finance", "otherDepartment"))); - Assertions.assertFalse(result.evaluate(Set.of("accounting", "finance", "bob"))); - Assertions.assertFalse(result.evaluate(Set.of("accounting", "admin"))); - Assertions.assertFalse(result.evaluate(Set.of("accounting"))); - Assertions.assertFalse(result.evaluate(Set.of("finance"))); - Assertions.assertFalse(result.evaluate(Set.of("john"))); + final RuleNode result = parse( "(accounting AND finance AND NOT(bob))" ); + Assertions.assertEquals( 3, result.getAllRoles().size() ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "accounting", "finance", "otherDepartment" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "accounting", "finance", "bob" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "accounting", "admin" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "accounting" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "john" ) ) ); } @Test - public void mismatchedParan() { - Assertions.assertThrows(IllegalArgumentException.class, () -> { - RuleParser instance = new RuleParser("(accounting AND finance AND NOT(bob)"); - RuleNode parse = instance.parse(); - System.out.println(parse); - }); + public void notBindsTighterThanAndAndAndTighterThanOr() { + final RuleNode result = parse( "a OR b AND NOT c" ); + Assertions.assertTrue( result.evaluate( Set.of( "a", "c" ) ) ); + Assertions.assertTrue( result.evaluate( Set.of( "b" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of( "b", "c" ) ) ); + Assertions.assertFalse( result.evaluate( Set.of() ) ); + } - RuleParser instance = new RuleParser("(accounting AND finance AND NOT(bob))"); - instance.parse(); + @Test + public void roleNodesKeepTheOrderTheyWereWritten() { + final RuleNode result = parse( "x AND (y OR NOT z)" ); + Assertions.assertEquals( 3, result.getRoleNodes().size() ); + Assertions.assertEquals( "x", result.getRoleNodes().get( 0 ).getRole() ); + Assertions.assertEquals( "z", result.getRoleNodes().get( 2 ).getRole() ); + } + + @Test + public void operatorsAreUpperCase() { + // a lower case word is a name, so this is two names without an operator between them + Assertions.assertThrows( IllegalArgumentException.class, () -> parse( "bob or mary" ) ); + Assertions.assertEquals( Set.of( "and", "or", "not" ), parse( "and AND or AND not" ).getAllRoles() ); + } - List invalidExprs = List.of( - "role1 AND", - "AND role1", - "role1 OR OR role2", - "role1 (role2 OR role3)", - "(role1 AND role2", - "role1 AND role2)", - "role1 AND NOT", - "NOT", - "role1 OR AND role2", - "()", - "( )", - "role1 AND (OR role2)", - "role1 AND (role2 OR)", - "role1 role2", - "role1 AND (NOT)", - "(role1 AND) OR role2", - "role1 AND ((role2)", - "role1 AND )role2(", - "role1 AND NOT ( )", - "NOT (role1 AND)" - ); + @Test + public void printedRuleReadsBackTheSame() { + final String expression = "x AND (y OR NOT z)"; + final RuleNode first = parse( expression ); + Assertions.assertEquals( first.toString(), parse( first.toString() ).toString() ); + } - for (String expr : invalidExprs) { - try { - RuleParser parser = new RuleParser(expr); - parser.parse(); - System.out.println("❌ Should have failed but parsed: " + expr); - } catch (Exception e) { - System.out.println("✅ Correctly failed: " + expr + " → " + e.getMessage()); - } - } + @ParameterizedTest + @ValueSource( strings = { "", " ", "role1 AND", "AND role1", "role1 OR OR role2", "role1 (role2 OR role3)", "(role1 AND role2", + "role1 AND role2)", "role1 AND NOT", "NOT", "role1 OR AND role2", "()", "( )", "role1 AND (OR role2)", + "role1 AND (role2 OR)", "role1 role2", "role1 AND (NOT)", "(role1 AND) OR role2", "role1 AND ((role2)", + "role1 AND )role2(", "role1 AND NOT ( )", "NOT (role1 AND)", "role1 OR role2, role3", "role1 , role2" } ) + public void invalidExpressionsAreRejected( final String expression ) { + Assertions.assertThrows( IllegalArgumentException.class, () -> parse( expression ) ); } } From 67eb544e1d58d4c4fb13115277cd3b9a8d4ae455 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Sat, 21 Nov 2026 17:45:57 +0100 Subject: [PATCH 3/3] JSPWIKI-1210 Fix the problems found in the review of the advanced rules A list of names with commas is always a simple rule, as it was before, so a name with an upper case AND, OR or NOT inside it does not turn the whole line into an advanced rule that fails. AND, OR and NOT next to parentheses are operators, as the parser reads them. Parsing the same page again does not add its advanced rules again. A page that is restricted only by advanced rules is not notified to the subscribers. Renaming a user profile changes the name in the advanced rules too. --- .../org/apache/wiki/auth/acl/AclImpl.java | 39 ++++++++++- .../wiki/auth/acl/DefaultAclManager.java | 12 ++-- .../org/apache/wiki/auth/acl/adv/NotNode.java | 8 +++ .../wiki/auth/acl/adv/OperatorNode.java | 9 +++ .../apache/wiki/auth/acl/adv/RoleNode.java | 11 ++++ .../apache/wiki/auth/acl/adv/RuleNode.java | 10 +++ .../DefaultSubscriptionManager.java | 8 ++- .../apache/wiki/pages/DefaultPageManager.java | 4 ++ .../acl/AdvancedAclAuthorizationTest.java | 10 +++ .../wiki/auth/acl/DefaultAclManagerTest.java | 64 ++++++++++++++++--- .../wiki/auth/acl/adv/RuleParserTest.java | 25 ++++---- .../DefaultSubscriptionManagerTest.java | 2 + 12 files changed, 176 insertions(+), 26 deletions(-) diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java index e0726f9de7..66f91a8afd 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/AclImpl.java @@ -29,7 +29,9 @@ Licensed to the Apache Software Foundation (ASF) under one import java.util.Collections; import java.util.Enumeration; import java.util.List; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.ReentrantLock; @@ -79,7 +81,42 @@ private AdvancedRule( final Permission permission, final RuleNode rule ) { * @since 3.0.2 */ public void addRule( final Permission permission, final RuleNode rule ) { - m_rules.add( new AdvancedRule( permission, rule ) ); + // The same page is parsed again each time it is rendered without the cache, and that must not add its rules again + Synchronizer.synchronize( lock, () -> { + for( final AdvancedRule r : m_rules ) { + if( r.permission.equals( permission ) && r.rule.toString().equals( rule.toString() ) ) { + return; + } + } + m_rules.add( new AdvancedRule( permission, rule ) ); + } ); + } + + /** + * Replaces the names of some principals in the advanced rules with another principal, as when a user renames a profile. + * + * @param oldPrincipals the principals to replace. + * @param newPrincipal the principal that takes their place. + * @return {@code true} if any rule was changed. + * @since 3.0.2 + */ + public boolean renameInRules( final Principal[] oldPrincipals, final Principal newPrincipal ) { + final Set< String > oldNames = new HashSet<>(); + for( final Principal p : oldPrincipals ) { + oldNames.add( p.getName() ); + } + return Synchronizer.synchronize( lock, () -> { + boolean changed = false; + for( int i = 0; i < m_rules.size(); i++ ) { + final AdvancedRule r = m_rules.get( i ); + final RuleNode renamed = r.rule.rename( oldNames, newPrincipal ); + if( renamed != r.rule ) { + m_rules.set( i, new AdvancedRule( r.permission, renamed ) ); + changed = true; + } + } + return changed; + } ); } /** diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java index 6416cf9409..f0abac193d 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/DefaultAclManager.java @@ -81,10 +81,10 @@ public class DefaultAclManager implements AclManager { private static final String ACL_REGEX = "\\[\\{\\s*ALLOW\\s+" + PERM_REGEX + "\\s*(.*?)\\s*\\}\\]"; /** - * Identifies an advanced rule, which is a rule that has AND, OR or NOT written in upper case as a word of its own. A name that - * contains one of them has to be written without spaces around it, or in lower case, to be read as a name. + * Identifies an advanced rule, which is a rule without commas that has AND, OR or NOT written in upper case as a word of its own. + * A name that contains one of them is a name when it is written without spaces around it, or in lower case, or in a list with commas. */ - private static final Pattern ADVANCED_RULE = Pattern.compile( "(?:^|[\\s(])(?:AND|OR|NOT)(?=[\\s(]|$)" ); + private static final Pattern ADVANCED_RULE = Pattern.compile( "(?:^|[\\s()])(?:AND|OR|NOT)(?=[\\s()]|$)" ); /** * Identifies ACL strings in wiki text; the first group is the action (view, edit) and @@ -113,8 +113,9 @@ public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurit fieldToks.nextToken(); final String actions = fieldToks.nextToken(); - final String expression = ruleLine.substring( ruleLine.indexOf( actions ) + actions.length() ).trim(); - if( ADVANCED_RULE.matcher( expression ).find() ) { + // a list of names with commas is a simple rule, as it always was, whatever words its names have + final String expression = ruleLine.trim().replaceFirst( "^\\S+\\s+\\S+", "" ).trim(); + if( expression.indexOf( ',' ) < 0 && ADVANCED_RULE.matcher( expression ).find() ) { addAdvancedRule( acl, page, actions, expression, ruleLine ); page.setAcl( acl ); LOG.debug( acl.toString() ); @@ -150,6 +151,7 @@ public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurit return acl; } + /** * Adds an advanced rule to an ACL. The ACL has to be one of the implementation of this manager, as that is the one that keeps rules. */ diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java index e94d5ab117..50f9c7ed41 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java @@ -18,6 +18,7 @@ */ package org.apache.wiki.auth.acl.adv; +import java.security.Principal; import java.util.List; import java.util.Set; @@ -56,6 +57,13 @@ public boolean evaluate( final Set< String > userRoles ) { return !child.evaluate( userRoles ); } + /** {@inheritDoc} */ + @Override + public RuleNode rename( final Set< String > oldNames, final Principal newPrincipal ) { + final RuleNode renamed = child.rename( oldNames, newPrincipal ); + return renamed == child ? this : new NotNode( renamed ); + } + /** {@inheritDoc} */ @Override public List< RoleNode > getRoleNodes() { diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java index 7deed76dc9..8afd720243 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java @@ -18,6 +18,7 @@ */ package org.apache.wiki.auth.acl.adv; +import java.security.Principal; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -85,6 +86,14 @@ public boolean evaluate( final Set< String > userRoles ) { : left.evaluate( userRoles ) || right.evaluate( userRoles ); } + /** {@inheritDoc} */ + @Override + public RuleNode rename( final Set< String > oldNames, final Principal newPrincipal ) { + final RuleNode newLeft = left.rename( oldNames, newPrincipal ); + final RuleNode newRight = right.rename( oldNames, newPrincipal ); + return newLeft == left && newRight == right ? this : new OperatorNode( operator, newLeft, newRight ); + } + /** {@inheritDoc} */ @Override public List< RoleNode > getRoleNodes() { diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java index 1b0cb6c622..2e3cae7464 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java @@ -76,6 +76,17 @@ public boolean evaluate( final Set< String > userRoles ) { return userRoles.contains( role ); } + /** {@inheritDoc} */ + @Override + public RuleNode rename( final Set< String > oldNames, final Principal newPrincipal ) { + if( !oldNames.contains( role ) ) { + return this; + } + final RoleNode renamed = new RoleNode( newPrincipal.getName() ); + renamed.setPrincipal( newPrincipal ); + return renamed; + } + /** {@inheritDoc} */ @Override public List< RoleNode > getRoleNodes() { diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java index 282996cfcb..c487b8b4b2 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java @@ -19,6 +19,7 @@ package org.apache.wiki.auth.acl.adv; import java.io.Serializable; +import java.security.Principal; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -47,6 +48,15 @@ public abstract class RuleNode implements Serializable { */ public abstract List< RoleNode > getRoleNodes(); + /** + * Returns a copy of this expression in which the given names stand for another principal, as when a user renames a profile. + * + * @param oldNames the names to replace. + * @param newPrincipal the principal the names are replaced with. + * @return the new expression, or this one if it does not mention any of the names. + */ + public abstract RuleNode rename( Set< String > oldNames, Principal newPrincipal ); + /** * Returns the names of all the roles, groups and users this expression mentions. * diff --git a/jspwiki-main/src/main/java/org/apache/wiki/notification/DefaultSubscriptionManager.java b/jspwiki-main/src/main/java/org/apache/wiki/notification/DefaultSubscriptionManager.java index 8e457b2718..7617bc5fea 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/notification/DefaultSubscriptionManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/notification/DefaultSubscriptionManager.java @@ -27,6 +27,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.api.engine.Initializable; import org.apache.wiki.api.exceptions.WikiException; import org.apache.wiki.auth.UserManager; +import org.apache.wiki.auth.acl.AclImpl; import org.apache.wiki.auth.acl.AclManager; import org.apache.wiki.auth.permissions.PermissionFactory; import org.apache.wiki.auth.user.UserDatabase; @@ -41,6 +42,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.util.MailUtil; import org.apache.wiki.util.TextUtil; +import java.security.Permission; import java.security.Principal; import java.util.ArrayList; import java.util.Collections; @@ -177,7 +179,11 @@ void notifySubscribers( final String pageName ) { private boolean isViewRestricted( final Page page ) { final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); - return acl != null && acl.findPrincipals( PermissionFactory.getPagePermission( page, "view" ) ).length > 0; + if( acl == null ) { + return false; + } + final Permission view = PermissionFactory.getPagePermission( page, "view" ); + return acl.findPrincipals( view ).length > 0 || acl instanceof AclImpl && !( ( AclImpl ) acl ).findRules( view ).isEmpty(); } private void sendMail( final UserProfile profile, final Page page ) { diff --git a/jspwiki-main/src/main/java/org/apache/wiki/pages/DefaultPageManager.java b/jspwiki-main/src/main/java/org/apache/wiki/pages/DefaultPageManager.java index 04a4adf2f0..a5a663f62f 100644 --- a/jspwiki-main/src/main/java/org/apache/wiki/pages/DefaultPageManager.java +++ b/jspwiki-main/src/main/java/org/apache/wiki/pages/DefaultPageManager.java @@ -37,6 +37,7 @@ Licensed to the Apache Software Foundation (ASF) under one import org.apache.wiki.attachment.AttachmentManager; import org.apache.wiki.auth.WikiPrincipal; import org.apache.wiki.auth.WikiSecurityException; +import org.apache.wiki.auth.acl.AclImpl; import org.apache.wiki.auth.acl.AclManager; import org.apache.wiki.auth.user.UserProfile; import org.apache.wiki.cache.CachingManager; @@ -750,6 +751,9 @@ protected boolean changeAcl( final Page page, final Principal[] oldPrincipals, f for( final AclEntry entry : entriesToAdd ) { acl.addEntry( entry ); } + if( acl instanceof AclImpl && ( ( AclImpl ) acl ).renameInRules( oldPrincipals, newPrincipal ) ) { + pageChanged = true; + } } return pageChanged; } diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java index 75c825adec..51f73222a0 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java @@ -169,6 +169,16 @@ public void testParenthesesChangeTheMeaning() throws Exception { Assertions.assertFalse( can( user( Users.CHARLIE ), "edit" ) ); } + /** NOT alone is true for everybody that does not hold the name, the users that are not logged in included. */ + @Test + public void testNotAloneIsTrueForUsersThatAreNotLoggedIn() throws Exception { + engine.saveText( PAGE, "Text. [{ALLOW view NOT Banned}]" ); + + Assertions.assertTrue( can( anonymous(), "view" ) ); + Assertions.assertTrue( can( user( Users.ALICE ), "view" ) ); + Assertions.assertFalse( can( user( Users.CHARLIE ), "view" ) ); + } + @Test public void testPageWithoutAdvancedRulesIsAsBefore() throws Exception { engine.saveText( PAGE, "Text. [{ALLOW edit Alice, Bob}]" ); diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java index 556d0780e2..aa4b9b91ae 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/DefaultAclManagerTest.java @@ -54,12 +54,12 @@ public class DefaultAclManagerTest public void setUp() throws Exception { m_engine.saveText( "TestDefaultPage", "Foo" ); m_engine.saveText( "TestAclPage", "Bar. [{ALLOW edit Charlie, Herman}] " ); - + m_engine.saveText("TestAdvAclPage", "Bar. [{ALLOW edit Charlie OR Herman}] [{ALLOW view Charlie OR Herman}] "); - + m_engine.saveText("TestAdvAclPage2", "Bar. [{ALLOW edit Charlie OR Admin OR NOT Accounting}] "); m_engine.saveText("TestAdvAclPage3", "Bar. [{ALLOW edit Group1 AND (Group2 OR Group3)}] "); - + } @AfterEach @@ -70,8 +70,8 @@ public void tearDown() { m_engine.getManager( PageManager.class ).deletePage( "TestAdvAclPage" ); m_engine.getManager( PageManager.class ).deletePage( "TestAdvAclPage2" ); m_engine.getManager( PageManager.class ).deletePage( "TestAdvAclPage3" ); - - + + } catch ( final ProviderException e ) { } } @@ -139,7 +139,7 @@ public void testGetPermissions() p = acl.findPrincipals( PermissionFactory.getPagePermission(page, "delete") ); Assertions.assertEquals( 0, p.length ); } - + private static RuleNode onlyRule( final Acl acl, final Page page, final String action ) { final List< RuleNode > rules = ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, action ) ); Assertions.assertEquals( 1, rules.size() ); @@ -227,7 +227,7 @@ public void testAdvancedRulesOfTheSameActionAddUp() throws Exception { public void testInvalidAdvancedRuleIsRejected() { final Page page = m_engine.getManager( PageManager.class ).getPage( "TestDefaultPage" ); final AclManager mgr = m_engine.getManager( AclManager.class ); - for( final String rule : new String[] { "Alice AND", "(Alice OR Bob", "Alice OR Bob, Charlie", "NOT", "AND OR" } ) { + for( final String rule : new String[] { "Alice AND", "(Alice OR Bob", "NOT", "AND OR" } ) { final WikiSecurityException e = Assertions.assertThrows( WikiSecurityException.class, () -> mgr.parseAcl( page, "ALLOW edit " + rule ), rule ); Assertions.assertTrue( e.getMessage().startsWith( "Invalid access rule: ALLOW edit " + rule ), e.getMessage() ); @@ -235,6 +235,54 @@ public void testInvalidAdvancedRuleIsRejected() { Assertions.assertTrue( page.getAcl() == null || page.getAcl().isEmpty() ); } + /** A list with commas is a simple rule, as it always was, even when the name of one of them has an upper case operator inside. */ + @Test + public void testListWithCommasIsASimpleRule() throws Exception { + m_engine.saveText( "TestCommaPage", "[{ALLOW view Alice, Bob AND Charlie}]" ); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestCommaPage" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertEquals( 2, acl.findPrincipals( PermissionFactory.getPagePermission( page, "view" ) ).length ); + Assertions.assertTrue( ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "view" ) ).isEmpty() ); + m_engine.getManager( PageManager.class ).deletePage( "TestCommaPage" ); + } + + @Test + public void testOperatorsNextToParenthesesAreOperators() throws Exception { + m_engine.saveText( "TestParenPage", "[{ALLOW view (Alice)AND(Bob)}]" ); + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestParenPage" ); + final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page ); + Assertions.assertEquals( 0, acl.findPrincipals( PermissionFactory.getPagePermission( page, "view" ) ).length ); + Assertions.assertEquals( 1, ( ( AclImpl ) acl ).findRules( PermissionFactory.getPagePermission( page, "view" ) ).size() ); + m_engine.getManager( PageManager.class ).deletePage( "TestParenPage" ); + } + + /** Rendering a page again, as it happens when the cache is not used, must not add its rules again. */ + @Test + public void testParsingAPageAgainDoesNotRepeatItsRules() throws Exception { + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestAdvAclPage2" ); + final AclManager mgr = m_engine.getManager( AclManager.class ); + mgr.parseAcl( page, "ALLOW edit Charlie OR Admin OR NOT Accounting" ); + mgr.parseAcl( page, "ALLOW edit Charlie OR Admin OR NOT Accounting" ); + Assertions.assertEquals( 1, ( ( AclImpl ) mgr.getPermissions( page ) ).findRules( PermissionFactory.getPagePermission( page, "edit" ) ).size() ); + // another expression for the same action is another rule + mgr.parseAcl( page, "ALLOW edit Alice OR Bob" ); + Assertions.assertEquals( 2, ( ( AclImpl ) mgr.getPermissions( page ) ).findRules( PermissionFactory.getPagePermission( page, "edit" ) ).size() ); + } + + /** A renamed profile keeps its access to the pages whose advanced rules name it. */ + @Test + public void testRenamingAUserChangesTheAdvancedRules() throws Exception { + final Page page = m_engine.getManager( PageManager.class ).getPage( "TestAdvAclPage3" ); + final AclImpl acl = ( AclImpl ) m_engine.getManager( AclManager.class ).getPermissions( page ); + final Principal newName = new WikiPrincipal( "Group9" ); + Assertions.assertTrue( acl.renameInRules( new Principal[] { new WikiPrincipal( "Group2" ) }, newName ) ); + final RuleNode node = onlyRule( acl, page, "edit" ); + Assertions.assertTrue( node.evaluate( Set.of( "Group1", "Group9" ) ) ); + Assertions.assertFalse( node.evaluate( Set.of( "Group1", "Group2" ) ) ); + Assertions.assertTrue( node.evaluate( Set.of( "Group1", "Group3" ) ) ); + Assertions.assertFalse( acl.renameInRules( new Principal[] { new WikiPrincipal( "Nobody" ) }, newName ) ); + } + /** Names that only contain the words of the operators are names, and a lower case operator is a name too. */ @Test public void testOperatorWordsInsideNamesAreNames() throws Exception { @@ -262,7 +310,7 @@ public void testPrintAclKeepsAdvancedRules() throws Exception { m_engine.getManager( PageManager.class ).deletePage( "TestPrintPage2" ); } - + @Test public void testAclRegex() { diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java index 356169f636..41a68432d4 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java @@ -1,17 +1,20 @@ /* - * Copyright 2025 The Apache Software Foundation. + * 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 * - * Licensed 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 * - * 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. + * 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.wiki.auth.acl.adv; diff --git a/jspwiki-main/src/test/java/org/apache/wiki/notification/DefaultSubscriptionManagerTest.java b/jspwiki-main/src/test/java/org/apache/wiki/notification/DefaultSubscriptionManagerTest.java index ad31c83646..54a7eed190 100644 --- a/jspwiki-main/src/test/java/org/apache/wiki/notification/DefaultSubscriptionManagerTest.java +++ b/jspwiki-main/src/test/java/org/apache/wiki/notification/DefaultSubscriptionManagerTest.java @@ -137,9 +137,11 @@ void savingASubscribedPageSendsAMail() throws Exception { @Test void aPageWithRestrictedViewIsNotNotified() throws Exception { manager.subscribe( "subscriber", "RestrictedPage" ); + manager.subscribe( "subscriber", "RestrictedAdvancedPage" ); manager.subscribe( "subscriber", "SubscribedPage" ); engine.saveText( "RestrictedPage", "[{ALLOW view Admin}]\nsecret" ); + engine.saveText( "RestrictedAdvancedPage", "[{ALLOW view Admin OR Editors}]\nsecret" ); engine.saveText( "SubscribedPage", "public" ); final List< SmtpMessage > mails = awaitMails( 1 );