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;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Engine;
024import org.apache.wiki.api.core.Session;
025import org.apache.wiki.api.spi.SessionSPI;
026import org.apache.wiki.api.spi.Wiki;
027import org.apache.wiki.event.WikiEventListener;
028import org.apache.wiki.event.WikiEventManager;
029import org.apache.wiki.event.WikiSecurityEvent;
030import org.apache.wiki.util.Synchronizer;
031import org.apache.wiki.util.comparators.PrincipalComparator;
032
033import jakarta.servlet.http.HttpServletRequest;
034import jakarta.servlet.http.HttpSession;
035import jakarta.servlet.http.HttpSessionEvent;
036import jakarta.servlet.http.HttpSessionListener;
037import java.lang.ref.WeakReference;
038import java.security.Principal;
039import java.util.ArrayList;
040import java.util.Arrays;
041import java.util.Collection;
042import java.util.List;
043import java.util.Map;
044import java.util.WeakHashMap;
045import java.util.concurrent.ConcurrentHashMap;
046import java.util.concurrent.locks.ReentrantLock;
047import java.util.stream.Collectors;
048import org.apache.wiki.security.EventUtil;
049
050/**
051 *  <p>Manages Sessions for different Engines.</p>
052 *  <p>The Sessions are stored both in the remote user HttpSession and in the SessionMonitor for the Engine.
053 *  This class must be configured as a session listener in the web.xml for the wiki web application.</p>
054 */
055public class SessionMonitor implements HttpSessionListener {
056
057    private static final Logger LOG = LogManager.getLogger( SessionMonitor.class );
058
059    /** Map with Engines as keys, and SessionMonitors as values. */
060    private static final ConcurrentHashMap< Engine, SessionMonitor > c_monitors = new ConcurrentHashMap<>();
061
062    /** Weak hashmap with HttpSessions as keys, and WikiSessions as values. */
063    private final Map< String, Session > m_sessions = new WeakHashMap<>();
064
065    private Engine m_engine;
066
067    private final PrincipalComparator m_comparator = new PrincipalComparator();
068
069    /**
070     * A lock used to ensure thread safety when accessing shared resources.
071     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
072     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
073     * waiting to acquire a lock.
074     *
075     * @see ReentrantLock
076     */
077    private final ReentrantLock mSessionsLock = new ReentrantLock();
078    private final ReentrantLock listenerLock = new ReentrantLock();
079
080
081    /**
082     * Returns the instance of the SessionMonitor for this wiki. Only one SessionMonitor exists per Engine.
083     *
084     * @param engine the wiki engine
085     * @return the session monitor
086     */
087    public static SessionMonitor getInstance( final Engine engine ) {
088        if( engine == null ) {
089            throw new IllegalArgumentException( "Engine cannot be null." );
090        }
091        SessionMonitor monitor = c_monitors.get( engine );
092        if( monitor == null ) {
093            monitor = new SessionMonitor( engine );
094            c_monitors.put( engine, monitor );
095        }
096
097        return monitor;
098    }
099
100    /** Constructs the SessionListener; the servlet container needs it, as web.xml declares this class as a listener. */
101    public SessionMonitor() {
102    }
103
104    private SessionMonitor( final Engine engine ) {
105        m_engine = engine;
106    }
107
108    /**
109     *  Just looks for a WikiSession; does not create a new one.
110     * This method may return <code>null</code>, <em>and
111     * callers should check for this value</em>.
112     *
113     *  @param session the user's HTTP session
114     *  @return the WikiSession, if found
115     */
116    private Session findSession( final HttpSession session ) {
117        final String sid = ( session == null ) ? "(null)" : session.getId();
118        return findSession( sid );
119    }
120
121    /**
122     *  Just looks for a WikiSession; does not create a new one.
123     * This method may return <code>null</code>, <em>and
124     * callers should check for this value</em>.
125     *
126     *  @param sessionId the user's HTTP session id
127     *  @return the WikiSession, if found
128     */
129    private Session findSession( final String sessionId ) {
130        final String sid = ( sessionId == null ) ? "(null)" : sessionId;
131        final Session storedSession = Synchronizer.synchronize( mSessionsLock, () -> m_sessions.get( sid ) );
132
133        // If the weak reference returns a wiki session, return it
134        if( storedSession != null ) {
135            LOG.debug( "Looking up WikiSession for session ID={}... found it", sid );
136        }
137
138        return storedSession;
139    }
140
141    /**
142     * <p>Looks up the wiki session associated with a user's Http session and adds it to the session cache. This method will return the
143     * "guest session" as constructed by {@link SessionSPI#guest(Engine)} if the HttpSession is not currently
144     * associated with a WikiSession. This method is guaranteed to return a non-<code>null</code> WikiSession.</p>
145     * <p>Internally, the session is stored in a HashMap; keys are the HttpSession objects, while the values are
146     * {@link WeakReference}-wrapped WikiSessions.</p>
147     *
148     * @param session the HTTP session
149     * @return the wiki session
150     */
151    public final Session find( final HttpSession session ) {
152        final Session wikiSession = findSession( session );
153        final String sid = ( session == null ) ? "(null)" : session.getId();
154        if( wikiSession == null ) {
155            return createGuestSessionFor( sid );
156        }
157
158        return wikiSession;
159    }
160
161    /**
162     * <p>Looks up the wiki session associated with a user's Http session and adds it to the session cache. This method will return the
163     * "guest session" as constructed by {@link SessionSPI#guest(Engine)} if the HttpSession is not currently
164     * associated with a WikiSession. This method is guaranteed to return a non-<code>null</code> WikiSession.</p>
165     * <p>Internally, the session is stored in a HashMap; keys are the HttpSession objects, while the values are
166     * {@link WeakReference}-wrapped WikiSessions.</p>
167     *
168     * @param sessionId the HTTP session
169     * @return the wiki session
170     */
171    public final Session find( final String sessionId ) {
172        final Session wikiSession = findSession( sessionId );
173        if( wikiSession == null ) {
174            return createGuestSessionFor( sessionId );
175        }
176
177        return wikiSession;
178    }
179
180    /**
181     * Creates a new session and stashes it
182     *
183     * @param sessionId id looked for before creating the guest session
184     * @return a new guest session
185     */
186    private Session createGuestSessionFor( final String sessionId ) {
187        LOG.debug( "Session for session ID={}... not found. Creating guestSession()", sessionId );
188        final Session wikiSession = Wiki.session().guest( m_engine );
189        Synchronizer.synchronize( mSessionsLock, () -> {
190            m_sessions.put(sessionId, wikiSession);
191        } );
192        return wikiSession;
193    }
194
195    /**
196     * Removes the wiki session associated with the user's HttpRequest from the session cache.
197     *
198     * @param request the user's HTTP request
199     */
200    public final void remove( final HttpServletRequest request ) {
201        if( request == null ) {
202            throw new IllegalArgumentException( "Request cannot be null." );
203        }
204        remove( request.getSession() );
205    }
206
207    /**
208     * Removes the wiki session associated with the user's HttpSession from the session cache.
209     *
210     * @param session the user's HTTP session
211     */
212    public final void remove( final HttpSession session ) {
213        if( session == null ) {
214            throw new IllegalArgumentException( "Session cannot be null." );
215        }
216        Synchronizer.synchronize( mSessionsLock, () -> {
217            m_sessions.remove( session.getId() );
218        } );
219    }
220
221    /**
222     * (Re-)associates a wiki session with the user's current HTTP session id. Needed after the HTTP session id has
223     * been rotated at authentication time (session-fixation defense), so that the upgraded privileges attach to the
224     * new session id instead of the pre-login one.
225     *
226     * @param session the user's HTTP session, carrying its current id
227     * @param wikiSession the wiki session to register under that id
228     */
229    public final void register( final HttpSession session, final Session wikiSession ) {
230        if( session == null || wikiSession == null ) {
231            throw new IllegalArgumentException( "Session cannot be null." );
232        }
233        Synchronizer.synchronize( mSessionsLock, () -> m_sessions.put( session.getId(), wikiSession ) );
234    }
235
236    /**
237     * Returns the current number of active wiki sessions.
238     * @return the number of sessions
239     */
240    public final int sessions()
241    {
242        return userPrincipals().length;
243    }
244
245    /**
246     * <p>Returns the current wiki users as a sorted array of Principal objects. The principals are those returned by
247     * each WikiSession's {@link Session#getUserPrincipal()}'s method.</p>
248     * <p>To obtain the list of current WikiSessions, we iterate through our session Map and obtain the list of values,
249     * which are WikiSessions wrapped in {@link WeakReference} objects. Those <code>WeakReference</code>s
250     * whose <code>get()</code> method returns non-<code>null</code> values are valid sessions.</p>
251     *
252     * @return the array of user principals
253     */
254    public final Principal[] userPrincipals() {
255        final Collection< Principal > principals = Synchronizer.synchronize( mSessionsLock, () ->
256                m_sessions.values().stream().map( Session::getUserPrincipal ).collect( Collectors.toList() ) );
257
258        final Principal[] p = principals.toArray( new Principal[ 0 ] );
259        Arrays.sort( p, m_comparator );
260        return p;
261    }
262
263    /**
264     * Registers a WikiEventListener with this instance.
265     *
266     * @param listener the event listener
267     * @since 2.4.75
268     */
269    public final void addWikiEventListener( final WikiEventListener listener ) {
270        Synchronizer.synchronize( listenerLock, () -> {
271            WikiEventManager.addWikiEventListener( this, listener );
272        });
273    }
274
275    /**
276     * Un-registers a WikiEventListener with this instance.
277     *
278     * @param listener the event listener
279     * @since 2.4.75
280     */
281    public final void removeWikiEventListener(final WikiEventListener listener) {
282        Synchronizer.synchronize( listenerLock, () -> {
283            WikiEventManager.removeWikiEventListener(this, listener);
284        });
285    }
286
287    /**
288     * Fires a WikiSecurityEvent to all registered listeners.
289     *
290     * @param type  the event type
291     * @param principal the user principal associated with this session
292     * @param session the wiki session
293     * @since 2.4.75
294     */
295    protected final void fireEvent( final int type, final Principal principal, final Session session ) {
296        if( WikiEventManager.isListening( this ) ) {
297            WikiEventManager.fireEvent( this, 
298                    EventUtil.applyFrom(new WikiSecurityEvent( this, type, principal, session ) ) );
299        }
300    }
301
302    /**
303     * Fires when the web container creates a new HTTP session.
304     *
305     * @param se the HTTP session event
306     */
307    @Override
308    public void sessionCreated( final HttpSessionEvent se ) {
309        final HttpSession session = se.getSession();
310        LOG.debug( "Created session: " + session.getId() + "." );
311    }
312
313    /**
314     * Removes the user's WikiSession from the internal session cache when the web
315     * container destroys an HTTP session.
316     * @param se the HTTP session event
317     */
318    @Override
319    public void sessionDestroyed( final HttpSessionEvent se ) {
320        final HttpSession session = se.getSession();
321        for( final SessionMonitor monitor : c_monitors.values() ) {
322            final Session storedSession = monitor.findSession( session );
323            monitor.remove( session );
324            LOG.debug( "Removed session " + session.getId() + "." );
325            if( storedSession != null ) {
326                fireEvent( WikiSecurityEvent.SESSION_EXPIRED, storedSession.getLoginPrincipal(), storedSession );
327            }
328        }
329    }
330
331    /**
332     * gets a list of other sessions for the same login id for auditing purposes.
333     * 
334     * @since 3.0.0
335     * @param name
336     * @return list
337     */
338    public List<Session> findOtherSessionsByUsername(String name) {
339        List<Session> otherSessions = new ArrayList<>();
340        Synchronizer.synchronize( mSessionsLock, () -> {
341            for( final Session m : m_sessions.values() ) {
342                if( m.getLoginPrincipal().getName().equals( name ) ) {
343                    otherSessions.add( m );
344                }
345            }
346        } );
347        return otherSessions;
348    }
349
350}