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.authorize;
020
021import org.apache.commons.lang3.ArrayUtils;
022import org.apache.logging.log4j.LogManager;
023import org.apache.logging.log4j.Logger;
024import org.apache.wiki.api.core.Context;
025import org.apache.wiki.api.core.Engine;
026import org.apache.wiki.api.core.Session;
027import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
028import org.apache.wiki.api.exceptions.WikiException;
029import org.apache.wiki.auth.AuthenticationManager;
030import org.apache.wiki.auth.Authorizer;
031import org.apache.wiki.auth.GroupPrincipal;
032import org.apache.wiki.auth.NoSuchPrincipalException;
033import org.apache.wiki.auth.UserManager;
034import org.apache.wiki.auth.WikiPrincipal;
035import org.apache.wiki.auth.WikiSecurityException;
036import org.apache.wiki.auth.user.UserProfile;
037import org.apache.wiki.event.WikiEvent;
038import org.apache.wiki.event.WikiEventListener;
039import org.apache.wiki.event.WikiEventManager;
040import org.apache.wiki.event.WikiSecurityEvent;
041import org.apache.wiki.ui.InputValidator;
042import org.apache.wiki.ui.Installer;
043import org.apache.wiki.util.ClassUtil;
044import org.apache.wiki.util.Synchronizer;
045
046import java.security.Principal;
047import java.util.Arrays;
048import java.util.HashSet;
049import java.util.Map;
050import java.util.Properties;
051import java.util.Set;
052import java.util.StringTokenizer;
053import java.util.concurrent.ConcurrentHashMap;
054import java.util.concurrent.locks.ReentrantLock;
055
056
057/**
058 * <p>
059 * Facade class for storing, retrieving and managing wiki groups on behalf of AuthorizationManager, JSPs and other presentation-layer
060 * classes. GroupManager works in collaboration with a back-end {@link GroupDatabase}, which persists groups to permanent storage.
061 * </p>
062 * <p>
063 * <em>Note: prior to JSPWiki 2.4.19, GroupManager was an interface; it is now a concrete, final class. The aspects of GroupManager
064 * which previously extracted group information from storage (e.g., wiki pages) have been refactored into the GroupDatabase interface.</em>
065 * </p>
066 * @since 2.4.19
067 */
068public class DefaultGroupManager implements GroupManager, Authorizer, WikiEventListener {
069
070    private static final Logger LOG = LogManager.getLogger( DefaultGroupManager.class );
071
072    protected Engine m_engine;
073
074    protected WikiEventListener m_groupListener;
075
076    private GroupDatabase m_groupDatabase;
077
078    /** Map with GroupPrincipals as keys, and Groups as values */
079    private final Map< Principal, Group > m_groups = new ConcurrentHashMap<>();
080
081    /**
082     * A lock used to ensure thread safety when accessing shared resources.
083     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
084     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
085     * waiting to acquire a lock.
086     *
087     * @see java.util.concurrent.locks.ReentrantLock
088     */
089    private final ReentrantLock wikiEventListenerLock = new ReentrantLock();
090
091    /** {@inheritDoc} */
092    @Override
093    public Principal findRole( final String name ) {
094        try {
095            final Group group = getGroup( name );
096            return group.getPrincipal();
097        } catch( final NoSuchPrincipalException e ) {
098            LOG.debug(e.getMessage(), e);
099            return null;
100        }
101    }
102
103    /** {@inheritDoc} */
104    @Override
105    public Group getGroup( final String name ) throws NoSuchPrincipalException {
106        final Group group = m_groups.get( new GroupPrincipal( name ) );
107        if( group != null ) {
108            return group;
109        }
110        throw new NoSuchPrincipalException( "Group " + name + " not found." );
111    }
112
113    /** {@inheritDoc} */
114    @Override
115    public GroupDatabase getGroupDatabase() throws WikiSecurityException {
116        if( m_groupDatabase != null ) {
117            return m_groupDatabase;
118        }
119
120        String dbClassName = "<unknown>";
121        String dbInstantiationError = null;
122        Throwable cause = null;
123        try {
124            final Properties props = m_engine.getWikiProperties();
125            dbClassName = props.getProperty( PROP_GROUPDATABASE );
126            if( dbClassName == null ) {
127                dbClassName = XMLGroupDatabase.class.getName();
128            }
129            LOG.info( "Attempting to load group database class {}", dbClassName );
130            m_groupDatabase = ClassUtil.buildInstance( "org.apache.wiki.auth.authorize", dbClassName );
131            m_groupDatabase.initialize( m_engine, m_engine.getWikiProperties() );
132            LOG.info( "Group database initialized." );
133        } catch( final ReflectiveOperationException e ) {
134            LOG.error( "UserDatabase {} cannot be instantiated", dbClassName, e );
135            dbInstantiationError = "Access GroupDatabase class " + dbClassName + " denied";
136            cause = e;
137        } catch( final NoRequiredPropertyException e ) {
138            LOG.error( "Missing property: " + e.getMessage() + "." );
139            dbInstantiationError = "Missing property: " + e.getMessage();
140            cause = e;
141        }
142
143        if( dbInstantiationError != null ) {
144            throw new WikiSecurityException( dbInstantiationError + " Cause: " + cause.getMessage(), cause );
145        }
146
147        return m_groupDatabase;
148    }
149
150    /** {@inheritDoc} */
151    @Override
152    public Principal[] getRoles() {
153        return m_groups.keySet().toArray( new Principal[0] );
154    }
155
156    /** {@inheritDoc} */
157    @Override
158    public void initialize( final Engine engine, final Properties props ) throws WikiSecurityException {
159        m_engine = engine;
160
161        try {
162            m_groupDatabase = getGroupDatabase();
163        } catch( final WikiException e ) {
164            throw new WikiSecurityException( e.getMessage(), e );
165        }
166
167        // Load all groups from the database into the cache
168        final Group[] groups = m_groupDatabase.groups();
169        for( final Group group : groups ) {
170            // Add new group to cache; fire GROUP_ADD event
171            m_groups.put( group.getPrincipal(), group );
172            fireEvent( WikiSecurityEvent.GROUP_ADD, group );
173        }
174
175        // Make the GroupManager listen for WikiEvents (WikiSecurityEvents for changed user profiles)
176        engine.getManager( UserManager.class ).addWikiEventListener( this );
177
178        // Success!
179        LOG.info( "Authorizer GroupManager initialized successfully; loaded " + groups.length + " group(s)." );
180    }
181
182    /** {@inheritDoc} */
183    @Override
184    public boolean isUserInRole( final Session session, final Principal role ) {
185        // Always return false if session/role is null, or if role isn't a GroupPrincipal
186        if ( session == null || !( role instanceof GroupPrincipal ) || !session.isAuthenticated() ) {
187            return false;
188        }
189
190        // Get the group we're examining
191        final Group group = m_groups.get( role );
192        if( group == null ) {
193            return false;
194        }
195
196        // Check each user principal to see if it belongs to the group
197        return Arrays.stream(session.getPrincipals()).anyMatch(principal -> AuthenticationManager.isUserPrincipal(principal) && group.isMember(principal));
198    }
199
200    /** {@inheritDoc} */
201    @Override
202    public Group parseGroup( String name, String memberLine, final boolean create ) throws WikiSecurityException {
203        // If null name parameter, it's because someone's creating a new group
204        if( name == null ) {
205            if( create ) {
206                name = "MyGroup";
207            } else {
208                //TODO i18n
209                throw new WikiSecurityException( "Group name cannot be blank." );
210            }
211        } else if( ArrayUtils.contains( Group.RESTRICTED_GROUPNAMES, name ) ) {
212            // Certain names are forbidden
213            throw new WikiSecurityException( "Illegal group name: " + name );
214        }
215        name = name.trim();
216
217        // Normalize the member line
218        if( InputValidator.isBlank( memberLine ) ) {
219            memberLine = "";
220        }
221        memberLine = memberLine.trim();
222
223        // Create or retrieve the group (may have been previously cached)
224        final Group group = new Group( name, m_engine.getApplicationName() );
225        try {
226            final Group existingGroup = getGroup( name );
227
228            // If existing, clone it
229            group.setCreator( existingGroup.getCreator() );
230            group.setCreated( existingGroup.getCreated() );
231            group.setModifier( existingGroup.getModifier() );
232            group.setLastModified( existingGroup.getLastModified() );
233            for( final Principal existingMember : existingGroup.members() ) {
234                group.add( existingMember );
235            }
236        } catch( final NoSuchPrincipalException e ) {
237            // It's a new group.... throw error if we don't create new ones
238            if( !create ) {
239                //TODO i18n
240                throw new NoSuchPrincipalException( "Group '" + name + "' does not exist." );
241            }
242        }
243
244        // If passed members not empty, overwrite
245        final String[] members = extractMembers( memberLine );
246        if( members.length > 0 ) {
247            group.clear();
248            for( final String member : members ) {
249                group.add( new WikiPrincipal( member ) );
250            }
251        }
252        
253        if( "false".equalsIgnoreCase( m_engine.getWikiProperties().getProperty( Engine.PROP_USE_2_X_ACL_LOGIC, "false" ) ) ) {
254            // check to ensure that the group name does not conflict with any existing user account login, email or wiki name
255            final UserManager userManager = m_engine.getManager( UserManager.class );
256            try {
257                userManager.getUserDatabase().findByEmail( name );
258                throw new WikiSecurityException( "Group name conflicts with a user account" );
259            } catch( final NoSuchPrincipalException e ) {
260                // no issues here
261            }
262            try {
263                userManager.getUserDatabase().findByLoginName( name );
264                throw new WikiSecurityException( "Group name conflicts with a user account" );
265            } catch( final NoSuchPrincipalException e ) {
266                // no issues here
267            }
268            try {
269                userManager.getUserDatabase().findByWikiName( name );
270                throw new WikiSecurityException( "Group name conflicts with a user account" );
271            }catch( final NoSuchPrincipalException e ) {
272                // no issues here
273            }
274        }
275
276        return group;
277    }
278
279    /** {@inheritDoc} */
280    @Override
281    public void removeGroup( final String index ) throws WikiSecurityException {
282        if( index == null ) {
283            throw new IllegalArgumentException( "Group cannot be null." );
284        }
285
286        final Group group = m_groups.get( new GroupPrincipal( index ) );
287        if( group == null ) {
288            throw new NoSuchPrincipalException( "Group " + index + " not found" );
289        }
290
291        // the default security policy grants AllPermission to this group, so removing it could leave the wiki without administrators
292        if( Installer.ADMIN_GROUP.equals( index ) ) {
293            throw new WikiSecurityException( "The " + Installer.ADMIN_GROUP + " group cannot be removed" );
294        }
295
296        // Delete the group
297        // TODO: need rollback procedure
298        m_groups.remove( group.getPrincipal() );
299        m_groupDatabase.delete( group );
300        fireEvent( WikiSecurityEvent.GROUP_REMOVE, group );
301    }
302
303    /** {@inheritDoc} */
304    @Override
305    public void setGroup( final Session session, final Group group ) throws WikiSecurityException {
306        // TODO: check for appropriate permissions
307
308        // If group already exists, delete it; fire GROUP_REMOVE event
309        final Group oldGroup = m_groups.get( group.getPrincipal() );
310        if( oldGroup != null ) {
311            fireEvent( WikiSecurityEvent.GROUP_REMOVE, oldGroup );
312            m_groups.remove( oldGroup.getPrincipal() );
313        }
314
315        // Copy existing modifier info & timestamps
316        if( oldGroup != null ) {
317            group.setCreator( oldGroup.getCreator() );
318            group.setCreated( oldGroup.getCreated() );
319            group.setModifier( oldGroup.getModifier() );
320            group.setLastModified( oldGroup.getLastModified() );
321        }
322
323        // Add new group to cache; announce GROUP_ADD event
324        m_groups.put( group.getPrincipal(), group );
325        fireEvent( WikiSecurityEvent.GROUP_ADD, group );
326
327        // Save the group to back-end database; if it fails, roll back to previous state. Note that the back-end
328        // MUST timestamp the create/modify fields in the Group.
329        try {
330            m_groupDatabase.save( group, session.getUserPrincipal() );
331        }
332
333        // We got an exception! Roll back...
334        catch( final WikiSecurityException e ) {
335            LOG.warn("setGroup failed, rolling back changes", e);
336            if( oldGroup != null ) {
337                // Restore previous version, re-throw...
338                fireEvent( WikiSecurityEvent.GROUP_REMOVE, group );
339                fireEvent( WikiSecurityEvent.GROUP_ADD, oldGroup );
340                m_groups.put( oldGroup.getPrincipal(), oldGroup );
341                throw new WikiSecurityException( e.getMessage() + " (rolled back to previous version).", e );
342            }
343            // Re-throw security exception
344            throw new WikiSecurityException( e.getMessage(), e );
345        }
346    }
347
348    /** {@inheritDoc} */
349    @Override
350    public void validateGroup( final Context context, final Group group ) {
351        final InputValidator validator = new InputValidator( MESSAGES_KEY, context );
352
353        // Name cannot be null or one of the restricted names
354        try {
355            checkGroupName( context, group.getName() );
356        } catch( final WikiSecurityException e ) {
357            LOG.debug(e.getMessage(), e);
358        }
359
360        // Member names must be "safe" strings
361        final Principal[] members = group.members();
362        for( final Principal member : members ) {
363            validator.validateNotNull( member.getName(), "Full name", InputValidator.ID );
364        }
365    }
366
367    /** {@inheritDoc} */
368    @Override
369    public void checkGroupName( final Context context, final String name ) throws WikiSecurityException {
370        // TODO: groups cannot have the same name as a user
371
372        // Name cannot be null
373        final InputValidator validator = new InputValidator( MESSAGES_KEY, context );
374        validator.validateNotNull( name, "Group name" );
375
376        // Name cannot be one of the restricted names either
377        if( ArrayUtils.contains( Group.RESTRICTED_GROUPNAMES, name ) ) {
378            throw new WikiSecurityException( "The group name '" + name + "' is illegal. Choose another." );
379        }
380    }
381
382    /**
383     * Extracts carriage-return separated members into a Set of String objects.
384     *
385     * @param memberLine the list of members
386     * @return the list of members
387     */
388    protected String[] extractMembers( final String memberLine ) {
389        final Set< String > members = new HashSet<>();
390        if( memberLine != null ) {
391            final StringTokenizer tok = new StringTokenizer( memberLine, "\n" );
392            while( tok.hasMoreTokens() ) {
393                final String uid = tok.nextToken().trim();
394                if( !uid.isEmpty() ) {
395                    members.add( uid );
396                }
397            }
398        }
399        return members.toArray( new String[0] );
400    }
401
402    // events processing .......................................................
403
404    /** {@inheritDoc} */
405    @Override
406    public void addWikiEventListener( final WikiEventListener listener ) {
407        Synchronizer.synchronize( wikiEventListenerLock, () -> {
408            WikiEventManager.addWikiEventListener( this, listener );
409        } );
410    }
411
412    /** {@inheritDoc} */
413    @Override
414    public void removeWikiEventListener( final WikiEventListener listener ) {
415        Synchronizer.synchronize( wikiEventListenerLock, () -> {
416            WikiEventManager.removeWikiEventListener( this, listener );
417        } );
418    }
419
420    /** {@inheritDoc} */
421    @Override
422    public void actionPerformed( final WikiEvent event ) {
423        if( !( event instanceof WikiSecurityEvent ) ) {
424            return;
425        }
426
427        final WikiSecurityEvent se = ( WikiSecurityEvent )event;
428        if( se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED ) {
429            final Session session = se.getSrc();
430            final UserProfile[] profiles = ( UserProfile[] )se.getTarget();
431            final Principal[] oldPrincipals = new Principal[] { new WikiPrincipal( profiles[ 0 ].getLoginName() ),
432                    new WikiPrincipal( profiles[ 0 ].getFullname() ), new WikiPrincipal( profiles[ 0 ].getWikiName() ) };
433            final Principal newPrincipal = new WikiPrincipal( profiles[ 1 ].getFullname() );
434
435            // Examine each group
436            int groupsChanged = 0;
437            try {
438                for( final Group group : m_groupDatabase.groups() ) {
439                    boolean groupChanged = false;
440                    for( final Principal oldPrincipal : oldPrincipals ) {
441                        if( group.isMember( oldPrincipal ) ) {
442                            group.remove( oldPrincipal );
443                            group.add( newPrincipal );
444                            groupChanged = true;
445                        }
446                    }
447                    if( groupChanged ) {
448                        setGroup( session, group );
449                        groupsChanged++;
450                    }
451                }
452            } catch( final WikiException e ) {
453                // Oooo! This is really bad...
454                LOG.error( "Could not change user name in Group lists because of GroupDatabase error:" + e.getMessage() );
455            }
456            LOG.info( "Profile name change for '" + newPrincipal + "' caused " + groupsChanged + " groups to change also." );
457        }
458    }
459
460}