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;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.OutboundUriPolicy;
021import com.revetsec.internal.http.UriChecks;
022import com.revetsec.internal.HostClassifier;
023import com.revetsec.internal.Limits;
024import com.revetsec.json.JsonArray;
025import com.revetsec.json.JsonObject;
026import com.revetsec.json.JsonString;
027import org.jspecify.annotations.NonNull;
028import org.jspecify.annotations.Nullable;
029import javax.annotation.concurrent.Immutable;
030import javax.annotation.concurrent.NotThreadSafe;
031import java.net.URI;
032import java.nio.charset.StandardCharsets;
033import java.util.ArrayList;
034import java.util.LinkedHashSet;
035import java.util.List;
036import static java.util.Objects.requireNonNull;
037
038/**
039 * Application-configured protected-resource metadata (RFC 9728 sections 2 and 3).
040 * The resource identifier is preserved exactly, including its raw path/query; no URI normalization or I/O occurs.
041 * The app serves {@link #toJson()} as application/json and chooses cache policy. This metadata grants no permission.
042 *
043 * @author <a href="https://www.revetkn.com">Mark Allen</a>
044 * @since 1.0.0
045 */
046@Immutable
047public final class ProtectedResourceMetadata {
048        private static final int MAXIMUM_JSON_LENGTH = Limits.HTTP_RESPONSE_BODY_SIZE.getDefaultIntValue();
049        private static final String WELL_KNOWN = "/.well-known/oauth-protected-resource";
050        private final @NonNull URI resource;
051        private final @NonNull List<@NonNull String> authorizationServers;
052        private final @NonNull List<@NonNull String> scopesSupported;
053        private final @NonNull String json;
054        private ProtectedResourceMetadata(@NonNull Builder builder, @NonNull String json) {
055                this.resource = builder.resource; this.authorizationServers = builder.authorizationServers;
056                this.scopesSupported = builder.scopesSupported; this.json = json;
057        }
058        /**
059         * Starts metadata for an exact configured resource identifier.
060         * @param resource the resource URI; HTTPS is required unless loopback HTTP is explicitly allowed
061         * @return the builder
062         * @throws NullPointerException if resource is null
063         * @since 1.0.0
064         */
065        public static @NonNull Builder withResource(@NonNull URI resource) { return new Builder(resource); }
066        /**
067         * Returns the exact configured resource identifier.
068         * @return the resource
069         * @since 1.0.0
070         */
071        public @NonNull URI getResource() { return this.resource; }
072        /**
073         * Returns exact authorization-server issuer strings in configured order, without duplicates.
074         * @return immutable issuer strings
075         * @since 1.0.0
076         */
077        public @NonNull List<@NonNull String> getAuthorizationServers() { return this.authorizationServers; }
078        /**
079         * Returns supported scope tokens in first-occurrence order.
080         * @return immutable scopes
081         * @since 1.0.0
082         */
083        public @NonNull List<@NonNull String> getScopesSupported() { return this.scopesSupported; }
084        /**
085         * Derives the RFC 9728 well-known location using raw components and stripping a terminating literal path slash.
086         * The configured resource identifier is unchanged, including percent escapes, dot segments and query.
087         * @return the metadata URI
088         * @since 1.0.0
089         */
090        public @NonNull URI getWellKnownUri() {
091                String path = requireNonNull(this.resource.getRawPath());
092                if (path.endsWith("/")) path = path.substring(0, path.length() - 1);
093                String query = this.resource.getRawQuery();
094                return URI.create(this.resource.getScheme() + "://" + this.resource.getRawAuthority() + WELL_KNOWN
095                                + path + (query == null ? "" : "?" + query));
096        }
097        /**
098         * Returns bounded compact JSON advertising only header bearer presentation. Empty optional arrays are omitted.
099         * @return the JSON text, at most 256 KiB in UTF-8
100         * @since 1.0.0
101         */
102        public @NonNull String toJson() { return this.json; }
103        /**
104         * Redacts metadata configuration from diagnostic text.
105         * @return the redacted description
106         * @since 1.0.0
107         */
108        @Override
109        public @NonNull String toString() { return "ProtectedResourceMetadata{configuration=<redacted>}"; }
110
111        static void requireResourceUri(@NonNull URI uri, boolean allowInsecureLoopback) {
112                String scheme = uri.getScheme(); String host = uri.getHost(); int port = uri.getPort();
113                if (scheme == null || uri.isOpaque() || host == null || (port != -1 && (port < 1 || port > 65_535))
114                                || uri.getRawUserInfo() != null || uri.getRawFragment() != null
115                                || !(scheme.equalsIgnoreCase("https") || (scheme.equalsIgnoreCase("http") && allowInsecureLoopback
116                                                && HostClassifier.isPlainHttpLoopbackHost(host))))
117                        throw new IllegalArgumentException("A resource URI must be absolute HTTPS without userinfo or fragment, "
118                                        + "or explicitly allowed loopback HTTP.");
119        }
120
121        static @NonNull List<@NonNull String> checkedScopes(@Nullable List<@NonNull String> values, long maximum) {
122                if (values == null) return List.of();
123                if (values.size() > maximum / 3) throw new IllegalArgumentException("The scope list is too large.");
124                LinkedHashSet<String> copy = new LinkedHashSet<>(); long length = 0;
125                for (String value : values) {
126                        requireNonNull(value);
127                        length += (long) value.length() + 3;
128                        if (length > maximum) throw new IllegalArgumentException("The scope list is too large.");
129                        if (value.isEmpty()) throw new IllegalArgumentException("A scope must not be empty.");
130                        for (int index = 0; index < value.length(); index++) {
131                                char c = value.charAt(index);
132                                if (c <= 0x20 || c == 0x22 || c == 0x5C || c >= 0x7F)
133                                        throw new IllegalArgumentException("A scope contains invalid characters.");
134                        }
135                        copy.add(value);
136                }
137                return List.copyOf(copy);
138        }
139
140        private static int jsonStringLength(@NonNull String value) {
141                if (value.length() > MAXIMUM_JSON_LENGTH) throw new IllegalArgumentException("Resource metadata is too large.");
142                return JsonString.fromValue(value).toJson().getBytes(StandardCharsets.UTF_8).length;
143        }
144
145        /**
146         * Mutable metadata configuration. Null optional values restore the empty/false defaults.
147         * @author <a href="https://www.revetkn.com">Mark Allen</a>
148         * @since 1.0.0
149         */
150        @NotThreadSafe
151        @CheckReturnValue
152        public static final class Builder {
153                private final @NonNull URI resource;
154                private @NonNull List<@NonNull String> authorizationServers = List.of();
155                private @NonNull List<@NonNull String> scopesSupported = List.of();
156                private boolean allowInsecureLoopback;
157                private Builder(@NonNull URI resource) { this.resource = requireNonNull(resource); }
158                /**
159                 * Replaces exact issuer identifiers. Uses the default outbound URI checks; queries are also invalid.
160                 * @param value issuer strings, or null/empty to omit
161                 * @return this builder
162                 * @since 1.0.0
163                 */
164                public @NonNull Builder authorizationServers(@Nullable List<@NonNull String> value) {
165                        if (value == null) { this.authorizationServers = List.of(); return this; }
166                        if (value.size() > MAXIMUM_JSON_LENGTH / 3) throw new IllegalArgumentException("Resource metadata is too large.");
167                        LinkedHashSet<String> copy = new LinkedHashSet<>(); long length = 0;
168                        for (String issuer : value) {
169                                requireNonNull(issuer);
170                                length += (long) jsonStringLength(issuer) + 1;
171                                if (length > MAXIMUM_JSON_LENGTH) throw new IllegalArgumentException("Resource metadata is too large.");
172                                copy.add(issuer);
173                        }
174                        this.authorizationServers = List.copyOf(copy); return this;
175                }
176                /**
177                 * Replaces supported scope tokens, preserving first occurrence order and removing duplicates.
178                 * @param value scope tokens, or null/empty to omit
179                 * @return this builder
180                 * @since 1.0.0
181                 */
182                public @NonNull Builder scopesSupported(@Nullable List<@NonNull String> value) {
183                        this.scopesSupported = checkedScopes(value, MAXIMUM_JSON_LENGTH); return this;
184                }
185                /**
186                 * Permits plain HTTP only to a recognized loopback literal or exactly localhost for local tests.
187                 * @param value whether to allow loopback HTTP, or null to restore false
188                 * @return this builder
189                 * @since 1.0.0
190                 */
191                public @NonNull Builder allowInsecureLoopback(@Nullable Boolean value) {
192                        this.allowInsecureLoopback = Boolean.TRUE.equals(value); return this;
193                }
194                /**
195                 * Checks URI policy and renders bounded metadata without I/O. Builders can be reused.
196                 * @return immutable metadata
197                 * @throws IllegalArgumentException if configuration is unsafe or serialized JSON exceeds 256 KiB
198                 * @since 1.0.0
199                 */
200                public @NonNull ProtectedResourceMetadata build() {
201                        requireResourceUri(this.resource, this.allowInsecureLoopback);
202                        long length = 51L + jsonStringLength(this.resource.toString());
203                        JsonObject.Builder json = JsonObject.builder().put("resource", this.resource.toString())
204                                        .put("bearer_methods_supported", JsonArray.fromElements(List.of(JsonString.fromValue("header"))));
205                        if (!this.authorizationServers.isEmpty()) length += 26;
206                        if (!this.scopesSupported.isEmpty()) length += 21;
207                        for (String issuer : this.authorizationServers) {
208                                URI uri;
209                                try { uri = URI.create(issuer); }
210                                catch (IllegalArgumentException exception) { throw new IllegalArgumentException("An issuer URI is malformed."); }
211                                UriChecks.requirePermitted(uri, OutboundUriPolicy.defaultInstance(), this.allowInsecureLoopback);
212                                if (uri.getRawQuery() != null) throw new IllegalArgumentException("An issuer must not have a query.");
213                                length += (long) jsonStringLength(issuer) + 1;
214                        }
215                        for (String scope : this.scopesSupported) length += (long) scope.length() + 3;
216                        // Bound the full JSON expansion before constructing arrays/rendering. Exact size is checked below.
217                        if (length > MAXIMUM_JSON_LENGTH) throw new IllegalArgumentException("Resource metadata is too large.");
218                        if (!this.authorizationServers.isEmpty()) json.put("authorization_servers", JsonArray.fromElements(
219                                        this.authorizationServers.stream().map(JsonString::fromValue).toList()));
220                        if (!this.scopesSupported.isEmpty()) json.put("scopes_supported", JsonArray.fromElements(
221                                        this.scopesSupported.stream().map(JsonString::fromValue).toList()));
222                        String text = json.build().toJson();
223                        if (text.getBytes(StandardCharsets.UTF_8).length > MAXIMUM_JSON_LENGTH)
224                                throw new IllegalArgumentException("Resource metadata is too large.");
225                        return new ProtectedResourceMetadata(this, text);
226                }
227        }
228}