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 */
016package com.revetsec.servlet.jakarta;
017
018import com.google.errorprone.annotations.CheckReturnValue;
019import com.revetsec.oauth.AuthorizationResponse;
020import jakarta.servlet.http.HttpServletRequest;
021import jakarta.servlet.http.HttpServletResponse;
022import org.jspecify.annotations.NonNull;
023
024import javax.annotation.concurrent.ThreadSafe;
025import java.io.IOException;
026import java.net.URI;
027import java.util.ArrayList;
028import java.util.Enumeration;
029import java.util.List;
030
031import static java.util.Objects.requireNonNull;
032
033/** Raw OAuth callback and redirect transport for application-routed Servlet endpoints. Parsing
034 * grants no identity; core completes the browser-bound authorization transaction.
035 * @since 1.0.0
036 */
037@ThreadSafe
038public final class ServletOAuth {
039    private static final int MAXIMUM_CALLBACK_BODY_BYTES = 32_768;
040
041    private ServletOAuth() { }
042
043    /** Parses the original GET query or bounded POST form without Servlet parameter decoding.
044     * Other methods, including HEAD, return Rejected without reading query, headers or body.
045     * The application selects the HTTP response (for example, a route-level 405) and must not
046     * load or consume pending login state for that rejection.
047     * @param request application-routed callback request
048     * @return parsed, rejected or oversized callback outcome
049     * @throws IOException if the Servlet input stream fails
050     * @since 1.0.0
051     */
052    @CheckReturnValue
053    public static @NonNull ServletOAuthCallbackResult authorizationResponseResultFor(@NonNull HttpServletRequest request)
054            throws IOException {
055        requireNonNull(request);
056        String method = request.getMethod();
057        if ("GET".equals(method)) {
058            String query = request.getQueryString();
059            return ServletOAuthCallbackResult.fromParseResult(AuthorizationResponse.fromQueryStringResult(query == null ? "" : query));
060        }
061        if (!"POST".equals(method))
062            return ServletOAuthCallbackResult.fromRejected();
063        byte[] body = request.getInputStream().readNBytes(MAXIMUM_CALLBACK_BODY_BYTES + 1);
064        if (body.length > MAXIMUM_CALLBACK_BODY_BYTES) return ServletOAuthCallbackResult.fromTooLarge();
065        List<String> contentTypes = new ArrayList<>(2);
066        Enumeration<String> values = request.getHeaders("Content-Type");
067        if (values != null) while (values.hasMoreElements() && contentTypes.size() < 2)
068            contentTypes.add(requireNonNull(values.nextElement()));
069        return ServletOAuthCallbackResult.fromParseResult(
070                AuthorizationResponse.fromFormBodyResult(body, List.copyOf(contentTypes), request.getQueryString()));
071    }
072
073    /** Writes an application-approved absolute HTTP(S) redirect without Servlet URL rewriting.
074     * The application sets any browser-bound pending cookie before writing the response.
075     * @param response application-owned response
076     * @param location trusted redirect destination
077     * @since 1.0.0
078     */
079    public static void writeRedirect(@NonNull HttpServletResponse response, @NonNull URI location) {
080        requireNonNull(response);
081        String value = redirectLocation(requireNonNull(location));
082        response.setStatus(HttpServletResponse.SC_FOUND);
083        response.setHeader("Location", value);
084        response.setHeader("Cache-Control", "no-store");
085        response.setHeader("Referrer-Policy", "no-referrer");
086    }
087
088    static @NonNull String redirectLocation(@NonNull URI location) {
089        String scheme = location.getScheme();
090        if (!location.isAbsolute() || location.isOpaque() || location.getHost() == null
091                || location.getHost().isEmpty() || location.getRawUserInfo() != null
092                || location.getPort() < -1 || location.getPort() > 65_535
093                || !("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)))
094            throw unsafeRedirect();
095        String value = location.toASCIIString();
096        for (int index = 0; index < value.length(); index++) {
097            char character = value.charAt(index);
098            if (character <= 0x20 || character >= 0x7f) throw unsafeRedirect();
099            if (character == '%' && index + 2 < value.length()) {
100                int high = Character.digit(value.charAt(index + 1), 16);
101                int low = Character.digit(value.charAt(index + 2), 16);
102                int decoded = high * 16 + low;
103                if (high >= 0 && low >= 0 && (decoded < 0x20 || decoded == 0x7f))
104                    throw unsafeRedirect();
105            }
106        }
107        return value;
108    }
109
110    private static @NonNull IllegalArgumentException unsafeRedirect() {
111        return new IllegalArgumentException("OAuth redirect requires a safe absolute HTTP(S) URI without userinfo");
112    }
113}