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;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.logging.log4j.LogManager;
023import org.apache.logging.log4j.Logger;
024import org.apache.wiki.api.core.Engine;
025import org.apache.wiki.api.core.Session;
026import org.apache.wiki.auth.AuthenticationManager;
027import org.apache.wiki.auth.GroupPrincipal;
028import org.apache.wiki.auth.NoSuchPrincipalException;
029import org.apache.wiki.auth.SessionMonitor;
030import org.apache.wiki.auth.UserManager;
031import org.apache.wiki.auth.WikiPrincipal;
032import org.apache.wiki.auth.authorize.Group;
033import org.apache.wiki.auth.authorize.GroupManager;
034import org.apache.wiki.auth.authorize.Role;
035import org.apache.wiki.auth.user.UserDatabase;
036import org.apache.wiki.auth.user.UserProfile;
037import org.apache.wiki.event.WikiEvent;
038import org.apache.wiki.event.WikiSecurityEvent;
039import org.apache.wiki.util.HttpUtil;
040
041import javax.security.auth.Subject;
042import javax.servlet.http.HttpServletRequest;
043import javax.servlet.http.HttpSession;
044import java.security.Principal;
045import java.util.Arrays;
046import java.util.HashSet;
047import java.util.LinkedHashSet;
048import java.util.Locale;
049import java.util.Map;
050import java.util.Set;
051import java.util.UUID;
052import java.util.concurrent.ConcurrentHashMap;
053
054
055/**
056 * <p>Default implementation for {@link Session}.</p>
057 * <p>In addition to methods for examining individual <code>WikiSession</code> objects, this class also contains a number of static
058 * methods for managing WikiSessions for an entire wiki. These methods allow callers to find, query and remove WikiSession objects, and
059 * to obtain a list of the current wiki session users.</p>
060 */
061public class WikiSession implements Session {
062
063    private static final Logger LOG = LogManager.getLogger( WikiSession.class );
064
065    private static final String ALL = "*";
066
067    private static final ThreadLocal< Session > c_guestSession = new ThreadLocal<>();
068
069    private final Subject m_subject = new Subject();
070
071    private final Map< String, Set< String > > m_messages  = new ConcurrentHashMap<>();
072
073    /** The Engine that created this session. */
074    private Engine m_engine;
075
076    private String antiCsrfToken;
077    private String m_status            = ANONYMOUS;
078
079    private Principal m_userPrincipal  = WikiPrincipal.GUEST;
080
081    private Principal m_loginPrincipal = WikiPrincipal.GUEST;
082
083    private Locale m_cachedLocale      = Locale.getDefault();
084
085    /**
086     * Returns <code>true</code> if one of this WikiSession's user Principals can be shown to belong to a particular wiki group. If
087     * the user is not authenticated, this method will always return <code>false</code>.
088     *
089     * @param group the group to test
090     * @return the result
091     */
092    protected boolean isInGroup( final Group group ) {
093        return Arrays.stream(getPrincipals()).anyMatch(principal -> isAuthenticated() && group.isMember(principal));
094    }
095
096    /**
097     * Private constructor to prevent WikiSession from being instantiated directly.
098     */
099    private WikiSession() {
100    }
101
102    /** {@inheritDoc} */
103    @Override
104    public boolean isAsserted() {
105        return m_subject.getPrincipals().contains( Role.ASSERTED );
106    }
107
108    /** {@inheritDoc} */
109    @Override
110    public boolean isAuthenticated() {
111        // If Role.AUTHENTICATED is in principals set, always return true.
112        if ( m_subject.getPrincipals().contains( Role.AUTHENTICATED ) ) {
113            return true;
114        }
115
116        // With non-JSPWiki LoginModules, the role may not be there, so we need to add it if the user really is authenticated.
117        if ( !isAnonymous() && !isAsserted() ) {
118            m_subject.getPrincipals().add( Role.AUTHENTICATED );
119            return true;
120        }
121
122        return false;
123    }
124
125    /** {@inheritDoc} */
126    @Override
127    public boolean isAnonymous() {
128        final Set< Principal > principals = m_subject.getPrincipals();
129        return principals.contains( Role.ANONYMOUS ) ||
130               principals.contains( WikiPrincipal.GUEST ) ||
131               HttpUtil.isIPV4Address( getUserPrincipal().getName() );
132    }
133
134    /** {@inheritDoc} */
135    @Override
136    public Principal getLoginPrincipal() {
137        return m_loginPrincipal;
138    }
139
140    /** {@inheritDoc} */
141    @Override
142    public Principal getUserPrincipal() {
143        return m_userPrincipal;
144    }
145
146    /** {@inheritDoc} */
147    @Override
148    public String antiCsrfToken() {
149        return antiCsrfToken;
150    }
151
152    /**
153     * Regenerates the anti-CSRF token. Called when the session's privilege level changes (i.e. at login), so that
154     * a token observed before authentication cannot be replayed against the authenticated session.
155     */
156    @Override
157    public void regenerateAntiCsrfToken() {
158        antiCsrfToken = UUID.randomUUID().toString();
159    }
160
161    /** {@inheritDoc} */
162    @Override
163    public Locale getLocale() {
164        return m_cachedLocale;
165    }
166
167    /** {@inheritDoc} */
168    @Override
169    public void addMessage( final String message ) {
170        addMessage( ALL, message );
171    }
172
173    /** {@inheritDoc} */
174    @Override
175    public void addMessage( final String topic, final String message ) {
176        if ( topic == null ) {
177            throw new IllegalArgumentException( "addMessage: topic cannot be null." );
178        }
179        final Set< String > messages = m_messages.computeIfAbsent( topic, k -> new LinkedHashSet<>() );
180        messages.add( StringUtils.defaultString( message ) );
181    }
182
183    /** {@inheritDoc} */
184    @Override
185    public void clearMessages() {
186        m_messages.clear();
187    }
188
189    /** {@inheritDoc} */
190    @Override
191    public void clearMessages( final String topic ) {
192        final Set< String > messages = m_messages.get( topic );
193        if ( messages != null ) {
194            m_messages.clear();
195        }
196    }
197
198    /** {@inheritDoc} */
199    @Override
200    public String[] getMessages() {
201        return getMessages( ALL );
202    }
203
204    /** {@inheritDoc} */
205    @Override
206    public String[] getMessages( final String topic ) {
207        final Set< String > messages = m_messages.get( topic );
208        if( messages == null || messages.isEmpty()) {
209            return new String[ 0 ];
210        }
211        return messages.toArray( new String[0] );
212    }
213
214    /** {@inheritDoc} */
215    @Override
216    public Principal[] getPrincipals() {
217
218        // Take the first non Role as the main Principal
219
220        return m_subject.getPrincipals().stream().filter(AuthenticationManager::isUserPrincipal).toArray(Principal[]::new);
221    }
222
223    /** {@inheritDoc} */
224    @Override
225    public Principal[] getRoles() {
226        final Set< Principal > roles = new HashSet<>();
227
228        // Add all the Roles possessed by the Subject directly
229        roles.addAll( m_subject.getPrincipals( Role.class ) );
230
231        // Add all the GroupPrincipals possessed by the Subject directly
232        roles.addAll( m_subject.getPrincipals( GroupPrincipal.class ) );
233
234        // Return a defensive copy
235        final Principal[] roleArray = roles.toArray( new Principal[0] );
236        Arrays.sort( roleArray, WikiPrincipal.COMPARATOR );
237        return roleArray;
238    }
239
240    /** {@inheritDoc} */
241    @Override
242    public boolean hasPrincipal( final Principal principal ) {
243        return m_subject.getPrincipals().contains( principal );
244    }
245
246    /**
247     * Listens for WikiEvents generated by source objects such as the GroupManager, UserManager or AuthenticationManager. This method adds
248     * Principals to the private Subject managed by the WikiSession.
249     *
250     * @see org.apache.wiki.event.WikiEventListener#actionPerformed(WikiEvent)
251     */
252    @Override
253    public void actionPerformed( final WikiEvent event ) {
254        if ( event instanceof WikiSecurityEvent ) {
255            final WikiSecurityEvent e = (WikiSecurityEvent)event;
256            if ( e.getTarget() != null ) {
257                switch( e.getType() ) {
258                case WikiSecurityEvent.GROUP_ADD:
259                    final Group groupAdd = ( Group )e.getTarget();
260                    if( isInGroup( groupAdd ) ) {
261                        m_subject.getPrincipals().add( groupAdd.getPrincipal() );
262                    }
263                    break;
264                case WikiSecurityEvent.GROUP_REMOVE:
265                    final Group group = ( Group )e.getTarget();
266                    m_subject.getPrincipals().remove( group.getPrincipal() );
267                    break;
268                case WikiSecurityEvent.GROUP_CLEAR_GROUPS:
269                    m_subject.getPrincipals().removeAll( m_subject.getPrincipals( GroupPrincipal.class ) );
270                    break;
271                case WikiSecurityEvent.LOGIN_INITIATED:
272                    // Do nothing
273                    break;
274                case WikiSecurityEvent.PRINCIPAL_ADD:
275                    final WikiSession targetPA = ( WikiSession )e.getTarget();
276                    if( this.equals( targetPA ) && m_status.equals( AUTHENTICATED ) ) {
277                        final Set< Principal > principals = m_subject.getPrincipals();
278                        principals.add( ( Principal )e.getPrincipal() );
279                    }
280                    break;
281                case WikiSecurityEvent.LOGIN_ANONYMOUS:
282                    final WikiSession targetLAN = ( WikiSession )e.getTarget();
283                    if( this.equals( targetLAN ) ) {
284                        m_status = ANONYMOUS;
285
286                        // Set the login/user principals and login status
287                        final Set< Principal > principals = m_subject.getPrincipals();
288                        m_loginPrincipal = ( Principal )e.getPrincipal();
289                        m_userPrincipal = m_loginPrincipal;
290
291                        // Add the login principal to the Subject, and set the built-in roles
292                        principals.clear();
293                        principals.add( m_loginPrincipal );
294                        principals.add( Role.ALL );
295                        principals.add( Role.ANONYMOUS );
296                    }
297                    break;
298                case WikiSecurityEvent.LOGIN_ASSERTED:
299                    final WikiSession targetLAS = ( WikiSession )e.getTarget();
300                    if( this.equals( targetLAS ) ) {
301                        m_status = ASSERTED;
302
303                        // Set the login/user principals and login status
304                        final Set< Principal > principals = m_subject.getPrincipals();
305                        m_loginPrincipal = ( Principal )e.getPrincipal();
306                        m_userPrincipal = m_loginPrincipal;
307
308                        // Add the login principal to the Subject, and set the built-in roles
309                        principals.clear();
310                        principals.add( m_loginPrincipal );
311                        principals.add( Role.ALL );
312                        principals.add( Role.ASSERTED );
313                    }
314                    break;
315                case WikiSecurityEvent.LOGIN_AUTHENTICATED:
316                    final WikiSession targetLAU = ( WikiSession )e.getTarget();
317                    if( this.equals( targetLAU ) ) {
318                        m_status = AUTHENTICATED;
319
320                        // Set the login/user principals and login status
321                        final Set< Principal > principals = m_subject.getPrincipals();
322                        m_loginPrincipal = ( Principal )e.getPrincipal();
323                        m_userPrincipal = m_loginPrincipal;
324
325                        // Add the login principal to the Subject, and set the built-in roles
326                        principals.clear();
327                        principals.add( m_loginPrincipal );
328                        principals.add( Role.ALL );
329                        principals.add( Role.AUTHENTICATED );
330
331                        // Add the user and group principals
332                        injectUserProfilePrincipals();  // Add principals for the user profile
333                        injectGroupPrincipals();  // Inject group principals
334                    }
335                    break;
336                case WikiSecurityEvent.PROFILE_SAVE:
337                    final WikiSession sourcePS = e.getSrc();
338                    if( this.equals( sourcePS ) ) {
339                        injectUserProfilePrincipals();  // Add principals for the user profile
340                        injectGroupPrincipals();  // Inject group principals
341                    }
342                    break;
343                case WikiSecurityEvent.PROFILE_NAME_CHANGED:
344                    // Refresh user principals based on new user profile
345                    final WikiSession sourcePNC = e.getSrc();
346                    if( this.equals( sourcePNC ) && m_status.equals( AUTHENTICATED ) ) {
347                        // To prepare for refresh, set the new full name as the primary principal
348                        final UserProfile[] profiles = ( UserProfile[] )e.getTarget();
349                        final UserProfile newProfile = profiles[ 1 ];
350                        if( newProfile.getFullname() == null ) {
351                            throw new IllegalStateException( "User profile FullName cannot be null." );
352                        }
353
354                        final Set< Principal > principals = m_subject.getPrincipals();
355                        m_loginPrincipal = new WikiPrincipal( newProfile.getLoginName() );
356
357                        // Add the login principal to the Subject, and set the built-in roles
358                        principals.clear();
359                        principals.add( m_loginPrincipal );
360                        principals.add( Role.ALL );
361                        principals.add( Role.AUTHENTICATED );
362
363                        // Add the user and group principals
364                        injectUserProfilePrincipals();  // Add principals for the user profile
365                        injectGroupPrincipals();  // Inject group principals
366                    }
367                    break;
368
369                //  No action, if the event is not recognized.
370                default:
371                    break;
372                }
373            }
374        }
375    }
376
377    /** {@inheritDoc} */
378    @Override
379    public void invalidate() {
380        m_subject.getPrincipals().clear();
381        m_subject.getPrincipals().add( WikiPrincipal.GUEST );
382        m_subject.getPrincipals().add( Role.ANONYMOUS );
383        m_subject.getPrincipals().add( Role.ALL );
384        m_userPrincipal = WikiPrincipal.GUEST;
385        m_loginPrincipal = WikiPrincipal.GUEST;
386    }
387
388    /**
389     * Injects GroupPrincipal objects into the user's Principal set based on the groups the user belongs to. For Groups, the algorithm
390     * first calls the {@link GroupManager#getRoles()} to obtain the array of GroupPrincipals the authorizer knows about. Then, the
391     * method {@link GroupManager#isUserInRole(Session, Principal)} is called for each Principal. If the user is a member of the
392     * group, an equivalent GroupPrincipal is injected into the user's principal set. Existing GroupPrincipals are flushed and replaced.
393     * This method should generally be called after a user's {@link org.apache.wiki.auth.user.UserProfile} is saved. If the wiki session
394     * is null, or there is no matching user profile, the method returns silently.
395     */
396    protected void injectGroupPrincipals() {
397        // Flush the existing GroupPrincipals
398        m_subject.getPrincipals().removeAll( m_subject.getPrincipals(GroupPrincipal.class) );
399
400        // Get the GroupManager and test for each Group
401        final GroupManager manager = m_engine.getManager( GroupManager.class );
402        for( final Principal group : manager.getRoles() ) {
403            if ( manager.isUserInRole( this, group ) ) {
404                m_subject.getPrincipals().add( group );
405            }
406        }
407    }
408
409    /**
410     * Adds Principal objects to the Subject that correspond to the logged-in user's profile attributes for the wiki name, full name
411     * and login name. These Principals will be WikiPrincipals, and they will replace all other WikiPrincipals in the Subject. <em>Note:
412     * this method is never called during anonymous or asserted sessions.</em>
413     */
414    protected void injectUserProfilePrincipals() {
415        // Search for the user profile
416        final String searchId = m_loginPrincipal.getName();
417        if ( searchId == null ) {
418            // Oh dear, this wasn't an authenticated user after all
419            LOG.info("Refresh principals failed because WikiSession had no user Principal; maybe not logged in?");
420            return;
421        }
422
423        // Look up the user and go get the new Principals
424        final UserDatabase database = m_engine.getManager( UserManager.class ).getUserDatabase();
425        if( database == null ) {
426            throw new IllegalStateException( "User database cannot be null." );
427        }
428        try {
429            final UserProfile profile = database.find( searchId );
430            final Principal[] principals = database.getPrincipals( profile.getLoginName() );
431            for( final Principal principal : principals ) {
432                // Add the Principal to the Subject
433                m_subject.getPrincipals().add( principal );
434
435                // Set the user principal if needed; we prefer FullName, but the WikiName will also work
436                final boolean isFullNamePrincipal = ( principal instanceof WikiPrincipal &&
437                                                      ( ( WikiPrincipal )principal ).getType().equals( WikiPrincipal.FULL_NAME ) );
438                if ( isFullNamePrincipal ) {
439                   m_userPrincipal = principal;
440                } else if ( !( m_userPrincipal instanceof WikiPrincipal ) ) {
441                    m_userPrincipal = principal;
442                }
443            }
444        } catch ( final NoSuchPrincipalException e ) {
445            // We will get here if the user has a principal but not a profile
446            // For example, it's a container-managed user who hasn't set up a profile yet
447            LOG.warn("User profile '" + searchId + "' not found. This is normal for container-auth users who haven't set up a profile yet.");
448        }
449    }
450
451    /** {@inheritDoc} */
452    @Override
453    public String getStatus() {
454        return m_status;
455    }
456
457    /** {@inheritDoc} */
458    @Override
459    public Subject getSubject() {
460        return m_subject;
461    }
462
463    /**
464     * Removes the wiki session associated with the user's HTTP request from the cache of wiki sessions, typically as part of a
465     * logout process.
466     *
467     * @param engine the wiki engine
468     * @param request the user's HTTP request
469     */
470    public static void removeWikiSession( final Engine engine, final HttpServletRequest request ) {
471        if ( engine == null || request == null ) {
472            throw new IllegalArgumentException( "Request or engine cannot be null." );
473        }
474        final SessionMonitor monitor = SessionMonitor.getInstance( engine );
475        monitor.remove( request.getSession() );
476        c_guestSession.remove();
477    }
478
479    /**
480     * <p>Static factory method that returns the Session object associated with the current HTTP request. This method looks up
481     * the associated HttpSession in an internal WeakHashMap and attempts to retrieve the WikiSession. If not found, one is created.
482     * This method is guaranteed to always return a Session, although the authentication status is unpredictable until the user
483     * attempts to log in. If the servlet request parameter is <code>null</code>, a synthetic {@link #guestSession(Engine)} is
484     * returned.</p>
485     * <p>When a session is created, this method attaches a WikiEventListener to the GroupManager, UserManager and AuthenticationManager,
486     * so that changes to users, groups, logins, etc. are detected automatically.</p>
487     *
488     * @param engine the engine
489     * @param request the servlet request object
490     * @return the existing (or newly created) session
491     */
492    public static Session getWikiSession( final Engine engine, final HttpServletRequest request ) {
493        if ( request == null ) {
494            LOG.debug( "Looking up WikiSession for NULL HttpRequest: returning guestSession()" );
495            return staticGuestSession( engine );
496        }
497
498        // Look for a WikiSession associated with the user's Http Session and create one if it isn't there yet.
499        final HttpSession session = request.getSession();
500        final SessionMonitor monitor = SessionMonitor.getInstance( engine );
501        final WikiSession wikiSession = ( WikiSession )monitor.find( session );
502
503        // Attach reference to wiki engine
504        wikiSession.m_engine = engine;
505        wikiSession.m_cachedLocale = request.getLocale();
506        return wikiSession;
507    }
508
509    /**
510     * Static factory method that creates a new "guest" session containing a single user Principal
511     * {@link org.apache.wiki.auth.WikiPrincipal#GUEST}, plus the role principals {@link Role#ALL} and {@link Role#ANONYMOUS}. This
512     * method also adds the session as a listener for GroupManager, AuthenticationManager and UserManager events.
513     *
514     * @param engine the wiki engine
515     * @return the guest wiki session
516     */
517    public static Session guestSession( final Engine engine ) {
518        final WikiSession session = new WikiSession();
519        session.m_engine = engine;
520        session.invalidate();
521        session.antiCsrfToken = UUID.randomUUID().toString();
522
523        // Add the session as listener for GroupManager, AuthManager, UserManager events
524        final GroupManager groupMgr = engine.getManager( GroupManager.class );
525        final AuthenticationManager authMgr = engine.getManager( AuthenticationManager.class );
526        final UserManager userMgr = engine.getManager( UserManager.class );
527        groupMgr.addWikiEventListener( session );
528        authMgr.addWikiEventListener( session );
529        userMgr.addWikiEventListener( session );
530
531        return session;
532    }
533
534    /**
535     *  Returns a static guest session, which is available for this thread only.  This guest session is used internally whenever
536     *  there is no HttpServletRequest involved, but the request is done e.g. when embedding JSPWiki code.
537     *
538     *  @param engine Engine for this session
539     *  @return A static WikiSession which is shared by all in this same Thread.
540     */
541    // FIXME: Should really use WeakReferences to clean away unused sessions.
542    private static Session staticGuestSession( final Engine engine ) {
543        Session session = c_guestSession.get();
544        if( session == null ) {
545            session = guestSession( engine );
546            c_guestSession.set( session );
547        }
548
549        return session;
550    }
551
552    /**
553     * Returns the total number of active wiki sessions for a particular wiki. This method delegates to the wiki's
554     * {@link SessionMonitor#sessions()} method.
555     *
556     * @param engine the wiki session
557     * @return the number of sessions
558     * @deprecated use {@link SessionMonitor#sessions()} instead
559     * @see SessionMonitor#sessions()
560     */
561    @Deprecated
562    public static int sessions( final Engine engine ) {
563        final SessionMonitor monitor = SessionMonitor.getInstance( engine );
564        return monitor.sessions();
565    }
566
567    /**
568     * Returns Principals representing the current users known to a particular wiki. Each Principal will correspond to the
569     * value returned by each WikiSession's {@link #getUserPrincipal()} method. This method delegates to
570     * {@link SessionMonitor#userPrincipals()}.
571     *
572     * @param engine the wiki engine
573     * @return an array of Principal objects, sorted by name
574     * @deprecated use {@link SessionMonitor#userPrincipals()} instead
575     * @see SessionMonitor#userPrincipals()
576     */
577    @Deprecated
578    public static Principal[] userPrincipals( final Engine engine ) {
579        final SessionMonitor monitor = SessionMonitor.getInstance( engine );
580        return monitor.userPrincipals();
581    }
582
583}