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