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.oidc;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020
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.time.Duration;
027import java.util.*;
028import static java.util.Objects.requireNonNull;
029import com.revetsec.oauth.AuthorizationRequestOptions;
030
031/**
032 * Per-login OIDC options (OpenID Connect Core section 3.1.2.1). Complete scope/resource and ACR acceptance sets replace defaults; explicit ACR preferences preserve order.
033 * Nonce is generated by the client. Requested max-age and ACR values are authenticated in pending state and enforced
034 * on the ID token. Application data still needs application redirect allowlisting.
035 *
036 * @author <a href="https://www.revetkn.com">Mark Allen</a>
037 * @since 1.0.0
038 */
039@Immutable
040public final class OidcAuthenticationOptions {
041        private final AuthorizationRequestOptions oauth;
042        private final @Nullable Set<String> scopes;
043        private final @Nullable List<URI> resources;
044        private final @Nullable Set<String> acrValues;
045        private final @Nullable List<String> acrPreferences;
046        private final @Nullable Duration maxAge;
047        private OidcAuthenticationOptions(@NonNull Builder builder) {
048                this.oauth = builder.oauth.build(); this.scopes = builder.scopes; this.resources = builder.resources;
049                this.acrValues = builder.acrValues; this.acrPreferences = builder.acrPreferences; this.maxAge = builder.maxAge;
050        }
051        /**
052         * Starts login options with no per-request overrides.
053         *
054         * @return the builder
055         * @since 1.0.0
056         */
057        public static @NonNull Builder builder() { return new Builder(); }
058        /**
059         * Returns the maximum authentication age.
060         *
061         * @return maximum authentication age
062         * @since 1.0.0
063         */
064        public @NonNull Optional<@NonNull Duration> getMaxAge() { return Optional.ofNullable(this.maxAge); }
065        /**
066         * Returns the ACR override.
067         *
068         * @return ACR override
069         * @since 1.0.0
070         */
071        public @NonNull Optional<@NonNull Set<@NonNull String>> getRequiredAcrValues() { return Optional.ofNullable(this.acrValues); }
072        /**
073         * Returns the ordered request preference override, independent of local acceptance requirements.
074         * @return immutable preferences; empty optional inherits defaults, present empty list omits the parameter
075         * @since 1.0.0
076         */
077        public @NonNull Optional<@NonNull List<@NonNull String>> getAcrPreferences() { return Optional.ofNullable(this.acrPreferences); }
078
079        /**
080         * Returns the scope override.
081         *
082         * @return scope override
083         * @since 1.0.0
084         */
085        public @NonNull Optional<@NonNull Set<@NonNull String>> getScopes() { return Optional.ofNullable(this.scopes); }
086        /**
087         * Returns the resource override.
088         *
089         * @return resource override
090         * @since 1.0.0
091         */
092        public @NonNull Optional<@NonNull List<@NonNull URI>> getResources() { return Optional.ofNullable(this.resources); }
093        /**
094         * Returns the prompt.
095         *
096         * @return prompt
097         * @since 1.0.0
098         */
099        public @NonNull Optional<@NonNull String> getPrompt() { return this.oauth.getPrompt(); }
100        /**
101         * Returns the login hint.
102         *
103         * @return login hint
104         * @since 1.0.0
105         */
106        public @NonNull Optional<@NonNull String> getLoginHint() { return this.oauth.getLoginHint(); }
107        /**
108         * Returns the application data.
109         *
110         * @return application data
111         * @since 1.0.0
112         */
113        public @NonNull Map<@NonNull String, @NonNull String> getApplicationData() { return this.oauth.getApplicationData(); }
114        @NonNull AuthorizationRequestOptions transactionOptions(@NonNull Set<@NonNull String> defaults, @NonNull List<@NonNull URI> defaultResources) {
115                Set<String> requested = new HashSet<>(this.scopes == null ? defaults : this.scopes);
116                requested.add("openid");
117                return AuthorizationRequestOptions.builder().scopes(requested)
118                                .resources(this.resources == null ? defaultResources : this.resources).responseMode(this.oauth.getResponseMode())
119                                .prompt(this.oauth.getPrompt().orElse(null)).loginHint(this.oauth.getLoginHint().orElse(null))
120                                .applicationData(this.oauth.getApplicationData()).additionalParameters(this.oauth.getAdditionalParameters()).build();
121        }
122        static @NonNull List<@NonNull String> requireAcrPreferences(@NonNull List<@NonNull String> values) {
123                List<String> copy = List.copyOf(values);
124                if (requireAcrValues(new HashSet<>(copy)).size() != copy.size())
125                        throw new IllegalArgumentException("ACR preferences must be distinct.");
126                return copy;
127        }
128        static @NonNull Set<@NonNull String> requireAcrValues(@NonNull Set<@NonNull String> values) {
129                Set<String> copy = Set.copyOf(values);
130                if (copy.stream().anyMatch(value -> value.isEmpty() || value.chars().anyMatch(c -> c <= 0x20 || c >= 0x7F)))
131                        throw new IllegalArgumentException("An ACR value contains invalid characters.");
132                return copy;
133        }
134        /**
135         * Redacts request options.
136         *
137         * @return a redacted description
138         * @since 1.0.0
139         */
140        @Override public @NonNull String toString() { return "OidcAuthenticationOptions{options=<redacted>}"; }
141        /**
142         * Mutable per-login option builder.
143         * @author <a href="https://www.revetkn.com">Mark Allen</a>
144         * @since 1.0.0
145         */
146        @NotThreadSafe
147        @CheckReturnValue
148        public static final class Builder {
149                private AuthorizationRequestOptions.Builder oauth = AuthorizationRequestOptions.builder();
150                private @Nullable Set<String> scopes;
151                private @Nullable List<URI> resources;
152                private @Nullable Set<String> acrValues;
153                private @Nullable List<String> acrPreferences;
154                private @Nullable Duration maxAge;
155                private Builder() { }
156                /**
157                 * Sets the complete scope override. Null restores the default.
158                 *
159                 * @param value the value, or null
160                 * @return this builder
161                 * @since 1.0.0
162                 */
163                public @NonNull Builder scopes(@Nullable Set<@NonNull String> value) { this.scopes = value == null ? null : AuthorizationRequestOptions.builder().scopes(value).build().getScopes(); return this; }
164                /**
165                 * Sets the ordered resource override. Null restores the default.
166                 *
167                 * @param value the value, or null
168                 * @return this builder
169                 * @since 1.0.0
170                 */
171                public @NonNull Builder resources(@Nullable List<@NonNull URI> value) { this.resources = value == null ? null : AuthorizationRequestOptions.builder().resources(value).build().getResources(); return this; }
172                /**
173                 * Sets the complete accepted ACR override. Null restores the default.
174                 *
175                 * @param value the value, or null
176                 * @return this builder
177                 * @since 1.0.0
178                 */
179                public @NonNull Builder requiredAcrValues(@Nullable Set<@NonNull String> value) { this.acrValues = value == null ? null : requireAcrValues(value); return this; }
180                /**
181                 * Sets ordered request preferences without changing ID-token acceptance. Null inherits client defaults;
182                 * an empty list omits acr_values while keeping the effective acceptance requirement.
183                 * @param value distinct nonempty visible-ASCII preferences, or null
184                 * @return this builder
185                 * @throws IllegalArgumentException if a value is malformed or duplicated
186                 * @since 1.0.0
187                 */
188                public @NonNull Builder acrPreferences(@Nullable List<@NonNull String> value) { this.acrPreferences = value == null ? null : requireAcrPreferences(value); return this; }
189
190                /**
191                 * Sets the maximum authentication age; zero still requires auth_time. Null restores the default.
192                 *
193                 * @param value the value, or null
194                 * @return this builder
195                 * @since 1.0.0
196                 */
197                // The nanosecond adjustment is deliberately checked: the wire value must be whole seconds.
198                @SuppressWarnings("JavaDurationGetSecondsGetNano")
199                public @NonNull Builder maxAge(@Nullable Duration value) { if (value != null && (value.isNegative() || value.getNano() != 0)) throw new IllegalArgumentException("Maximum authentication age must be whole non-negative seconds."); this.maxAge = value; return this; }
200                /**
201                 * Sets the Core prompt values; none must be used alone. Null restores the default.
202                 *
203                 * @param value the value, or null
204                 * @return this builder
205                 * @since 1.0.0
206                 */
207                public @NonNull Builder prompt(@Nullable String value) { if (value != null) { List<String> prompts = List.of(value.split(" ", -1)); if (prompts.stream().anyMatch(p -> !Set.of("none", "login", "consent", "select_account").contains(p)) || Set.copyOf(prompts).size() != prompts.size() || (prompts.contains("none") && prompts.size() != 1)) throw new IllegalArgumentException("The OIDC prompt is invalid."); } this.oauth = this.oauth.prompt(value); return this; }
208                /**
209                 * Sets the login hint. Null restores the default.
210                 *
211                 * @param value the value, or null
212                 * @return this builder
213                 * @since 1.0.0
214                 */
215                public @NonNull Builder loginHint(@Nullable String value) { this.oauth = this.oauth.loginHint(value); return this; }
216                /**
217                 * Sets the complete application data. Null restores the default.
218                 *
219                 * @param value the value, or null
220                 * @return this builder
221                 * @since 1.0.0
222                 */
223                public @NonNull Builder applicationData(@Nullable Map<@NonNull String, @NonNull String> value) { this.oauth = this.oauth.applicationData(value == null ? Map.of() : value); return this; }
224                /**
225                 * Sets the complete nonreserved authorization parameters. Null restores the default.
226                 *
227                 * @param value the value, or null
228                 * @return this builder
229                 * @since 1.0.0
230                 */
231                public @NonNull Builder additionalParameters(@Nullable Map<@NonNull String, @NonNull String> value) { this.oauth = this.oauth.additionalParameters(value == null ? Map.of() : value); return this; }
232                /**
233                 * Sets callback delivery. Null restores query delivery.
234                 *
235                 * @param value mode, or null
236                 * @return this builder
237                 * @since 1.0.0
238                 */
239                public @NonNull Builder responseMode(AuthorizationRequestOptions.@Nullable ResponseMode value) { this.oauth = this.oauth.responseMode(value == null ? AuthorizationRequestOptions.ResponseMode.QUERY : value); return this; }
240                /**
241                 * Builds immutable login options.
242                 *
243                 * @return the options
244                 * @since 1.0.0
245                 */
246                public @NonNull OidcAuthenticationOptions build() { return new OidcAuthenticationOptions(this); }
247        }
248}