001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.auth.acl;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Acl;
024import org.apache.wiki.api.core.AclEntry;
025import org.apache.wiki.api.core.Attachment;
026import org.apache.wiki.api.core.Context;
027import org.apache.wiki.api.core.Engine;
028import org.apache.wiki.api.core.Page;
029import org.apache.wiki.api.exceptions.ProviderException;
030import org.apache.wiki.api.spi.Wiki;
031import org.apache.wiki.auth.AuthorizationManager;
032import org.apache.wiki.auth.WikiSecurityException;
033import org.apache.wiki.auth.permissions.PagePermission;
034import org.apache.wiki.auth.permissions.PermissionFactory;
035import org.apache.wiki.pages.PageLock;
036import org.apache.wiki.pages.PageManager;
037import org.apache.wiki.render.RenderingManager;
038import org.apache.wiki.util.comparators.PrincipalComparator;
039
040import java.security.Permission;
041import java.security.Principal;
042import java.util.ArrayList;
043import java.util.Enumeration;
044import java.util.HashSet;
045import java.util.List;
046import java.util.Map;
047import java.util.NoSuchElementException;
048import java.util.Properties;
049import java.util.Set;
050import java.util.StringTokenizer;
051import java.util.TreeMap;
052import java.util.regex.Matcher;
053import java.util.regex.Pattern;
054
055/**
056 * Default implementation that parses Acls from wiki page markup.
057 *
058 * @since 2.3
059 */
060public class DefaultAclManager implements AclManager {
061
062    private static final Logger LOG = LogManager.getLogger(DefaultAclManager.class);
063
064    private AuthorizationManager m_auth;
065    private Engine m_engine;
066
067    /** The pages whose ACL this thread is reading right now. */
068    private final ThreadLocal< Set< String > > parsing = ThreadLocal.withInitial( HashSet::new );
069    private static final String PERM_REGEX = "("
070                                              + PagePermission.COMMENT_ACTION + "|"
071                                              + PagePermission.DELETE_ACTION  + "|"
072                                              + PagePermission.EDIT_ACTION    + "|"
073                                              + PagePermission.MODIFY_ACTION  + "|"
074                                              + PagePermission.RENAME_ACTION  + "|"
075                                              + PagePermission.UPLOAD_ACTION  + "|"
076                                              + PagePermission.VIEW_ACTION    +
077                                             ")";
078    private static final String ACL_REGEX = "\\[\\{\\s*ALLOW\\s+" + PERM_REGEX + "\\s*(.*?)\\s*\\}\\]";
079
080    /**
081     * Identifies ACL strings in wiki text; the first group is the action (view, edit) and
082     * the second is the list of Principals separated by commas. The overall match is
083     * the ACL string from [{ to }].
084     */
085    public static final Pattern ACL_PATTERN = Pattern.compile( ACL_REGEX );
086
087    /** {@inheritDoc} */
088    @Override
089    public void initialize( final Engine engine, final Properties props ) {
090        m_auth = engine.getManager( AuthorizationManager.class );
091        m_engine = engine;
092    }
093
094    /** {@inheritDoc} */
095    @Override
096    public Acl parseAcl( final Page page, final String ruleLine ) throws WikiSecurityException {
097        Acl acl = page.getAcl();
098        if (acl == null) {
099            acl = Wiki.acls().acl();
100        }
101
102        try {
103            final StringTokenizer fieldToks = new StringTokenizer(ruleLine);
104            fieldToks.nextToken();
105            final String actions = fieldToks.nextToken();
106
107            while( fieldToks.hasMoreTokens() ) {
108                final String principalName = fieldToks.nextToken(",").trim();
109                final Principal principal = m_auth.resolvePrincipal(principalName);
110                final AclEntry oldEntry = acl.getAclEntry(principal);
111
112                if( oldEntry != null ) {
113                    LOG.debug( "Adding to old acl list: " + principal + ", " + actions );
114                    oldEntry.addPermission( PermissionFactory.getPagePermission( page, actions ) );
115                } else {
116                    LOG.debug( "Adding new acl entry for " + actions );
117                    final AclEntry entry = Wiki.acls().entry();
118                    entry.setPrincipal( principal );
119                    entry.addPermission( PermissionFactory.getPagePermission( page, actions ) );
120
121                    acl.addEntry( entry );
122                }
123            }
124
125            page.setAcl( acl );
126            LOG.debug( acl.toString() );
127        } catch( final NoSuchElementException nsee ) {
128            LOG.warn( "Invalid access rule: " + ruleLine + " - defaults will be used." );
129            throw new WikiSecurityException( "Invalid access rule: " + ruleLine, nsee );
130        } catch( final IllegalArgumentException iae ) {
131            throw new WikiSecurityException("Invalid permission type: " + ruleLine, iae);
132        }
133
134        return acl;
135    }
136
137
138    /** {@inheritDoc} */
139    @Override
140    public Acl getPermissions( final Page page ) {
141        //  Does the page already have cached ACLs?
142        Acl acl = page.getAcl();
143        LOG.debug( "page=" + page.getName() + "\n" + acl );
144
145        if( acl == null ) {
146            //  If null, try the parent.
147            if( page instanceof Attachment ) {
148                final Page parent = m_engine.getManager( PageManager.class ).getPage( ( ( Attachment ) page ).getParentName() );
149                acl = getPermissions(parent);
150            } else {
151                //  Or, try parsing the page
152                final String key = page.getName() + ":" + page.getVersion();
153                if( !parsing.get().add( key ) ) {
154                    // A page filter asked for the permissions of this page while its ACL is being read; rendering it again would never end
155                    return Wiki.acls().acl();
156                }
157                try {
158                    final Context ctx = Wiki.context().create( m_engine, page );
159                    ctx.setVariable( Context.VAR_EXECUTE_PLUGINS, Boolean.FALSE );
160                    m_engine.getManager( RenderingManager.class ).getHTML(ctx, page);
161                } finally {
162                    parsing.get().remove( key );
163                }
164
165                if (page.getAcl() == null) {
166                    page.setAcl( Wiki.acls().acl() );
167                }
168                acl = page.getAcl();
169            }
170        }
171
172        return acl;
173    }
174
175    /** {@inheritDoc} */
176    @Override
177    public void setPermissions( final Page page, final Acl acl ) throws WikiSecurityException {
178        final PageManager pageManager = m_engine.getManager( PageManager.class );
179
180        // Forcibly expire any page locks
181        final PageLock lock = pageManager.getCurrentLock( page );
182        if( lock != null ) {
183            pageManager.unlockPage( lock );
184        }
185
186        // Remove all of the existing ACLs.
187        final String pageText = m_engine.getManager( PageManager.class ).getPureText( page );
188        final Matcher matcher = DefaultAclManager.ACL_PATTERN.matcher( pageText );
189        final String cleansedText = matcher.replaceAll("" );
190        final String newText = DefaultAclManager.printAcl( page.getAcl() ) + cleansedText;
191        try {
192            pageManager.putPageText( page, newText );
193        } catch( final ProviderException e ) {
194            throw new WikiSecurityException( "Could not set Acl. Reason: ProviderExcpetion " + e.getMessage(), e );
195        }
196    }
197
198    /**
199     * Generates an ACL string for inclusion in a wiki page, based on a supplied Acl object. All of the permissions in this Acl are
200     * assumed to apply to the same page scope. The names of the pages are ignored; only the actions and principals matter.
201     *
202     * @param acl the ACL
203     * @return the ACL string
204     */
205    protected static String printAcl( final Acl acl ) {
206        // Extract the ACL entries into a Map with keys == permissions, values == principals
207        final Map< String, List< Principal > > permissionPrincipals = new TreeMap<>();
208        final Enumeration< AclEntry > entries = acl.aclEntries();
209        while( entries.hasMoreElements() ) {
210            final AclEntry entry = entries.nextElement();
211            final Principal principal = entry.getPrincipal();
212            final Enumeration< Permission > permissions = entry.permissions();
213            while( permissions.hasMoreElements() ) {
214                final Permission permission = permissions.nextElement();
215                List< Principal > principals = permissionPrincipals.get( permission.getActions() );
216                if (principals == null) {
217                    principals = new ArrayList<>();
218                    final String action = permission.getActions();
219                    if( action.indexOf(',') != -1 ) {
220                        throw new IllegalStateException("AclEntry permission cannot have multiple targets.");
221                    }
222                    permissionPrincipals.put( action, principals );
223                }
224                principals.add( principal );
225            }
226        }
227
228        // Now, iterate through each permission in the map and generate an ACL string
229        final StringBuilder s = new StringBuilder();
230        for( final Map.Entry< String, List< Principal > > entry : permissionPrincipals.entrySet() ) {
231            final String action = entry.getKey();
232            final List< Principal > principals = entry.getValue();
233            principals.sort( new PrincipalComparator() );
234            s.append( "[{ALLOW " ).append( action ).append( " " );
235            for( int i = 0; i < principals.size(); i++ ) {
236                final Principal principal = principals.get( i );
237                s.append( principal.getName() );
238                if( i < ( principals.size() - 1 ) ) {
239                    s.append( "," );
240                }
241            }
242            s.append( "}]\n" );
243        }
244        return s.toString();
245    }
246
247}