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 com.revetsec.internal.xml.EnvelopedSignatureVerifier;
020import com.revetsec.internal.xml.SamlResponseStructure;
021import com.revetsec.internal.xml.SecureXmlParser;
022import com.revetsec.internal.xml.XmlNcName;
023import com.revetsec.internal.ObserverDispatch;
024import org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.Nullable;
026import com.google.errorprone.annotations.CheckReturnValue;
027
028import javax.annotation.concurrent.NotThreadSafe;
029import javax.annotation.concurrent.ThreadSafe;
030import java.net.URI;
031import java.security.MessageDigest;
032import java.security.PrivateKey;
033import java.util.ArrayList;
034import java.security.SecureRandom;
035import java.security.interfaces.RSAPrivateKey;
036import java.nio.charset.StandardCharsets;
037import java.time.Clock;
038import java.time.DateTimeException;
039import java.time.Duration;
040import java.time.Instant;
041import java.util.Objects;
042import java.util.List;
043import java.util.Base64;
044import java.nio.ByteBuffer;
045import java.security.NoSuchAlgorithmException;
046import java.util.function.Function;
047import java.util.function.Supplier;
048import org.w3c.dom.Element;
049import org.w3c.dom.Node;
050
051/**
052 * An immutable SAML 2.0 service provider for Redirect or POST login requests, POST assertion
053 * response completion and signed Redirect or POST logout. The application owns browser cookies or pending storage,
054 * account linking and application sessions. The replay cache is supplied explicitly and must
055 * be shared across nodes for a distributed deployment.
056 *
057 * @since 1.0.0
058 */
059@ThreadSafe
060public final class SamlServiceProvider {
061    private static final @NonNull String XML_DSIG_SECURE_VALIDATION =
062            "org.jcp.xml.dsig.secureValidation";
063    private final @NonNull String entityId;
064    private final @NonNull URI assertionConsumerServiceUrl;
065    private final @Nullable URI singleLogoutServiceUrl;
066    private final @Nullable URI postSingleLogoutServiceUrl;
067    private final @NonNull SamlReplayCache replayCache;
068    private final @Nullable PrivateKey signingKey;
069    private final @Nullable SamlCredential signingCredential;
070    private final @NonNull List<@NonNull SamlCredential> decryptionCredentials;
071    private final @NonNull Clock clock;
072    private final @NonNull SecureRandom random;
073    private final @NonNull Duration clockSkew;
074    private final @NonNull Duration maximumResponseAge;
075    private final @NonNull Duration pendingLifetime;
076    private final @NonNull Duration replayBudget;
077    private final @NonNull SamlObserver observer;
078
079    private SamlServiceProvider(@NonNull Builder builder) {
080        this.entityId = builder.entityId;
081        this.assertionConsumerServiceUrl = Objects.requireNonNull(builder.assertionConsumerServiceUrl);
082        this.singleLogoutServiceUrl = builder.singleLogoutServiceUrl;
083        this.postSingleLogoutServiceUrl = builder.postSingleLogoutServiceUrl;
084        this.replayCache = Objects.requireNonNull(builder.replayCache);
085        this.signingKey = builder.signingKey;
086        this.signingCredential = builder.signingCredential;
087        this.decryptionCredentials = List.copyOf(builder.decryptionCredentials);
088        this.clock = builder.clock;
089        this.random = builder.random;
090        this.clockSkew = builder.clockSkew;
091        this.maximumResponseAge = builder.maximumResponseAge;
092        this.pendingLifetime = builder.pendingLifetime;
093        this.replayBudget = builder.replayBudget;
094        this.observer = builder.observer;
095    }
096
097    /**
098     * Begins SP configuration with its exact entity ID.
099     *
100     * @param entityId nonempty SP entity ID, well-formed text of at most 2048 UTF-16 code units
101     * @return a builder
102     * @since 1.0.0
103     */
104    public static @NonNull Builder withEntityId(@NonNull String entityId) {
105        if (!PendingSamlAuthenticationCodec.fitsText(Objects.requireNonNull(entityId), 2048))
106            throw new IllegalArgumentException("Invalid SP entity ID");
107        return new Builder(entityId);
108    }
109
110    /**
111     * Creates one outbound Redirect AuthnRequest with a fresh request ID and RelayState handle.
112     * Persist its pending state in the initiating browser before sending the redirect.
113     *
114     * @param identityProvider approved IdP connection
115     * @return a prepared redirect and pending state, rejection, or unavailability
116     * @since 1.0.0
117     */
118    public @NonNull SamlAuthenticationRequestResult beginAuthenticationResult(
119            @NonNull SamlIdentityProvider identityProvider) {
120        return beginAuthenticationResult(identityProvider, SamlAuthenticationRequestOptions.builder().build());
121    }
122
123    /**
124     * Begins a Redirect AuthnRequest with explicit freshness, context and application state.
125     * @param identityProvider approved IdP connection
126     * @param options request policy sealed into pending state
127     * @return prepared request and pending state, rejection or unavailability
128     * @since 1.0.0
129     */
130    public @NonNull SamlAuthenticationRequestResult beginAuthenticationResult(
131            @NonNull SamlIdentityProvider identityProvider,
132            @NonNull SamlAuthenticationRequestOptions options) {
133        return observed(SamlObserver.Operation.BEGIN_AUTHENTICATION,
134                () -> beginAuthenticationInternal(identityProvider, options), SamlServiceProvider::outcome);
135    }
136
137    private @NonNull SamlAuthenticationRequestResult beginAuthenticationInternal(
138            @NonNull SamlIdentityProvider identityProvider,
139            @NonNull SamlAuthenticationRequestOptions options) {
140        Objects.requireNonNull(identityProvider);
141        Objects.requireNonNull(options);
142        URI endpoint = identityProvider.redirectSingleSignOnService();
143        if (endpoint == null) return SamlAuthenticationRequestResult.Rejected.CONFIGURATION;
144        SamlRedirectAuthnRequest.Result prepared = SamlRedirectAuthnRequest.prepare(entityId,
145                assertionConsumerServiceUrl, endpoint, signingKey,
146                identityProvider.wantAuthnRequestsSigned(), random, clock, pendingLifetime, options);
147        if (prepared instanceof SamlRedirectAuthnRequest.Rejected)
148            return SamlAuthenticationRequestResult.Rejected.CONFIGURATION;
149        if (prepared instanceof SamlRedirectAuthnRequest.Unavailable)
150            return SamlAuthenticationRequestResult.Unavailable.INSTANCE;
151        SamlRedirectAuthnRequest.Prepared request = (SamlRedirectAuthnRequest.Prepared) prepared;
152        PendingSamlAuthentication pending = new PendingSamlAuthentication(entityId, request.requestId(),
153                request.relayState(), identityProvider.getConnectionId(), identityProvider.getEntityId(),
154                assertionConsumerServiceUrl.toASCIIString(), request.issuedAt(), request.expiresAt(), options);
155        return new SamlAuthenticationRequestResult.Prepared(request.redirect(), pending);
156    }
157
158    /**
159     * Begins a POST-binding AuthnRequest. The returned form contains a signed XML request when
160     * this SP has a signing key. Persist pending state before delivering the form page.
161     *
162     * @param identityProvider approved IdP connection with a POST endpoint
163     * @return prepared form and pending state, rejection or unavailability
164     * @since 1.0.0
165     */
166    public @NonNull SamlAuthenticationRequestResult beginPostAuthenticationResult(
167            @NonNull SamlIdentityProvider identityProvider) {
168        return beginPostAuthenticationResult(identityProvider, SamlAuthenticationRequestOptions.builder().build());
169    }
170
171    /**
172     * Begins a POST AuthnRequest with explicit freshness, context and application state.
173     * @param identityProvider approved IdP connection with a POST endpoint
174     * @param options request policy sealed into pending state
175     * @return prepared form and pending state, rejection or unavailability
176     * @since 1.0.0
177     */
178    public @NonNull SamlAuthenticationRequestResult beginPostAuthenticationResult(
179            @NonNull SamlIdentityProvider identityProvider,
180            @NonNull SamlAuthenticationRequestOptions options) {
181        return observed(SamlObserver.Operation.BEGIN_POST_AUTHENTICATION,
182                () -> beginPostAuthenticationInternal(identityProvider, options), SamlServiceProvider::outcome);
183    }
184
185    private @NonNull SamlAuthenticationRequestResult beginPostAuthenticationInternal(
186            @NonNull SamlIdentityProvider identityProvider,
187            @NonNull SamlAuthenticationRequestOptions options) {
188        Objects.requireNonNull(identityProvider);
189        Objects.requireNonNull(options);
190        URI endpoint = identityProvider.postSingleSignOnService();
191        if (endpoint == null) return SamlAuthenticationRequestResult.Rejected.CONFIGURATION;
192        SamlRedirectAuthnRequest.Result prepared = SamlRedirectAuthnRequest.preparePost(entityId,
193                assertionConsumerServiceUrl, endpoint, signingKey,
194                identityProvider.wantAuthnRequestsSigned(), random, clock, pendingLifetime, options);
195        if (prepared instanceof SamlRedirectAuthnRequest.Rejected)
196            return SamlAuthenticationRequestResult.Rejected.CONFIGURATION;
197        if (prepared instanceof SamlRedirectAuthnRequest.Unavailable)
198            return SamlAuthenticationRequestResult.Unavailable.INSTANCE;
199        SamlRedirectAuthnRequest.PostPrepared request = (SamlRedirectAuthnRequest.PostPrepared) prepared;
200        PendingSamlAuthentication pending = new PendingSamlAuthentication(entityId, request.requestId(),
201                request.relayState(), identityProvider.getConnectionId(), identityProvider.getEntityId(),
202                assertionConsumerServiceUrl.toASCIIString(), request.issuedAt(), request.expiresAt(), options);
203        return new SamlAuthenticationRequestResult.PostPrepared(request.form(), pending);
204    }
205
206    /**
207     * Completes an SP-initiated login. It authenticates the browser's pending record and RelayState
208     * before parsing XML. Identity is returned only after a successful atomic replay insertion.
209     * The application clears the pending cookie on every terminal outcome.
210     * The fixed assertion attribute profile is described by {@link SamlAttribute}. An exceeded
211     * attribute limit rejects the entire login before replay insertion; store-backed pending
212     * state has already been consumed before XML parsing. Start a new login after rejection.
213     *
214     * @param message opaque POST-binding message
215     * @param pendingSource pending state received from the initiating browser
216     * @param identityProvider approved IdP connection
217     * @return a result with identity only on success
218     * @since 1.0.0
219     */
220    public @NonNull SamlAuthenticationResult completeAuthenticationResult(@NonNull SamlPostBindingMessage message,
221            @NonNull PendingSamlAuthenticationSource pendingSource,
222            @NonNull SamlIdentityProvider identityProvider) {
223        return observed(SamlObserver.Operation.COMPLETE_AUTHENTICATION,
224                () -> completeAuthenticationInternal(message, pendingSource, identityProvider),
225                SamlServiceProvider::outcome);
226    }
227
228    private @NonNull SamlAuthenticationResult completeAuthenticationInternal(@NonNull SamlPostBindingMessage message,
229            @NonNull PendingSamlAuthenticationSource pendingSource,
230            @NonNull SamlIdentityProvider identityProvider) {
231        Objects.requireNonNull(message);
232        Objects.requireNonNull(pendingSource);
233        Objects.requireNonNull(identityProvider);
234        if (message.getKind() != SamlPostBindingMessage.Kind.RESPONSE)
235            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
236        PendingSamlAuthenticationSource.Resolution resolution = pendingSource.resolve(clock,
237                message.relayState(), replayBudget);
238        if (resolution instanceof PendingSamlAuthenticationSource.Rejected)
239            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.PENDING);
240        if (resolution instanceof PendingSamlAuthenticationSource.Unavailable)
241            return SamlAuthenticationResult.Unavailable.INSTANCE;
242        if (resolution instanceof PendingSamlAuthenticationSource.Indeterminate)
243            return SamlAuthenticationResult.Indeterminate.INSTANCE;
244        PendingSamlAuthentication pending = ((PendingSamlAuthenticationSource.Resolved) resolution).pending();
245        Instant now;
246        try { now = clock.instant(); }
247        catch (RuntimeException exception) { return SamlAuthenticationResult.Unavailable.INSTANCE; }
248        if (!entityId.equals(pending.spEntityId()) || !identityProvider.getConnectionId().equals(pending.connectionId())
249                || !identityProvider.getEntityId().equals(pending.idpEntityId())
250                || !assertionConsumerServiceUrl.toASCIIString().equals(pending.acs())
251                || !pending.issuedAt().isBefore(pending.expiresAt()) || !now.isBefore(pending.expiresAt())
252                || !sameHandle(pending.relayState(), message.relayState()))
253            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.PENDING);
254        SamlInboundResponse.Result inbound = SamlInboundResponse.parse(message);
255        if (inbound instanceof SamlInboundResponse.Rejected)
256            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
257        if (inbound instanceof SamlInboundResponse.Unavailable)
258            return SamlAuthenticationResult.Unavailable.INSTANCE;
259        SamlInboundResponse.Accepted parsed = (SamlInboundResponse.Accepted) inbound;
260        if (parsed.shape().getAssertion() == null && parsed.shape().getEncryptedAssertion() == null)
261            return statusResult(parsed, pending, identityProvider, now);
262        SamlInboundResponse.SignatureResult signatures = SamlInboundResponse.verifySuccessSignatures(
263                parsed, identityProvider.signingKeys(), decryptionKeys(),
264                identityProvider.allowAesCbcEncryption(), identityProvider.allowSha1Signatures(), random);
265        if (signatures instanceof SamlInboundResponse.SignatureRejected rejected)
266            return new SamlAuthenticationResult.Rejected("DECRYPTION".equals(rejected.reason())
267                    ? SamlAuthenticationResult.Reason.DECRYPTION : SamlAuthenticationResult.Reason.SIGNATURE);
268        if (signatures instanceof SamlInboundResponse.SignatureUnavailable)
269            return SamlAuthenticationResult.Unavailable.INSTANCE;
270        SamlResponseSemantics.Expectation expected = new SamlResponseSemantics.Expectation(entityId,
271                identityProvider.getConnectionId(), identityProvider.getEntityId(),
272                assertionConsumerServiceUrl.toASCIIString(), pending.requestId(), pending.relayState(),
273                pending.expiresAt(), clock, clockSkew, maximumResponseAge,
274                identityProvider.requireSignedAssertions(), identityProvider.authorizedIdentifierScopes(),
275                replayCache, replayBudget);
276        SamlResponseSemantics.Result checked = SamlResponseSemantics.validate(
277                (SamlInboundResponse.SignaturesVerified) signatures, expected,
278                pending.issuedAt(), pending.options());
279        if (checked instanceof SamlResponseSemantics.Rejected rejected)
280            return new SamlAuthenticationResult.Rejected(map(rejected.reason()));
281        if (checked instanceof SamlResponseSemantics.Unavailable)
282            return SamlAuthenticationResult.Unavailable.INSTANCE;
283        if (checked instanceof SamlResponseSemantics.Indeterminate)
284            return SamlAuthenticationResult.Indeterminate.INSTANCE;
285        return new SamlAuthenticationResult.Succeeded(new SamlAuthentication(identityProvider.getConnectionId(),
286                identityProvider.getEntityId(), (SamlResponseSemantics.Accepted) checked, false),
287                pending.getApplicationData().orElse(null));
288    }
289
290    /**
291     * Completes an IdP-initiated login only for a connection that explicitly enables it.
292     * RelayState is rejected and never treated as an application return destination. The
293     * assertion age is limited to two minutes before skew.
294     * The same fixed {@link SamlAttribute} limits apply as for an SP-initiated login.
295     *
296     * @param message POST-binding message
297     * @param identityProvider approved IdP connection
298     * @return validated identity or a fixed non-success outcome
299     * @since 1.0.0
300     */
301    public @NonNull SamlAuthenticationResult completeUnsolicitedAuthenticationResult(
302            @NonNull SamlPostBindingMessage message, @NonNull SamlIdentityProvider identityProvider) {
303        return observed(SamlObserver.Operation.COMPLETE_UNSOLICITED_AUTHENTICATION,
304                () -> completeUnsolicitedAuthenticationInternal(message, identityProvider),
305                SamlServiceProvider::outcome);
306    }
307
308    private @NonNull SamlAuthenticationResult completeUnsolicitedAuthenticationInternal(
309            @NonNull SamlPostBindingMessage message, @NonNull SamlIdentityProvider identityProvider) {
310        Objects.requireNonNull(message);
311        Objects.requireNonNull(identityProvider);
312        if (message.getKind() != SamlPostBindingMessage.Kind.RESPONSE)
313            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
314        if (!identityProvider.allowUnsolicitedResponses() || message.relayState() != null)
315            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.REQUEST_BINDING);
316        SamlInboundResponse.Result inbound = SamlInboundResponse.parse(message);
317        if (inbound instanceof SamlInboundResponse.Rejected)
318            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
319        if (inbound instanceof SamlInboundResponse.Unavailable)
320            return SamlAuthenticationResult.Unavailable.INSTANCE;
321        SamlInboundResponse.Accepted parsed = (SamlInboundResponse.Accepted) inbound;
322        if (parsed.shape().getAssertion() == null && parsed.shape().getEncryptedAssertion() == null)
323            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.STATUS);
324        SamlInboundResponse.SignatureResult signatures = SamlInboundResponse.verifySuccessSignatures(parsed,
325                identityProvider.signingKeys(), decryptionKeys(), identityProvider.allowAesCbcEncryption(),
326                identityProvider.allowSha1Signatures(), random);
327        if (signatures instanceof SamlInboundResponse.SignatureRejected rejected)
328            return new SamlAuthenticationResult.Rejected("DECRYPTION".equals(rejected.reason())
329                    ? SamlAuthenticationResult.Reason.DECRYPTION : SamlAuthenticationResult.Reason.SIGNATURE);
330        if (signatures instanceof SamlInboundResponse.SignatureUnavailable)
331            return SamlAuthenticationResult.Unavailable.INSTANCE;
332        Duration age = maximumResponseAge.compareTo(Duration.ofMinutes(2)) < 0
333                ? maximumResponseAge : Duration.ofMinutes(2);
334        SamlResponseSemantics.Expectation expected = new SamlResponseSemantics.Expectation(entityId,
335                identityProvider.getConnectionId(), identityProvider.getEntityId(),
336                assertionConsumerServiceUrl.toASCIIString(), null, null, null, clock, clockSkew, age,
337                identityProvider.requireSignedAssertions(), identityProvider.authorizedIdentifierScopes(),
338                replayCache, replayBudget);
339        SamlResponseSemantics.Result checked = SamlResponseSemantics.validate(
340                (SamlInboundResponse.SignaturesVerified) signatures, expected);
341        if (checked instanceof SamlResponseSemantics.Rejected rejected)
342            return new SamlAuthenticationResult.Rejected(map(rejected.reason()));
343        if (checked instanceof SamlResponseSemantics.Unavailable)
344            return SamlAuthenticationResult.Unavailable.INSTANCE;
345        if (checked instanceof SamlResponseSemantics.Indeterminate)
346            return SamlAuthenticationResult.Indeterminate.INSTANCE;
347        return new SamlAuthenticationResult.Succeeded(new SamlAuthentication(identityProvider.getConnectionId(),
348                identityProvider.getEntityId(), (SamlResponseSemantics.Accepted) checked, true));
349    }
350
351    /**
352     * Validates a signed IdP-initiated HTTP-Redirect LogoutRequest. A successful result only
353     * identifies sessions; the application remains responsible for ending them.
354     *
355     * @param message parsed raw-query Redirect message
356     * @param identityProvider approved IdP connection
357     * @return checked logout request or a fixed failure
358     * @since 1.0.0
359     */
360    public @NonNull SamlLogoutRequestResult acceptLogoutRequestResult(
361            @NonNull SamlRedirectBindingMessage message,
362            @NonNull SamlIdentityProvider identityProvider) {
363        return observed(SamlObserver.Operation.ACCEPT_LOGOUT_REQUEST,
364                () -> acceptLogoutRequestInternal(message, identityProvider), SamlServiceProvider::outcome);
365    }
366
367    private @NonNull SamlLogoutRequestResult acceptLogoutRequestInternal(
368            @NonNull SamlRedirectBindingMessage message,
369            @NonNull SamlIdentityProvider identityProvider) {
370        Objects.requireNonNull(message);
371        Objects.requireNonNull(identityProvider);
372        URI logoutEndpoint = singleLogoutServiceUrl;
373        if (logoutEndpoint == null || message.getKind() != SamlRedirectBindingMessage.Kind.REQUEST
374                || !message.verify(identityProvider.signingKeys(), identityProvider.allowSha1Signatures()))
375            return SamlLogoutRequestResult.Rejected.INSTANCE;
376        SecureXmlParser.Result parsed = SecureXmlParser.parseResponse(message.xml());
377        if (parsed instanceof SecureXmlParser.Result.Unavailable)
378            return SamlLogoutRequestResult.Unavailable.INSTANCE;
379        if (!(parsed instanceof SecureXmlParser.Result.Accepted accepted))
380            return SamlLogoutRequestResult.Rejected.INSTANCE;
381        return acceptLogoutRequestDocument(accepted.getDocument().getDocumentElement(), message.relayState(),
382                identityProvider, logoutEndpoint, false);
383    }
384
385    /**
386     * Validates an IdP-initiated POST LogoutRequest whose XML signature covers its exact root.
387     * The application matches the checked session fields and ends only matching local sessions.
388     *
389     * @param message parsed logout form message
390     * @param identityProvider approved IdP connection
391     * @return checked logout request or a fixed failure
392     * @since 1.0.0
393     */
394    public @NonNull SamlLogoutRequestResult acceptLogoutRequestResult(@NonNull SamlPostBindingMessage message,
395            @NonNull SamlIdentityProvider identityProvider) {
396        return observed(SamlObserver.Operation.ACCEPT_LOGOUT_REQUEST, () -> {
397            Objects.requireNonNull(message);
398            Objects.requireNonNull(identityProvider);
399            URI endpoint = postSingleLogoutServiceUrl;
400            if (endpoint == null || message.getKind() != SamlPostBindingMessage.Kind.REQUEST)
401                return SamlLogoutRequestResult.Rejected.INSTANCE;
402            SecureXmlParser.Result parsed = SecureXmlParser.parseResponse(message.xml());
403            if (parsed instanceof SecureXmlParser.Result.Unavailable)
404                return SamlLogoutRequestResult.Unavailable.INSTANCE;
405            if (!(parsed instanceof SecureXmlParser.Result.Accepted accepted))
406                return SamlLogoutRequestResult.Rejected.INSTANCE;
407            EnvelopedSignatureVerifier.Result proof = EnvelopedSignatureVerifier.verifyLogout(accepted,
408                    identityProvider.signingKeys(), identityProvider.allowSha1Signatures());
409            if (proof instanceof EnvelopedSignatureVerifier.Unavailable)
410                return SamlLogoutRequestResult.Unavailable.INSTANCE;
411            if (!(proof instanceof EnvelopedSignatureVerifier.Verified))
412                return SamlLogoutRequestResult.Rejected.INSTANCE;
413            return acceptLogoutRequestDocument(accepted.getDocument().getDocumentElement(), message.relayState(),
414                    identityProvider, endpoint, true);
415        }, SamlServiceProvider::outcome);
416    }
417
418    private @NonNull SamlLogoutRequestResult acceptLogoutRequestDocument(@Nullable Element root,
419            @Nullable String relayState, @NonNull SamlIdentityProvider identityProvider,
420            @NonNull URI logoutEndpoint, boolean enveloped) {
421        if (root == null || !SamlResponseStructure.PROTOCOL.equals(root.getNamespaceURI())
422                || !"LogoutRequest".equals(root.getLocalName())
423                || !SamlResponseSemantics.scalarDeclarationAllowed(root,
424                        SamlResponseStructure.PROTOCOL, "LogoutRequestType")
425                || !"2.0".equals(root.getAttributeNS(null, "Version"))
426                || !logoutEndpoint.toASCIIString().equals(root.getAttributeNS(null, "Destination")))
427            return SamlLogoutRequestResult.Rejected.INSTANCE;
428        String id = root.getAttributeNS(null, "ID");
429        if (id.length() > 256 || !XmlNcName.valid(id)) return SamlLogoutRequestResult.Rejected.INSTANCE;
430        Instant now;
431        try { now = clock.instant(); }
432        catch (RuntimeException exception) { return SamlLogoutRequestResult.Unavailable.INSTANCE; }
433        Instant issued = SamlDateTime.parse(root.getAttributeNS(null, "IssueInstant"));
434        Instant replayExpiry = logoutReplayExpiry(issued, now);
435        if (replayExpiry == null)
436            return SamlLogoutRequestResult.Rejected.INSTANCE;
437        if (root.hasAttributeNS(null, "NotOnOrAfter")) {
438            Instant expires = SamlDateTime.parse(root.getAttributeNS(null, "NotOnOrAfter"));
439            if (expires == null || !now.isBefore(expires)) return SamlLogoutRequestResult.Rejected.INSTANCE;
440        }
441        Element issuer = null;
442        Element nameId = null;
443        List<String> sessionIndexes = new ArrayList<>();
444        int phase = 0;
445        boolean signatureSeen = false;
446        for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
447            if (!(child instanceof Element element)) {
448                if (!ignorableStructuralNode(child)) return SamlLogoutRequestResult.Rejected.INSTANCE;
449                continue;
450            }
451            if (enveloped && phase == 1 && !signatureSeen
452                    && "http://www.w3.org/2000/09/xmldsig#".equals(element.getNamespaceURI())
453                    && "Signature".equals(element.getLocalName())) {
454                signatureSeen = true;
455                continue;
456            }
457            if (SamlResponseStructure.ASSERTION.equals(element.getNamespaceURI())
458                    && "Issuer".equals(element.getLocalName())) {
459                if (phase != 0 || !SamlResponseSemantics.scalarDeclarationAllowed(element,
460                        SamlResponseStructure.ASSERTION, "NameIDType"))
461                    return SamlLogoutRequestResult.Rejected.INSTANCE;
462                issuer = element;
463                phase = 1;
464            } else if (SamlResponseStructure.ASSERTION.equals(element.getNamespaceURI())
465                    && "NameID".equals(element.getLocalName())) {
466                if (phase != 1 || !SamlResponseSemantics.scalarDeclarationAllowed(element,
467                        SamlResponseStructure.ASSERTION, "NameIDType"))
468                    return SamlLogoutRequestResult.Rejected.INSTANCE;
469                nameId = element;
470                phase = 2;
471            } else if (SamlResponseStructure.PROTOCOL.equals(element.getNamespaceURI())
472                    && "SessionIndex".equals(element.getLocalName())) {
473                if (phase != 2 || !SamlResponseSemantics.scalarDeclarationAllowed(element,
474                        "http://www.w3.org/2001/XMLSchema", "string"))
475                    return SamlLogoutRequestResult.Rejected.INSTANCE;
476                String value = textOnly(element);
477                if (value == null || value.isEmpty() || value.length() > 2048
478                        || sessionIndexes.size() >= 32) return SamlLogoutRequestResult.Rejected.INSTANCE;
479                sessionIndexes.add(value);
480            } else return SamlLogoutRequestResult.Rejected.INSTANCE;
481        }
482        if (signatureSeen != enveloped || issuer == null || nameId == null || !identityProvider.getEntityId().equals(textOnly(issuer)))
483            return SamlLogoutRequestResult.Rejected.INSTANCE;
484        String format = issuer.getAttributeNS(null, "Format");
485        if (!format.isEmpty() && !"urn:oasis:names:tc:SAML:2.0:nameid-format:entity".equals(format))
486            return SamlLogoutRequestResult.Rejected.INSTANCE;
487        String name = textOnly(nameId);
488        if (name == null || name.isEmpty() || name.length() > 4096)
489            return SamlLogoutRequestResult.Rejected.INSTANCE;
490        String nameFormat = optionalNameIdField(nameId, "Format");
491        String nameQualifier = optionalNameIdField(nameId, "NameQualifier");
492        String spQualifier = optionalNameIdField(nameId, "SPNameQualifier");
493        String spProvidedId = optionalNameIdField(nameId, "SPProvidedID");
494        if (longField(nameFormat) || longField(nameQualifier) || longField(spQualifier)
495                || longField(spProvidedId))
496            return SamlLogoutRequestResult.Rejected.INSTANCE;
497        String replayKey;
498        try { replayKey = logoutReplayKey(identityProvider, SamlRedirectBindingMessage.Kind.REQUEST, id); }
499        catch (NoSuchAlgorithmException exception) { return SamlLogoutRequestResult.Unavailable.INSTANCE; }
500        SamlReplayCache.MarkResult mark;
501        try { mark = replayCache.markIfAbsent(identityProvider.getConnectionId(), replayKey,
502                replayExpiry, replayBudget); }
503        catch (RuntimeException exception) { return SamlLogoutRequestResult.Indeterminate.INSTANCE; }
504        if (mark == null || mark == SamlReplayCache.MarkResult.INDETERMINATE)
505            return SamlLogoutRequestResult.Indeterminate.INSTANCE;
506        if (mark == SamlReplayCache.MarkResult.ALREADY_PRESENT)
507            return SamlLogoutRequestResult.Rejected.INSTANCE;
508        if (mark != SamlReplayCache.MarkResult.MARKED)
509            return SamlLogoutRequestResult.Unavailable.INSTANCE;
510        return new SamlLogoutRequestResult.Accepted(new SamlLogoutRequest(identityProvider.getConnectionId(),
511                entityId, identityProvider.getEntityId(), id, relayState,
512                new SamlNameId(name, nameFormat, nameQualifier, spQualifier, spProvidedId), sessionIndexes));
513    }
514
515    /**
516     * Begins signed SP-initiated front-channel logout for a stored session reference.
517     * The application saves the returned pending state in the initiating browser and ends its
518     * local session before sending the redirect. A missing or failed IdP return never restores
519     * that session.
520     *
521     * @param identityProvider approved IdP connection
522     * @param session checked reference retained with the application session
523     * @return signed Redirect and pending state, or a fixed failure
524     * @since 1.0.0
525     */
526    public @NonNull SamlLogoutRedirectResult beginLogoutResult(@NonNull SamlIdentityProvider identityProvider,
527            @NonNull SamlSessionReference session) {
528        return observed(SamlObserver.Operation.BEGIN_LOGOUT,
529                () -> beginLogoutInternal(identityProvider, session), SamlServiceProvider::outcome);
530    }
531
532    private @NonNull SamlLogoutRedirectResult beginLogoutInternal(@NonNull SamlIdentityProvider identityProvider,
533            @NonNull SamlSessionReference session) {
534        Objects.requireNonNull(identityProvider);
535        Objects.requireNonNull(session);
536        URI destination = identityProvider.redirectSingleLogoutService();
537        if (singleLogoutServiceUrl == null || destination == null || signingKey == null
538                || !safeLogoutEndpointQuery(destination)
539                || !identityProvider.getConnectionId().equals(session.getIdentityProviderConnectionId())
540                || !identityProvider.getEntityId().equals(session.getIdentityProviderEntityId()))
541            return SamlLogoutRedirectResult.Rejected.CONFIGURATION;
542        try {
543            Instant now = clock.instant();
544            Instant expiry = now.plus(pendingLifetime);
545            String id = SamlRedirectLogout.id(random);
546            String relay = SamlRedirectLogout.relay(random);
547            URI redirect = SamlRedirectLogout.request(destination, entityId, session, id, relay,
548                    now, signingKey);
549            if (redirect == null) return SamlLogoutRedirectResult.Unavailable.INSTANCE;
550            PendingSamlAuthentication fields = new PendingSamlAuthentication(entityId, id, relay,
551                    identityProvider.getConnectionId(), identityProvider.getEntityId(),
552                    singleLogoutServiceUrl.toASCIIString(), now, expiry);
553            return new SamlLogoutRedirectResult.Prepared(redirect, new PendingSamlLogout(fields));
554        } catch (RuntimeException exception) { return SamlLogoutRedirectResult.Unavailable.INSTANCE; }
555    }
556
557    /**
558     * Completes SP-initiated logout after authenticating browser pending state and the signed
559     * IdP Redirect response. The application still owns its local session lifecycle.
560     *
561     * @param message parsed raw-query Redirect message
562     * @param pendingSource source bound to the initiating browser
563     * @param identityProvider approved IdP connection
564     * @return verified IdP status or a fixed failure
565     * @since 1.0.0
566     */
567    public @NonNull SamlLogoutResult completeLogoutResult(@NonNull SamlRedirectBindingMessage message,
568            @NonNull PendingSamlLogoutSource pendingSource,
569            @NonNull SamlIdentityProvider identityProvider) {
570        return observed(SamlObserver.Operation.COMPLETE_LOGOUT,
571                () -> completeLogoutInternal(message, pendingSource, identityProvider),
572                SamlServiceProvider::outcome);
573    }
574
575    private @NonNull SamlLogoutResult completeLogoutInternal(@NonNull SamlRedirectBindingMessage message,
576            @NonNull PendingSamlLogoutSource pendingSource,
577            @NonNull SamlIdentityProvider identityProvider) {
578        Objects.requireNonNull(message);
579        Objects.requireNonNull(pendingSource);
580        Objects.requireNonNull(identityProvider);
581        if (message.getKind() != SamlRedirectBindingMessage.Kind.RESPONSE
582                || singleLogoutServiceUrl == null
583                || !message.verify(identityProvider.signingKeys(), identityProvider.allowSha1Signatures()))
584            return SamlLogoutResult.Rejected.INSTANCE;
585        SecureXmlParser.Result parsed = SecureXmlParser.parseResponse(message.xml());
586        if (parsed instanceof SecureXmlParser.Result.Unavailable) return SamlLogoutResult.Unavailable.INSTANCE;
587        if (!(parsed instanceof SecureXmlParser.Result.Accepted accepted)) return SamlLogoutResult.Rejected.INSTANCE;
588        Element root = accepted.getDocument().getDocumentElement();
589        return completeLogoutDocument(root, message.relayState(), pendingSource, identityProvider,
590                Objects.requireNonNull(singleLogoutServiceUrl), false);
591    }
592
593    /**
594     * Completes SP-initiated logout after verifying a POST response's exact-root XML signature.
595     * Invalid signatures or response semantics never consume pending state. POST browser callbacks
596     * require SameSite=None; Secure on the application-owned pending cookie. Clear that cookie after
597     * a verified terminal status; rejected callbacks do not end a valid pending attempt.
598     *
599     * @param message parsed logout form message
600     * @param pendingSource source bound to the initiating browser
601     * @param identityProvider approved IdP connection
602     * @return verified IdP status or a fixed failure
603     * @since 1.0.0
604     */
605    public @NonNull SamlLogoutResult completeLogoutResult(@NonNull SamlPostBindingMessage message,
606            @NonNull PendingSamlLogoutSource pendingSource, @NonNull SamlIdentityProvider identityProvider) {
607        return observed(SamlObserver.Operation.COMPLETE_LOGOUT, () -> {
608            Objects.requireNonNull(message);
609            Objects.requireNonNull(pendingSource);
610            Objects.requireNonNull(identityProvider);
611            URI endpoint = postSingleLogoutServiceUrl;
612            if (endpoint == null || message.getKind() != SamlPostBindingMessage.Kind.RESPONSE)
613                return SamlLogoutResult.Rejected.INSTANCE;
614            SecureXmlParser.Result parsed = SecureXmlParser.parseResponse(message.xml());
615            if (parsed instanceof SecureXmlParser.Result.Unavailable) return SamlLogoutResult.Unavailable.INSTANCE;
616            if (!(parsed instanceof SecureXmlParser.Result.Accepted accepted)) return SamlLogoutResult.Rejected.INSTANCE;
617            EnvelopedSignatureVerifier.Result proof = EnvelopedSignatureVerifier.verifyLogout(accepted,
618                    identityProvider.signingKeys(), identityProvider.allowSha1Signatures());
619            if (proof instanceof EnvelopedSignatureVerifier.Unavailable) return SamlLogoutResult.Unavailable.INSTANCE;
620            if (!(proof instanceof EnvelopedSignatureVerifier.Verified)) return SamlLogoutResult.Rejected.INSTANCE;
621            return completeLogoutDocument(accepted.getDocument().getDocumentElement(), message.relayState(),
622                    pendingSource, identityProvider, endpoint, true);
623        }, SamlServiceProvider::outcome);
624    }
625
626    private @NonNull SamlLogoutResult completeLogoutDocument(@Nullable Element root, @Nullable String relayState,
627            @NonNull PendingSamlLogoutSource pendingSource, @NonNull SamlIdentityProvider identityProvider,
628            @NonNull URI logoutEndpoint, boolean enveloped) {
629        Instant now;
630        try { now = clock.instant(); }
631        catch (RuntimeException exception) { return SamlLogoutResult.Unavailable.INSTANCE; }
632        if (root == null || !SamlResponseStructure.PROTOCOL.equals(root.getNamespaceURI())
633                || !"LogoutResponse".equals(root.getLocalName())
634                || !SamlResponseSemantics.scalarDeclarationAllowed(root,
635                        SamlResponseStructure.PROTOCOL, "StatusResponseType")
636                || !"2.0".equals(root.getAttributeNS(null, "Version"))
637                || !logoutEndpoint.toASCIIString().equals(root.getAttributeNS(null, "Destination")))
638            return SamlLogoutResult.Rejected.INSTANCE;
639        String responseId = root.getAttributeNS(null, "ID");
640        String inResponseTo = root.getAttributeNS(null, "InResponseTo");
641        if (responseId.length() > 256 || !XmlNcName.valid(responseId)
642                || inResponseTo.length() > 256 || !XmlNcName.valid(inResponseTo))
643            return SamlLogoutResult.Rejected.INSTANCE;
644        Instant issued = SamlDateTime.parse(root.getAttributeNS(null, "IssueInstant"));
645        Instant replayExpiry = logoutReplayExpiry(issued, now);
646        if (replayExpiry == null)
647            return SamlLogoutResult.Rejected.INSTANCE;
648        Element issuer = null;
649        Element status = null;
650        int phase = 0;
651        boolean signatureSeen = false;
652        for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
653            if (!(child instanceof Element element)) {
654                if (!ignorableStructuralNode(child)) return SamlLogoutResult.Rejected.INSTANCE;
655                continue;
656            }
657            if (enveloped && phase == 1 && !signatureSeen
658                    && "http://www.w3.org/2000/09/xmldsig#".equals(element.getNamespaceURI())
659                    && "Signature".equals(element.getLocalName())) {
660                signatureSeen = true;
661                continue;
662            }
663            if (SamlResponseStructure.ASSERTION.equals(element.getNamespaceURI())
664                    && "Issuer".equals(element.getLocalName())) {
665                if (phase != 0 || !SamlResponseSemantics.scalarDeclarationAllowed(element,
666                        SamlResponseStructure.ASSERTION, "NameIDType"))
667                    return SamlLogoutResult.Rejected.INSTANCE;
668                issuer = element;
669                phase = 1;
670            } else if (SamlResponseStructure.PROTOCOL.equals(element.getNamespaceURI())
671                    && "Status".equals(element.getLocalName())) {
672                if (phase != 1)
673                    return SamlLogoutResult.Rejected.INSTANCE;
674                status = element;
675                phase = 2;
676            } else return SamlLogoutResult.Rejected.INSTANCE;
677        }
678        if (signatureSeen != enveloped || issuer == null || status == null || !identityProvider.getEntityId().equals(textOnly(issuer)))
679            return SamlLogoutResult.Rejected.INSTANCE;
680        SamlResponseSemantics.Status checkedStatus = SamlResponseSemantics.inspectStatus(status);
681        if (checkedStatus == null || (SamlLogoutStatus.SUCCESS.uri().equals(checkedStatus.primary())
682                && !checkedStatus.plainSuccess() && !checkedStatus.partialLogout()))
683            return SamlLogoutResult.Rejected.INSTANCE;
684        String replayKey;
685        try { replayKey = logoutReplayKey(identityProvider, SamlRedirectBindingMessage.Kind.RESPONSE,
686                responseId); }
687        catch (NoSuchAlgorithmException exception) { return SamlLogoutResult.Unavailable.INSTANCE; }
688        // All document semantics are checked before touching pending state. The supplied predicate
689        // authenticates and matches the exact pending record before the store atomically removes it.
690        PendingSamlLogoutSource.Resolution resolved = pendingSource.resolve(clock, relayState, replayBudget,
691                pending -> {
692                    Instant current = clock.instant();
693                    return logoutReplayExpiry(issued, current) != null
694                        && entityId.equals(pending.spEntityId())
695                        && logoutEndpoint.toASCIIString().equals(pending.acs())
696                        && identityProvider.getConnectionId().equals(pending.connectionId())
697                        && identityProvider.getEntityId().equals(pending.idpEntityId())
698                        && current.isBefore(pending.expiresAt())
699                        && sameHandle(pending.relayState(), relayState)
700                        && pending.requestId().equals(inResponseTo);
701                });
702        if (resolved instanceof PendingSamlLogoutSource.Rejected) return SamlLogoutResult.Rejected.INSTANCE;
703        if (resolved instanceof PendingSamlLogoutSource.Unavailable) return SamlLogoutResult.Unavailable.INSTANCE;
704        if (resolved instanceof PendingSamlLogoutSource.Indeterminate)
705            return SamlLogoutResult.Indeterminate.INSTANCE;
706        boolean pendingConsumed = ((PendingSamlLogoutSource.Resolved) resolved).consumed();
707        SamlReplayCache.MarkResult mark;
708        try { mark = replayCache.markIfAbsent(identityProvider.getConnectionId(), replayKey,
709                replayExpiry, replayBudget); }
710        catch (RuntimeException exception) { return SamlLogoutResult.Indeterminate.INSTANCE; }
711        if (mark == null || mark == SamlReplayCache.MarkResult.INDETERMINATE)
712            return SamlLogoutResult.Indeterminate.INSTANCE;
713        if (mark == SamlReplayCache.MarkResult.ALREADY_PRESENT)
714            return pendingConsumed ? SamlLogoutResult.Indeterminate.INSTANCE : SamlLogoutResult.Rejected.INSTANCE;
715        if (mark != SamlReplayCache.MarkResult.MARKED)
716            return pendingConsumed ? SamlLogoutResult.Indeterminate.INSTANCE : SamlLogoutResult.Unavailable.INSTANCE;
717        if (checkedStatus.plainSuccess()) return SamlLogoutResult.Succeeded.INSTANCE;
718        return checkedStatus.partialLogout() ? SamlLogoutResult.StatusReceived.PARTIAL_LOGOUT
719                : SamlLogoutResult.StatusReceived.NON_SUCCESS;
720    }
721
722    /**
723     * Prepares a signed response after the application has handled a verified IdP-initiated
724     * logout request. The application chooses the status based on its session termination result.
725     *
726     * @param request checked request returned by this SP
727     * @param identityProvider approved IdP connection
728     * @param status application-selected outcome
729     * @return signed Redirect or fixed failure
730     * @since 1.0.0
731     */
732    public @NonNull SamlLogoutResponseRedirectResult respondToLogoutRequestResult(
733            @NonNull SamlLogoutRequest request, @NonNull SamlIdentityProvider identityProvider,
734            @NonNull SamlLogoutStatus status) {
735        return observed(SamlObserver.Operation.RESPOND_TO_LOGOUT_REQUEST,
736                () -> respondToLogoutRequestInternal(request, identityProvider, status),
737                SamlServiceProvider::outcome);
738    }
739
740    private @NonNull SamlLogoutResponseRedirectResult respondToLogoutRequestInternal(
741            @NonNull SamlLogoutRequest request, @NonNull SamlIdentityProvider identityProvider,
742            @NonNull SamlLogoutStatus status) {
743        Objects.requireNonNull(request);
744        Objects.requireNonNull(identityProvider);
745        Objects.requireNonNull(status);
746        URI destination = identityProvider.redirectSingleLogoutResponseService();
747        if (singleLogoutServiceUrl == null || signingKey == null || destination == null
748                || !safeLogoutEndpointQuery(destination)
749                || !entityId.equals(request.spEntityId())
750                || !identityProvider.getConnectionId().equals(request.getIdentityProviderConnectionId())
751                || !identityProvider.getEntityId().equals(request.idpEntityId()))
752            return SamlLogoutResponseRedirectResult.Rejected.INSTANCE;
753        try {
754            URI redirect = SamlRedirectLogout.response(destination, entityId,
755                    SamlRedirectLogout.id(random), request.getRequestId(), request.relayState(),
756                    clock.instant(), status, signingKey);
757            return redirect == null ? SamlLogoutResponseRedirectResult.Unavailable.INSTANCE
758                    : new SamlLogoutResponseRedirectResult.Prepared(redirect);
759        } catch (RuntimeException exception) { return SamlLogoutResponseRedirectResult.Unavailable.INSTANCE; }
760    }
761
762    /**
763     * Prepares a signed POST LogoutRequest and browser-bound pending state. Save pending state and
764     * end the local session before sending the form; a failed IdP return never restores the session.
765     *
766     * @param identityProvider approved IdP connection
767     * @param session checked reference retained with the application session
768     * @return signed POST form and pending state, or a fixed failure
769     * @since 1.0.0
770     */
771    public @NonNull SamlLogoutPostResult beginPostLogoutResult(@NonNull SamlIdentityProvider identityProvider,
772            @NonNull SamlSessionReference session) {
773        return observed(SamlObserver.Operation.BEGIN_LOGOUT, () -> {
774            Objects.requireNonNull(identityProvider);
775            Objects.requireNonNull(session);
776            URI destination = identityProvider.postSingleLogoutService();
777            if (postSingleLogoutServiceUrl == null || destination == null || signingKey == null
778                    || !safeLogoutEndpointQuery(destination)
779                    || !identityProvider.getConnectionId().equals(session.getIdentityProviderConnectionId())
780                    || !identityProvider.getEntityId().equals(session.getIdentityProviderEntityId()))
781                return SamlLogoutPostResult.Rejected.CONFIGURATION;
782            try {
783                Instant now = clock.instant();
784                Instant expiry = now.plus(pendingLifetime);
785                String id = SamlRedirectLogout.id(random);
786                String relay = SamlRedirectLogout.relay(random);
787                SamlPostForm form = SamlPostLogout.request(destination, entityId, session, id, relay, now, signingKey);
788                if (form == null) return SamlLogoutPostResult.Unavailable.INSTANCE;
789                PendingSamlAuthentication fields = new PendingSamlAuthentication(entityId, id, relay,
790                        identityProvider.getConnectionId(), identityProvider.getEntityId(),
791                        postSingleLogoutServiceUrl.toASCIIString(), now, expiry);
792                return new SamlLogoutPostResult.Prepared(form, new PendingSamlLogout(fields));
793            } catch (RuntimeException exception) { return SamlLogoutPostResult.Unavailable.INSTANCE; }
794        }, SamlServiceProvider::outcome);
795    }
796
797    /**
798     * Prepares a signed POST response after the application handles a checked IdP logout request.
799     *
800     * @param request checked request returned by this SP
801     * @param identityProvider approved IdP connection
802     * @param status application-selected outcome
803     * @return signed POST form or fixed failure
804     * @since 1.0.0
805     */
806    public @NonNull SamlLogoutResponsePostResult respondToPostLogoutRequestResult(
807            @NonNull SamlLogoutRequest request, @NonNull SamlIdentityProvider identityProvider,
808            @NonNull SamlLogoutStatus status) {
809        return observed(SamlObserver.Operation.RESPOND_TO_LOGOUT_REQUEST, () -> {
810            Objects.requireNonNull(request);
811            Objects.requireNonNull(identityProvider);
812            Objects.requireNonNull(status);
813            URI destination = identityProvider.postSingleLogoutResponseService();
814            if (postSingleLogoutServiceUrl == null || signingKey == null || destination == null
815                    || !safeLogoutEndpointQuery(destination) || !entityId.equals(request.spEntityId())
816                    || !identityProvider.getConnectionId().equals(request.getIdentityProviderConnectionId())
817                    || !identityProvider.getEntityId().equals(request.idpEntityId()))
818                return SamlLogoutResponsePostResult.Rejected.INSTANCE;
819            try {
820                SamlPostForm form = SamlPostLogout.response(destination, entityId, SamlRedirectLogout.id(random),
821                        request.getRequestId(), request.relayState(), clock.instant(), status, signingKey);
822                return form == null ? SamlLogoutResponsePostResult.Unavailable.INSTANCE
823                        : new SamlLogoutResponsePostResult.Prepared(form);
824            } catch (RuntimeException exception) { return SamlLogoutResponsePostResult.Unavailable.INSTANCE; }
825        }, SamlServiceProvider::outcome);
826    }
827
828    private <T> @NonNull T observed(SamlObserver.@NonNull Operation operation,
829            @NonNull Supplier<@NonNull T> work,
830            @NonNull Function<@NonNull T, SamlObserver.@NonNull Outcome> classify) {
831        long started = System.nanoTime();
832        ObserverDispatch.dispatch(observer, value -> value.willHandleOperation(operation));
833        try {
834            T result = work.get();
835            SamlObserver.Outcome outcome = classify.apply(result);
836            Duration elapsed = Duration.ofNanos(Math.max(0, System.nanoTime() - started));
837            ObserverDispatch.dispatch(observer, value -> value.didHandleOperation(operation, outcome, elapsed));
838            return result;
839        } catch (RuntimeException exception) {
840            Duration elapsed = Duration.ofNanos(Math.max(0, System.nanoTime() - started));
841            ObserverDispatch.dispatch(observer, value -> value.didHandleOperation(
842                    operation, SamlObserver.Outcome.FAILED, elapsed));
843            throw exception;
844        }
845    }
846
847    private static SamlObserver.@NonNull Outcome outcome(@NonNull SamlAuthenticationRequestResult result) {
848        if (result instanceof SamlAuthenticationRequestResult.Prepared
849                || result instanceof SamlAuthenticationRequestResult.PostPrepared)
850            return SamlObserver.Outcome.SUCCEEDED;
851        if (result instanceof SamlAuthenticationRequestResult.Rejected) return SamlObserver.Outcome.REJECTED;
852        if (result instanceof SamlAuthenticationRequestResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
853        throw new IllegalStateException("Unclassified SAML authentication request result");
854    }
855
856    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlAuthenticationResult result) {
857        if (result instanceof SamlAuthenticationResult.Succeeded) return SamlObserver.Outcome.SUCCEEDED;
858        if (result instanceof SamlAuthenticationResult.StatusReceived) return SamlObserver.Outcome.STATUS_RECEIVED;
859        if (result instanceof SamlAuthenticationResult.Rejected) return SamlObserver.Outcome.REJECTED;
860        if (result instanceof SamlAuthenticationResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
861        if (result instanceof SamlAuthenticationResult.Indeterminate) return SamlObserver.Outcome.INDETERMINATE;
862        throw new IllegalStateException("Unclassified SAML authentication result");
863    }
864
865    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlLogoutRequestResult result) {
866        if (result instanceof SamlLogoutRequestResult.Accepted) return SamlObserver.Outcome.SUCCEEDED;
867        if (result instanceof SamlLogoutRequestResult.Rejected) return SamlObserver.Outcome.REJECTED;
868        if (result instanceof SamlLogoutRequestResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
869        if (result instanceof SamlLogoutRequestResult.Indeterminate) return SamlObserver.Outcome.INDETERMINATE;
870        throw new IllegalStateException("Unclassified SAML logout request result");
871    }
872
873    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlLogoutRedirectResult result) {
874        if (result instanceof SamlLogoutRedirectResult.Prepared) return SamlObserver.Outcome.SUCCEEDED;
875        if (result instanceof SamlLogoutRedirectResult.Rejected) return SamlObserver.Outcome.REJECTED;
876        if (result instanceof SamlLogoutRedirectResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
877        throw new IllegalStateException("Unclassified SAML logout redirect result");
878    }
879
880    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlLogoutResult result) {
881        if (result instanceof SamlLogoutResult.Succeeded) return SamlObserver.Outcome.SUCCEEDED;
882        if (result instanceof SamlLogoutResult.StatusReceived) return SamlObserver.Outcome.STATUS_RECEIVED;
883        if (result instanceof SamlLogoutResult.Rejected) return SamlObserver.Outcome.REJECTED;
884        if (result instanceof SamlLogoutResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
885        if (result instanceof SamlLogoutResult.Indeterminate) return SamlObserver.Outcome.INDETERMINATE;
886        throw new IllegalStateException("Unclassified SAML logout result");
887    }
888
889    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlLogoutResponseRedirectResult result) {
890        if (result instanceof SamlLogoutResponseRedirectResult.Prepared) return SamlObserver.Outcome.SUCCEEDED;
891        if (result instanceof SamlLogoutResponseRedirectResult.Rejected) return SamlObserver.Outcome.REJECTED;
892        if (result instanceof SamlLogoutResponseRedirectResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
893        throw new IllegalStateException("Unclassified SAML logout response result");
894    }
895
896    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlLogoutPostResult result) {
897        if (result instanceof SamlLogoutPostResult.Prepared) return SamlObserver.Outcome.SUCCEEDED;
898        if (result instanceof SamlLogoutPostResult.Rejected) return SamlObserver.Outcome.REJECTED;
899        if (result instanceof SamlLogoutPostResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
900        throw new IllegalStateException("Unclassified SAML logout POST result");
901    }
902
903    static SamlObserver.@NonNull Outcome outcome(@NonNull SamlLogoutResponsePostResult result) {
904        if (result instanceof SamlLogoutResponsePostResult.Prepared) return SamlObserver.Outcome.SUCCEEDED;
905        if (result instanceof SamlLogoutResponsePostResult.Rejected) return SamlObserver.Outcome.REJECTED;
906        if (result instanceof SamlLogoutResponsePostResult.Unavailable) return SamlObserver.Outcome.UNAVAILABLE;
907        throw new IllegalStateException("Unclassified SAML logout POST response result");
908    }
909
910    private @NonNull String logoutReplayKey(@NonNull SamlIdentityProvider idp,
911            SamlRedirectBindingMessage.@NonNull Kind kind, @NonNull String messageId)
912            throws NoSuchAlgorithmException {
913        MessageDigest digest = MessageDigest.getInstance("SHA-256");
914        for (String value : List.of("saml-logout-replay", kind.name(), entityId, idp.getConnectionId(),
915                idp.getEntityId(), messageId)) {
916            byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
917            digest.update(ByteBuffer.allocate(4).putInt(bytes.length).array());
918            digest.update(bytes);
919        }
920        return Base64.getUrlEncoder().withoutPadding().encodeToString(digest.digest());
921    }
922
923    private @Nullable Instant logoutReplayExpiry(@Nullable Instant issued, @NonNull Instant now) {
924        if (issued == null) return null;
925        Instant latestIssue = plus(now, clockSkew);
926        Instant ageEnd = plus(issued, maximumResponseAge);
927        Instant acceptanceExpiry = ageEnd == null ? null : plus(ageEnd, clockSkew);
928        if (latestIssue == null || acceptanceExpiry == null || issued.isAfter(latestIssue)
929                || !now.isBefore(acceptanceExpiry)) return null;
930        // Replay keys span bindings and time policies. Retain a successful admission until no
931        // supported SP policy can accept this signed message, even during configuration rollover.
932        Instant maximumAgeEnd = plus(issued, SamlResponseSemantics.MAXIMUM_CONFIGURED_RESPONSE_AGE);
933        return maximumAgeEnd == null ? null : plus(maximumAgeEnd, SamlResponseSemantics.MAXIMUM_CONFIGURED_SKEW);
934    }
935
936    private static @Nullable Instant plus(@NonNull Instant instant, @NonNull Duration duration) {
937        try { return instant.plus(duration); }
938        catch (DateTimeException | ArithmeticException exception) { return null; }
939    }
940
941    private static @Nullable String optionalNameIdField(@NonNull Element nameId, @NonNull String field) {
942        return nameId.hasAttributeNS(null, field) ? nameId.getAttributeNS(null, field) : null;
943    }
944
945    private static boolean longField(@Nullable String value) {
946        return value != null && value.length() > 2048;
947    }
948
949    private @NonNull SamlAuthenticationResult statusResult(SamlInboundResponse.@NonNull Accepted inbound,
950            @NonNull PendingSamlAuthentication pending, @NonNull SamlIdentityProvider idp,
951            @NonNull Instant now) {
952        SamlResponseStructure.Shape shape = inbound.shape();
953        if (shape.getEncryptedAssertion() != null)
954            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
955        Element response = shape.getResponse();
956        if (!SamlResponseSemantics.validResponseEnvelope(response))
957            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
958        if (!pending.requestId().equals(response.getAttributeNS(null, "InResponseTo")))
959            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.REQUEST_BINDING);
960        Element issuer = shape.getIssuer();
961        if (issuer == null || !SamlResponseSemantics.scalarDeclarationAllowed(issuer,
962                SamlResponseStructure.ASSERTION, "NameIDType")
963                || (!issuer.getAttributeNS(null, "Format").isEmpty()
964                    && !"urn:oasis:names:tc:SAML:2.0:nameid-format:entity".equals(
965                            issuer.getAttributeNS(null, "Format")))
966                || !idp.getEntityId().equals(textOnly(issuer)))
967            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.ISSUER);
968        String destination = response.getAttributeNS(null, "Destination");
969        if (!destination.isEmpty() && !assertionConsumerServiceUrl.toASCIIString().equals(destination))
970            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.DESTINATION);
971        EnvelopedSignatureVerifier.Result proof = SamlInboundResponse.verifyStatusSignature(inbound,
972                idp.signingKeys(), idp.allowSha1Signatures());
973        if (proof instanceof EnvelopedSignatureVerifier.Unavailable)
974            return SamlAuthenticationResult.Unavailable.INSTANCE;
975        if (proof instanceof EnvelopedSignatureVerifier.Rejected)
976            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.SIGNATURE);
977        boolean authenticated = proof instanceof EnvelopedSignatureVerifier.Verified;
978        if (authenticated && destination.isEmpty())
979            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.DESTINATION);
980        Instant issued = SamlDateTime.parse(response.getAttributeNS(null, "IssueInstant"));
981        Instant latestIssue = plus(now, clockSkew);
982        Instant ageEnd = issued == null ? null : plus(issued, maximumResponseAge);
983        Instant expiry = ageEnd == null ? null : plus(ageEnd, clockSkew);
984        if (issued == null || latestIssue == null || expiry == null
985                || issued.isAfter(latestIssue) || now.isAfter(expiry))
986            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.RESPONSE_AGE);
987        SamlResponseSemantics.Status status = SamlResponseSemantics.inspectStatus(shape.getStatus());
988        if (status == null || SamlLogoutStatus.SUCCESS.uri().equals(status.primary()))
989            return new SamlAuthenticationResult.Rejected(SamlAuthenticationResult.Reason.MESSAGE);
990        String code = status.authenticationCode();
991        SamlAuthenticationResult.StatusCode classification = switch (code) {
992            case "urn:oasis:names:tc:SAML:2.0:status:AuthnFailed" ->
993                    SamlAuthenticationResult.StatusCode.AUTHN_FAILED;
994            case "urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext" ->
995                    SamlAuthenticationResult.StatusCode.NO_AUTHN_CONTEXT;
996            case "urn:oasis:names:tc:SAML:2.0:status:RequestDenied" ->
997                    SamlAuthenticationResult.StatusCode.REQUEST_DENIED;
998            case "urn:oasis:names:tc:SAML:2.0:status:Requester" ->
999                    SamlAuthenticationResult.StatusCode.REQUESTER;
1000            case "urn:oasis:names:tc:SAML:2.0:status:Responder" ->
1001                    SamlAuthenticationResult.StatusCode.RESPONDER;
1002            case "urn:oasis:names:tc:SAML:2.0:status:VersionMismatch" ->
1003                    SamlAuthenticationResult.StatusCode.VERSION_MISMATCH;
1004            default -> SamlAuthenticationResult.StatusCode.OTHER;
1005        };
1006        return new SamlAuthenticationResult.StatusReceived(classification, authenticated);
1007    }
1008
1009    private static @Nullable String textOnly(@NonNull Element element) {
1010        StringBuilder text = new StringBuilder();
1011        for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
1012            if (child.getNodeType() != Node.TEXT_NODE) return null;
1013            text.append(child.getNodeValue());
1014        }
1015        return text.toString();
1016    }
1017
1018    private static boolean ignorableStructuralNode(@NonNull Node node) {
1019        if (node.getNodeType() == Node.COMMENT_NODE || node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE)
1020            return true;
1021        if (node.getNodeType() != Node.TEXT_NODE) return false;
1022        String value = node.getNodeValue();
1023        if (value == null) return false;
1024        for (int index = 0; index < value.length(); index++) {
1025            char character = value.charAt(index);
1026            if (character != ' ' && character != '\t' && character != '\r' && character != '\n') return false;
1027        }
1028        return true;
1029    }
1030
1031    private static SamlAuthenticationResult.@NonNull Reason map(SamlResponseSemantics.@NonNull Reason reason) {
1032        return switch (reason) {
1033            case PENDING -> SamlAuthenticationResult.Reason.PENDING;
1034            case COVERAGE -> SamlAuthenticationResult.Reason.SIGNATURE;
1035            case ISSUER -> SamlAuthenticationResult.Reason.ISSUER;
1036            case DESTINATION -> SamlAuthenticationResult.Reason.DESTINATION;
1037            case REQUEST_BINDING -> SamlAuthenticationResult.Reason.REQUEST_BINDING;
1038            case STATUS -> SamlAuthenticationResult.Reason.STATUS;
1039            case SUBJECT -> SamlAuthenticationResult.Reason.SUBJECT;
1040            case CONFIRMATION -> SamlAuthenticationResult.Reason.CONFIRMATION;
1041            case CONDITIONS -> SamlAuthenticationResult.Reason.CONDITIONS;
1042            case AUTHN_STATEMENT -> SamlAuthenticationResult.Reason.AUTHN_STATEMENT;
1043            case RESPONSE_AGE -> SamlAuthenticationResult.Reason.RESPONSE_AGE;
1044            case REPLAYED -> SamlAuthenticationResult.Reason.REPLAYED;
1045            case ASSERTION_SHAPE -> SamlAuthenticationResult.Reason.ASSERTION_SHAPE;
1046        };
1047    }
1048
1049    private static boolean sameHandle(@NonNull String expected, @Nullable String actual) {
1050        return actual != null && MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
1051                actual.getBytes(StandardCharsets.UTF_8));
1052    }
1053
1054    private static boolean safeLogoutEndpointQuery(@NonNull URI endpoint) {
1055        String query = endpoint.getRawQuery();
1056        return query == null || (!query.isEmpty() && SamlRedirectAuthnRequest.safeEndpointQuery(query));
1057    }
1058
1059    @Nullable SamlCredential signingCredential() { return signingCredential; }
1060    @NonNull List<@NonNull SamlCredential> decryptionCredentials() { return decryptionCredentials; }
1061    private @NonNull List<@NonNull PrivateKey> decryptionKeys() {
1062        List<PrivateKey> keys = new ArrayList<>();
1063        for (SamlCredential credential : decryptionCredentials) keys.add(credential.privateKey());
1064        return List.copyOf(keys);
1065    }
1066    @NonNull String entityId() { return entityId; }
1067    @NonNull URI assertionConsumerServiceUrl() { return assertionConsumerServiceUrl; }
1068    @Nullable URI singleLogoutServiceUrl() { return singleLogoutServiceUrl; }
1069    @Nullable URI postSingleLogoutServiceUrl() { return postSingleLogoutServiceUrl; }
1070
1071    /**
1072     * Redacts configuration and keys.
1073     *
1074     * @since 1.0.0
1075     */
1076    @Override public @NonNull String toString() { return "SamlServiceProvider{<redacted>}"; }
1077
1078    /**
1079     * Mutable configuration before creating an immutable SP.
1080     *
1081     * @since 1.0.0
1082     */
1083    @NotThreadSafe
1084    @CheckReturnValue
1085    public static final class Builder {
1086        private final @NonNull String entityId;
1087        private @Nullable URI assertionConsumerServiceUrl;
1088        private @Nullable URI singleLogoutServiceUrl;
1089        private @Nullable URI postSingleLogoutServiceUrl;
1090        private @Nullable SamlReplayCache replayCache;
1091        private @Nullable PrivateKey signingKey;
1092        private @Nullable SamlCredential signingCredential;
1093        private @NonNull List<@NonNull SamlCredential> decryptionCredentials = List.of();
1094        private @NonNull Clock clock = Clock.systemUTC();
1095        private @NonNull SecureRandom random = new SecureRandom();
1096        private @NonNull Duration clockSkew = Duration.ofMinutes(3);
1097        private @NonNull Duration maximumResponseAge = Duration.ofMinutes(5);
1098        private @NonNull Duration pendingLifetime = Duration.ofMinutes(5);
1099        private @NonNull Duration replayBudget = Duration.ofSeconds(5);
1100        private @NonNull SamlObserver observer = SamlObserver.disabledInstance();
1101        private boolean acknowledgeGlobalSecureValidationDisabled;
1102
1103        private Builder(@NonNull String entityId) { this.entityId = entityId; }
1104
1105        /**
1106         * Configures this option.
1107         *
1108         * @param value HTTPS ACS URL, at most 2048 characters in ASCII URI form
1109         * @return this builder
1110         * @since 1.0.0
1111         */
1112        @CheckReturnValue public @NonNull Builder assertionConsumerServiceUrl(@Nullable URI value) {
1113            this.assertionConsumerServiceUrl = value;
1114            return this;
1115        }
1116        /**
1117         * Configures the public SP HTTP-Redirect logout receiver.
1118         *
1119         * @param value HTTPS logout URI of at most 2048 ASCII URI characters, or null to disable Redirect logout
1120         * @return this builder
1121         * @since 1.0.0
1122         */
1123        @CheckReturnValue public @NonNull Builder singleLogoutServiceUrl(@Nullable URI value) {
1124            this.singleLogoutServiceUrl = value;
1125            return this;
1126        }
1127        /**
1128         * Configures the public SP HTTP-POST logout receiver.
1129         *
1130         * @param value HTTPS logout URI of at most 2048 ASCII URI characters, or null to disable POST logout
1131         * @return this builder
1132         * @since 1.0.0
1133         */
1134        @CheckReturnValue public @NonNull Builder postSingleLogoutServiceUrl(@Nullable URI value) {
1135            this.postSingleLogoutServiceUrl = value;
1136            return this;
1137        }
1138        /**
1139         * Configures this option.
1140         *
1141         * @param value explicitly selected replay cache
1142         * @return this builder
1143         * @since 1.0.0
1144         */
1145        @CheckReturnValue public @NonNull Builder replayCache(@Nullable SamlReplayCache value) {
1146            this.replayCache = value;
1147            return this;
1148        }
1149        /**
1150         * Configures this option.
1151         *
1152         * @param value optional RSA signing key for authentication and logout messages
1153         * @return this builder
1154         * @since 1.0.0
1155         */
1156        @CheckReturnValue public @NonNull Builder signingPrivateKey(@Nullable PrivateKey value) {
1157            this.signingKey = value;
1158            this.signingCredential = null;
1159            return this;
1160        }
1161        /**
1162         * Configures a signing key and certificate for requests and metadata.
1163         *
1164         * @param value signing credential, or null to clear
1165         * @return this builder
1166         * @since 1.0.0
1167         */
1168        @CheckReturnValue public @NonNull Builder signingCredential(@Nullable SamlCredential value) {
1169            this.signingCredential = value;
1170            this.signingKey = value == null ? null : value.privateKey();
1171            return this;
1172        }
1173        /**
1174         * Configures decryption credentials, including rollover keys.
1175         *
1176         * @param value credentials, or null to clear
1177         * @return this builder
1178         * @since 1.0.0
1179         */
1180        @CheckReturnValue public @NonNull Builder decryptionCredentials(
1181                @Nullable List<@NonNull SamlCredential> value) {
1182            this.decryptionCredentials = value == null ? List.of() : List.copyOf(value);
1183            return this;
1184        }
1185        /**
1186         * Configures this option.
1187         *
1188         * @param value validation clock, or null to reset to system UTC
1189         * @return this builder
1190         * @since 1.0.0
1191         */
1192        @CheckReturnValue public @NonNull Builder clock(@Nullable Clock value) {
1193            this.clock = value == null ? Clock.systemUTC() : value;
1194            return this;
1195        }
1196        /**
1197         * Configures this option.
1198         *
1199         * @param value cryptographic random source, or null for a new default
1200         * @return this builder
1201         * @since 1.0.0
1202         */
1203        @CheckReturnValue public @NonNull Builder random(@Nullable SecureRandom value) {
1204            this.random = value == null ? new SecureRandom() : value;
1205            return this;
1206        }
1207        /**
1208         * Configures this option.
1209         *
1210         * @param value skew from zero to five minutes, or null for three minutes
1211         * @return this builder
1212         * @since 1.0.0
1213         */
1214        @CheckReturnValue public @NonNull Builder clockSkew(@Nullable Duration value) {
1215            this.clockSkew = value == null ? Duration.ofMinutes(3) : value;
1216            return this;
1217        }
1218        /**
1219         * Configures this option.
1220         *
1221         * @param value assertion age from one second to fifteen minutes, or null for five minutes
1222         * @return this builder
1223         * @since 1.0.0
1224         */
1225        @CheckReturnValue public @NonNull Builder maximumResponseAge(@Nullable Duration value) {
1226            this.maximumResponseAge = value == null ? Duration.ofMinutes(5) : value;
1227            return this;
1228        }
1229        /**
1230         * Configures this option.
1231         *
1232         * @param value pending lifetime from one second to fifteen minutes, or null for five minutes
1233         * @return this builder
1234         * @since 1.0.0
1235         */
1236        @CheckReturnValue public @NonNull Builder pendingAuthenticationLifetime(@Nullable Duration value) {
1237            this.pendingLifetime = value == null ? Duration.ofMinutes(5) : value;
1238            return this;
1239        }
1240        /**
1241         * Configures this option.
1242         *
1243         * @param value replay operation budget from one millisecond to thirty seconds
1244         * @return this builder
1245         * @since 1.0.0
1246         */
1247        @CheckReturnValue public @NonNull Builder replayBudget(@Nullable Duration value) {
1248            this.replayBudget = value == null ? Duration.ofSeconds(5) : value;
1249            return this;
1250        }
1251
1252        /**
1253         * Configures redacted caller-thread SAML events; null restores the disabled observer.
1254         *
1255         * @param value observer, or null to disable events
1256         * @return this builder
1257         * @since 1.0.0
1258         */
1259        @CheckReturnValue public @NonNull Builder observer(@Nullable SamlObserver value) {
1260            this.observer = value == null ? SamlObserver.disabledInstance() : value;
1261            return this;
1262        }
1263
1264        /**
1265         * Acknowledges that this JVM globally disables XML-signature secure validation. Revetsec
1266         * still sets secure validation on each verification context and enforces its own signature
1267         * shape and algorithm allowlists. The setting is reported to the observer at build time.
1268         *
1269         * @param value true to acknowledge; false or null restores the safe default
1270         * @return this builder
1271         * @since 1.0.0
1272         */
1273        @CheckReturnValue public @NonNull Builder acknowledgeGlobalSecureValidationDisabled(
1274                @Nullable Boolean value) {
1275            this.acknowledgeGlobalSecureValidationDisabled = Boolean.TRUE.equals(value);
1276            return this;
1277        }
1278
1279        /**
1280         * Returns this value.
1281         *
1282         * @return immutable SP configuration
1283         * @since 1.0.0
1284         */
1285        public @NonNull SamlServiceProvider build() {
1286            String globalSecureValidation = System.getProperty(XML_DSIG_SECURE_VALIDATION);
1287            boolean globallyDisabled = globalSecureValidation != null
1288                    && !"true".equalsIgnoreCase(globalSecureValidation);
1289            if (globallyDisabled && !acknowledgeGlobalSecureValidationDisabled)
1290                throw new IllegalStateException("Global XML signature secure validation is disabled; "
1291                        + "set acknowledgeGlobalSecureValidationDisabled(true) to accept this runtime");
1292            URI acs = assertionConsumerServiceUrl;
1293            if (acs == null || !PendingSamlAuthenticationCodec.fitsText(acs.toString(), 2048)
1294                    || !PendingSamlAuthenticationCodec.fitsText(acs.toASCIIString(), 2048)
1295                    || !"https".equalsIgnoreCase(acs.getScheme()) || acs.getHost() == null
1296                    || acs.getRawUserInfo() != null || acs.getRawFragment() != null)
1297                throw new IllegalStateException("HTTPS ACS URL is required");
1298            if (singleLogoutServiceUrl != null
1299                    && (!PendingSamlAuthenticationCodec.fitsText(singleLogoutServiceUrl.toString(), 2048)
1300                        || !PendingSamlAuthenticationCodec.fitsText(singleLogoutServiceUrl.toASCIIString(), 2048)
1301                        || !"https".equalsIgnoreCase(singleLogoutServiceUrl.getScheme())
1302                        || singleLogoutServiceUrl.getHost() == null
1303                        || singleLogoutServiceUrl.getRawUserInfo() != null
1304                        || singleLogoutServiceUrl.getRawFragment() != null
1305                        || singleLogoutServiceUrl.getRawQuery() != null))
1306                throw new IllegalStateException("Invalid HTTPS SAML logout URL");
1307            if (postSingleLogoutServiceUrl != null
1308                    && (!PendingSamlAuthenticationCodec.fitsText(postSingleLogoutServiceUrl.toString(), 2048)
1309                        || !PendingSamlAuthenticationCodec.fitsText(postSingleLogoutServiceUrl.toASCIIString(), 2048)
1310                        || !"https".equalsIgnoreCase(postSingleLogoutServiceUrl.getScheme())
1311                        || postSingleLogoutServiceUrl.getHost() == null
1312                        || postSingleLogoutServiceUrl.getRawUserInfo() != null
1313                        || postSingleLogoutServiceUrl.getRawFragment() != null
1314                        || !safeLogoutEndpointQuery(postSingleLogoutServiceUrl)))
1315                throw new IllegalStateException("Invalid HTTPS SAML POST logout URL");
1316            if ((singleLogoutServiceUrl != null || postSingleLogoutServiceUrl != null) && signingKey == null)
1317                throw new IllegalStateException("SAML logout requires a signing key");
1318            if (replayCache == null) throw new IllegalStateException("SAML replay cache is required");
1319            if (decryptionCredentials.size() > 4)
1320                throw new IllegalStateException("Too many SAML decryption credentials");
1321            if (signingKey != null && (!(signingKey instanceof RSAPrivateKey rsa)
1322                    || rsa.getModulus().bitLength() < 2048))
1323                throw new IllegalStateException("Unsupported or weak SAML signing key");
1324            if (clockSkew.isNegative()
1325                    || clockSkew.compareTo(SamlResponseSemantics.MAXIMUM_CONFIGURED_SKEW) > 0
1326                    || maximumResponseAge.compareTo(Duration.ofSeconds(1)) < 0
1327                    || maximumResponseAge.compareTo(
1328                            SamlResponseSemantics.MAXIMUM_CONFIGURED_RESPONSE_AGE) > 0
1329                    || pendingLifetime.compareTo(Duration.ofSeconds(1)) < 0
1330                    || pendingLifetime.compareTo(Duration.ofMinutes(15)) > 0
1331                    || replayBudget.compareTo(Duration.ofMillis(1)) < 0
1332                    || replayBudget.compareTo(Duration.ofSeconds(30)) > 0)
1333                throw new IllegalStateException("Invalid SAML time policy");
1334            SamlServiceProvider provider = new SamlServiceProvider(this);
1335            if (globallyDisabled)
1336                ObserverDispatch.dispatch(observer,
1337                        SamlObserver::didAcknowledgeGlobalSecureValidationDisabled);
1338            return provider;
1339        }
1340    }
1341}