001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package com.revetsec.saml;
017
018import com.revetsec.internal.xml.SecureXmlParser;
019import com.revetsec.internal.xml.EnvelopedSignatureVerifier;
020import com.revetsec.internal.pem.Pem;
021import com.revetsec.internal.pem.PemException;
022import org.jspecify.annotations.NonNull;
023import org.jspecify.annotations.Nullable;
024import org.w3c.dom.Element;
025import org.w3c.dom.Node;
026
027import javax.annotation.concurrent.Immutable;
028import java.net.URI;
029import java.security.cert.X509Certificate;
030import java.security.PublicKey;
031import java.time.Clock;
032import java.time.Instant;
033import java.util.ArrayList;
034import java.util.Base64;
035import java.util.List;
036import java.util.Objects;
037import java.util.Optional;
038
039/**
040 * One bounded, application-supplied SAML IdP metadata descriptor. No network fetch occurs and
041 * parsing does not approve the entity as an application connection.
042 * A verified signature authenticates content, not its age. The application owns retrieval,
043 * refresh, maximum age and expiry of any installed connection built from this snapshot.
044 *
045 * @since 1.0.0
046 */
047@Immutable
048public final class SamlIdentityProviderMetadata {
049    private static final String MD = "urn:oasis:names:tc:SAML:2.0:metadata";
050    private static final String DS = "http://www.w3.org/2000/09/xmldsig#";
051    private static final String SHIBMD = "urn:mace:shibboleth:metadata:1.0";
052    private static final String REDIRECT = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
053    private static final String POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
054
055    private final @NonNull String entityId;
056    private final @Nullable URI redirectSso;
057    private final @Nullable URI postSso;
058    private final @Nullable URI redirectSlo;
059    private final @Nullable URI postSlo;
060    private final @Nullable URI redirectSloResponse;
061    private final @Nullable URI postSloResponse;
062    private final @NonNull List<@NonNull X509Certificate> signingCertificates;
063    private final boolean wantAuthnRequestsSigned;
064    private final @Nullable Instant validUntil;
065    private final @NonNull List<@NonNull String> authorizedScopes;
066
067    private SamlIdentityProviderMetadata(@NonNull String entityId, @Nullable URI redirectSso,
068            @Nullable URI postSso, @Nullable URI redirectSlo, @Nullable URI postSlo,
069            @Nullable URI redirectSloResponse, @Nullable URI postSloResponse,
070            @NonNull List<@NonNull X509Certificate> signingCertificates,
071            boolean wantAuthnRequestsSigned, @Nullable Instant validUntil,
072            @NonNull List<@NonNull String> authorizedScopes) {
073        this.entityId = entityId;
074        this.redirectSso = redirectSso;
075        this.postSso = postSso;
076        this.redirectSlo = redirectSlo;
077        this.postSlo = postSlo;
078        this.redirectSloResponse = redirectSloResponse;
079        this.postSloResponse = postSloResponse;
080        this.signingCertificates = List.copyOf(signingCertificates);
081        this.wantAuthnRequestsSigned = wantAuthnRequestsSigned;
082        this.validUntil = validUntil;
083        this.authorizedScopes = List.copyOf(authorizedScopes);
084    }
085
086    /**
087     * Parses a single EntityDescriptor using the system UTC clock.
088     *
089     * @param xml application-supplied metadata bytes
090     * @return parsed metadata or a fixed failure
091     * @since 1.0.0
092     */
093    public static @NonNull SamlIdentityProviderMetadataResult fromXmlResult(byte @NonNull [] xml) {
094        return fromXmlResult(xml, null, Clock.systemUTC());
095    }
096
097    /**
098     * Selects one entity from a single or aggregate descriptor using the system UTC clock.
099     *
100     * @param xml application-supplied metadata bytes
101     * @param expectedEntityId exact entity ID to select
102     * @return parsed metadata or a fixed failure
103     * @since 1.0.0
104     */
105    public static @NonNull SamlIdentityProviderMetadataResult fromXmlResult(byte @NonNull [] xml,
106            @NonNull String expectedEntityId) {
107        return fromXmlResult(xml, Objects.requireNonNull(expectedEntityId), Clock.systemUTC());
108    }
109
110    /**
111     * Parses metadata with an explicit validation clock.
112     *
113     * @param xml application-supplied metadata bytes
114     * @param expectedEntityId exact entity ID for aggregate selection, or null for a single descriptor
115     * @param clock validation clock
116     * @return parsed metadata or a fixed failure
117     * @since 1.0.0
118     */
119    public static @NonNull SamlIdentityProviderMetadataResult fromXmlResult(byte @NonNull [] xml,
120            @Nullable String expectedEntityId, @NonNull Clock clock) {
121        return parse(xml, expectedEntityId, clock, null, false);
122    }
123
124    /**
125     * Parses metadata only when a pinned trusted key verifies a signature covering the selected
126     * entity or its containing aggregate. Embedded KeyInfo is never a trust anchor.
127     * A missing {@code validUntil} is accepted for application-managed freshness; a signature
128     * alone is not evidence of recency. Use {@link #fromXmlRequiringValidUntilResult(byte[], String,
129     * Clock, List)} when a signed deadline is required. Any present covered deadline must still
130     * be in the future when parsing completes. This snapshot does not expire an installed connection.
131     *
132     * @param xml application-supplied metadata bytes
133     * @param expectedEntityId exact entity ID for aggregate selection, or null for a single descriptor
134     * @param clock validation clock
135     * @param trustedMetadataKeys one to four application-pinned verification keys
136     * @return parsed metadata or a fixed failure
137     * @since 1.0.0
138     */
139    public static @NonNull SamlIdentityProviderMetadataResult fromXmlResult(byte @NonNull [] xml,
140            @Nullable String expectedEntityId, @NonNull Clock clock,
141            @NonNull List<@NonNull PublicKey> trustedMetadataKeys) {
142        requireMetadataKeys(trustedMetadataKeys);
143        return parse(xml, expectedEntityId, clock, trustedMetadataKeys, false);
144    }
145
146    /**
147     * Requires a pinned signature and a future, signature-covered {@code validUntil} on the
148     * selected entity, its IdP role, or a verified containing aggregate. The earliest covered
149     * deadline wins. An unsigned parent's deadline cannot satisfy this policy.
150     * This checks expiry at parse completion, not publication age or freshness of the retrieval.
151     * Applications must cap trusted acquisition age and retire installed connections themselves;
152     * reparsing the same bytes must not reset that acquisition time.
153     *
154     * @param xml application-supplied metadata bytes
155     * @param expectedEntityId exact entity ID, or null for a single descriptor
156     * @param clock trusted validation clock
157     * @param trustedMetadataKeys one to four application-pinned verification keys
158     * @return metadata with a verified future deadline, rejection, or provider/clock unavailability
159     * @since 1.0.0
160     */
161    public static @NonNull SamlIdentityProviderMetadataResult fromXmlRequiringValidUntilResult(
162            byte @NonNull [] xml, @Nullable String expectedEntityId, @NonNull Clock clock,
163            @NonNull List<@NonNull PublicKey> trustedMetadataKeys) {
164        requireMetadataKeys(trustedMetadataKeys);
165        return parse(xml, expectedEntityId, clock, trustedMetadataKeys, true);
166    }
167
168    private static void requireMetadataKeys(@NonNull List<@NonNull PublicKey> trustedMetadataKeys) {
169        Objects.requireNonNull(trustedMetadataKeys);
170        if (trustedMetadataKeys.isEmpty() || trustedMetadataKeys.size() > 4
171                || trustedMetadataKeys.stream().anyMatch(key -> key == null))
172            throw new IllegalArgumentException("Expected one to four pinned metadata keys");
173    }
174
175    private static @NonNull SamlIdentityProviderMetadataResult parse(byte @NonNull [] xml,
176            @Nullable String expectedEntityId, @NonNull Clock clock,
177            @Nullable List<@NonNull PublicKey> trustedMetadataKeys, boolean requireValidUntil) {
178        Objects.requireNonNull(xml);
179        Objects.requireNonNull(clock);
180        SecureXmlParser.Result parsed = SecureXmlParser.parseMetadata(xml);
181        if (parsed instanceof SecureXmlParser.Result.Rejected)
182            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
183        if (parsed instanceof SecureXmlParser.Result.Unavailable)
184            return SamlIdentityProviderMetadataResult.Unavailable.INSTANCE;
185        Instant now;
186        try { now = clock.instant(); }
187        catch (RuntimeException exception) { return SamlIdentityProviderMetadataResult.Unavailable.INSTANCE; }
188        Element root = ((SecureXmlParser.Result.Accepted) parsed).getDocument().getDocumentElement();
189        if (root == null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
190        Element entity = root;
191        Instant aggregateLimit = null;
192        boolean aggregate = is(root, MD, "EntitiesDescriptor");
193        if (aggregate) {
194            if (expectedEntityId == null || expectedEntityId.isEmpty())
195                return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
196            entity = null;
197            boolean aggregateSignature = false;
198            boolean sawEntity = false;
199            for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
200                if (!(child instanceof Element candidate)) continue;
201                if (is(candidate, DS, "Signature")) {
202                    if (aggregateSignature || sawEntity)
203                        return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
204                    aggregateSignature = true;
205                    continue;
206                }
207                if (!is(candidate, MD, "EntityDescriptor"))
208                    return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
209                sawEntity = true;
210                if (expectedEntityId.equals(candidate.getAttributeNS(null, "entityID"))) {
211                    if (entity != null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
212                    entity = candidate;
213                }
214            }
215        }
216        if (entity == null || !is(entity, MD, "EntityDescriptor"))
217            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
218        String entityId = entity.getAttributeNS(null, "entityID");
219        if (entityId.isEmpty() || entityId.length() > 2048
220                || (expectedEntityId != null && !expectedEntityId.equals(entityId)))
221            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
222        boolean aggregateCovered = trustedMetadataKeys == null;
223        if (trustedMetadataKeys != null) {
224            Element signed = !root.isSameNode(entity) && directSignature(root) ? root : entity;
225            EnvelopedSignatureVerifier.Result proof = EnvelopedSignatureVerifier.verifyMetadata(
226                    (SecureXmlParser.Result.Accepted) parsed, signed, trustedMetadataKeys);
227            if (proof instanceof EnvelopedSignatureVerifier.Unavailable)
228                return SamlIdentityProviderMetadataResult.Unavailable.INSTANCE;
229            if (!(proof instanceof EnvelopedSignatureVerifier.Verified))
230                return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
231            aggregateCovered = signed.isSameNode(root);
232        }
233        if (aggregate && aggregateCovered) {
234            // An entity signature does not authenticate validity on its enclosing aggregate.
235            aggregateLimit = validity(root, now);
236            if (root.hasAttributeNS(null, "validUntil") && aggregateLimit == null)
237                return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
238        }
239        Instant entityLimit = validity(entity, now);
240        if (entity.hasAttributeNS(null, "validUntil") && entityLimit == null)
241            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
242        Instant validUntil = entityLimit == null ? aggregateLimit
243                : aggregateLimit == null || entityLimit.isBefore(aggregateLimit) ? entityLimit : aggregateLimit;
244        Element descriptor = null;
245        for (Node child = entity.getFirstChild(); child != null; child = child.getNextSibling()) {
246            if (!(child instanceof Element candidate)) continue;
247            if (is(candidate, MD, "IDPSSODescriptor")) {
248                if (descriptor != null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
249                descriptor = candidate;
250            }
251        }
252        if (descriptor == null || !descriptor.getAttributeNS(null, "protocolSupportEnumeration")
253                .matches("(?:^|.*\\s)urn:oasis:names:tc:SAML:2\\.0:protocol(?:\\s.*|$)"))
254            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
255        Instant roleLimit = validity(descriptor, now);
256        if (descriptor.hasAttributeNS(null, "validUntil") && roleLimit == null)
257            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
258        if (roleLimit != null && (validUntil == null || roleLimit.isBefore(validUntil)))
259            validUntil = roleLimit;
260        URI redirect = null;
261        URI post = null;
262        URI logout = null;
263        URI postLogout = null;
264        URI logoutResponse = null;
265        URI postLogoutResponse = null;
266        List<X509Certificate> certificates = new ArrayList<>();
267        List<String> scopes = new ArrayList<>();
268        for (Node child = descriptor.getFirstChild(); child != null; child = child.getNextSibling()) {
269            if (!(child instanceof Element element)) continue;
270            if (is(element, MD, "SingleSignOnService")) {
271                String binding = element.getAttributeNS(null, "Binding");
272                if (!REDIRECT.equals(binding) && !POST.equals(binding)) continue;
273                URI location = endpoint(element.getAttributeNS(null, "Location"));
274                if (location == null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
275                if (REDIRECT.equals(binding)) {
276                    if (redirect != null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
277                    redirect = location;
278                } else if (POST.equals(binding)) {
279                    if (post != null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
280                    post = location;
281                }
282            } else if (is(element, MD, "SingleLogoutService")) {
283                String binding = element.getAttributeNS(null, "Binding");
284                if (!REDIRECT.equals(binding) && !POST.equals(binding)) continue;
285                URI location = endpoint(element.getAttributeNS(null, "Location"));
286                if (location == null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
287                URI responseLocation = element.hasAttributeNS(null, "ResponseLocation")
288                        ? endpoint(element.getAttributeNS(null, "ResponseLocation")) : null;
289                if (element.hasAttributeNS(null, "ResponseLocation") && responseLocation == null)
290                    return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
291                if (REDIRECT.equals(binding)) {
292                    if (logout != null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
293                    logout = location;
294                    logoutResponse = responseLocation;
295                } else {
296                    if (postLogout != null) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
297                    postLogout = location;
298                    postLogoutResponse = responseLocation;
299                }
300            } else if (is(element, MD, "KeyDescriptor")) {
301                String use = element.getAttributeNS(null, "use");
302                if (!use.isEmpty() && !"signing".equals(use) && !"encryption".equals(use))
303                    return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
304                if (!"encryption".equals(use)) {
305                    X509Certificate certificate = certificate(element);
306                    if (certificate == null || certificates.size() >= 8)
307                        return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
308                    certificates.add(certificate);
309                }
310            } else if (is(element, MD, "Extensions")) {
311                for (Node extension = element.getFirstChild(); extension != null;
312                        extension = extension.getNextSibling()) {
313                    if (!(extension instanceof Element scope) || !is(scope, SHIBMD, "Scope")) continue;
314                    if ("true".equals(scope.getAttributeNS(null, "regexp"))) continue;
315                    String literal = textOnly(scope);
316                    if (literal == null || literal.isEmpty() || literal.length() > 255
317                            || literal.contains("@") || literal.contains("*") || literal.contains(" ")
318                            || scopes.size() >= 32) return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
319                    scopes.add(literal);
320                }
321            }
322        }
323        if ((redirect == null && post == null) || certificates.isEmpty())
324            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
325        String wants = descriptor.getAttributeNS(null, "WantAuthnRequestsSigned");
326        if (!wants.isEmpty() && !wants.equals("true") && !wants.equals("false")
327                && !wants.equals("1") && !wants.equals("0"))
328            return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
329        if (trustedMetadataKeys != null) {
330            Instant completed;
331            try { completed = clock.instant(); }
332            catch (RuntimeException exception) { return SamlIdentityProviderMetadataResult.Unavailable.INSTANCE; }
333            if (completed.isBefore(now)) return SamlIdentityProviderMetadataResult.Unavailable.INSTANCE;
334            if (!freshnessAllows(validUntil, completed, requireValidUntil))
335                return SamlIdentityProviderMetadataResult.Rejected.INSTANCE;
336        }
337        return new SamlIdentityProviderMetadataResult.Parsed(new SamlIdentityProviderMetadata(entityId,
338                redirect, post, logout, postLogout, logoutResponse, postLogoutResponse,
339                certificates, wants.equals("true") || wants.equals("1"),
340                validUntil, scopes));
341    }
342
343    private static boolean freshnessAllows(@Nullable Instant validUntil, @NonNull Instant now,
344            boolean requireValidUntil) {
345        return validUntil == null ? !requireValidUntil : now.isBefore(validUntil);
346    }
347
348    private static @Nullable Instant validity(@NonNull Element element, @NonNull Instant now) {
349        if (!element.hasAttributeNS(null, "validUntil")) return null;
350        Instant until = SamlDateTime.parse(element.getAttributeNS(null, "validUntil"));
351        return until != null && now.isBefore(until) ? until : null;
352    }
353
354    private static boolean directSignature(@NonNull Element element) {
355        for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling())
356            if (child instanceof Element candidate && is(candidate, DS, "Signature")) return true;
357        return false;
358    }
359
360    private static @Nullable URI endpoint(@NonNull String text) {
361        try {
362            URI value = URI.create(text);
363            return "https".equalsIgnoreCase(value.getScheme()) && value.getHost() != null
364                    && value.getRawUserInfo() == null && value.getRawFragment() == null ? value : null;
365        } catch (IllegalArgumentException exception) { return null; }
366    }
367
368    private static @Nullable X509Certificate certificate(@NonNull Element descriptor) {
369        Element keyInfo = onlyChild(descriptor, DS, "KeyInfo");
370        Element data = keyInfo == null ? null : onlyChild(keyInfo, DS, "X509Data");
371        Element encoded = data == null ? null : onlyChild(data, DS, "X509Certificate");
372        if (encoded == null) return null;
373        String content = textOnly(encoded);
374        if (content == null) return null;
375        String value = content.replaceAll("[ \\t\\r\\n]", "");
376        if (value.isEmpty() || value.length() > 32768) return null;
377        try {
378            byte[] der = Base64.getDecoder().decode(value);
379            if (der.length > 24576) return null;
380            return Pem.parseCertificateDer(der);
381        } catch (IllegalArgumentException | PemException exception) { return null; }
382    }
383
384    private static @Nullable Element onlyChild(@NonNull Element parent, @NonNull String namespace,
385            @NonNull String local) {
386        Element match = null;
387        for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
388            if (!(child instanceof Element candidate)) continue;
389            if (is(candidate, namespace, local)) {
390                if (match != null) return null;
391                match = candidate;
392            }
393        }
394        return match;
395    }
396
397    private static boolean is(@NonNull Element element, @NonNull String namespace, @NonNull String local) {
398        return namespace.equals(element.getNamespaceURI()) && local.equals(element.getLocalName());
399    }
400
401    private static @Nullable String textOnly(@NonNull Element element) {
402        StringBuilder value = new StringBuilder();
403        for (Node child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
404            if (child.getNodeType() != Node.TEXT_NODE) return null;
405            value.append(child.getNodeValue());
406        }
407        return value.toString();
408    }
409
410    /**
411     * Returns the selected IdP entity ID.
412     *
413     * @return entity ID
414     * @since 1.0.0
415     */
416    public @NonNull String getEntityId() { return entityId; }
417    /**
418     * Returns the Redirect SSO endpoint when advertised.
419     *
420     * @return optional endpoint
421     * @since 1.0.0
422     */
423    public @NonNull Optional<@NonNull URI> getRedirectSingleSignOnService() {
424        return Optional.ofNullable(redirectSso);
425    }
426    /**
427     * Returns the POST SSO endpoint when advertised.
428     *
429     * @return optional endpoint
430     * @since 1.0.0
431     */
432    public @NonNull Optional<@NonNull URI> getPostSingleSignOnService() { return Optional.ofNullable(postSso); }
433    /**
434     * Returns the HTTP-Redirect SLO endpoint when advertised.
435     *
436     * @return optional endpoint
437     * @since 1.0.0
438     */
439    public @NonNull Optional<@NonNull URI> getRedirectSingleLogoutService() {
440        return Optional.ofNullable(redirectSlo);
441    }
442    /** Returns the HTTP-POST logout endpoint, if advertised.
443     * @return POST logout endpoint
444     * @since 1.0.0
445     */
446    public @NonNull Optional<@NonNull URI> getPostSingleLogoutService() {
447        return Optional.ofNullable(postSlo);
448    }
449    /** Returns a distinct HTTP-Redirect SLO ResponseLocation, if advertised.
450     * @return response endpoint, or empty to use the request endpoint
451     * @since 1.0.0
452     */
453    public @NonNull Optional<@NonNull URI> getRedirectSingleLogoutResponseService() {
454        return Optional.ofNullable(redirectSloResponse);
455    }
456    /** Returns a distinct HTTP-POST SLO ResponseLocation, if advertised.
457     * @return response endpoint, or empty to use the request endpoint
458     * @since 1.0.0
459     */
460    public @NonNull Optional<@NonNull URI> getPostSingleLogoutResponseService() {
461        return Optional.ofNullable(postSloResponse);
462    }
463
464    /**
465     * Returns signing certificates from this metadata, including rollover certificates.
466     *
467     * @return immutable certificate list
468     * @since 1.0.0
469     */
470    public @NonNull List<@NonNull X509Certificate> getSigningCertificates() {
471        return signingCertificates;
472    }
473    /**
474     * Reports whether the IdP requests signed AuthnRequests.
475     *
476     * @return true if requested
477     * @since 1.0.0
478     */
479    public @NonNull Boolean wantsAuthnRequestsSigned() { return wantAuthnRequestsSigned; }
480    /**
481     * Returns the earliest applicable metadata expiry when present. Pinned-signature parsing
482     * includes only deadlines covered by that proof; raw parsing does not establish trust.
483     * The application must stop using an installed connection at its effective deadline.
484     *
485     * @return optional expiry
486     * @since 1.0.0
487     */
488    public @NonNull Optional<@NonNull Instant> getValidUntil() { return Optional.ofNullable(validUntil); }
489    /**
490     * Returns literal identifier scopes advertised by this metadata. The application still
491     * approves the scopes before building a connection.
492     *
493     * @return immutable literal scopes
494     * @since 1.0.0
495     */
496    public @NonNull List<@NonNull String> getAuthorizedIdentifierScopes() { return authorizedScopes; }
497    /**
498     * Redacts certificate and endpoint data.
499     *
500     * @return redacted description
501     * @since 1.0.0
502     */
503    @Override public @NonNull String toString() { return "SamlIdentityProviderMetadata{<redacted>}"; }
504}