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 */
016
017package com.revetsec.oauth.server;
018
019import com.revetsec.internal.Limits;
020import org.jspecify.annotations.NonNull;
021import org.jspecify.annotations.Nullable;
022import com.google.errorprone.annotations.CheckReturnValue;
023import javax.annotation.concurrent.Immutable;
024import java.net.URI;
025import java.nio.charset.StandardCharsets;
026import java.util.Collections;
027import java.util.LinkedHashMap;
028import java.util.List;
029import java.util.Map;
030import java.util.Optional;
031import java.util.Set;
032import static java.util.Objects.requireNonNull;
033
034/**
035 * An immutable, bounded response prepared by the authorization server. Credential emission is explicit;
036 * ordinary headers exclude Location. Instances retain identity equality and fixed redacted diagnostics.
037 * Applications may add their own browser cookies at the HTTP edge.
038 *
039 * @since 1.0.0
040 */
041@Immutable
042public final class OAuthServerResponse {
043 private static final @NonNull Set<@NonNull String> HEADER_NAMES = Set.of("Content-Type", "Cache-Control", "Pragma",
044  "Content-Length", "Referrer-Policy", "Allow", "ETag", "WWW-Authenticate");
045 private final int status;
046 private final @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headers;
047 private final @Nullable URI location;
048 private final byte @NonNull [] body, wireHeaders;
049 private OAuthServerResponse(int status, @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headers,
050   @Nullable URI location, byte @NonNull [] body, byte @NonNull [] wireHeaders) {
051  this.status = status; this.headers = Map.copyOf(headers); this.location = location; this.body = body; this.wireHeaders = wireHeaders;
052 }
053 /** Returns the HTTP status code.
054  *
055  * @return the HTTP status code
056  * @since 1.0.0
057  */
058 @CheckReturnValue public @NonNull Integer getStatusCode() { return this.status; }
059 /** Returns immutable ordinary headers; credential-bearing Location is separate.
060  *
061  * @return immutable response headers, excluding Location
062  * @since 1.0.0
063  */
064 @CheckReturnValue public @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> getHeaders() { return this.headers; }
065 /** Returns the optional credential-bearing redirect for HTTP emission.
066  *
067  * @return the optional credential-bearing redirect; use only for HTTP emission
068  * @since 1.0.0
069  */
070 @CheckReturnValue public @NonNull Optional<@NonNull URI> getLocationWithCredentials() { return Optional.ofNullable(this.location); }
071 /** Emits a defensive bounded HTTP body copy that may contain credentials or personal data.
072  *
073  * @return a defensive copy of the bounded HTTP body, which may contain credentials or personal data
074  * @since 1.0.0
075  */
076 @CheckReturnValue public byte @NonNull [] toHttpBodyWithCredentials() { return this.body.clone(); }
077 /** Returns a fixed description that omits response contents.
078  *
079  * @return a fixed description that omits response contents
080  * @since 1.0.0
081  */
082 @Override public @NonNull String toString() { return "OAuthServerResponse{<redacted>}"; }
083
084 // Restricted to core preparation; never expose a public raw-holder factory or builder.
085 static @NonNull OAuthServerResponse prepare(int status, @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headers,
086   @Nullable URI location, byte @NonNull [] body, int bodyCap, int headerCap) {
087  Limits.AS_MAXIMUM_RESPONSE_BODY_BYTES.require(bodyCap); Limits.AS_MAXIMUM_HEADER_BYTES.require(headerCap);
088  requireNonNull(body); requireNonNull(headers);
089  String reason = switch (status) {
090   case 200 -> "OK"; case 303 -> "See Other"; case 400 -> "Bad Request"; case 401 -> "Unauthorized";
091   case 403 -> "Forbidden"; case 404 -> "Not Found"; case 405 -> "Method Not Allowed"; case 503 -> "Service Unavailable";
092   default -> throw OAuthStoreFormat.invalid();
093  };
094  if (body.length > bodyCap || (location != null && status != 303) || (status == 303 && location == null)) throw OAuthStoreFormat.invalid();
095  Map<String, List<String>> copy = new LinkedHashMap<>();
096  StringBuilder wire = new StringBuilder("HTTP/1.1 ").append(status).append(' ').append(reason).append("\r\n");
097  for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
098   String name = requireNonNull(entry.getKey());
099   if (!HEADER_NAMES.contains(name)) throw OAuthStoreFormat.invalid();
100   List<String> values = List.copyOf(requireNonNull(entry.getValue()));
101   if (values.size() != 1) throw OAuthStoreFormat.invalid();
102   String value = values.get(0);
103   if (value.length() > headerCap) throw OAuthStoreFormat.invalid();
104   for (int i = 0; i < value.length(); i++) if (value.charAt(i) < 0x20 || value.charAt(i) > 0x7e) throw OAuthStoreFormat.invalid();
105   copy.put(name, values); wire.append(name).append(": ").append(value).append("\r\n");
106   if (wire.length() > headerCap) throw OAuthStoreFormat.invalid();
107  }
108  if (!List.of("no-referrer").equals(copy.get("Referrer-Policy"))) throw OAuthStoreFormat.invalid();
109  if (location != null) {
110   if (!location.isAbsolute() || location.getRawFragment() != null || location.getRawUserInfo() != null
111    || OAuthServerConfiguration.hasEncodedAsciiControl(location.toString())) throw OAuthStoreFormat.invalid();
112   String ascii = location.toASCIIString();
113   if (ascii.length() > headerCap) throw OAuthStoreFormat.invalid();
114   for (int i = 0; i < ascii.length(); i++) if (ascii.charAt(i) < 0x21 || ascii.charAt(i) > 0x7e) throw OAuthStoreFormat.invalid();
115   wire.append("Location: ").append(ascii).append("\r\n");
116  }
117  wire.append("\r\n");
118  if (wire.length() > headerCap) throw OAuthStoreFormat.invalid();
119  return new OAuthServerResponse(status, Collections.unmodifiableMap(copy), location, body.clone(), wire.toString().getBytes(StandardCharsets.US_ASCII));
120 }
121 static @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> privateHeaders(int length) {
122  Map<String, List<String>> headers = new LinkedHashMap<>();
123  headers.put("Content-Type", List.of("application/json")); headers.put("Cache-Control", List.of("no-store"));
124  headers.put("Pragma", List.of("no-cache")); headers.put("Referrer-Policy", List.of("no-referrer"));
125  headers.put("Content-Length", List.of(Integer.toString(length))); return headers;
126 }
127 byte @NonNull [] wireHeaders() { return this.wireHeaders.clone(); }
128}