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.internal.Limits;
021import org.jspecify.annotations.NonNull;
022import org.jspecify.annotations.Nullable;
023import javax.annotation.concurrent.Immutable;
024import javax.annotation.concurrent.NotThreadSafe;
025import java.net.URI;
026import java.util.List;
027
028/**
029 * A bounded WWW-Authenticate Bearer value (RFC 6750 section 3 and RFC 9728 section 5).
030 * Supply only trusted application configuration, never reflected token/provider error text. The app chooses the
031 * HTTP status. An initial 401 challenge has no error. At least one rendered parameter is required.
032 *
033 * @author <a href="https://www.revetkn.com">Mark Allen</a>
034 * @since 1.0.0
035 */
036@Immutable
037public final class BearerChallenge {
038        private final @NonNull String headerValue;
039        private BearerChallenge(@NonNull String headerValue) { this.headerValue = headerValue; }
040        /**
041         * Starts a challenge with no parameters and an 8 KiB rendered field limit.
042         * @return the builder
043         * @since 1.0.0
044         */
045        public static @NonNull Builder builder() { return new Builder(); }
046        /**
047         * Returns the complete ASCII field value, suitable for WWW-Authenticate.
048         * @return the header value
049         * @since 1.0.0
050         */
051        public @NonNull String getHeaderValue() { return this.headerValue; }
052        /**
053         * Redacts challenge configuration from diagnostic text.
054         * @return the redacted description
055         * @since 1.0.0
056         */
057        @Override
058        public @NonNull String toString() { return "BearerChallenge{parameters=<redacted>}"; }
059
060        private static void requireText(@NonNull String value, boolean description) {
061                if (value.length() > Limits.BEARER_CHALLENGE_SIZE.getCap())
062                        throw new IllegalArgumentException("A challenge parameter is too large.");
063                for (int index = 0; index < value.length(); index++) {
064                        char c = value.charAt(index);
065                        if (c < 0x20 || c > 0x7E || (description && (c == '"' || c == '\\')))
066                                throw new IllegalArgumentException("A challenge parameter contains invalid characters.");
067                }
068        }
069
070        private static void append(@NonNull StringBuilder output, @NonNull String name, @NonNull String value, int maximum) {
071                long length = (long) output.length() + (output.length() == 6 ? 1 : 2) + name.length() + 3 + value.length();
072                for (int index = 0; index < value.length(); index++) {
073                        char c = value.charAt(index);
074                        if (c == '"' || c == '\\') length++;
075                }
076                if (length > maximum) throw new IllegalArgumentException("The rendered bearer challenge is too large.");
077                output.append(output.length() == 6 ? " " : ", ").append(name).append("=\"");
078                for (int index = 0; index < value.length(); index++) {
079                        char c = value.charAt(index);
080                        if (c == '"' || c == '\\') output.append('\\');
081                        output.append(c);
082                }
083                output.append('"');
084        }
085
086        /**
087         * Mutable challenge configuration. Null property values restore omission or the documented default.
088         * @author <a href="https://www.revetkn.com">Mark Allen</a>
089         * @since 1.0.0
090         */
091        @NotThreadSafe
092        @CheckReturnValue
093        public static final class Builder {
094                private @Nullable String realm;
095                private @Nullable BearerError error;
096                private @Nullable String errorDescription;
097                private @NonNull List<@NonNull String> scopes = List.of();
098                private @Nullable URI resourceMetadata;
099                private int maximumHeaderLength = Limits.BEARER_CHALLENGE_SIZE.getDefaultIntValue();
100                private boolean allowInsecureLoopback;
101                private Builder() { }
102                /**
103                 * Sets a quoted ASCII realm. Quote/backslash are escaped; controls and non-ASCII are rejected.
104                 * @param value the realm, or null to omit
105                 * @return this builder
106                 * @since 1.0.0
107                 */
108                public @NonNull Builder realm(@Nullable String value) {
109                        if (value != null) requireText(value, false);
110                        this.realm = value; return this;
111                }
112                /**
113                 * Sets the protocol error. Omit for an initial missing-credential challenge.
114                 * @param value the error, or null to omit
115                 * @return this builder
116                 * @since 1.0.0
117                 */
118                public @NonNull Builder error(@Nullable BearerError value) { this.error = value; return this; }
119                /**
120                 * Sets trusted ASCII prose satisfying RFC 6750's error_description grammar; quotes/backslashes are invalid.
121                 * @param value the description, or null to omit
122                 * @return this builder
123                 * @since 1.0.0
124                 */
125                public @NonNull Builder errorDescription(@Nullable String value) {
126                        if (value != null) requireText(value, true);
127                        this.errorDescription = value; return this;
128                }
129                /**
130                 * Replaces required scopes, preserving first-occurrence order and removing duplicates.
131                 * @param value the scope tokens, or null/empty to omit
132                 * @return this builder
133                 * @since 1.0.0
134                 */
135                public @NonNull Builder scopes(@Nullable List<@NonNull String> value) {
136                        this.scopes = ProtectedResourceMetadata.checkedScopes(value,
137                                        Limits.BEARER_CHALLENGE_SIZE.getCap()); return this;
138                }
139                /**
140                 * Sets the trusted resource metadata location. HTTPS is required except explicit loopback HTTP.
141                 * @param value the metadata URI, or null to omit
142                 * @return this builder
143                 * @since 1.0.0
144                 */
145                public @NonNull Builder resourceMetadata(@Nullable URI value) { this.resourceMetadata = value; return this; }
146                /**
147                 * Sets the rendered ASCII field byte limit, including quote/backslash expansion.
148                 * @param value the limit from 1 KiB through 64 KiB, or null to restore 8 KiB
149                 * @return this builder
150                 * @since 1.0.0
151                 */
152                public @NonNull Builder maximumHeaderLength(@Nullable Integer value) {
153                        this.maximumHeaderLength = value == null ? Limits.BEARER_CHALLENGE_SIZE.getDefaultIntValue()
154                                        : Limits.BEARER_CHALLENGE_SIZE.require(value); return this;
155                }
156                /**
157                 * Permits plain HTTP only to an existing recognized loopback literal or exactly localhost, for local tests.
158                 * @param value whether to allow local HTTP, or null to restore false
159                 * @return this builder
160                 * @since 1.0.0
161                 */
162                public @NonNull Builder allowInsecureLoopback(@Nullable Boolean value) {
163                        this.allowInsecureLoopback = Boolean.TRUE.equals(value); return this;
164                }
165                /**
166                 * Builds the field without I/O.
167                 * @return the immutable challenge
168                 * @throws IllegalStateException if no parameter would be rendered
169                 * @throws IllegalArgumentException if the supplied configuration is incompatible, unsafe or oversized
170                 * @since 1.0.0
171                 */
172                public @NonNull BearerChallenge build() {
173                        if (this.errorDescription != null && this.error == null)
174                                throw new IllegalArgumentException("A bearer error description requires an error.");
175                        StringBuilder output = new StringBuilder("Bearer");
176                        if (this.realm != null) append(output, "realm", this.realm, this.maximumHeaderLength);
177                        if (this.error != null) append(output, "error", this.error.getWireValue(), this.maximumHeaderLength);
178                        if (this.errorDescription != null) append(output, "error_description", this.errorDescription, this.maximumHeaderLength);
179                        if (!this.scopes.isEmpty()) append(output, "scope", String.join(" ", this.scopes), this.maximumHeaderLength);
180                        if (this.resourceMetadata != null) {
181                                ProtectedResourceMetadata.requireResourceUri(this.resourceMetadata, this.allowInsecureLoopback);
182                                if (this.resourceMetadata.toString().length() > this.maximumHeaderLength)
183                                        throw new IllegalArgumentException("The rendered bearer challenge is too large.");
184                                append(output, "resource_metadata", this.resourceMetadata.toASCIIString(), this.maximumHeaderLength);
185                        }
186                        if (output.length() == 6) throw new IllegalStateException("A bearer challenge requires a parameter.");
187                        return new BearerChallenge(output.toString());
188                }
189        }
190}