001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-2022 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.http;
020
021import java.lang.management.ManagementFactory;
022import java.lang.ref.WeakReference;
023import java.net.HttpCookie;
024import java.security.SecureRandom;
025import java.time.Duration;
026import java.time.Instant;
027import java.util.HashSet;
028import java.util.Optional;
029import java.util.Set;
030import java.util.function.Supplier;
031import javax.management.InstanceAlreadyExistsException;
032import javax.management.InstanceNotFoundException;
033import javax.management.MBeanRegistrationException;
034import javax.management.MBeanServer;
035import javax.management.MalformedObjectNameException;
036import javax.management.NotCompliantMBeanException;
037import javax.management.ObjectName;
038import org.jdrupes.httpcodec.protocols.http.HttpField;
039import org.jdrupes.httpcodec.protocols.http.HttpRequest;
040import org.jdrupes.httpcodec.protocols.http.HttpResponse;
041import org.jdrupes.httpcodec.types.CacheControlDirectives;
042import org.jdrupes.httpcodec.types.Converters;
043import org.jdrupes.httpcodec.types.Converters.SameSiteAttribute;
044import org.jdrupes.httpcodec.types.CookieList;
045import org.jdrupes.httpcodec.types.Directive;
046import org.jgrapes.core.Associator;
047import org.jgrapes.core.Channel;
048import org.jgrapes.core.Component;
049import org.jgrapes.core.Components;
050import org.jgrapes.core.Components.Timer;
051import org.jgrapes.core.annotation.Handler;
052import org.jgrapes.core.internal.ComponentVertex;
053import org.jgrapes.core.internal.EventBase;
054import org.jgrapes.http.annotation.RequestHandler;
055import org.jgrapes.http.events.DiscardSession;
056import org.jgrapes.http.events.ProtocolSwitchAccepted;
057import org.jgrapes.http.events.Request;
058import org.jgrapes.io.IOSubchannel;
059
060/**
061 * A base class for session managers. A session manager associates 
062 * {@link Request} events with a 
063 * {@link Supplier {@code Supplier<Optional<Session>>}}
064 * for a {@link Session} using `Session.class` as association identifier
065 * (see {@link Session#from}). Note that the `Optional` will never by
066 * empty. The return type has been chosen to be in accordance with
067 * {@link Associator#associatedGet(Class)}.
068 * 
069 * The {@link Request} handler has a default priority of 1000.
070 * 
071 * Managers track requests using a cookie with a given name and path. The 
072 * path is a prefix that has to be matched by the request, often "/".
073 * If no cookie with the given name (see {@link #idName()}) is found,
074 * a new cookie with that name and the specified path is created.
075 * The cookie's value is the unique session id that is used to lookup
076 * the session object.
077 * 
078 * Session managers provide additional support for web sockets. If a
079 * web socket is accepted, the session associated with the request
080 * is automatically made available to the {@link IOSubchannel} that
081 * is subsequently used for the web socket events. This allows
082 * handlers for web socket messages to access the session like
083 * {@link Request} handlers (see {@link #onProtocolSwitchAccepted}).
084 * 
085 * @see EventBase#setAssociated(Object, Object)
086 * @see "[OWASP Session Management Cheat Sheet](https://www.owasp.org/index.php/Session_Management_Cheat_Sheet)"
087 */
088@SuppressWarnings({ "PMD.AvoidPrintStackTrace", "PMD.TooManyMethods",
089    "PMD.CouplingBetweenObjects", "PMD.AvoidSynchronizedStatement" })
090public abstract class SessionManager extends Component {
091
092    private static SecureRandom secureRandom = new SecureRandom();
093
094    private String idName = "id";
095    private String path = "/";
096    private long absoluteTimeout = 9 * 60 * 60 * 1000;
097    private long idleTimeout = 30 * 60 * 1000;
098    private int maxSessions = 1000;
099    private Timer nextPurge;
100
101    /**
102     * Creates a new session manager with its channel set to
103     * itself and the path set to "/". The manager handles
104     * all {@link Request} events.
105     */
106    public SessionManager() {
107        this("/");
108    }
109
110    /**
111     * Creates a new session manager with its channel set to
112     * itself and the path set to the given path. The manager
113     * handles all requests that match the given path, using the
114     * same rules as browsers do for selecting the cookies that
115     * are to be sent.
116     * 
117     * @param path the path
118     */
119    public SessionManager(String path) {
120        this(SELF, path);
121    }
122
123    /**
124     * Creates a new session manager with its channel set to
125     * the given channel and the path to "/". The manager handles
126     * all {@link Request} events.
127     * 
128     * @param componentChannel the component channel
129     */
130    public SessionManager(Channel componentChannel) {
131        this(componentChannel, "/");
132    }
133
134    /**
135     * Creates a new session manager with the given channel and path.
136     * The manager handles all requests that match the given path, using
137     * the same rules as browsers do for selecting the cookies that
138     * are to be sent.
139     *  
140     * @param componentChannel the component channel
141     * @param path the path
142     */
143    public SessionManager(Channel componentChannel, String path) {
144        this(componentChannel, derivePattern(path), 1000, path);
145    }
146
147    /**
148     * Returns the path.
149     *
150     * @return the string
151     */
152    public String path() {
153        return path;
154    }
155
156    /**
157     * Derives the resource pattern from the path.
158     *
159     * @param path the path
160     * @return the pattern
161     */
162    @SuppressWarnings({ "PMD.AvoidLiteralsInIfCondition" })
163    protected static String derivePattern(String path) {
164        String pattern;
165        if ("/".equals(path)) {
166            pattern = "/**";
167        } else {
168            String patternBase = path;
169            if (patternBase.endsWith("/")) {
170                patternBase = path.substring(0, path.length() - 1);
171            }
172            pattern = patternBase + "|," + patternBase + "/**";
173        }
174        return pattern;
175    }
176
177    /**
178     * Creates a new session manager using the given channel and path.
179     * The manager handles only requests that match the given pattern.
180     * The handler is registered with the given priority.
181     * 
182     * This constructor can be used if special handling of top level
183     * requests is needed.
184     *
185     * @param componentChannel the component channel
186     * @param pattern the path part of a {@link ResourcePattern}
187     * @param priority the priority
188     * @param path the path
189     */
190    public SessionManager(Channel componentChannel, String pattern,
191            int priority, String path) {
192        super(componentChannel);
193        this.path = path;
194        RequestHandler.Evaluator.add(this, "onRequest", pattern, priority);
195        MBeanView.addManager(this);
196    }
197
198    private Optional<Long> minTimeout() {
199        if (absoluteTimeout > 0 && idleTimeout > 0) {
200            return Optional.of(Math.min(absoluteTimeout, idleTimeout));
201        }
202        if (absoluteTimeout > 0) {
203            return Optional.of(absoluteTimeout);
204        }
205        if (idleTimeout > 0) {
206            return Optional.of(idleTimeout);
207        }
208        return Optional.empty();
209    }
210
211    private void startPurger() {
212        synchronized (this) {
213            if (nextPurge == null) {
214                minTimeout().ifPresent(timeout -> Components
215                    .schedule(this::purgeAction, Duration.ofMillis(timeout)));
216            }
217        }
218    }
219
220    @SuppressWarnings({ "PMD.UnusedFormalParameter" })
221    private void purgeAction(Timer timer) {
222        nextPurge = startDiscarding(absoluteTimeout, idleTimeout)
223            .map(nextAt -> Components.schedule(this::purgeAction, nextAt))
224            .orElse(null);
225    }
226
227    /**
228     * The name used for the session id cookie. Defaults to "`id`".
229     * 
230     * @return the id name
231     */
232    public String idName() {
233        return idName;
234    }
235
236    /**
237     * @param idName the id name to set
238     * 
239     * @return the session manager for easy chaining
240     */
241    public SessionManager setIdName(String idName) {
242        this.idName = idName;
243        return this;
244    }
245
246    /**
247     * Set the maximum number of sessions. If the value is zero or less,
248     * an unlimited number of sessions is supported. The default value
249     * is 1000.
250     * 
251     * If adding a new session would exceed the limit, first all
252     * sessions older than {@link #absoluteTimeout()} are removed.
253     * If this doesn't free a slot, the least recently used session
254     * is removed.
255     * 
256     * @param maxSessions the maxSessions to set
257     * @return the session manager for easy chaining
258     */
259    public SessionManager setMaxSessions(int maxSessions) {
260        this.maxSessions = maxSessions;
261        return this;
262    }
263
264    /**
265     * @return the maxSessions
266     */
267    public int maxSessions() {
268        return maxSessions;
269    }
270
271    /**
272     * Sets the absolute timeout for a session. The absolute
273     * timeout is the time after which a session is invalidated (relative
274     * to its creation time). Defaults to 9 hours. Zero or less disables
275     * the timeout.
276     * 
277     * @param timeout the absolute timeout
278     * @return the session manager for easy chaining
279     */
280    public SessionManager setAbsoluteTimeout(Duration timeout) {
281        this.absoluteTimeout = timeout.toMillis();
282        return this;
283    }
284
285    /**
286     * @return the absolute session timeout (in seconds)
287     */
288    public Duration absoluteTimeout() {
289        return Duration.ofMillis(absoluteTimeout);
290    }
291
292    /**
293     * Sets the idle timeout for a session. Defaults to 30 minutes.
294     * Zero or less disables the timeout. 
295     * 
296     * @param timeout the absolute timeout
297     * @return the session manager for easy chaining
298     */
299    public SessionManager setIdleTimeout(Duration timeout) {
300        this.idleTimeout = timeout.toMillis();
301        return this;
302    }
303
304    /**
305     * @return the idle timeout
306     */
307    public Duration idleTimeout() {
308        return Duration.ofMillis(idleTimeout);
309    }
310
311    /**
312     * Associates the event with a {@link Session} object
313     * using `Session.class` as association identifier.
314     * Does nothing if a session is already associated or
315     * the request has already been fulfilled.
316     * 
317     * @param event the event
318     */
319    @RequestHandler(dynamic = true)
320    public void onRequest(Request.In event) {
321        if (event.associated(Session.class).isPresent() || event.fulfilled()) {
322            return;
323        }
324        final HttpRequest request = event.httpRequest();
325        Optional<String> requestedSessionId = request.findValue(
326            HttpField.COOKIE, Converters.COOKIE_LIST)
327            .flatMap(cookies -> cookies.stream().filter(
328                cookie -> cookie.getName().equals(idName()))
329                .findFirst().map(HttpCookie::getValue));
330        if (requestedSessionId.isPresent()) {
331            String sessionId = requestedSessionId.get();
332            synchronized (this) {
333                Optional<Session> session = lookupSession(sessionId);
334                if (session.isPresent()) {
335                    setSessionSupplier(event, sessionId);
336                    session.get().updateLastUsedAt();
337                    return;
338                }
339            }
340        }
341        Session session = createSession(
342            addSessionCookie(request.response().get(), createSessionId()));
343        setSessionSupplier(event, session.id());
344        startPurger();
345    }
346
347    /**
348     * Associated the associator with a session supplier for the 
349     * given session id and note `this` as session manager.
350     *
351     * @param holder the channel
352     * @param sessionId the session id
353     */
354    protected void setSessionSupplier(Associator holder, String sessionId) {
355        holder.setAssociated(SessionManager.class, this);
356        holder.setAssociated(Session.class,
357            new SessionSupplier(holder, sessionId));
358    }
359
360    /**
361     * Supports obtaining a {@link Session} from an {@link IOSubchannel}. 
362     */
363    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
364    private class SessionSupplier implements Supplier<Optional<Session>> {
365
366        private final Associator holder;
367        private final String sessionId;
368
369        /**
370         * Instantiates a new session supplier.
371         *
372         * @param holder the channel
373         * @param sessionId the session id
374         */
375        public SessionSupplier(Associator holder, String sessionId) {
376            this.holder = holder;
377            this.sessionId = sessionId;
378        }
379
380        @Override
381        public Optional<Session> get() {
382            Optional<Session> session = lookupSession(sessionId);
383            if (session.isPresent()) {
384                session.get().updateLastUsedAt();
385                return session;
386            }
387            Session newSession = createSession(createSessionId());
388            setSessionSupplier(holder, newSession.id());
389            return Optional.of(newSession);
390        }
391
392    }
393
394    /**
395     * Creates a session id and adds the corresponding cookie to the
396     * response.
397     * 
398     * @param response the response
399     * @return the session id
400     */
401    protected String addSessionCookie(HttpResponse response, String sessionId) {
402        HttpCookie sessionCookie = new HttpCookie(idName(), sessionId);
403        sessionCookie.setPath(path);
404        sessionCookie.setHttpOnly(true);
405        response.computeIfAbsent(HttpField.SET_COOKIE,
406            () -> new CookieList(SameSiteAttribute.STRICT))
407            .value().add(sessionCookie);
408        response.computeIfAbsent(
409            HttpField.CACHE_CONTROL, CacheControlDirectives::new).value()
410            .add(new Directive("no-cache", "SetCookie, Set-Cookie2"));
411        return sessionId;
412    }
413
414    private String createSessionId() {
415        StringBuilder sessionIdBuilder = new StringBuilder();
416        byte[] bytes = new byte[16];
417        secureRandom.nextBytes(bytes);
418        for (byte b : bytes) {
419            sessionIdBuilder.append(Integer.toHexString(b & 0xff));
420        }
421        return sessionIdBuilder.toString();
422    }
423
424    /**
425     * Checks if the absolute or idle timeout has been reached.
426     *
427     * @param session the session
428     * @return true, if successful
429     */
430    protected boolean hasTimedOut(Session session) {
431        Instant now = Instant.now();
432        return absoluteTimeout > 0 && Duration
433            .between(session.createdAt(), now).toMillis() > absoluteTimeout
434            || idleTimeout > 0 && Duration.between(session.lastUsedAt(),
435                now).toMillis() > idleTimeout;
436    }
437
438    /**
439     * Start discarding all sessions (generate {@link DiscardSession} events)
440     * that have reached their absolute or idle timeout. Do not
441     * make the sessions unavailable yet. 
442     * 
443     * Returns the time when the next timeout occurs. This method is 
444     * called only if at least one of the timeouts has been specified.
445     * 
446     * Implementations have to take care that sessions are only discarded
447     * once. As they must remain available while the {@link DiscardSession}
448     * event is handled this may require marking them as being discarded. 
449     *
450     * @param absoluteTimeout the absolute timeout
451     * @param idleTimeout the idle timeout
452     * @return the next timeout (empty if no sessions left)
453     */
454    protected abstract Optional<Instant> startDiscarding(long absoluteTimeout,
455            long idleTimeout);
456
457    /**
458     * Creates a new session with the given id.
459     * 
460     * @param sessionId
461     * @return the session
462     */
463    protected abstract Session createSession(String sessionId);
464
465    /**
466     * Lookup the session with the given id. Lookup will fail if
467     * the session has timed out.
468     * 
469     * @param sessionId
470     * @return the session
471     */
472    protected abstract Optional<Session> lookupSession(String sessionId);
473
474    /**
475     * Removes the given session from the cache.
476     * 
477     * @param sessionId the session id
478     */
479    protected abstract void removeSession(String sessionId);
480
481    /**
482     * Return the number of established sessions.
483     * 
484     * @return the result
485     */
486    protected abstract int sessionCount();
487
488    /**
489     * Discards the given session. The handler has a priority of -1000,
490     * thus allowing other handler to make use of the session (for a
491     * time) before it becomes unavailable.
492     * 
493     * @param event the event
494     */
495    @Handler(channels = Channel.class, priority = -1000)
496    public void onDiscard(DiscardSession event) {
497        removeSession(event.session().id());
498        event.session().close();
499    }
500
501    /**
502     * Associates the channel with a 
503     * {@link Supplier {@code Supplier<Optional<Session>>}} 
504     * for the session. Initially, the associated session is the session
505     * associated with the protocol switch event. If this session times out,
506     * a new session is returned as a fallback, thus making sure that
507     * the `Optional` is never empty. The new session is, however, created 
508     * independently of any new session created by {@link #onRequest}.
509     * 
510     * Applications should avoid any ambiguity by executing a proper 
511     * cleanup of the web application in response to a 
512     * {@link DiscardSession} event (including reestablishing the web
513     * socket connections from new requests).
514     * 
515     * @param event the event
516     * @param channel the channel
517     */
518    @Handler(priority = 1000)
519    @SuppressWarnings("PMD.CompareObjectsWithEquals")
520    public void onProtocolSwitchAccepted(
521            ProtocolSwitchAccepted event, IOSubchannel channel) {
522        Request.In request = event.requestEvent();
523        request.associated(SessionManager.class).filter(sm -> sm == this)
524            .ifPresent(
525                sm -> setSessionSupplier(channel, Session.from(request).id()));
526    }
527
528    /**
529     * An MBean interface for getting information about the 
530     * established sessions.
531     */
532    @SuppressWarnings("PMD.CommentRequired")
533    public interface SessionManagerMXBean {
534
535        String getComponentPath();
536
537        String getPath();
538
539        int getMaxSessions();
540
541        long getAbsoluteTimeout();
542
543        long getIdleTimeout();
544
545        int getSessionCount();
546    }
547
548    /**
549     * The session manager information.
550     */
551    public static class SessionManagerInfo implements SessionManagerMXBean {
552
553        private static MBeanServer mbs
554            = ManagementFactory.getPlatformMBeanServer();
555
556        private ObjectName mbeanName;
557        private final WeakReference<SessionManager> sessionManagerRef;
558
559        /**
560         * Instantiates a new session manager info.
561         *
562         * @param sessionManager the session manager
563         */
564        @SuppressWarnings({ "PMD.AvoidCatchingGenericException",
565            "PMD.EmptyCatchBlock" })
566        public SessionManagerInfo(SessionManager sessionManager) {
567            try {
568                mbeanName = new ObjectName("org.jgrapes.http:type="
569                    + SessionManager.class.getSimpleName() + ",name="
570                    + ObjectName.quote(Components.simpleObjectName(
571                        sessionManager)));
572            } catch (MalformedObjectNameException e) {
573                // Won't happen
574            }
575            sessionManagerRef = new WeakReference<>(sessionManager);
576            try {
577                mbs.unregisterMBean(mbeanName);
578            } catch (Exception e) {
579                // Just in case, should not work
580            }
581            try {
582                mbs.registerMBean(this, mbeanName);
583            } catch (InstanceAlreadyExistsException | MBeanRegistrationException
584                    | NotCompliantMBeanException e) {
585                // Have to live with that
586            }
587        }
588
589        /**
590         * Returns the session manager.
591         *
592         * @return the optional session manager
593         */
594        @SuppressWarnings({ "PMD.EmptyCatchBlock" })
595        public Optional<SessionManager> manager() {
596            SessionManager manager = sessionManagerRef.get();
597            if (manager == null) {
598                try {
599                    mbs.unregisterMBean(mbeanName);
600                } catch (MBeanRegistrationException
601                        | InstanceNotFoundException e) {
602                    // Should work.
603                }
604            }
605            return Optional.ofNullable(manager);
606        }
607
608        @Override
609        public String getComponentPath() {
610            return manager().map(ComponentVertex::componentPath)
611                .orElse("<removed>");
612        }
613
614        @Override
615        public String getPath() {
616            return manager().map(mgr -> mgr.path).orElse("<unknown>");
617        }
618
619        @Override
620        public int getMaxSessions() {
621            return manager().map(SessionManager::maxSessions).orElse(0);
622        }
623
624        @Override
625        public long getAbsoluteTimeout() {
626            return manager().map(mgr -> mgr.absoluteTimeout().toMillis())
627                .orElse(0L);
628        }
629
630        @Override
631        public long getIdleTimeout() {
632            return manager().map(mgr -> mgr.idleTimeout().toMillis())
633                .orElse(0L);
634        }
635
636        @Override
637        public int getSessionCount() {
638            return manager().map(SessionManager::sessionCount).orElse(0);
639        }
640    }
641
642    /**
643     * An MBean interface for getting information about all session
644     * managers.
645     * 
646     * There is currently no summary information. However, the (periodic)
647     * invocation of {@link SessionManagerSummaryMXBean#getManagers()} ensures
648     * that entries for removed {@link SessionManager}s are unregistered.
649     */
650    @SuppressWarnings("PMD.ImplicitFunctionalInterface")
651    public interface SessionManagerSummaryMXBean {
652
653        /**
654         * Gets the managers.
655         *
656         * @return the managers
657         */
658        Set<SessionManagerMXBean> getManagers();
659    }
660
661    /**
662     * The MBean view.
663     */
664    @SuppressWarnings("PMD.PublicMemberInNonPublicType")
665    private static final class MBeanView
666            implements SessionManagerSummaryMXBean {
667        private static Set<SessionManagerInfo> managerInfos = new HashSet<>();
668
669        /**
670         * Adds a manager.
671         *
672         * @param manager the manager
673         */
674        public static void addManager(SessionManager manager) {
675            synchronized (managerInfos) {
676                managerInfos.add(new SessionManagerInfo(manager));
677            }
678        }
679
680        @Override
681        public Set<SessionManagerMXBean> getManagers() {
682            Set<SessionManagerInfo> expired = new HashSet<>();
683            synchronized (managerInfos) {
684                for (SessionManagerInfo managerInfo : managerInfos) {
685                    if (!managerInfo.manager().isPresent()) {
686                        expired.add(managerInfo);
687                    }
688                }
689                managerInfos.removeAll(expired);
690            }
691            @SuppressWarnings("unchecked")
692            Set<SessionManagerMXBean> result
693                = (Set<SessionManagerMXBean>) (Object) managerInfos;
694            return result;
695        }
696    }
697
698    static {
699        try {
700            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
701            ObjectName mxbeanName = new ObjectName("org.jgrapes.http:type="
702                + SessionManager.class.getSimpleName() + "s");
703            mbs.registerMBean(new MBeanView(), mxbeanName);
704        } catch (MalformedObjectNameException | InstanceAlreadyExistsException
705                | MBeanRegistrationException | NotCompliantMBeanException e) {
706            // Does not happen
707            e.printStackTrace();
708        }
709    }
710}