001package ca.uhn.fhir.rest.server.interceptor;
002
003/*
004 * #%L
005 * HAPI FHIR - Server Framework
006 * %%
007 * Copyright (C) 2014 - 2019 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.util.HashSet;
024import java.util.Set;
025
026import javax.servlet.http.HttpServletRequest;
027import javax.servlet.http.HttpServletResponse;
028
029import ca.uhn.fhir.rest.api.RequestTypeEnum;
030import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException;
031
032/**
033 * This interceptor causes the server to reject invocations for HTTP methods
034 * other than those supported by the server with an HTTP 405. This is a requirement
035 * of some security assessments.
036 */
037public class BanUnsupportedHttpMethodsInterceptor extends InterceptorAdapter {
038
039        private Set<RequestTypeEnum> myAllowedMethods = new HashSet<RequestTypeEnum>();
040        
041        public BanUnsupportedHttpMethodsInterceptor() {
042                myAllowedMethods.add(RequestTypeEnum.GET);
043                myAllowedMethods.add(RequestTypeEnum.OPTIONS);
044                myAllowedMethods.add(RequestTypeEnum.DELETE);
045                myAllowedMethods.add(RequestTypeEnum.PUT);
046                myAllowedMethods.add(RequestTypeEnum.POST);
047                myAllowedMethods.add(RequestTypeEnum.PATCH);
048                myAllowedMethods.add(RequestTypeEnum.HEAD);
049        }
050        
051        @Override
052        public boolean incomingRequestPreProcessed(HttpServletRequest theRequest, HttpServletResponse theResponse) {
053                RequestTypeEnum requestType = RequestTypeEnum.valueOf(theRequest.getMethod());
054                if (myAllowedMethods.contains(requestType)) {
055                        return true;
056                }
057                
058                throw new MethodNotAllowedException("Method not supported: " + theRequest.getMethod());
059        }
060
061}