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-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/DefaultAuthorizationManager.java index 296e2e3574..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; @@ -59,9 +62,11 @@ 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; @@ -169,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..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 @@ -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,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; @@ -51,6 +55,100 @@ 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 ) { + // 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; + } ); + } + + /** + * 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 +229,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 +250,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 e31b8334a0..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 @@ -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; @@ -77,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 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()]|$)" ); + /** * 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 @@ -104,6 +113,15 @@ public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurit fieldToks.nextToken(); final String actions = fieldToks.nextToken(); + // 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() ); + return acl; + } + while( fieldToks.hasMoreTokens() ) { final String principalName = fieldToks.nextToken(",").trim(); final Principal principal = m_auth.resolvePrincipal(principalName); @@ -134,6 +152,25 @@ 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. + */ + 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 ); + } + 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} */ @Override @@ -241,6 +278,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/NotNode.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java new file mode 100644 index 0000000000..50f9c7ed41 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/NotNode.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.wiki.auth.acl.adv; + +import java.security.Principal; +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. + * + * @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; + } + + /** {@inheritDoc} */ + @Override + 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() { + return child.getRoleNodes(); + } + + /** {@inheritDoc} */ + @Override + public String toString() { + return "(NOT " + child + ")"; + } + +} 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..8afd720243 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/OperatorNode.java @@ -0,0 +1,111 @@ +/* + * 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.adv; + +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * Combines two expressions with AND or OR. + * + * @since 3.0.2 + */ +public class OperatorNode extends RuleNode { + + 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; + 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; + } + + /** {@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 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() { + 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 new file mode 100644 index 0000000000..2e3cae7464 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RoleNode.java @@ -0,0 +1,102 @@ +/* + * 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.adv; + +import java.security.Principal; +import java.util.List; +import java.util.Set; + +/** + * A role, group or user name in an advanced access rule. + * + * @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; + } + + /** + * Sets the principal the name resolved to. + * + * @param principal the principal. + */ + public void setPrincipal( final Principal principal ) { + this.principal = principal; + } + + /** + * 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 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() { + return List.of( this ); + } + + /** {@inheritDoc} */ + @Override + 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 new file mode 100644 index 0000000000..c487b8b4b2 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleNode.java @@ -0,0 +1,73 @@ +/* + * 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.adv; + +import java.io.Serializable; +import java.security.Principal; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * A node of the expression tree of an advanced access rule, such as {@code Admin AND (Editors OR NOT Banned)}. + * + * @since 3.0.2 + */ +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 ); + + /** + * Returns the leaves of this expression, in the order they were written. + * + * @return the role nodes of this expression. + */ + 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. + * + * @return the names, without duplicates. + */ + 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 new file mode 100644 index 0000000000..af0c867ea2 --- /dev/null +++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/acl/adv/RuleParser.java @@ -0,0 +1,126 @@ +/* + * 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.adv; + +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}. + * + * @since 3.0.2 + */ +public class RuleParser { + + 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() { + final RuleNode node = parseOr(); + if( pos < tokens.size() ) { + throw new IllegalArgumentException( "Unexpected token: " + tokens.get( pos ) ); + } + return node; + } + + private RuleNode parseOr() { + RuleNode left = parseAnd(); + while( match( "OR" ) ) { + left = new OperatorNode( OperatorNode.Operator.OR, left, parseAnd() ); + } + return left; + } + + private RuleNode parseAnd() { + RuleNode left = parseNot(); + while( match( "AND" ) ) { + left = new OperatorNode( OperatorNode.Operator.AND, left, parseNot() ); + } + return left; + } + + private RuleNode parseNot() { + if( match( "NOT" ) ) { + return new NotNode( parseNot() ); + } + return parsePrimary(); + } + + private RuleNode parsePrimary() { + if( match( "(" ) ) { + final RuleNode expr = parseOr(); + expect( ")" ); + return expr; + } + return new RoleNode( expectIdentifier() ); + } + + private boolean match( final String token ) { + if( pos < tokens.size() && tokens.get( pos ).equals( token ) ) { + pos++; + return true; + } + return false; + } + + private void expect( final String token ) { + if( !match( token ) ) { + throw new IllegalArgumentException( "Expected '" + token + "'" ); + } + } + + private String expectIdentifier() { + 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 a name at position " + pos ); + } + + 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/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 new file mode 100644 index 0000000000..51f73222a0 --- /dev/null +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/AdvancedAclAuthorizationTest.java @@ -0,0 +1,191 @@ +/* + * 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" ) ); + } + + /** 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}]" ); + + 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 b953e84657..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 @@ -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,8 +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.RuleNode; public class DefaultAclManagerTest { @@ -50,6 +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 @@ -57,6 +67,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 ) { } } @@ -125,6 +140,177 @@ 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() { + 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 + public void testGetPermissionsAdvancedAcl2() { + 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" ); + } + } + + /** 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" ); + } + + @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", "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() ); + } + + /** 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 { + 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" ); + } + + @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..41a68432d4 --- /dev/null +++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/acl/adv/RuleParserTest.java @@ -0,0 +1,122 @@ +/* + * 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.adv; + +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; + +import java.util.Set; + +/** + * Tests the parser of the expressions of advanced access rules. + */ +public class RuleParserTest { + + private static RuleNode parse( final String expression ) { + return new RuleParser( expression ).parse(); + } + + @Test + public void simpleOrStatement() { + 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() { + 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() { + 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() { + 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 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() ) ); + } + + @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() ); + } + + @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() ); + } + + @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 ) ); + } + +} 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 );