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.soklet;
017
018import com.google.errorprone.annotations.CheckReturnValue;
019import com.revetsec.jose.JwksPublisher;
020import com.revetsec.jose.PublishedJwk;
021import com.revetsec.json.JsonObject;
022import com.soklet.Request;
023import com.soklet.Response;
024import org.jspecify.annotations.NonNull;
025
026import javax.annotation.concurrent.Immutable;
027import javax.annotation.concurrent.ThreadSafe;
028import java.util.LinkedHashMap;
029import java.util.List;
030import java.util.Map;
031
032import static java.util.Objects.requireNonNull;
033
034/**
035 * Prepares logical public JSON Web Key Set responses on application-owned Soklet routes.
036 * Applications choose the route and its key set; no OAuth authorization server is required.
037 * {@link #from(JwksPublisher, Request)} returns a Soklet response with a typed {@link Body} for
038 * application-owned JSON serialization, weak entity tags and no prepared content length.
039 * For prepared bytes and Soklet's default marshaler, use {@link JwksMarshaledResponse} instead.
040 *
041 * @since 1.0.0
042 */
043@ThreadSafe
044public final class JwksResponse {
045
046        private JwksResponse() {}
047
048        /**
049         * Prepares a logical JWKS response for application-owned JSON serialization.
050         * A successful GET has an immutable {@link Body}; HEAD, not-modified responses and rejections have no body.
051         * Entity tags are weak document fingerprints. No content length is supplied, because the application's
052         * marshaler chooses the encoded representation. Other prepared headers are retained.
053         * The default Soklet marshaler uses diagnostic {@code toString()} output for arbitrary objects; applications
054         * must configure their JSON marshaler to serialize {@link Body#toJsonObject()} or {@link Body#toJson()}.
055         *
056         * @param publisher configured public-key publisher
057         * @param request request on the application's JWKS route
058         * @return logical response whose body is ready for application serialization or structural assertions
059         * @throws NullPointerException if a required argument is null
060         * @since 1.0.0
061         */
062        @CheckReturnValue
063        public static @NonNull Response from(@NonNull JwksPublisher publisher, @NonNull Request request) {
064                requireNonNull(publisher);
065                requireNonNull(request);
066                com.revetsec.jose.JwksResponse prepared = publisher.responseFor(request.getHttpMethod().name(),
067                                JwksRequestHeaders.ifNoneMatchFor(request));
068                Map<String, List<String>> headers = new LinkedHashMap<>(prepared.getHeaders());
069                headers.remove("Content-Length");
070                headers.computeIfPresent("ETag", (name, values) -> values.stream().map(value -> "W/" + value).toList());
071                Response.Builder builder = Response.withStatusCode(prepared.getStatusCode()).headers(headers);
072                prepared.getDocument().ifPresent(document -> builder.body(new Body(publisher.getKeys(), document)));
073                return builder.build();
074        }
075
076        /**
077         * Immutable public JWKS body for application serialization and structural assertions.
078         * Its keys and JSON tree come from one publisher snapshot. JSON emission is explicit; diagnostics redact
079         * key identifiers, public parameters and certificate material.
080         *
081         * @since 1.0.0
082         */
083        @Immutable
084        public static final class Body {
085                private final @NonNull List<@NonNull PublishedJwk> keys;
086                private final @NonNull JsonObject document;
087
088                private Body(@NonNull List<@NonNull PublishedJwk> keys, @NonNull JsonObject document) {
089                        this.keys = List.copyOf(keys);
090                        this.document = requireNonNull(document);
091                }
092
093                /**
094                 * Returns the immutable public keys in publication order.
095                 * @return the public key snapshot
096                 * @since 1.0.0
097                 */
098                public @NonNull List<@NonNull PublishedJwk> getKeys() {
099                        return this.keys;
100                }
101
102                /**
103                 * Returns the immutable public JWKS document, including certificate metadata.
104                 * @return the structured document for explicit serialization or inspection
105                 * @since 1.0.0
106                 */
107                public @NonNull JsonObject toJsonObject() {
108                        return this.document;
109                }
110
111                /**
112                 * Serializes the complete public JWKS document as JSON text.
113                 * @return the JSON text, including configured identifiers and certificate metadata
114                 * @since 1.0.0
115                 */
116                public @NonNull String toJson() {
117                        return this.document.toJson();
118                }
119
120                /**
121                 * Describes the body without key or certificate contents.
122                 * @return a redacted description
123                 * @since 1.0.0
124                 */
125                @Override
126                public @NonNull String toString() {
127                        return "JwksResponse.Body{keyCount=" + this.keys.size() + "}";
128                }
129        }
130
131}