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.saml;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021import com.google.errorprone.annotations.CheckReturnValue;
022
023import javax.annotation.concurrent.Immutable;
024import javax.annotation.concurrent.NotThreadSafe;
025import java.net.URI;
026import java.security.PublicKey;
027import java.security.interfaces.ECPublicKey;
028import java.security.interfaces.RSAPublicKey;
029import java.security.cert.X509Certificate;
030import java.util.List;
031import java.util.Objects;
032import java.util.Set;
033
034/**
035 * An immutable application-approved IdP connection. The required connection ID is the application's
036 * account and replay namespace; the self-asserted SAML entity ID cannot replace it. Metadata parsing
037 * never automatically approves a connection.
038 *
039 * @since 1.0.0
040 */
041@Immutable
042public final class SamlIdentityProvider {
043    private final @NonNull String connectionId;
044    private final @NonNull String entityId;
045    private final @Nullable URI redirectSingleSignOnService;
046    private final @Nullable URI postSingleSignOnService;
047    private final @Nullable URI redirectSingleLogoutService;
048    private final @Nullable URI postSingleLogoutService;
049    private final @Nullable URI redirectSingleLogoutResponseService;
050    private final @Nullable URI postSingleLogoutResponseService;
051    private final @NonNull List<@NonNull PublicKey> signingKeys;
052    private final boolean wantAuthnRequestsSigned;
053    private final boolean requireSignedAssertions;
054    private final boolean allowUnsolicitedResponses;
055    private final boolean allowAesCbcEncryption;
056    private final @NonNull Set<@NonNull SamlCompatibilityMode> compatibility;
057    private final @NonNull List<@NonNull String> authorizedIdentifierScopes;
058
059    private SamlIdentityProvider(@NonNull Builder builder) {
060        this.connectionId = Objects.requireNonNull(builder.connectionId);
061        this.entityId = builder.entityId;
062        this.redirectSingleSignOnService = builder.redirectSingleSignOnService;
063        this.postSingleSignOnService = builder.postSingleSignOnService;
064        this.redirectSingleLogoutService = builder.redirectSingleLogoutService;
065        this.postSingleLogoutService = builder.postSingleLogoutService;
066        this.redirectSingleLogoutResponseService = builder.redirectSingleLogoutResponseService;
067        this.postSingleLogoutResponseService = builder.postSingleLogoutResponseService;
068        this.signingKeys = List.copyOf(builder.signingKeys);
069        this.wantAuthnRequestsSigned = builder.wantAuthnRequestsSigned;
070        this.requireSignedAssertions = builder.requireSignedAssertions;
071        this.allowUnsolicitedResponses = builder.allowUnsolicitedResponses;
072        this.allowAesCbcEncryption = builder.allowAesCbcEncryption;
073        this.compatibility = Set.copyOf(builder.compatibility);
074        this.authorizedIdentifierScopes = List.copyOf(builder.authorizedIdentifierScopes);
075    }
076
077    /**
078     * Starts manual trust configuration for one IdP.
079     *
080     * @param entityId nonempty exact IdP entity ID, well-formed text of at most 2048 UTF-16 code units
081     * @return a builder
082     * @since 1.0.0
083     */
084    public static @NonNull Builder withEntityId(@NonNull String entityId) {
085        if (!PendingSamlAuthenticationCodec.fitsText(Objects.requireNonNull(entityId), 2048))
086            throw new IllegalArgumentException("Invalid IdP entity ID");
087        return new Builder(entityId);
088    }
089
090    /**
091     * Prefills a builder from application-approved metadata. The application must assign a
092     * connection ID and decide whether to trust the supplied metadata source.
093     *
094     * @param metadata selected IdP metadata
095     * @return a builder requiring a connection ID
096     * @since 1.0.0
097     */
098    public static @NonNull Builder withMetadata(@NonNull SamlIdentityProviderMetadata metadata) {
099        Objects.requireNonNull(metadata);
100        List<PublicKey> keys = metadata.getSigningCertificates().stream()
101                .map(X509Certificate::getPublicKey).toList();
102        return withEntityId(metadata.getEntityId())
103                .redirectSingleSignOnService(metadata.getRedirectSingleSignOnService().orElse(null))
104                .postSingleSignOnService(metadata.getPostSingleSignOnService().orElse(null))
105                .redirectSingleLogoutService(metadata.getRedirectSingleLogoutService().orElse(null))
106                .postSingleLogoutService(metadata.getPostSingleLogoutService().orElse(null))
107                .redirectSingleLogoutResponseService(metadata.getRedirectSingleLogoutResponseService().orElse(null))
108                .postSingleLogoutResponseService(metadata.getPostSingleLogoutResponseService().orElse(null))
109                .authorizedIdentifierScopes(metadata.getAuthorizedIdentifierScopes())
110                .signingKeys(keys).wantAuthnRequestsSigned(metadata.wantsAuthnRequestsSigned());
111    }
112
113    /**
114     * Returns this value.
115     *
116     * @return the application-assigned connection ID
117     * @since 1.0.0
118     */
119    public @NonNull String getConnectionId() { return connectionId; }
120    /**
121     * Returns this value.
122     *
123     * @return the IdP's exact entity ID
124     * @since 1.0.0
125     */
126    public @NonNull String getEntityId() { return entityId; }
127    /**
128     * Redacts connection and trust details.
129     *
130     * @since 1.0.0
131     */
132    @Override public @NonNull String toString() { return "SamlIdentityProvider{<redacted>}"; }
133
134    @Nullable URI redirectSingleSignOnService() { return redirectSingleSignOnService; }
135    @Nullable URI postSingleSignOnService() { return postSingleSignOnService; }
136    @Nullable URI redirectSingleLogoutService() { return redirectSingleLogoutService; }
137    @Nullable URI postSingleLogoutService() { return postSingleLogoutService; }
138    @Nullable URI redirectSingleLogoutResponseService() {
139        return redirectSingleLogoutResponseService == null
140                ? redirectSingleLogoutService : redirectSingleLogoutResponseService;
141    }
142    @Nullable URI postSingleLogoutResponseService() {
143        return postSingleLogoutResponseService == null
144                ? postSingleLogoutService : postSingleLogoutResponseService;
145    }
146    @NonNull List<@NonNull PublicKey> signingKeys() { return signingKeys; }
147    boolean wantAuthnRequestsSigned() { return wantAuthnRequestsSigned; }
148    boolean requireSignedAssertions() { return requireSignedAssertions; }
149    boolean allowUnsolicitedResponses() {
150        return allowUnsolicitedResponses || compatibility.contains(SamlCompatibilityMode.UNSOLICITED_RESPONSES);
151    }
152    boolean allowAesCbcEncryption() {
153        return allowAesCbcEncryption || compatibility.contains(SamlCompatibilityMode.AES_CBC_ENCRYPTION);
154    }
155    boolean allowSha1Signatures() { return compatibility.contains(SamlCompatibilityMode.SHA1_SIGNATURES); }
156    @NonNull List<@NonNull String> authorizedIdentifierScopes() { return authorizedIdentifierScopes; }
157
158    /**
159     * Configures one trusted IdP connection.
160     *
161     * @since 1.0.0
162     */
163    @NotThreadSafe
164    @CheckReturnValue
165    public static final class Builder {
166        private final @NonNull String entityId;
167        private @Nullable String connectionId;
168        private @Nullable URI redirectSingleSignOnService;
169        private @Nullable URI postSingleSignOnService;
170        private @Nullable URI redirectSingleLogoutService;
171        private @Nullable URI postSingleLogoutService;
172        private @Nullable URI redirectSingleLogoutResponseService;
173        private @Nullable URI postSingleLogoutResponseService;
174        private @NonNull List<@NonNull PublicKey> signingKeys = List.of();
175        private boolean wantAuthnRequestsSigned;
176        private boolean requireSignedAssertions;
177        private boolean allowUnsolicitedResponses;
178        private boolean allowAesCbcEncryption;
179        private @NonNull Set<@NonNull SamlCompatibilityMode> compatibility = Set.of();
180        private @NonNull List<@NonNull String> authorizedIdentifierScopes = List.of();
181
182        private Builder(@NonNull String entityId) { this.entityId = entityId; }
183
184        /**
185         * Configures this option.
186         *
187         * @param value application-unique nonempty namespace of at most 256 well-formed UTF-16 code units
188         * @return this builder
189         * @since 1.0.0
190         */
191        @CheckReturnValue public @NonNull Builder connectionId(@Nullable String value) {
192            this.connectionId = value;
193            return this;
194        }
195
196        /**
197         * Configures this option.
198         *
199         * @param value HTTPS HTTP-Redirect SSO endpoint
200         * @return this builder
201         * @since 1.0.0
202         */
203        @CheckReturnValue public @NonNull Builder redirectSingleSignOnService(@Nullable URI value) {
204            this.redirectSingleSignOnService = value;
205            return this;
206        }
207
208        /**
209         * Configures this IdP's HTTP-POST AuthnRequest endpoint.
210         *
211         * @param value HTTPS endpoint, or null to clear
212         * @return this builder
213         * @since 1.0.0
214         */
215        @CheckReturnValue public @NonNull Builder postSingleSignOnService(@Nullable URI value) {
216            this.postSingleSignOnService = value;
217            return this;
218        }
219        /**
220         * Configures the IdP's HTTP-Redirect Single Logout endpoint.
221         *
222         * @param value HTTPS endpoint, or null to clear
223         * @return this builder
224         * @since 1.0.0
225         */
226        @CheckReturnValue public @NonNull Builder redirectSingleLogoutService(@Nullable URI value) {
227            this.redirectSingleLogoutService = value;
228            return this;
229        }
230
231        /**
232         * Configures the IdP's HTTP-POST Single Logout endpoint.
233         *
234         * @param value HTTPS endpoint, or null to clear
235         * @return this builder
236         * @since 1.0.0
237         */
238        @CheckReturnValue public @NonNull Builder postSingleLogoutService(@Nullable URI value) {
239            this.postSingleLogoutService = value;
240            return this;
241        }
242        /** Configures a distinct HTTP-Redirect endpoint for LogoutResponse messages.
243         * @param value HTTPS ResponseLocation, or null to use the request endpoint
244         * @return this builder
245         * @since 1.0.0
246         */
247        @CheckReturnValue public @NonNull Builder redirectSingleLogoutResponseService(@Nullable URI value) {
248            this.redirectSingleLogoutResponseService = value;
249            return this;
250        }
251        /** Configures a distinct HTTP-POST endpoint for LogoutResponse messages.
252         * @param value HTTPS ResponseLocation, or null to use the request endpoint
253         * @return this builder
254         * @since 1.0.0
255         */
256        @CheckReturnValue public @NonNull Builder postSingleLogoutResponseService(@Nullable URI value) {
257            this.postSingleLogoutResponseService = value;
258            return this;
259        }
260
261        /**
262         * Configures this option.
263         *
264         * @param value trusted current and rollover verification keys
265         * @return this builder
266         * @since 1.0.0
267         */
268        @CheckReturnValue public @NonNull Builder signingKeys(@Nullable List<@NonNull PublicKey> value) {
269            this.signingKeys = value == null ? List.of() : List.copyOf(value);
270            return this;
271        }
272
273        /**
274         * Configures this option.
275         *
276         * @param value whether the IdP requires signed AuthnRequests
277         * @return this builder
278         * @since 1.0.0
279         */
280        @CheckReturnValue public @NonNull Builder wantAuthnRequestsSigned(@Nullable Boolean value) {
281            this.wantAuthnRequestsSigned = Boolean.TRUE.equals(value);
282            return this;
283        }
284
285        /**
286         * Configures this option.
287         *
288         * @param value whether the Assertion must carry its own valid signature
289         * @return this builder
290         * @since 1.0.0
291         */
292        @CheckReturnValue public @NonNull Builder requireSignedAssertions(@Nullable Boolean value) {
293            this.requireSignedAssertions = Boolean.TRUE.equals(value);
294            return this;
295        }
296
297        /**
298         * Enables a separate IdP-initiated login operation for this connection. It is off by
299         * default and still requires signature, audience, bearer and replay checks.
300         *
301         * @param value true to allow unsolicited responses, or null to reset to false
302         * @return this builder
303         * @since 1.0.0
304         */
305        @CheckReturnValue public @NonNull Builder allowUnsolicitedResponses(@Nullable Boolean value) {
306            this.allowUnsolicitedResponses = Boolean.TRUE.equals(value);
307            return this;
308        }
309        /**
310         * Enables decrypting AES-CBC assertions only beneath a verified Response signature.
311         * It is off by default and never advertised in SP metadata.
312         *
313         * @param value true to enable CBC for this IdP, or null to reset to false
314         * @return this builder
315         * @since 1.0.0
316         */
317        @CheckReturnValue public @NonNull Builder allowAesCbcEncryption(@Nullable Boolean value) {
318            this.allowAesCbcEncryption = Boolean.TRUE.equals(value);
319            return this;
320        }
321        /**
322         * Sets explicit compatibility modes for this one trusted IdP connection.
323         * Null clears all modes. SHA-1 stays rejected unless listed here.
324         *
325         * @param value enabled modes, or null to clear
326         * @return this builder
327         * @since 1.0.0
328         */
329        @CheckReturnValue public @NonNull Builder compatibility(
330                @Nullable Set<@NonNull SamlCompatibilityMode> value) {
331            this.compatibility = value == null ? Set.of() : Set.copyOf(value);
332            return this;
333        }
334        /**
335         * Sets exact approved scopes for SAML subject-id and pairwise-id attributes. A scope
336         * advertised by metadata is only a starting value; the application approves this list.
337         *
338         * @param value exact literal scopes, or null to clear
339         * @return this builder
340         * @since 1.0.0
341         */
342        @CheckReturnValue public @NonNull Builder authorizedIdentifierScopes(
343                @Nullable List<@NonNull String> value) {
344            this.authorizedIdentifierScopes = value == null ? List.of() : List.copyOf(value);
345            return this;
346        }
347
348        /**
349         * Returns this value.
350         *
351         * @return the immutable IdP connection
352         * @since 1.0.0
353         */
354        public @NonNull SamlIdentityProvider build() {
355            if (connectionId == null || !PendingSamlAuthenticationCodec.fitsText(connectionId, 256))
356                throw new IllegalStateException("IdP connection ID is required");
357            if ((redirectSingleSignOnService == null && postSingleSignOnService == null)
358                    || !safeEndpoint(redirectSingleSignOnService) || !safeEndpoint(postSingleSignOnService)
359                    || !safeEndpoint(redirectSingleLogoutService) || !safeEndpoint(postSingleLogoutService)
360                    || !safeEndpoint(redirectSingleLogoutResponseService)
361                    || !safeEndpoint(postSingleLogoutResponseService))
362                throw new IllegalStateException("An IdP HTTPS SSO endpoint is required");
363            if (signingKeys.isEmpty() || signingKeys.size() > 8)
364                throw new IllegalStateException("IdP signing keys are required");
365            for (PublicKey key : signingKeys) {
366                if (!(key instanceof RSAPublicKey rsa && rsa.getModulus().bitLength() >= 2048)
367                        && !(key instanceof ECPublicKey ec && ec.getParams().getCurve().getField().getFieldSize() >= 256))
368                    throw new IllegalStateException("Unsupported or weak IdP signing key");
369            }
370            if (authorizedIdentifierScopes.size() > 32 || authorizedIdentifierScopes.stream()
371                    .anyMatch(scope -> scope.isEmpty() || scope.length() > 255
372                            || scope.contains("@") || scope.contains("*") || scope.contains(" ")))
373                throw new IllegalStateException("Invalid SAML identifier scope policy");
374            return new SamlIdentityProvider(this);
375        }
376
377        private static boolean safeEndpoint(@Nullable URI endpoint) {
378            return endpoint == null || ("https".equalsIgnoreCase(endpoint.getScheme())
379                    && endpoint.getHost() != null && endpoint.getRawUserInfo() == null
380                    && endpoint.getRawFragment() == null);
381        }
382    }
383}