001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.servlet.jakarta; 018 019import com.google.errorprone.annotations.CheckReturnValue; 020import com.revetsec.BrowserRequestOriginPolicy; 021import com.revetsec.BrowserRequestOriginResult; 022import jakarta.servlet.http.HttpServletRequest; 023import org.jspecify.annotations.NonNull; 024 025import javax.annotation.concurrent.ThreadSafe; 026import java.util.ArrayList; 027import java.util.Enumeration; 028import java.util.List; 029 030import static java.util.Objects.requireNonNull; 031 032/** 033 * Servlet request extraction for Revetsec's browser request-origin policy. The helper installs no filter and changes 034 * no application state. 035 * 036 * @since 1.0.0 037 */ 038@ThreadSafe 039public final class ServletBrowserRequestOrigins { 040 private ServletBrowserRequestOrigins() { } 041 042 /** 043 * Checks the request method and all exposed {@code Sec-Fetch-Site} and {@code Origin} occurrences. 044 * 045 * @param policy configured core policy 046 * @param request routed request 047 * @return closed request-origin outcome 048 * @throws NullPointerException if an argument is {@code null} 049 * @throws IllegalStateException if Servlet request headers are unavailable 050 * @since 1.0.0 051 */ 052 @CheckReturnValue 053 public static @NonNull BrowserRequestOriginResult browserRequestOriginResultFor( 054 @NonNull BrowserRequestOriginPolicy policy, @NonNull HttpServletRequest request) { 055 requireNonNull(request); 056 return requireNonNull(policy).checkResult(requireNonNull(request.getMethod()), 057 valuesFor(request, "Sec-Fetch-Site"), valuesFor(request, "Origin")); 058 } 059 060 private static @NonNull List<@NonNull String> valuesFor(@NonNull HttpServletRequest request, 061 @NonNull String name) { 062 Enumeration<String> source = request.getHeaders(name); 063 if (source == null) throw new IllegalStateException("Servlet request headers are unavailable"); 064 List<String> values = new ArrayList<>(2); 065 while (source.hasMoreElements() && values.size() < 2) 066 values.add(requireNonNull(source.nextElement())); 067 return List.copyOf(values); 068 } 069}