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.javax;
017
018import com.google.errorprone.annotations.CheckReturnValue;
019import com.revetsec.BrowserBinding;
020import com.revetsec.oauth.server.OAuthAuthorizationResult;
021import com.revetsec.oauth.server.OAuthAuthorizationServer;
022import com.revetsec.oauth.server.OAuthIntrospectionResult;
023import com.revetsec.oauth.server.OAuthRevocationResult;
024import com.revetsec.oauth.server.OAuthServerResponse;
025import com.revetsec.oauth.server.OAuthTokenResult;
026import javax.servlet.http.HttpServletRequest;
027import javax.servlet.http.HttpServletResponse;
028import org.jspecify.annotations.NonNull;
029
030import javax.annotation.concurrent.ThreadSafe;
031import java.io.IOException;
032import java.util.ArrayList;
033import java.util.Enumeration;
034import java.util.LinkedHashMap;
035import java.util.List;
036import java.util.Map;
037import java.util.Optional;
038
039import static java.util.Objects.requireNonNull;
040
041/** Thin issuer transport for application-routed Servlet requests and core-prepared responses.
042 * Applications own route and issuer selection, browser sessions, authentication, consent and CSRF.
043 * Read the original body before Servlet parameter decoding. Container and trusted-edge allocation
044 * and time limits must also apply before this adapter is called. Header-name overflow returns
045 * core's malformed-request result rather than an input exception. Enumeration keeps its existing
046 * bounded cutoff; under the bound, original names, casing and duplicate values reach core unchanged.
047 * @since 1.0.0
048 */
049@ThreadSafe
050public final class ServletOAuthAuthorizationServer {
051    // Core's configurable issuer ingress cap cannot exceed 65,536 bytes.
052    private static final int MAXIMUM_ISSUER_BODY_BYTES = 65_536;
053    private static final int REJECTING_HEADER_COUNT = 65;
054
055    private ServletOAuthAuthorizationServer() { }
056
057    /** Admits unchanged authorization input with an independent application-held browser binding.
058     * @param server configured issuer
059     * @param request request on the configured authorization route
060     * @param browserBinding canonical random binding retained in the protected session
061     * @return core's restricted interaction or rejection
062     * @throws IOException if the Servlet input stream fails
063     * @since 1.0.0
064     */
065    @CheckReturnValue
066    public static @NonNull OAuthAuthorizationResult beginAuthorizationResultFor(
067            @NonNull OAuthAuthorizationServer server, @NonNull HttpServletRequest request,
068            @NonNull BrowserBinding browserBinding) throws IOException {
069        requireNonNull(server); requireNonNull(request); requireNonNull(browserBinding);
070        return server.beginAuthorizationResult(request.getMethod(), request.getQueryString(), bodyFor(request),
071                headersFor(request), browserBinding);
072    }
073
074    /** Handles unchanged token form bytes and all materialized header occurrences.
075     * @param server configured issuer
076     * @param request request on the configured token route
077     * @return core's committed response or rejection
078     * @throws IOException if the Servlet input stream fails
079     * @since 1.0.0
080     */
081    @CheckReturnValue
082    public static @NonNull OAuthTokenResult tokenResultFor(@NonNull OAuthAuthorizationServer server,
083            @NonNull HttpServletRequest request) throws IOException {
084        requireNonNull(server); requireNonNull(request);
085        return server.tokenResult(request.getMethod(), request.getQueryString(), bodyFor(request), headersFor(request));
086    }
087
088    /** Handles unchanged revocation form bytes on its configured route.
089     * @param server configured issuer
090     * @param request request on the configured revocation route
091     * @return core's committed response or rejection
092     * @throws IOException if the Servlet input stream fails
093     * @since 1.0.0
094     */
095    @CheckReturnValue
096    public static @NonNull OAuthRevocationResult revocationResultFor(@NonNull OAuthAuthorizationServer server,
097            @NonNull HttpServletRequest request) throws IOException {
098        requireNonNull(server); requireNonNull(request);
099        return server.revokeResult(request.getMethod(), request.getQueryString(), bodyFor(request), headersFor(request));
100    }
101
102    /** Handles unchanged introspection form bytes without selecting caller or resource policy.
103     * @param server configured issuer
104     * @param request request on the configured introspection route
105     * @return core's committed response or rejection
106     * @throws IOException if the Servlet input stream fails
107     * @since 1.0.0
108     */
109    @CheckReturnValue
110    public static @NonNull OAuthIntrospectionResult introspectionResultFor(
111            @NonNull OAuthAuthorizationServer server, @NonNull HttpServletRequest request) throws IOException {
112        requireNonNull(server); requireNonNull(request);
113        return server.introspectionResult(request.getMethod(), request.getQueryString(), bodyFor(request),
114                headersFor(request));
115    }
116
117    /** Emits the exact prepared status, physical headers, credential-bearing Location and body.
118     * Keep this response out of diagnostics and add application-owned browser cookies at the edge.
119     * @param response application-owned transport response
120     * @param prepared restricted core response
121     * @throws IOException if the Servlet output stream fails
122     * @since 1.0.0
123     */
124    public static void writeResponse(@NonNull HttpServletResponse response,
125            @NonNull OAuthServerResponse prepared) throws IOException {
126        requireNonNull(response); requireNonNull(prepared);
127        Optional<String> destination = prepared.getLocationWithCredentials().map(ServletOAuth::redirectLocation);
128        response.setStatus(prepared.getStatusCode());
129        for (Map.Entry<String, List<String>> header : prepared.getHeaders().entrySet()) {
130            boolean first = true;
131            for (String value : header.getValue()) {
132                if (first) response.setHeader(header.getKey(), value);
133                else response.addHeader(header.getKey(), value);
134                first = false;
135            }
136        }
137        if (destination.isPresent()) response.setHeader("Location", destination.orElseThrow());
138        byte[] body = prepared.toHttpBodyWithCredentials();
139        if (body.length != 0) response.getOutputStream().write(body);
140    }
141
142    private static byte @NonNull [] bodyFor(@NonNull HttpServletRequest request) throws IOException {
143        return request.getInputStream().readNBytes(MAXIMUM_ISSUER_BODY_BYTES + 1);
144    }
145
146    /** Stops after enough fields to guarantee a core rejection, retaining duplicate occurrences. */
147    private static @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headersFor(
148            @NonNull HttpServletRequest request) {
149        Enumeration<String> names = request.getHeaderNames();
150        if (names == null) throw new IllegalArgumentException("Servlet request headers are unavailable");
151        Map<String, List<String>> fields = new LinkedHashMap<>();
152        int occurrences = 0;
153        int namesSeen = 0;
154        while (names.hasMoreElements() && fields.size() < REJECTING_HEADER_COUNT
155                && occurrences < REJECTING_HEADER_COUNT) {
156            if (++namesSeen >= REJECTING_HEADER_COUNT)
157                // An empty field name guarantees core refusal, even for repeated names with no values.
158                return Map.of("", List.of());
159            String name = requireNonNull(names.nextElement());
160            List<String> values = fields.computeIfAbsent(name, ignored -> new ArrayList<>());
161            Enumeration<String> originals = request.getHeaders(name);
162            if (originals == null) throw new IllegalStateException("Servlet request headers are unavailable");
163            while (originals.hasMoreElements()
164                    && values.size() < REJECTING_HEADER_COUNT
165                    && occurrences < REJECTING_HEADER_COUNT) {
166                values.add(requireNonNull(originals.nextElement()));
167                occurrences++;
168            }
169        }
170        Map<String, List<String>> result = new LinkedHashMap<>();
171        fields.forEach((name, values) -> result.put(name, List.copyOf(values)));
172        return result;
173    }
174}