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.ui;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.logging.log4j.ThreadContext;
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.spi.Wiki;
028import org.apache.wiki.auth.AuthenticationManager;
029import org.apache.wiki.auth.SessionMonitor;
030import org.apache.wiki.auth.WikiSecurityException;
031
032import jakarta.servlet.Filter;
033import jakarta.servlet.FilterChain;
034import jakarta.servlet.FilterConfig;
035import jakarta.servlet.ServletContext;
036import jakarta.servlet.ServletException;
037import jakarta.servlet.ServletRequest;
038import jakarta.servlet.ServletResponse;
039import jakarta.servlet.http.HttpServletRequest;
040import jakarta.servlet.http.HttpServletRequestWrapper;
041import java.io.IOException;
042import java.io.PrintWriter;
043
044/**
045 * Filter that verifies that the {@link org.apache.wiki.api.core.Engine} is running, and sets the authentication status for the user's
046 * Session. Each HTTP request processed by this filter is wrapped by a {@link WikiRequestWrapper}. The wrapper's primary responsibility
047 * is to return the correct <code>userPrincipal</code> and <code>remoteUser</code> for authenticated JSPWiki users (whether authenticated
048 * by container or by JSPWiki's custom system). The wrapper's other responsibility is to incorporate JSPWiki built-in roles
049 * into the role-checking algorithm for {@link  HttpServletRequest#isUserInRole(String)}. Just before the request is wrapped, the method
050 * {@link org.apache.wiki.auth.AuthenticationManager#login(HttpServletRequest)} executes; this method contains all of the logic needed to
051 * grab any user login credentials set by the container or by cookies.
052 */
053public class WikiServletFilter implements Filter {
054
055    private static final Logger LOG = LogManager.getLogger( WikiServletFilter.class );
056    protected Engine m_engine;
057
058    /**
059     * Initializes the WikiServletFilter.
060     * 
061     * @param config The FilterConfig.
062     * @throws ServletException If a Engine cannot be started.
063     */
064    @Override
065    public void init( final FilterConfig config ) throws ServletException {
066        final ServletContext context = config.getServletContext();
067
068        m_engine = Wiki.engine().find( context, null );
069    }
070
071    /**
072     * Destroys the WikiServletFilter.
073     */
074    @Override
075    public void destroy() {
076    }
077
078    /**
079    * Checks that the Engine is running ok, wraps the current HTTP request, and sets the correct authentication state for the users's
080    * Session. First, the method {@link org.apache.wiki.auth.AuthenticationManager#login(HttpServletRequest)}
081    * executes, which sets the authentication state. Then, the request is wrapped with a
082    * {@link WikiRequestWrapper}.
083    * @param request the current HTTP request object
084    * @param response the current HTTP response object
085    * @param chain The Filter chain passed down.
086    * @throws ServletException if {@link org.apache.wiki.auth.AuthenticationManager#login(HttpServletRequest)} fails for any reason
087    * @throws IOException If writing to the servlet response fails. 
088    */
089    @Override
090    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
091        //  Sanity check; it might be true in some conditions, but we need to know where.
092        if( chain == null ) {
093            throw new ServletException("FilterChain is null, even if it should not be.  Please report this to the jspwiki development team.");
094        }
095        
096        if( m_engine == null ) {
097            final PrintWriter out = response.getWriter();
098            out.print("<!DOCTYPE html><html lang=\"en\"><head><title>Fatal problem with JSPWiki</title></head>");
099            out.print("<body>");
100            out.print("<h1>JSPWiki has not been started</h1>");
101            out.print("<p>JSPWiki is not running.  This is probably due to a configuration error in your jspwiki.properties file, ");
102            out.print("or a problem with your servlet container.  Please double-check everything before issuing a bug report ");
103            out.print("at jspwiki.apache.org.</p>");
104            out.print("<p>We apologize for the inconvenience.  No, really, we do.  We're trying to ");
105            out.print("JSPWiki as easy as we can, but there is only so much we have time to test ");
106            out.print("platforms.</p>");
107            out.print( "<p>Please go to the <a href='Install.jsp'>installer</a> to continue.</p>" );
108            out.print("</body></html>");
109            return;
110        }   
111        
112        // If we haven't done so, wrap the request
113        HttpServletRequest httpRequest = ( HttpServletRequest )request;
114        
115        // Set the character encoding
116        httpRequest.setCharacterEncoding( m_engine.getContentEncoding().displayName() );
117        
118        if ( !isWrapped( request ) ) {
119            // Prepare the Session
120            try {
121                m_engine.getManager( AuthenticationManager.class ).login( httpRequest );
122                final Session wikiSession = SessionMonitor.getInstance( m_engine ).find( httpRequest.getSession() );
123                httpRequest = new WikiRequestWrapper( m_engine, httpRequest );
124                LOG.debug( "Executed security filters for user={}, path={}",wikiSession.getLoginPrincipal().getName(), httpRequest.getRequestURI() );
125            } catch( final WikiSecurityException e ) {
126                throw new ServletException( e );
127            }
128        }
129
130        try {
131            ThreadContext.push( m_engine.getApplicationName() + ":" + httpRequest.getRequestURL() );
132            chain.doFilter( httpRequest, response );
133        } finally {
134            ThreadContext.pop();
135            ThreadContext.remove( m_engine.getApplicationName() + ":" + httpRequest.getRequestURL() );
136        }
137    }
138
139    /**
140     *  Figures out the wiki context from the request.  This method does not create the context if it does not exist.
141     *  
142     *  @param request The request to examine
143     *  @return A valid WikiContext value (or null, if the context could not be located).
144     */
145    protected Context getWikiContext( final ServletRequest request ) {
146        final HttpServletRequest httpRequest = (HttpServletRequest) request;
147        return ( Context )httpRequest.getAttribute( Context.ATTR_CONTEXT );
148    }
149
150    /** 
151     * Determines whether the request has been previously wrapped with a WikiRequestWrapper. 
152     * We find the wrapper by recursively unwrapping successive request wrappers, if they have been supplied.
153     *
154     * @param request the current HTTP request
155     * @return <code>true</code> if the request has previously been wrapped; <code>false</code> otherwise
156     */
157    private boolean isWrapped( ServletRequest request ) {
158        while( !(request instanceof WikiRequestWrapper ) && request instanceof HttpServletRequestWrapper ) {
159            request = ( ( HttpServletRequestWrapper ) request ).getRequest();
160        }
161        return request instanceof WikiRequestWrapper;
162    }
163
164}