001/*
002
003    Licensed to the Apache Software Foundation (ASF) under one
004    or more contributor license agreements.  See the NOTICE file
005    distributed with this work for additional information
006    regarding copyright ownership.  The ASF licenses this file
007    to you under the Apache License, Version 2.0 (the
008    "License"); you may not use this file except in compliance
009    with the License.  You may obtain a copy of the License at
010
011       http://www.apache.org/licenses/LICENSE-2.0
012
013    Unless required by applicable law or agreed to in writing,
014    software distributed under the License is distributed on an
015    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016    KIND, either express or implied.  See the License for the
017    specific language governing permissions and limitations
018    under the License.
019 */
020package org.apache.wiki.ajax;
021
022import org.apache.commons.lang3.StringUtils;
023import org.apache.logging.log4j.LogManager;
024import org.apache.logging.log4j.Logger;
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.AuthorizationManager;
029import org.apache.wiki.auth.SessionMonitor;
030import org.apache.wiki.auth.permissions.PagePermission;
031import org.apache.wiki.event.WikiEventManager;
032import org.apache.wiki.event.WikiSecurityEvent;
033import org.apache.wiki.util.TextUtil;
034
035import javax.servlet.ServletConfig;
036import javax.servlet.ServletException;
037import javax.servlet.http.HttpServlet;
038import javax.servlet.http.HttpServletRequest;
039import javax.servlet.http.HttpServletResponse;
040import java.io.IOException;
041import java.security.Permission;
042import java.util.ArrayList;
043import java.util.Arrays;
044import java.util.List;
045import java.util.Map;
046import java.util.concurrent.ConcurrentHashMap;
047
048
049/**
050 * This provides a simple ajax servlet for handling /ajax/<ClassName> requests. HttpServlet classes need to be registered using
051 * {@link WikiAjaxDispatcherServlet#registerServlet(WikiAjaxServlet)}
052 *
053 * @since 2.10.2-svn12
054 */
055public class WikiAjaxDispatcherServlet extends HttpServlet {
056
057    private static final long serialVersionUID = 1L;
058    private static final Map< String, AjaxServletContainer > ajaxServlets = new ConcurrentHashMap<>();
059    private static final Logger LOG = LogManager.getLogger( WikiAjaxDispatcherServlet.class.getName() );
060    private String PATH_AJAX = "/ajax/";
061    private Engine m_engine;
062
063    /**
064     * {@inheritDoc}
065     *
066     * This sets the AjaxPath to "/ajax/" as configured in "jspwiki.ajax.url.prefix".
067     * Note: Do not change this without also changing the web.xml file.
068     */
069    @Override
070    public void init( final ServletConfig config ) throws ServletException {
071        super.init( config );
072        m_engine = Wiki.engine().find( config );
073        PATH_AJAX = "/" + TextUtil.getStringProperty( m_engine.getWikiProperties(), "jspwiki.ajax.url.prefix", "ajax" ) + "/";
074        LOG.info( "WikiAjaxDispatcherServlet initialized." );
075    }
076
077    /**
078     * Register a {@link WikiAjaxServlet} using the servlet mapping as the alias
079     */
080    public static void registerServlet( final WikiAjaxServlet servlet ) {
081        registerServlet( servlet.getServletMapping(), servlet );
082    }
083
084    /**
085     * Register a {@link WikiAjaxServlet} with a specific alias, and default permission {@link PagePermission#VIEW}.
086     */
087    public static void registerServlet( final String alias, final WikiAjaxServlet servlet ) {
088        registerServlet( alias, servlet, PagePermission.VIEW );
089    }
090
091    /**
092     * Regster a {@link WikiAjaxServlet} given an alias, the servlet, and the permission.
093     * This creates a temporary bundle object called {@link WikiAjaxDispatcherServlet.AjaxServletContainer}
094     *
095     * @param alias the uri link to this servlet
096     * @param servlet the servlet being registered
097     * @param perm the permission required to execute the servlet.
098     */
099    public static void registerServlet( final String alias, final WikiAjaxServlet servlet, final Permission perm ) {
100        LOG.info( "WikiAjaxDispatcherServlet registering " + alias + "=" + servlet + " perm=" + perm );
101        ajaxServlets.put( alias, new AjaxServletContainer( alias, servlet, perm ) );
102    }
103
104    /**
105     * Calls {@link #performAction}
106     */
107    @Override
108    public void doPost( final HttpServletRequest req, final HttpServletResponse res ) throws IOException, ServletException {
109        performAction( req, res );
110    }
111
112    /**
113     * Calls {@link #performAction}
114     */
115    @Override
116    public void doGet( final HttpServletRequest req, final HttpServletResponse res ) throws IOException, ServletException {
117        performAction( req, res );
118    }
119
120    /**
121     * The main method which get the requestURI "/ajax/<ServletName>", gets the {@link #getServletName} and finds the servlet using
122     * {@link #findServletByName}. It then calls {@link WikiAjaxServlet#service} method.
123     *
124     * @param req the inbound request
125     * @param res the outbound response
126     * @throws IOException if WikiEngine's content encoding is valid
127     * @throws ServletException if no registered servlet can be found
128     */
129    private void performAction( final HttpServletRequest req, final HttpServletResponse res ) throws IOException, ServletException {
130        final String path = req.getRequestURI();
131        final String servletName = getServletName( path );
132        if( servletName != null) {
133            final AjaxServletContainer container = findServletContainer( servletName );
134            if( container != null ) {
135                final WikiAjaxServlet servlet = container.servlet;
136                final Session wikiSession = SessionMonitor.getInstance( m_engine ).find( req.getSession() );
137                if ( validatePermission( req, container ) ) {
138                    req.setCharacterEncoding( m_engine.getContentEncoding().displayName() );
139                    res.setCharacterEncoding( m_engine.getContentEncoding().displayName() );
140                    final String actionName = AjaxUtil.getNextPathPart( req.getRequestURI(), servlet.getServletMapping() );
141                    // Prefer the request header: a token sent as a GET parameter ends up in access logs and
142                    // browser history. The parameter is still accepted for compatibility with older clients.
143                    String xsrfToken = req.getHeader( "X-XSRF-TOKEN" );
144                    if( xsrfToken == null ) {
145                        xsrfToken = req.getParameter( "X-XSRF-TOKEN" );
146                    }
147                    if( !wikiSession.antiCsrfToken().equals( xsrfToken ) ) {
148                        res.sendError( 400, "X-XSRF-TOKEN missing or invalid." );
149                        WikiEventManager.fireEvent( this, new WikiSecurityEvent( wikiSession, WikiSecurityEvent.ACCESS_DENIED,
150                                                                                req.getUserPrincipal(), "X-XSRF-TOKEN missing or invalid." ) );
151                        return;
152                    }
153                    LOG.debug( "actionName=" + actionName );
154                    final String params = req.getParameter( "params" );
155                    LOG.debug( "params=" + params );
156                    List< String > paramValues = new ArrayList<>();
157                    if( params != null ) {
158                        if( StringUtils.isNotBlank( params ) ) {
159                            paramValues = Arrays.asList( params.trim().split( "," ) );
160                        }
161                    }
162                    servlet.service( req, res, actionName, paramValues );
163                } else {
164                    LOG.warn( "Servlet container " + container + " not authorised. Permission required." );
165                    WikiEventManager.fireEvent( this, new WikiSecurityEvent( wikiSession, WikiSecurityEvent.ACCESS_DENIED,
166                                                                            req.getUserPrincipal(), container.permission ) );
167                    res.sendError( 400, "Denied." );
168                    return;
169                }
170            } else {
171                LOG.warn( "No registered class for servletName=" + servletName + " in path=" + path );
172                res.sendError( 400, "Unknown Service." );
173                //should this be an auditable event?
174                //throw new ServletException( "No registered class for servletName=" + servletName );
175            }
176        }
177    }
178
179    /**
180     * Validate the permission of the {@link WikiAjaxServlet} using the {@link AuthorizationManager#checkPermission}
181     *
182     * @param req the servlet request
183     * @param container the container info of the servlet
184     * @return true if permission is valid
185     */
186    private boolean validatePermission( final HttpServletRequest req, final AjaxServletContainer container ) {
187        final Engine e = Wiki.engine().find( req.getSession().getServletContext(), null );
188        boolean valid = false;
189        if( container != null ) {
190            valid = e.getManager( AuthorizationManager.class ).checkPermission( Wiki.session().find( e, req ), container.permission );
191        }
192        return valid;
193    }
194
195    /**
196     * Get the ServletName from the requestURI "/ajax/<ServletName>", using {@link AjaxUtil#getNextPathPart}.
197     *
198     * @param path The requestURI, which must contains "/ajax/<ServletName>" in the path
199     * @return The ServletName for the requestURI, or null
200     * @throws ServletException if the path is invalid
201     */
202    public String getServletName( final String path ) throws ServletException {
203        return AjaxUtil.getNextPathPart( path, PATH_AJAX );
204    }
205
206    /**
207     * Find the {@link AjaxServletContainer} as registered in {@link #registerServlet}.
208     *
209     * @param servletAlias the name of the servlet from {@link #getServletName}
210     * @return The first servlet found, or null.
211     */
212    private AjaxServletContainer findServletContainer( final String servletAlias ) {
213        return ajaxServlets.get( servletAlias );
214    }
215
216    /**
217     * Find the {@link WikiAjaxServlet} given the servletAlias that it was registered with.
218     *
219     * @param servletAlias the value provided to {@link #registerServlet}
220     * @return the {@link WikiAjaxServlet} given the servletAlias that it was registered with.
221     */
222    public WikiAjaxServlet findServletByName( final String servletAlias ) {
223        final AjaxServletContainer container = ajaxServlets.get( servletAlias );
224        if( container != null ) {
225            return container.servlet;
226        }
227        return null;
228    }
229
230    private static class AjaxServletContainer {
231
232        final String alias;
233        final WikiAjaxServlet servlet;
234        final Permission permission;
235
236        public AjaxServletContainer( final String alias, final WikiAjaxServlet servlet, final Permission permission ) {
237            this.alias = alias;
238            this.servlet = servlet;
239            this.permission = permission;
240        }
241
242        @Override
243        public String toString() {
244            return getClass().getSimpleName() + " " + alias + "=" + servlet.getClass().getSimpleName() + " permission=" + permission;
245        }
246
247    }
248
249}