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.webauthn.WebAuthnBrowserRequest;
020import com.revetsec.webauthn.WebAuthnSettings;
021import javax.servlet.http.HttpServletRequest;
022import javax.servlet.http.HttpServletResponse;
023import org.jspecify.annotations.NonNull;
024
025import javax.annotation.concurrent.ThreadSafe;
026import java.io.IOException;
027import java.io.InterruptedIOException;
028import java.net.SocketTimeoutException;
029import java.nio.charset.StandardCharsets;
030import java.util.Enumeration;
031
032import static java.util.Objects.requireNonNull;
033
034/** Raw WebAuthn browser transport. The application owns account approval, browser sessions,
035 * browser binding, ceremony-ID routing, CSRF and the final sign-in decision.
036 * @since 1.0.0
037 */
038@ThreadSafe
039public final class ServletWebAuthn {
040    private ServletWebAuthn() { }
041
042    /** Reads one bounded POST JSON completion body before Servlet parameter decoding. A method,
043     * media-type or size failure releases no body bytes. Interrupted reads retain the interrupt flag.
044     * @param settings the configured relying party's body limits
045     * @param request application-routed browser completion request
046     * @return unchanged bytes, explicit rejection or unavailable input
047     * @since 1.0.0
048     */
049    @CheckReturnValue
050    public static @NonNull ServletWebAuthnBodyResult bodyResultFor(@NonNull WebAuthnSettings settings,
051            @NonNull HttpServletRequest request) {
052        requireNonNull(settings); requireNonNull(request);
053        if (!"POST".equals(request.getMethod()) || !jsonContentType(request))
054            return ServletWebAuthnBodyResult.Rejected.INSTANCE;
055        if (Thread.currentThread().isInterrupted()) return ServletWebAuthnBodyResult.Unavailable.INSTANCE;
056        int cap = settings.getMaximumResponseBodyBytes();
057        try {
058            byte[] bytes = request.getInputStream().readNBytes(cap + 1);
059            if (Thread.currentThread().isInterrupted()) return ServletWebAuthnBodyResult.Unavailable.INSTANCE;
060            return bytes.length > cap ? ServletWebAuthnBodyResult.Rejected.INSTANCE
061                    : new ServletWebAuthnBodyResult.Read(bytes);
062        } catch (InterruptedIOException failure) {
063            if (!(failure instanceof SocketTimeoutException)) Thread.currentThread().interrupt();
064            return ServletWebAuthnBodyResult.Unavailable.INSTANCE;
065        } catch (IOException failure) {
066            return ServletWebAuthnBodyResult.Unavailable.INSTANCE;
067        }
068    }
069
070    /** Writes core-prepared registration or authentication options as exact UTF-8 JSON.
071     * @param response application-owned response
072     * @param prepared core-prepared browser request
073     * @throws IOException if the Servlet output stream fails
074     * @since 1.0.0
075     */
076    public static void writeBrowserRequest(@NonNull HttpServletResponse response,
077            @NonNull WebAuthnBrowserRequest prepared) throws IOException {
078        requireNonNull(response); requireNonNull(prepared);
079        byte[] body = prepared.getJson().getBytes(StandardCharsets.UTF_8);
080        response.setStatus(HttpServletResponse.SC_OK);
081        response.setHeader("Content-Type", "application/json; charset=UTF-8");
082        response.setHeader("Cache-Control", "no-store");
083        response.setHeader("Pragma", "no-cache");
084        response.setHeader("Referrer-Policy", "no-referrer");
085        response.setHeader("X-Content-Type-Options", "nosniff");
086        response.setContentLength(body.length);
087        response.getOutputStream().write(body);
088    }
089
090    private static boolean jsonContentType(@NonNull HttpServletRequest request) {
091        Enumeration<String> values = request.getHeaders("Content-Type");
092        if (values == null || !values.hasMoreElements()) return false;
093        String field = requireNonNull(values.nextElement());
094        if (values.hasMoreElements()) return false;
095        if (field.length() > 128) return false;
096        for (int index = 0; index < field.length(); index++) {
097            char character = field.charAt(index);
098            if ((character < 0x20 && character != '\t') || character > 0x7e) return false;
099        }
100        int start = 0;
101        int end = field.length();
102        while (start < end && (field.charAt(start) == ' ' || field.charAt(start) == '\t')) start++;
103        while (end > start && (field.charAt(end - 1) == ' ' || field.charAt(end - 1) == '\t')) end--;
104        String normalized = field.substring(start, end);
105        return "application/json".equalsIgnoreCase(normalized)
106                || "application/json; charset=utf-8".equalsIgnoreCase(normalized)
107                || "application/json;charset=utf-8".equalsIgnoreCase(normalized);
108    }
109}