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.saml;
017
018import com.google.errorprone.annotations.CheckReturnValue;
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.Immutable;
023import javax.annotation.concurrent.NotThreadSafe;
024import java.net.URI;
025import java.nio.CharBuffer;
026import java.nio.charset.CodingErrorAction;
027import java.nio.charset.StandardCharsets;
028import com.revetsec.internal.encoding.StrictUtf8;
029import java.util.List;
030import java.util.Objects;
031import java.util.Optional;
032
033/**
034 * Optional policy on an SP-initiated AuthnRequest. The options are sealed into pending state and
035 * checked again at completion. Application data is an opaque local hint, never a RelayState URL.
036 *
037 * @since 1.0.0
038 */
039@Immutable
040public final class SamlAuthenticationRequestOptions {
041    private final boolean forceAuthn;
042    private final boolean passive;
043    private final @NonNull List<@NonNull String> contextClassRefs;
044    private final @Nullable String applicationData;
045
046    private SamlAuthenticationRequestOptions(@NonNull Builder builder) {
047        this.forceAuthn = builder.forceAuthn;
048        this.passive = builder.passive;
049        this.contextClassRefs = List.copyOf(builder.contextClassRefs);
050        this.applicationData = builder.applicationData;
051    }
052
053    /**
054     * Starts optional request-policy configuration.
055     *
056     * @return a request-options builder
057     * @since 1.0.0
058     */
059    public static @NonNull Builder builder() { return new Builder(); }
060
061    /**
062     * Reports whether fresh authentication was requested.
063     *
064     * @return true when the IdP must freshly authenticate the principal
065     * @since 1.0.0
066     */
067    public @NonNull Boolean isForceAuthn() { return forceAuthn; }
068    /**
069     * Reports whether noninteractive authentication was requested.
070     *
071     * @return true when the IdP must not visibly interact with the principal
072     * @since 1.0.0
073     */
074    public @NonNull Boolean isPassive() { return passive; }
075    /**
076     * Returns the exact requested authentication context classes.
077     *
078     * @return exact accepted authentication context class URIs
079     * @since 1.0.0
080     */
081    public @NonNull List<@NonNull String> getRequestedAuthnContextClassRefs() { return contextClassRefs; }
082    /**
083     * Returns the application-owned local hint.
084     *
085     * @return application-owned local hint, if supplied
086     * @since 1.0.0
087     */
088    public @NonNull Optional<@NonNull String> getApplicationData() { return Optional.ofNullable(applicationData); }
089
090    /** @return redacted description @since 1.0.0 */
091    @Override public @NonNull String toString() {
092        return "SamlAuthenticationRequestOptions{<redacted>}";
093    }
094
095    /**
096     * Mutable options builder.
097     * @since 1.0.0
098     */
099    @NotThreadSafe
100    @CheckReturnValue
101    public static final class Builder {
102        private boolean forceAuthn;
103        private boolean passive;
104        private @NonNull List<@NonNull String> contextClassRefs = List.of();
105        private @Nullable String applicationData;
106        private Builder() { }
107
108        /**
109         * Requests a fresh authentication; null restores false.
110         * @param value policy value or null
111         * @return this builder
112         * @since 1.0.0
113         */
114        public @NonNull Builder forceAuthn(@Nullable Boolean value) {
115            forceAuthn = value != null && value;
116            return this;
117        }
118
119        /**
120         * Requests noninteractive authentication; null restores false.
121         * @param value policy value or null
122         * @return this builder
123         * @since 1.0.0
124         */
125        public @NonNull Builder passive(@Nullable Boolean value) {
126            passive = value != null && value;
127            return this;
128        }
129
130        /**
131         * Requests exact authentication context classes. Empty or null restores no restriction.
132         * @param values absolute class URIs
133         * @return this builder
134         * @since 1.0.0
135         */
136        public @NonNull Builder requestedAuthnContextClassRefs(@Nullable List<@NonNull String> values) {
137            if (values == null || values.isEmpty()) { contextClassRefs = List.of(); return this; }
138            if (values.size() > 8) throw new IllegalArgumentException("Too many SAML authentication contexts");
139            for (String value : values) {
140                Objects.requireNonNull(value);
141                if (value.isEmpty() || value.length() > 512 || !StrictUtf8.isWellFormed(value))
142                    throw new IllegalArgumentException("Invalid SAML context");
143                try { if (!URI.create(value).isAbsolute()) throw new IllegalArgumentException("Invalid SAML context"); }
144                catch (IllegalArgumentException exception) { throw new IllegalArgumentException("Invalid SAML context"); }
145            }
146            contextClassRefs = List.copyOf(values);
147            return this;
148        }
149
150        /**
151         * Carries an opaque local hint in sealed pending state; null clears it.
152         * @param value local hint, or null
153         * @return this builder
154         * @since 1.0.0
155         */
156        public @NonNull Builder applicationData(@Nullable String value) {
157            if (value != null) {
158                try {
159                    if (StandardCharsets.UTF_8.newEncoder().onMalformedInput(CodingErrorAction.REPORT)
160                            .onUnmappableCharacter(CodingErrorAction.REPORT)
161                            .encode(CharBuffer.wrap(value)).remaining() > 512)
162                        throw new IllegalArgumentException("SAML application data is too long");
163                } catch (java.nio.charset.CharacterCodingException exception) {
164                    throw new IllegalArgumentException("Invalid SAML application data");
165                }
166            }
167            applicationData = value;
168            return this;
169        }
170
171        /**
172         * Creates immutable options.
173         * @return request options
174         * @since 1.0.0
175         */
176        public @NonNull SamlAuthenticationRequestOptions build() {
177            if (forceAuthn && passive) throw new IllegalArgumentException("Conflicting SAML request options");
178            return new SamlAuthenticationRequestOptions(this);
179        }
180    }
181}