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.revetsec.jose.JwksPublisher;
019import com.revetsec.jose.JwksResponse;
020import javax.servlet.http.HttpServletRequest;
021import javax.servlet.http.HttpServletResponse;
022import org.jspecify.annotations.NonNull;
023import org.jspecify.annotations.Nullable;
024
025import javax.annotation.concurrent.ThreadSafe;
026import java.io.IOException;
027import java.util.Enumeration;
028import java.util.List;
029import java.util.Map;
030
031import static java.util.Objects.requireNonNull;
032
033/**
034 * Publishes standalone public JSON Web Key Sets on application-owned Servlet routes.
035 * The core publisher prepares method handling, conditional responses, cache headers and JSON bytes.
036 * Applications choose the route and its key set; no OAuth authorization server is required.
037 *
038 * @since 1.0.0
039 */
040@ThreadSafe
041public final class ServletJwks {
042
043        private static final int MAXIMUM_CONDITIONAL_HEADER_CHARACTERS = 8_192;
044
045        private ServletJwks() {}
046
047        /**
048         * Prepares and writes a standalone JWKS response using every {@code If-None-Match} occurrence.
049         * Servlet header lookup is case-insensitive and retains repeated physical field values.
050         *
051         * @param publisher configured public-key publisher
052         * @param request request on the application's JWKS route
053         * @param response application-owned transport response
054         * @throws NullPointerException if a required argument is null
055         * @throws IllegalStateException if the Servlet does not expose request headers
056         * @throws IOException if the Servlet output stream fails
057         * @since 1.0.0
058         */
059        public static void writeResponse(@NonNull JwksPublisher publisher,
060                        @NonNull HttpServletRequest request, @NonNull HttpServletResponse response) throws IOException {
061                requireNonNull(publisher);
062                requireNonNull(request);
063                requireNonNull(response);
064                writeResponse(response, publisher.responseFor(request.getMethod(), ifNoneMatchFor(request)));
065        }
066
067        /**
068         * Writes a prepared core response without JSON marshalling or header regeneration.
069         * A prepared HEAD or not-modified response does not obtain or write the output stream.
070         *
071         * @param response application-owned transport response
072         * @param prepared prepared standalone JWKS response
073         * @throws NullPointerException if a required argument is null
074         * @throws IOException if the Servlet output stream fails
075         * @since 1.0.0
076         */
077        public static void writeResponse(@NonNull HttpServletResponse response,
078                        @NonNull JwksResponse prepared) throws IOException {
079                requireNonNull(response);
080                requireNonNull(prepared);
081                response.setStatus(prepared.getStatusCode());
082                for (Map.Entry<String, List<String>> header : prepared.getHeaders().entrySet()) {
083                        boolean first = true;
084                        for (String value : header.getValue()) {
085                                if (first)
086                                        response.setHeader(header.getKey(), value);
087                                else
088                                        response.addHeader(header.getKey(), value);
089                                first = false;
090                        }
091                }
092                byte[] body = prepared.toHttpBody();
093                if (body.length != 0)
094                        response.getOutputStream().write(body);
095        }
096
097        private static @Nullable String ifNoneMatchFor(@NonNull HttpServletRequest request) {
098                Enumeration<String> values = request.getHeaders("If-None-Match");
099                if (values == null)
100                        throw new IllegalStateException("Servlet request headers are unavailable");
101                StringBuilder combined = new StringBuilder();
102                boolean present = false;
103                while (values.hasMoreElements()) {
104                        String value = requireNonNull(values.nextElement());
105                        int separator = present ? 1 : 0;
106                        if (value.length() > MAXIMUM_CONDITIONAL_HEADER_CHARACTERS - combined.length() - separator)
107                                return "x".repeat(MAXIMUM_CONDITIONAL_HEADER_CHARACTERS + 1);
108                        if (present)
109                                combined.append(',');
110                        combined.append(value);
111                        present = true;
112                }
113                return present ? combined.toString() : null;
114        }
115}