001package ca.uhn.fhir.rest.server.interceptor;
002
003/*
004 * #%L
005 * HAPI FHIR - Server Framework
006 * %%
007 * Copyright (C) 2014 - 2022 Smile CDR, Inc.
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 ca.uhn.fhir.i18n.Msg;
024import java.util.HashSet;
025import java.util.Set;
026
027import javax.servlet.http.HttpServletRequest;
028import javax.servlet.http.HttpServletResponse;
029
030import ca.uhn.fhir.rest.api.RequestTypeEnum;
031import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException;
032
033/**
034 * This interceptor causes the server to reject invocations for HTTP methods
035 * other than those supported by the server with an HTTP 405. This is a requirement
036 * of some security assessments.
037 */
038public class BanUnsupportedHttpMethodsInterceptor extends InterceptorAdapter {
039
040        private Set<RequestTypeEnum> myAllowedMethods = new HashSet<RequestTypeEnum>();
041        
042        public BanUnsupportedHttpMethodsInterceptor() {
043                myAllowedMethods.add(RequestTypeEnum.GET);
044                myAllowedMethods.add(RequestTypeEnum.OPTIONS);
045                myAllowedMethods.add(RequestTypeEnum.DELETE);
046                myAllowedMethods.add(RequestTypeEnum.PUT);
047                myAllowedMethods.add(RequestTypeEnum.POST);
048                myAllowedMethods.add(RequestTypeEnum.PATCH);
049                myAllowedMethods.add(RequestTypeEnum.HEAD);
050        }
051        
052        @Override
053        public boolean incomingRequestPreProcessed(HttpServletRequest theRequest, HttpServletResponse theResponse) {
054                RequestTypeEnum requestType = RequestTypeEnum.valueOf(theRequest.getMethod());
055                if (myAllowedMethods.contains(requestType)) {
056                        return true;
057                }
058                
059                throw new MethodNotAllowedException(Msg.code(329) + "Method not supported: " + theRequest.getMethod());
060        }
061
062}