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 org.jspecify.annotations.NonNull;
019import javax.annotation.concurrent.Immutable;
020import javax.xml.stream.XMLOutputFactory;
021import javax.xml.stream.XMLStreamException;
022import javax.xml.stream.XMLStreamWriter;
023import java.io.ByteArrayOutputStream;
024import java.net.URI;
025import java.nio.charset.StandardCharsets;
026import java.security.cert.CertificateEncodingException;
027import java.util.Base64;
028import java.util.Objects;
029
030/**
031 * Local SP metadata publication. It advertises only capabilities that the SP can actually use.
032 *
033 * @since 1.0.0
034 */
035@Immutable
036public final class SamlServiceProviderMetadata {
037    private static final String MD = "urn:oasis:names:tc:SAML:2.0:metadata";
038    private static final String DS = "http://www.w3.org/2000/09/xmldsig#";
039    private static final String PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol";
040    private static final String POST = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
041
042    private SamlServiceProviderMetadata() { }
043
044    /**
045     * Produces one EntityDescriptor. A signing certificate is required, and encryption is never
046     * advertised until the configured engine can complete the corresponding profile.
047     *
048     * @param serviceProvider immutable SP configuration
049     * @return generated metadata or a fixed failure
050     * @since 1.0.0
051     */
052    public static @NonNull SamlServiceProviderMetadataResult fromServiceProviderResult(
053            @NonNull SamlServiceProvider serviceProvider) {
054        Objects.requireNonNull(serviceProvider);
055        SamlCredential signing = serviceProvider.signingCredential();
056        if (signing == null)
057            return SamlServiceProviderMetadataResult.Rejected.CONFIGURATION;
058        byte[] certificate;
059        try { certificate = signing.getCertificate().getEncoded(); }
060        catch (CertificateEncodingException exception) {
061            return SamlServiceProviderMetadataResult.Unavailable.INSTANCE;
062        }
063        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
064        try {
065            XMLStreamWriter xml = XMLOutputFactory.newDefaultFactory().createXMLStreamWriter(bytes, "UTF-8");
066            try {
067                xml.writeStartDocument("UTF-8", "1.0");
068                xml.writeStartElement("md", "EntityDescriptor", MD);
069                xml.writeNamespace("md", MD);
070                xml.writeNamespace("ds", DS);
071                xml.writeAttribute("entityID", serviceProvider.entityId());
072                xml.writeStartElement("md", "SPSSODescriptor", MD);
073                xml.writeAttribute("protocolSupportEnumeration", PROTOCOL);
074                xml.writeAttribute("AuthnRequestsSigned", "true");
075                xml.writeAttribute("WantAssertionsSigned", "false");
076                xml.writeStartElement("md", "KeyDescriptor", MD);
077                xml.writeAttribute("use", "signing");
078                xml.writeStartElement("ds", "KeyInfo", DS);
079                xml.writeStartElement("ds", "X509Data", DS);
080                xml.writeStartElement("ds", "X509Certificate", DS);
081                xml.writeCharacters(Base64.getEncoder().encodeToString(certificate));
082                xml.writeEndElement();
083                xml.writeEndElement();
084                xml.writeEndElement();
085                xml.writeEndElement();
086                for (SamlCredential decryption : serviceProvider.decryptionCredentials()) {
087                    xml.writeStartElement("md", "KeyDescriptor", MD);
088                    xml.writeAttribute("use", "encryption");
089                    xml.writeStartElement("ds", "KeyInfo", DS);
090                    xml.writeStartElement("ds", "X509Data", DS);
091                    xml.writeStartElement("ds", "X509Certificate", DS);
092                    xml.writeCharacters(Base64.getEncoder().encodeToString(
093                            decryption.getCertificate().getEncoded()));
094                    xml.writeEndElement();
095                    xml.writeEndElement();
096                    xml.writeEndElement();
097                    xml.writeEmptyElement("md", "EncryptionMethod", MD);
098                    xml.writeAttribute("Algorithm", "http://www.w3.org/2009/xmlenc11#aes128-gcm");
099                    xml.writeEmptyElement("md", "EncryptionMethod", MD);
100                    xml.writeAttribute("Algorithm", "http://www.w3.org/2009/xmlenc11#aes192-gcm");
101                    xml.writeEmptyElement("md", "EncryptionMethod", MD);
102                    xml.writeAttribute("Algorithm", "http://www.w3.org/2009/xmlenc11#aes256-gcm");
103                    xml.writeEmptyElement("md", "EncryptionMethod", MD);
104                    xml.writeAttribute("Algorithm", "http://www.w3.org/2009/xmlenc11#rsa-oaep");
105                    xml.writeEndElement();
106                }
107                URI logoutUrl = serviceProvider.singleLogoutServiceUrl();
108                if (logoutUrl != null) {
109                    xml.writeEmptyElement("md", "SingleLogoutService", MD);
110                    xml.writeAttribute("Binding",
111                            "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
112                    xml.writeAttribute("Location", logoutUrl.toASCIIString());
113                }
114                URI postLogoutUrl = serviceProvider.postSingleLogoutServiceUrl();
115                if (postLogoutUrl != null) {
116                    xml.writeEmptyElement("md", "SingleLogoutService", MD);
117                    xml.writeAttribute("Binding", POST);
118                    xml.writeAttribute("Location", postLogoutUrl.toASCIIString());
119                }
120                xml.writeEmptyElement("md", "AssertionConsumerService", MD);
121                xml.writeAttribute("Binding", POST);
122                xml.writeAttribute("Location", serviceProvider.assertionConsumerServiceUrl().toASCIIString());
123                xml.writeAttribute("index", "0");
124                xml.writeAttribute("isDefault", "true");
125                xml.writeEndElement();
126                xml.writeEndElement();
127                xml.writeEndDocument();
128                xml.flush();
129            } finally { xml.close(); }
130            return new SamlServiceProviderMetadataResult.Generated(bytes.toString(StandardCharsets.UTF_8));
131        } catch (XMLStreamException | CertificateEncodingException | RuntimeException exception) {
132            return SamlServiceProviderMetadataResult.Unavailable.INSTANCE;
133        }
134    }
135}