[java-plugin-shibd-saml] branch main updated: Untested metadata publication flow and support classes.
Codeberg
noreply at shibboleth.net
Tue Nov 10 19:43:38 UTC 2026
This is an automated email from the git hooks/post-receive script.
codeberg pushed a commit to branch main
in repository java-plugin-shibd-saml.
View the commit online:
https://codeberg.org/Shibboleth/java-plugin-shibd-saml/commit/b833fd52b77138e8b0ed4b1a9e269ba96b582c6a
The following commit(s) were added to refs/heads/main by this push:
new b833fd5 Untested metadata publication flow and support classes.
b833fd5 is described below
commit b833fd52b77138e8b0ed4b1a9e269ba96b582c6a
Author: Scott Cantor <scott at restingparrotsoftware.com>
AuthorDate: Tue Nov 10 14:43:14 2026 -0500
Untested metadata publication flow and support classes.
---
sp-saml-api/pom.xml | 11 +
.../MetadataPublishingProfileConfiguration.java | 125 +++++++
.../config/logic/SignMetadataPredicate.java | 46 +++
...ignatureSigningConfigurationLookupFunction.java | 63 ++++
.../profile/config/navigate/package-info.java | 18 +
.../idp/flows/sp/metadata/saml2/saml2-beans.xml | 72 ++++
.../idp/flows/sp/metadata/saml2/saml2-flow.xml | 44 +++
.../net/shibboleth/sp/service/agent/postconfig.xml | 27 +-
.../shibboleth/idp/module/conf/sp/saml.properties | 69 ++++
.../messaging/impl/XMLObjectMessageEncoder.java | 108 ++++++
.../MetadataPublishingProfileConfiguration.java | 237 ++++++++++++
.../sp/saml/saml2/profile/impl/AddMetadata.java | 403 +++++++++++++++++++++
12 files changed, 1220 insertions(+), 3 deletions(-)
diff --git a/sp-saml-api/pom.xml b/sp-saml-api/pom.xml
index 5bbdc3c..7af82de 100644
--- a/sp-saml-api/pom.xml
+++ b/sp-saml-api/pom.xml
@@ -49,6 +49,17 @@
<artifactId>shib-metadata-api</artifactId>
<scope>provided</scope>
</dependency>
+
+ <dependency>
+ <groupId>${opensaml.groupId}</groupId>
+ <artifactId>opensaml-xmlsec-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>${opensaml.groupId}</groupId>
+ <artifactId>opensaml-xmlsec-impl</artifactId>
+ <scope>provided</scope>
+ </dependency>
<!-- Test Dependencies -->
</dependencies>
diff --git a/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/MetadataPublishingProfileConfiguration.java b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/MetadataPublishingProfileConfiguration.java
new file mode 100644
index 0000000..c8d10f3
--- /dev/null
+++ b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/MetadataPublishingProfileConfiguration.java
@@ -0,0 +1,125 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.shibboleth.sp.saml.saml2.profile.config;
+
+import java.time.Duration;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.saml.metadata.resolver.MetadataResolver;
+import org.opensaml.security.credential.Credential;
+
+import net.shibboleth.profile.config.ProfileConfiguration;
+import net.shibboleth.shared.annotation.ConfigurationSetting;
+import net.shibboleth.shared.annotation.constraint.NonNegative;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+
+/** Configuration support for publishing SAML 2.0 Metadata. */
+public interface MetadataPublishingProfileConfiguration extends ProfileConfiguration {
+
+ /** ID for this profile configuration. */
+ @Nonnull @NotEmpty static final String PROFILE_ID = "http://shibboleth.net/ns/profiles/saml2/metadata";
+
+ /**
+ * Gets the path to a template XML file to source for the metadata.
+ *
+ * <p>Defaults to null, resulting in a query to the configured {@link MetadataResolver} service
+ * for the configured "issuer" value as entityID to obtain metadata loaded into the Hub.</p>
+ *
+ * <p>If set, the path is evaluated as a Velocity template with the following variables populated:</p>
+ *
+ * <ul>
+ * <li>agentID</li>
+ * <li>applicationID</li>
+ * <li>issuer</li>
+ * <li>entityID</li>
+ * </ul>
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return templated path to XML file to serve
+ */
+ @ConfigurationSetting(name="templatePath")
+ @Nullable @NotEmpty String getTemplatePath(@Nullable final ProfileRequestContext profileRequestContext);
+
+ /**
+ * Gets whether the template returned by {@link #getTemplatePath(ProfileRequestContext)} is evaluated
+ * by Velocity or returned directly.
+ *
+ * <p>Defaults to false; only relevant if a template path is used. The same variables are populated
+ * in evaluating the template as described for {@link #getTemplatePath(ProfileRequestContext)}.</p>
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return true iff Velocity should be applied to the template
+ */
+ @ConfigurationSetting(name="useVelocity")
+ boolean isUseVelocity(@Nullable final ProfileRequestContext profileRequestContext);
+ /**
+ * Gets whether to sign the metadata being published dynamically.
+ *
+ * <p>Defaults to false.</p>
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return true iff the metadata should be signed in real time
+ */
+ @ConfigurationSetting(name="signMetadata")
+ boolean isSignMetadata(@Nullable final ProfileRequestContext profileRequestContext);
+
+ /**
+ * Gets an optional {@link Credential} to use to sign the metadata if
+ * {@link #isSignMetadata(ProfileRequestContext)} is true.</p>
+ *
+ * <p>If unset, the default configured service is used, resulting in effectively self-signed
+ * metadata using the same key used for SAML messages.</p>
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return a signing credential or null
+ */
+ @ConfigurationSetting(name="credentialResolver")
+ @Nullable Credential getSigningCredential(@Nullable final ProfileRequestContext profileRequestContext);
+
+ /**
+ * Gets the optional lifetime from which to compute and set the root element's <code>validUntil</code>
+ * attribute.
+ *
+ * <p>Defaults to null.</p>
+ *
+ * <p>Only applied if the root element's existing value would be longer.</p>
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return the time added to the current timestamp to set, or null to leave as is
+ */
+ @ConfigurationSetting(name="lifetime")
+ @Nullable @NonNegative Duration getLifetime(@Nullable final ProfileRequestContext profileRequestContext);
+
+ /**
+ * Gets the optional value to set in the root element's <code>cacehDuration</code> attribute.
+ *
+ * <p>Defaults to null.</p>
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return the cache duration, or null to leave as is
+ */
+ @ConfigurationSetting(name="cacheDuration")
+ @Nullable @NonNegative Duration getCacheDuration(@Nullable final ProfileRequestContext profileRequestContext);
+
+}
\ No newline at end of file
diff --git a/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/logic/SignMetadataPredicate.java b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/logic/SignMetadataPredicate.java
new file mode 100644
index 0000000..0471329
--- /dev/null
+++ b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/logic/SignMetadataPredicate.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.shibboleth.sp.saml.saml2.profile.config.logic;
+
+import javax.annotation.Nullable;
+
+import net.shibboleth.profile.context.RelyingPartyContext;
+import net.shibboleth.profile.context.logic.AbstractRelyingPartyPredicate;
+import net.shibboleth.sp.saml.saml2.profile.config.MetadataPublishingProfileConfiguration;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+
+/**
+ * A predicate that evaluates a {@link ProfileRequestContext} and extracts the effective
+ * setting of {@link MetadataPublishingProfileConfiguration#isSignMetadata(ProfileRequestContext)}.
+ *
+ * <p>Defaults to false.</p>
+ */
+public class SignMetadataPredicate extends AbstractRelyingPartyPredicate {
+
+ /** {@inheritDoc} */
+ public boolean test(@Nullable final ProfileRequestContext input) {
+
+ final RelyingPartyContext rpc = getRelyingPartyContext(input);
+ if (rpc != null) {
+ if (rpc.getProfileConfig() instanceof MetadataPublishingProfileConfiguration pub) {
+ return pub.isSignMetadata(input);
+ }
+ }
+
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/navigate/MetadataSignatureSigningConfigurationLookupFunction.java b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/navigate/MetadataSignatureSigningConfigurationLookupFunction.java
new file mode 100644
index 0000000..3fb251a
--- /dev/null
+++ b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/navigate/MetadataSignatureSigningConfigurationLookupFunction.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.shibboleth.sp.saml.saml2.profile.config.navigate;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.security.credential.Credential;
+import org.opensaml.xmlsec.SignatureSigningConfiguration;
+import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration;
+
+import net.shibboleth.profile.config.ProfileConfiguration;
+import net.shibboleth.profile.config.navigate.SignatureSigningConfigurationLookupFunction;
+import net.shibboleth.profile.context.RelyingPartyContext;
+import net.shibboleth.shared.annotation.constraint.Live;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.sp.saml.saml2.profile.config.MetadataPublishingProfileConfiguration;
+
+/**
+ *
+ */
+public class MetadataSignatureSigningConfigurationLookupFunction extends SignatureSigningConfigurationLookupFunction {
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable @Live public List<SignatureSigningConfiguration> apply(@Nullable final ProfileRequestContext input) {
+ final List<SignatureSigningConfiguration> configs = super.apply(input);
+
+ final RelyingPartyContext rpc = getRelyingPartyContextLookupStrategy().apply(input);
+ if (rpc != null) {
+ final ProfileConfiguration pc = rpc.getProfileConfig();
+ if (pc instanceof MetadataPublishingProfileConfiguration pub) {
+ final Credential cred = pub.getSigningCredential(input);
+ if (cred != null) {
+ final BasicSignatureSigningConfiguration special = new BasicSignatureSigningConfiguration();
+ special.setSigningCredentials(CollectionSupport.singletonList(cred));
+ if (configs != null) {
+ configs.add(special);
+ } else {
+ return CollectionSupport.singletonList(special);
+ }
+ }
+ }
+ }
+
+ return configs;
+ }
+
+}
\ No newline at end of file
diff --git a/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/navigate/package-info.java b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/navigate/package-info.java
new file mode 100644
index 0000000..fde58fc
--- /dev/null
+++ b/sp-saml-api/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/navigate/package-info.java
@@ -0,0 +1,18 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Navigation functions that access profile configuration settings.
+ */
+package net.shibboleth.sp.saml.saml2.profile.config.navigate;
\ No newline at end of file
diff --git a/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-beans.xml b/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-beans.xml
new file mode 100644
index 0000000..0050229
--- /dev/null
+++ b/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-beans.xml
@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:c="http://www.springframework.org/schema/c"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
+ default-init-method="initialize">
+
+ <util:constant id="shibboleth.sp.profileId"
+ static-field="net.shibboleth.sp.saml.saml2.profile.config.MetadataPublishingProfileConfiguration.PROFILE_ID" />
+
+ <bean id="shibboleth.sp.loggingId" class="java.lang.String" c:_0="%{sp.saml.service.logging.metadata:Metadata.SAML2}" />
+
+ <util:constant id="shibboleth.metrics.ProfileCounter"
+ static-field="net.shibboleth.sp.saml.saml2.profile.config.impl.MetadataPublishingProfileConfiguration.PROFILE_COUNTER" />
+
+ <!-- This is a convenience as it does what is needed for this flow also. -->
+ <bean id="ValidateSessionInitiatorRequest"
+ class="net.shibboleth.sp.profile.impl.ValidateSessionInitiatorRequest" scope="prototype"
+ p:flowId="metadata/saml2"
+ p:requireDiscoveryURL="false"
+ p:requireRelyingPartyId="false" />
+
+ <bean id="PopulateMetadataSignatureSigningParameters"
+ class="org.opensaml.saml.common.profile.impl.PopulateSignatureSigningParameters" scope="prototype"
+ p:configurationLookupStrategy-ref="MetadataSignatureSigningConfigurationLookup"
+ p:signatureSigningParametersResolver-ref="shibboleth.SignatureSigningParametersResolver"
+ p:noResultIsError="false">
+ <property name="activationCondition">
+ <bean class="net.shibboleth.sp.saml.saml2.profile.config.logic.SignMetadataPredicate" />
+ </property>
+ </bean>
+
+ <!-- Supplements usual signing config with a profile-directed signing key, if any. -->
+ <bean id="MetadataSignatureSigningConfigurationLookup"
+ class="net.shibboleth.sp.saml.saml2.profile.config.navigate.MetadataSignatureSigningConfigurationLookupFunction" />
+
+ <bean id="AddMetadata"
+ class="net.shibboleth.sp.saml.saml2.profile.impl.AddMetadata" scope="prototype"
+ p:velocityEngine-ref="shibboleth.VelocityEngine" />
+
+ <bean id="SignMetadata"
+ class="net.shibboleth.idp.profile.impl.WebFlowMessageHandlerAdaptor" scope="prototype"
+ c:executionDirection="OUTBOUND">
+ <property name="messageHandler">
+ <bean class="org.opensaml.saml.common.binding.security.impl.SAMLOutboundProtocolMessageSigningHandler" scope="prototype" />
+ </property>
+ <property name="errorEvent">
+ <util:constant static-field="org.opensaml.profile.action.EventIds.MESSAGE_PROC_ERROR" />
+ </property>
+ </bean>
+
+ <!-- Hardwired to a single encoder. -->
+
+ <bean id="EncodeMessage" class="net.shibboleth.sp.profile.impl.EncodeMessage" scope="prototype"
+ p:messageEncoderFactory-ref="metadataEncoderFactory" />
+
+ <bean id="metadataEncoderFactory" parent="shibboleth.Functions.Expression"
+ c:_0="#{getObject('metadataEncoder')}"
+ p:outputType="org.opensaml.messaging.encoder.MessageEncoder" />
+
+ <bean id="metadataEncoder"
+ class="net.shibboleth.sp.saml.saml2.messaging.impl.XMLObjectMessageEncoder" scope="prototype" init-method=""
+ p:contentType="application/samlmetadata+xml"
+ p:httpServletResponseSupplier-ref="shibboleth.RemotedHttpServletResponseSupplier" />
+
+</beans>
diff --git a/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-flow.xml b/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-flow.xml
new file mode 100644
index 0000000..3daf5ca
--- /dev/null
+++ b/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-flow.xml
@@ -0,0 +1,44 @@
+<flow xmlns="http://www.springframework.org/schema/webflow"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow.xsd"
+ parent="sp/application">
+
+ <action-state id="DoApplicationOperation">
+ <evaluate expression="ValidateSessionInitiatorRequest" />
+ <evaluate expression="PrepareInboundMessageContext" />
+ <evaluate expression="'proceed'" />
+ <transition on="proceed" to="CheckForRelyingParty" />
+ </action-state>
+
+ <decision-state id="CheckForRelyingParty">
+ <if test="opensamlProfileRequestContext.getSubcontext(T(net.shibboleth.profile.context.RelyingPartyContext))?.getRelyingPartyId() != null"
+ then="MetadataLookup" else="ContinueMetadataRequest" />
+ </decision-state>
+
+ <action-state id="MetadataLookup">
+ <evaluate expression="SAMLProtocolAndRole" />
+ <evaluate expression="SAMLMetadataLookup" />
+ <evaluate expression="InitializeRelyingPartyContextFromSAMLPeer" />
+ <evaluate expression="'proceed'" />
+
+ <transition on="proceed" to="ContinueMetadataRequest" />
+ </action-state>
+
+ <action-state id="ContinueMetadataRequest">
+ <evaluate expression="SelectRelyingPartyConfiguration" />
+ <evaluate expression="PostLookupPopulateAuditContext" />
+ <evaluate expression="SelectProfileConfiguration" />
+ <evaluate expression="PopulateMetadataSignatureSigningParameters" />
+ <evaluate expression="AddMetadata" />
+ <evaluate expression="SignMetadata" />
+ <evaluate expression="EncodeMessage" />
+ <evaluate expression="'proceed'" />
+
+ <transition on="proceed" to="EncodeAgentResponse" />
+ </action-state>
+
+
+ <!-- The file really exists in this directory, but it's referenced from extending flow-directories -->
+ <bean-import resource="classpath:/META-INF/net/shibboleth/idp/flows/sp/metadata/saml2/saml2-beans.xml" />
+
+</flow>
diff --git a/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/sp/service/agent/postconfig.xml b/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/sp/service/agent/postconfig.xml
index 1da5107..b31516f 100644
--- a/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/sp/service/agent/postconfig.xml
+++ b/sp-saml-conf-impl/src/main/resources/META-INF/net/shibboleth/sp/service/agent/postconfig.xml
@@ -34,10 +34,23 @@
<ref bean="SAML2.ECP" />
<ref bean="SAML2.Logout" />
<ref bean="SAML2.AttributeQuery" />
+ <ref bean="SAML2.Metadata" />
</list>
</property>
<property name="metadataDrivenDefaultProfileConfigurations">
<list>
+ <!-- TODO: replace once wiring is added -->
+ <ref bean="SAML2.SSO" />
+ <ref bean="SAML2.ECP" />
+ <ref bean="SAML2.Logout" />
+ <ref bean="SAML2.AttributeQuery" />
+ <ref bean="SAML2.Metadata" />
+ </list>
+ </property>
+
+ <property name="unverifiedProfileConfigurations">
+ <list>
+ <ref bean="SAML2.Metadata" />
</list>
</property>
</bean>
@@ -49,8 +62,16 @@
a suite of metadata-driven lookup strategies pre-injected.
-->
+ <bean id="SAML2.Metadata" lazy-init="true"
+ class="net.shibboleth.sp.saml.saml2.profile.config.impl.MetadataPublishingProfileConfiguration"
+ p:templatePath="%{sp.saml.metadata.templatePath:}"
+ p:useVelocity="%{sp.saml.metadata.useVelocity:false}"
+ p:signMetadata="%{sp.saml.metadata.sign:false}"
+ p:lifetime="%{sp.saml.metadata.lifetime:PT0S}"
+ p:cacheDuration="%{sp.saml.metadata.cacheDuration:PT0S}" />
+
<bean id="SAML2.SSO" lazy-init="true"
- class="net.shibboleth.sp.saml.saml2.profile.config.impl.BrowserSSOProfileConfiguration"
+ class="net.shibboleth.sp.saml.saml2.profile.config.impl.BrowserSSOProfileConfiguration"
p:securityConfiguration-ref="%{sp.saml.security.config:shibboleth.sp.DefaultXMLSecurityConfiguration}"
p:encryptionOptionalPredicate="%{sp.saml.encryption.optional:true}"
p:maximumTimeSinceAuthn="%{sp.saml.maxTimeSinceAuthn:0}"
@@ -82,13 +103,13 @@
p:providerName="%{sp.saml.providerName:}" />
<bean id="SAML2.Logout" lazy-init="true"
- class="net.shibboleth.sp.saml.saml2.profile.config.impl.SingleLogoutProfileConfiguration"
+ class="net.shibboleth.sp.saml.saml2.profile.config.impl.SingleLogoutProfileConfiguration"
p:securityConfiguration-ref="%{sp.saml.security.config:shibboleth.sp.DefaultXMLSecurityConfiguration}"
p:encryptionOptionalPredicate="%{sp.saml.encryption.optional:true}"
p:asynchronousPredicate="%{sp.saml.logout.asynchronous:true}" />
<bean id="SAML2.AttributeQuery" lazy-init="true"
- class="net.shibboleth.sp.saml.saml2.profile.config.impl.AttributeQueryProfileConfiguration"
+ class="net.shibboleth.sp.saml.saml2.profile.config.impl.AttributeQueryProfileConfiguration"
p:securityConfiguration-ref="%{sp.saml.security.config:shibboleth.sp.DefaultXMLSecurityConfiguration}" />
diff --git a/sp-saml-conf-impl/src/test/resources/net/shibboleth/idp/module/conf/sp/saml.properties b/sp-saml-conf-impl/src/test/resources/net/shibboleth/idp/module/conf/sp/saml.properties
new file mode 100644
index 0000000..8250c04
--- /dev/null
+++ b/sp-saml-conf-impl/src/test/resources/net/shibboleth/idp/module/conf/sp/saml.properties
@@ -0,0 +1,69 @@
+# SAML-specific SP settings
+
+# Settings for default SAML public/private signing and encryption key(s)
+# These can be replaced, supplemented, defined per-Agent, etc., see docs.
+sp.saml.signing.key = %{idp.home}/credentials/sp/saml-default-signing.key
+sp.saml.signing.cert = %{idp.home}/credentials/sp/saml-default-signing.crt
+sp.saml.encryption.key = %{idp.home}/credentials/sp/saml-default-encryption.key
+sp.saml.encryption.cert = %{idp.home}/credentials/sp/saml-default-encryption.crt
+
+# Global profile defaults
+#sp.saml.encryption.optional = true
+# Turn off to allow SubjectConfirmationData/@Recipient to be absent
+#sp.saml.requireRecipient = true
+# Turn off to allow SubjectConfirmationData/@NotOnOrAfter to be absent
+#sp.saml.requireNotOnOrAfter = true
+# Turn off to disallow unsolicited SSO responses
+#sp.saml.allowUnsolicited = true
+# Turn off to disable address check during assertion validation
+#sp.saml.checkAddress = true
+# Turn off to disable message correlation checking
+#sp.saml.checkInResponseTo = true
+# Set to non-zero duration to limit time since authentication
+#sp.saml.maxTimeSinceAuthn = 0
+# Turn off to disable Asynchronous logout extension
+#sp.saml.logout.asynchronous = true
+
+# Default security configuration for SAML
+#sp.saml.security.config = shibboleth.sp.DefaultXMLSecurityConfiguration
+
+# To downgrade to SHA-1, set to shibboleth.sp.SigningConfiguration.SHA1
+#sp.saml.signing.config = shibboleth.sp.SigningConfiguration.SHA256
+
+# To upgrade to AES-GCM, set to shibboleth.sp.EncryptionConfiguration.GCM
+#sp.saml.encryption.config = shibboleth.sp.EncryptionConfiguration.CBC
+
+# Configures trust evaluation of keys used by services at runtime
+#sp.saml.trust.signatures = shibboleth.sp.ExplicitKeySignatureTrustEngine
+# Other options:
+# shibboleth.sp.ChainingSignatureTrustEngine, shibboleth.sp.PKIXSignatureTrustEngine
+#sp.saml.trust.certificates = shibboleth.sp.ExplicitKeyX509TrustEngine
+# Other options:
+# shibboleth.sp.ChainingX509TrustEngine, shibboleth.sp.PKIXX509TrustEngine
+
+# Set true to accept any decided attributes without a filtering rule
+sp.saml.acceptUnfilteredAttributes = false
+
+# "Standard" attribute extraction from SAML response/assertion
+sp.saml.extractStandardAttributes = false
+# Legacy names defaulted into agents
+#sp.saml.issuerAttributeId = Shib-Identity-Provider
+#sp.saml.authnInstantAttributeId = Shib-Authentication-Instant
+#sp.saml.authnContextClassRefAttributeId = Shib-AuthnContext-Class
+#sp.saml.authnContextDeclRefAttributeId = Shib-AuthnContext-Decl
+#sp.saml.sessionIndexAttributeId = Shib-Session-Index
+# Additonal extraction points available
+#sp.saml.consentAttributeId =
+#sp.saml.authorityAttributeId =
+#sp.saml.notBeforeAttributeId =
+#sp.saml.notOnOrAfterAttributeId =
+#sp.saml.sessionNotOnOrAfterAttributeId =
+#sp.saml.addressAttributeId =
+#sp.saml.dnsNameAttributeId =
+
+# Configures use of the Attribute Resolver for enrichment
+#sp.saml.resolveAttributes = false
+
+# Each protocol plugin will contain an order priority controlling
+# relative order of use when handling requests, lower is "earlier".
+#sp.saml.relativeOrder = 1
diff --git a/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/messaging/impl/XMLObjectMessageEncoder.java b/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/messaging/impl/XMLObjectMessageEncoder.java
new file mode 100644
index 0000000..0b499b1
--- /dev/null
+++ b/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/messaging/impl/XMLObjectMessageEncoder.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.shibboleth.sp.saml.saml2.messaging.impl;
+
+import java.io.IOException;
+
+import javax.annotation.Nonnull;
+
+import org.apache.hc.core5.http.HttpStatus;
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.messaging.encoder.MessageEncoder;
+import org.opensaml.messaging.encoder.MessageEncodingException;
+import org.opensaml.messaging.encoder.servlet.BaseHttpServletResponseXMLMessageEncoder;
+import org.w3c.dom.Element;
+
+import jakarta.servlet.http.HttpServletResponse;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.StringSupport;
+import net.shibboleth.shared.servlet.HttpServletSupport;
+import net.shibboleth.shared.xml.SerializeSupport;
+
+/**
+ * Simple {@link MessageEncoder} for sending an {@link XMLObject} message directly into
+ * servlet output stream.
+ */
+public class XMLObjectMessageEncoder extends BaseHttpServletResponseXMLMessageEncoder {
+
+ /** Content type of output. */
+ @Nonnull @NotEmpty private String contentType;
+
+ /** Constructor. */
+ public XMLObjectMessageEncoder() {
+ contentType ="text/xml";
+ }
+
+ /**
+ * Sets the Content-Type to output.
+ *
+ * @param type content type
+ */
+ public void setContentType(@Nonnull @NotEmpty final String type) {
+ contentType = Constraint.isNotNull(StringSupport.trimOrNull(type), "Content type cannot be null or empty");
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected void doEncode() throws MessageEncodingException {
+
+ final Object message = getMessageContext().getMessage();
+ if (message instanceof XMLObject xml) {
+ final Element envelopeElem = marshallMessage(xml);
+ final HttpServletResponse response = prepareHttpServletResponse();
+ try {
+ SerializeSupport.writeNode(envelopeElem, response.getOutputStream());
+ } catch (final IOException e) {
+ throw new MessageEncodingException("Problem writing XML to servlet output stream", e);
+ }
+ } else {
+ throw new MessageEncodingException("Message was not an XMLObject");
+ }
+ }
+
+ /**
+ * <p>
+ * This implementation performs the following actions on the context's {@link HttpServletResponse}:
+ * </p>
+ * <ol>
+ * <li>Adds the HTTP header: "Cache-control: no-cache, no-store"</li>
+ * <li>Adds the HTTP header: "Pragma: no-cache"</li>
+ * <li>Sets the character encoding to: "UTF-8"</li>
+ * <li>Sets the content type as configured</li>
+ * that returns non-null.</li>
+ * </ol>
+ *
+ * @return the prepared response
+ *
+ * @throws MessageEncodingException thrown if there is a problem preprocessing the transport
+ */
+ @Nonnull protected HttpServletResponse prepareHttpServletResponse() throws MessageEncodingException {
+
+ final HttpServletResponse response = getHttpServletResponse();
+ if (response == null) {
+ throw new MessageEncodingException("HttpServletResponse was null");
+ }
+
+ HttpServletSupport.addNoCacheHeaders(response);
+ HttpServletSupport.setUTF8Encoding(response);
+ HttpServletSupport.setContentType(response, contentType);
+
+ response.setStatus(HttpStatus.SC_OK);
+
+ return response;
+ }
+
+}
diff --git a/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/impl/MetadataPublishingProfileConfiguration.java b/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/impl/MetadataPublishingProfileConfiguration.java
new file mode 100644
index 0000000..2c9b1ba
--- /dev/null
+++ b/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/profile/config/impl/MetadataPublishingProfileConfiguration.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.shibboleth.sp.saml.saml2.profile.config.impl;
+
+import java.time.Duration;
+import java.util.function.Function;
+import java.util.function.Predicate;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.security.credential.Credential;
+
+import net.shibboleth.shared.annotation.constraint.NonNegative;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.logic.FunctionSupport;
+import net.shibboleth.shared.logic.PredicateSupport;
+import net.shibboleth.shared.primitive.StringSupport;
+import net.shibboleth.sp.profile.config.AbstractConditionalProfileConfiguration;
+
+/** Configuration support for publishing SAML 2.0 Metadata. */
+public class MetadataPublishingProfileConfiguration extends AbstractConditionalProfileConfiguration
+ implements net.shibboleth.sp.saml.saml2.profile.config.MetadataPublishingProfileConfiguration {
+
+ /** Name of profile counter. */
+ @Nonnull @NotEmpty public static final String PROFILE_COUNTER = "net.shibboleth.sp.profiles.saml2.metadata";
+
+ /** Lookup strategy for metadata template path. */
+ @Nonnull private Function<ProfileRequestContext,String> templatePathLookupStrategy;
+
+ /** Predicate used to determine whether to use Velocity. */
+ @Nonnull private Predicate<ProfileRequestContext> useVelocityPredicate;
+
+ /** Predicate used to determine whether to sign metadata. */
+ @Nonnull private Predicate<ProfileRequestContext> signMetadataPredicate;
+
+ /** Lookup strategy for signing credential. */
+ @Nonnull private Function<ProfileRequestContext,Credential> signingCredentialLookupStrategy;
+
+ /** Lookup strategy for lifetime to apply via validUntil. */
+ @Nonnull private Function<ProfileRequestContext,Duration> lifetimeLookupStrategy;
+
+ /** Lookup strategy for cacheDuration. */
+ @Nonnull private Function<ProfileRequestContext,Duration> cacheDurationLookupStrategy;
+
+ /** Constructor. */
+ public MetadataPublishingProfileConfiguration() {
+ this(PROFILE_ID);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param profileId unique ID for this profile
+ */
+ protected MetadataPublishingProfileConfiguration(@Nonnull @NotEmpty final String profileId) {
+ super(profileId);
+
+ templatePathLookupStrategy = FunctionSupport.constant(null);
+ useVelocityPredicate = PredicateSupport.alwaysFalse();
+ signMetadataPredicate = PredicateSupport.alwaysFalse();
+ signingCredentialLookupStrategy = FunctionSupport.constant(null);
+ lifetimeLookupStrategy = FunctionSupport.constant(null);
+ cacheDurationLookupStrategy = FunctionSupport.constant(null);
+ }
+
+ /** {@inheritDoc} */
+ @Nullable @NotEmpty public String getTemplatePath(@Nullable final ProfileRequestContext profileRequestContext) {
+ return templatePathLookupStrategy.apply(profileRequestContext);
+ }
+
+ /**
+ * Sets the path to a template XML file to source for the metadata.
+ *
+ * @param path template path
+ */
+ public void setTemplatePath(@Nullable @NotEmpty final String path) {
+ templatePathLookupStrategy = FunctionSupport.constant(StringSupport.trimOrNull(path));
+ }
+
+ /**
+ * Sets the lookup strategy for the path to a template XML file to source for the metadata.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setTemplatePathLookupStrategy(@Nonnull final Function<ProfileRequestContext,String> strategy) {
+ templatePathLookupStrategy = Constraint.isNotNull(strategy, "Template path lookup strategy cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ public boolean isUseVelocity(@Nullable final ProfileRequestContext profileRequestContext) {
+ return useVelocityPredicate.test(profileRequestContext);
+ }
+
+ /**
+ * Sets whether the template returned by getTemplatePath(ProfileRequestContext) is evaluated by Velocity
+ * or returned directly.
+ *
+ * @param flag flag to set
+ */
+ public void setUseVelocity(final boolean flag) {
+ useVelocityPredicate = flag ? PredicateSupport.alwaysTrue() : PredicateSupport.alwaysFalse();
+ }
+
+ /**
+ * Sets a condition to determine whether the template returned by getTemplatePath(ProfileRequestContext)
+ * is evaluated by Velocity or returned directly.
+ *
+ * @param condition condition to set
+ */
+ public void setUseVelocityPredicate(@Nonnull final Predicate<ProfileRequestContext> condition) {
+ useVelocityPredicate = Constraint.isNotNull(condition, "Velocity usage condition cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ public boolean isSignMetadata(@Nullable final ProfileRequestContext profileRequestContext) {
+ return signMetadataPredicate.test(profileRequestContext);
+ }
+
+ /**
+ * Sets whether to sign the metadata being published dynamically.
+ *
+ * @param flag flag to set
+ */
+ public void setSignMetadata(final boolean flag) {
+ signMetadataPredicate = flag ? PredicateSupport.alwaysTrue() : PredicateSupport.alwaysFalse();
+ }
+
+ /**
+ * Sets a condition to determine whether to sign the metadata being published dynamically.
+ *
+ * @param condition condition to set
+ */
+ public void setSignMetadataPredicate(@Nonnull final Predicate<ProfileRequestContext> condition) {
+ signMetadataPredicate = Constraint.isNotNull(condition, "Metadata signing condition cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ @Nullable public Credential getSigningCredential(@Nullable final ProfileRequestContext profileRequestContext) {
+ return signingCredentialLookupStrategy.apply(profileRequestContext);
+ }
+
+ /**
+ * Sets an optional Credential to use to sign the metadata if isSignMetadata(ProfileRequestContext) is true.
+ *
+ * @param credential credential to set
+ */
+ public void setSigningCredential(@Nullable final Credential credential) {
+ signingCredentialLookupStrategy = FunctionSupport.constant(credential);
+ }
+
+ /**
+ * Sets a lookup strategy for an optional Credential to use to sign the metadata if
+ * isSignMetadata(ProfileRequestContext) is true.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setSigningCredentialLookupStrategy(@Nonnull final Function<ProfileRequestContext,Credential> strategy) {
+ signingCredentialLookupStrategy =
+ Constraint.isNotNull(strategy, "Signing credential lookup strategy cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ @Nullable @NonNegative public Duration getLifetime(@Nullable final ProfileRequestContext profileRequestContext) {
+ return lifetimeLookupStrategy.apply(profileRequestContext);
+ }
+
+ /**
+ * Sets the optional lifetime from which to compute and set the root element's <code>validUntil</code> attribute.
+ *
+ * <p>Passing zero is equivalent to null and will not alter the source value.</p>
+ *
+ * @param lifetime metadata lifetime
+ */
+ public void setLifetime(@Nullable @NonNegative final Duration lifetime) {
+ if (lifetime != null) {
+ Constraint.isFalse(lifetime.isNegative(), "Lifetime cannot be negative");
+ }
+
+ lifetimeLookupStrategy = FunctionSupport.constant(lifetime);
+ }
+
+ /**
+ * Sets the lookup strategy for the optional lifetime from which to compute and set the root element's
+ * <code>validUntil</code> attribute.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setLifetimeLookupStrategy(@Nonnull final Function<ProfileRequestContext,Duration> strategy) {
+ lifetimeLookupStrategy = Constraint.isNotNull(strategy, "Lifetime lookup strategy cannot be null");
+ }
+
+ /** {@inheritDoc} */
+ @Nullable @NonNegative public Duration getCacheDuration(@Nullable final ProfileRequestContext profileRequestContext) {
+ return cacheDurationLookupStrategy.apply(profileRequestContext);
+ }
+
+ /**
+ * Sets the optional value to set in the root element's <code>cacheDuration</code> attribute.
+ *
+ * <p>Passing zero is equivalent to null and will not alter the source value.</p>
+ *
+ * @param cacheDuration metadata cache duration
+ */
+ public void setCacheDuration(@Nullable @NonNegative final Duration cacheDuration) {
+ if (cacheDuration != null) {
+ Constraint.isFalse(cacheDuration.isNegative(), "Cache duration cannot be negative");
+ }
+
+ cacheDurationLookupStrategy = FunctionSupport.constant(cacheDuration);
+ }
+
+ /**
+ * Sets the lookup strategy for the optional value to set in the root element's
+ * <code>cacheDuration</code> attribute.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setCacheDurationLookupStrategy(@Nonnull final Function<ProfileRequestContext,Duration> strategy) {
+ cacheDurationLookupStrategy = Constraint.isNotNull(strategy, "Cache duration lookup strategy cannot be null");
+ }
+
+}
\ No newline at end of file
diff --git a/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/profile/impl/AddMetadata.java b/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/profile/impl/AddMetadata.java
new file mode 100644
index 0000000..cba4d34
--- /dev/null
+++ b/sp-saml-impl/src/main/java/net/shibboleth/sp/saml/saml2/profile/impl/AddMetadata.java
@@ -0,0 +1,403 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.shibboleth.sp.saml.saml2.profile.impl;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Map;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.idp.profile.IdPEventIds;
+import net.shibboleth.profile.context.RelyingPartyContext;
+import net.shibboleth.profile.context.navigate.IssuerLookupFunction;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.NonnullBeforeExec;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.sp.Agent;
+import net.shibboleth.sp.Application;
+import net.shibboleth.sp.context.AgentRequestContext;
+import net.shibboleth.sp.ddf.DDF;
+import net.shibboleth.sp.profile.AbstractApplicationAction;
+import net.shibboleth.sp.saml.saml2.SAML2ProtocolSupportService;
+import net.shibboleth.sp.saml.saml2.profile.config.MetadataPublishingProfileConfiguration;
+
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.exception.VelocityException;
+import org.opensaml.core.criterion.EntityIdCriterion;
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.core.xml.io.UnmarshallingException;
+import org.opensaml.core.xml.util.XMLObjectSupport;
+import org.opensaml.messaging.context.MessageContext;
+import org.opensaml.profile.action.ActionSupport;
+import org.opensaml.profile.action.EventIds;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.saml.metadata.resolver.MetadataResolver;
+import org.opensaml.saml.saml2.metadata.EntityDescriptor;
+import org.slf4j.Logger;
+
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.resolver.CriteriaSet;
+import net.shibboleth.shared.resolver.ResolverException;
+import net.shibboleth.shared.service.ServiceException;
+import net.shibboleth.shared.service.ServiceableComponent;
+import net.shibboleth.shared.velocity.Template;
+import net.shibboleth.shared.xml.ParserPool;
+import net.shibboleth.shared.xml.XMLParserException;
+
+/**
+ * Action that adds an outbound {@link MessageContext} and stores a SAML Metadata document as the
+ * outbound message.
+ *
+ * <p>Metadata is produced from different possible sources based on profile configuration,
+ * currently either an evaluated Velocity template on a configurable path, or sourced from
+ * the hub's {@link MetadataResolver} service.</p>
+ *
+ * @event {@link EventIds#PROCEED_EVENT_ID}
+ * @event {@link EventIds#INVALID_MESSAGE}
+ * @event {@link EventIds#INVALID_MSG_CTX}
+ * @event {@link EventIds#INVALID_PROFILE_CTX}
+ * @event {@link EventIds#IO_ERROR}
+ * @event {@link EventIds#MESSAGE_PROC_ERROR}
+ * @event {@link EventIds#UNABLE_TO_DECODE}
+ * @event {@link IdPEventIds#INVALID_PROFILE_CONFIG}
+ *
+ * @post ProfileRequestContext.getOutboundMessageContext().getMessage() instanceof EntityDescriptor
+ */
+public class AddMetadata extends AbstractApplicationAction {
+
+
+ /** The Velocity context variable name for the Agent ID. */
+ @Nonnull @NotEmpty public static final String CONTEXT_KEY_AGENT_ID = "agentID";
+
+ /** The Velocity context variable name for the Application ID. */
+ @Nonnull @NotEmpty public static final String CONTEXT_KEY_APPLICATION_ID = "applicationID";
+
+ /** The Velocity context variable name for the issuer about whom the metadata is. */
+ @Nonnull @NotEmpty public static final String CONTEXT_KEY_ISSUER = "issuer";
+
+ /** The Velocity context variable name for the entity ID requesting the metadata. */
+ @Nonnull @NotEmpty public static final String CONTEXT_KEY_ENTITY_ID = "entityID";
+
+ /** The Velocity context variable name for the {@link ProfileRequestContext}. */
+ @Nonnull @NotEmpty public static final String CONTEXT_KEY_PRC = "profileRequestContext";
+
+ /** Class logger. */
+ @Nonnull private Logger log = LoggerFactory.getLogger(AddMetadata.class);
+
+ /** Parser to use. */
+ @NonnullAfterInit private ParserPool parserPool;
+
+ /** Velocity engine. */
+ @NonnullAfterInit private VelocityEngine velocityEngine;
+
+ /** Strategy used to obtain the request issuer value. */
+ @Nullable private Function<ProfileRequestContext,String> issuerLookupStrategy;
+
+ /** Map of agent binding tokens to SAML binding constants. */
+ @Nonnull private Map<String,String> inboundBindingMap;
+
+ /** Applicable profile configuration. */
+ @NonnullBeforeExec private MetadataPublishingProfileConfiguration profileConfiguration;
+
+ /** Input message from agent. */
+ @NonnullBeforeExec private DDF input;
+
+ /** EntityID to populate into Issuer element. */
+ @Nullable private String issuerId;
+
+ /** Constructor. */
+ public AddMetadata() {
+ issuerLookupStrategy = new IssuerLookupFunction();
+
+ inboundBindingMap = CollectionSupport.emptyMap();
+ }
+
+ /**
+ * Sets the {@link ParserPool} to use.
+ *
+ * @param pool parser pool
+ */
+ public void setParserPool(@Nonnull final ParserPool pool) {
+ checkSetterPreconditions();
+
+ parserPool = Constraint.isNotNull(pool, "ParserPool cannot be null");
+ }
+
+ /**
+ * Sets the {@link VelocityEngine} to use.
+ *
+ * @param engine Velocity engine
+ */
+ public void setVelocityEngine(@Nonnull final VelocityEngine engine) {
+ checkSetterPreconditions();
+
+ velocityEngine = Constraint.isNotNull(engine, "VelocityEngine cannot be null");
+ }
+
+ /**
+ * Set the strategy used to locate the issuer value to use.
+ *
+ * @param strategy lookup strategy
+ */
+ public void setIssuerLookupStrategy(@Nullable final Function<ProfileRequestContext,String> strategy) {
+ checkSetterPreconditions();
+ issuerLookupStrategy = strategy;
+ }
+
+ /**
+ * Set mapping of legacy binding tokens to SAML binding constants.
+ *
+ * <p>This is a legacy compatibility feature allowing binding-specific response endpoints to be supported.
+ * Agents will supply a structure that maps endpoints to binding tokens (e.g., POST, Artifact) and this
+ * mapping determines the binding constants to use in requests. This is a simplification to avoid contaminating
+ * agents with SAML constants.</p>
+ *
+ * @param map binding map
+ */
+ public void setInboundBindingMap(@Nullable final Map<String,String> map) {
+ checkSetterPreconditions();
+ if (map != null) {
+ inboundBindingMap = CollectionSupport.copyToMap(map);
+ } else {
+ inboundBindingMap = CollectionSupport.emptyMap();
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+
+ if (parserPool == null) {
+ throw new ComponentInitializationException("ParserPool cannot be null");
+ } else if (velocityEngine == null) {
+ throw new ComponentInitializationException("VelocityEngine cannot be null");
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected boolean doPreExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
+
+ if (!super.doPreExecute(profileRequestContext)) {
+ return false;
+ }
+
+ input = ensureAgentRequestContext().getInput();
+ if (input == null) {
+ log.error("{} No input message", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
+ return false;
+ }
+
+ final RelyingPartyContext rpCtx = profileRequestContext.getSubcontext(RelyingPartyContext.class);
+ if (rpCtx != null && rpCtx.getProfileConfig() instanceof MetadataPublishingProfileConfiguration pub) {
+ profileConfiguration = pub;
+ }
+
+ if (profileConfiguration == null) {
+ log.error("{} MetadataPublishingProfileConfiguration not found", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, IdPEventIds.INVALID_PROFILE_CONFIG);
+ return false;
+ }
+
+ if (issuerLookupStrategy != null) {
+ issuerId = issuerLookupStrategy.apply(profileRequestContext);
+ }
+
+ return true;
+ }
+
+// Checkstyle: MethodLength OFF
+ /** {@inheritDoc} */
+ @Override
+ protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
+
+ final EntityDescriptor entityDescriptor;
+
+ final String templatePath = profileConfiguration.getTemplatePath(profileRequestContext);
+ if (templatePath != null) {
+ log.debug("{} Evaluating template path to metadata: {}", getLogPrefix(), templatePath);
+ entityDescriptor = doTemplate(profileRequestContext,
+ Template.fromTemplate(velocityEngine, templatePath, StandardCharsets.UTF_8));
+ } else {
+ entityDescriptor = doResolver(profileRequestContext);
+ }
+
+ if (entityDescriptor != null) {
+ adjustTimestamps(profileRequestContext, entityDescriptor);
+ profileRequestContext.ensureOutboundMessageContext().setMessage(entityDescriptor);
+ log.info("{} Populated Metadata for {}", getLogPrefix(), entityDescriptor.getEntityID());
+ } else {
+ log.error("{} No metadata produced for request", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, EventIds.MESSAGE_PROC_ERROR);
+ }
+ }
+
+ /**
+ * Produce metadata by parsing a template, with or without Velocity.
+ *
+ * @param profileRequestContext profile request context
+ * @param template the path to the metadata
+ *
+ * @return parsed metadata or null if an error occurs
+ */
+ @Nullable private EntityDescriptor doTemplate(@Nonnull final ProfileRequestContext profileRequestContext,
+ @Nonnull final Template template) {
+
+ final VelocityContext ctx = getVelocityContext(profileRequestContext);
+ String finalPath = null;
+ try {
+ finalPath = template.merge(ctx);
+ log.debug("{} Loading metadata from {}", getLogPrefix(), finalPath);
+ final String metadataContent;
+ final String metadataTemplateContent = Files.readString(Path.of(finalPath));
+ if (profileConfiguration.isUseVelocity(profileRequestContext)) {
+ log.debug("{} Evaluating metadata content from {} with Velocity", getLogPrefix(), finalPath);
+ metadataContent = Template.fromTemplate(velocityEngine, metadataTemplateContent,
+ StandardCharsets.UTF_8).merge(ctx);
+ } else {
+ log.debug("{} Parsing metadata content from {} directly", getLogPrefix(), finalPath);
+ metadataContent = metadataTemplateContent;
+ }
+
+ try (final StringReader reader = new StringReader(metadataContent)) {
+ final XMLObject ret = XMLObjectSupport.unmarshallFromReader(parserPool, reader);
+ if (ret instanceof EntityDescriptor entity) {
+ return entity;
+ }
+
+ log.error("{} Metadata root element was invalid: {}", ret.getElementQName());
+ return null;
+ }
+ } catch (final VelocityException e) {
+ log.error("{} Velocity error evaluating metadata template", getLogPrefix(), e);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.MESSAGE_PROC_ERROR);
+ } catch (final IOException e) {
+ log.error("{} Error loading metadata template from path: {}", getLogPrefix(), finalPath, e);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.IO_ERROR);
+ } catch (final XMLParserException|UnmarshallingException e) {
+ log.error("{} Error parsing metadata from {}", getLogPrefix(), finalPath, e);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.UNABLE_TO_DECODE);
+ }
+
+ return null;
+ }
+
+ /**
+ * Creates and populates a {@link VelocityContext} for template evaluation.
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return context
+ */
+ @Nonnull private VelocityContext getVelocityContext(@Nonnull final ProfileRequestContext profileRequestContext) {
+ final VelocityContext ctx = new VelocityContext();
+
+ ctx.put(CONTEXT_KEY_PRC, profileRequestContext);
+
+ final AgentRequestContext arc = ensureAgentRequestContext();
+ final Agent agent = arc.getAgent();
+ final Application app = arc.getApplication();
+
+ if (agent != null) {
+ ctx.put(CONTEXT_KEY_AGENT_ID, agent.getId());
+ }
+ if (app != null) {
+ ctx.put(CONTEXT_KEY_APPLICATION_ID, app.getApplicationId());
+ }
+
+ if (issuerId != null) {
+ ctx.put(CONTEXT_KEY_ISSUER, issuerId);
+ }
+
+ final RelyingPartyContext relyingPartyCtx = profileRequestContext.getSubcontext(RelyingPartyContext.class);
+ if (relyingPartyCtx != null) {
+ ctx.put(CONTEXT_KEY_ENTITY_ID, relyingPartyCtx.getRelyingPartyId());
+ }
+
+ return ctx;
+ }
+
+ /**
+ * Queries the system's {@link MetadataResolver} for metadata about the issuer.
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return queries metadata or null if an error occurs
+ */
+ @Nullable private EntityDescriptor doResolver(@Nonnull final ProfileRequestContext profileRequestContext) {
+
+ if (issuerId == null) {
+ log.warn("{} No issuer established from comfiguration to query metadata for", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, IdPEventIds.INVALID_PROFILE_CONFIG);
+ return null;
+ }
+
+ final AgentRequestContext arc = getAgentRequestContext();
+ if (arc != null) {
+ final Application application = arc.getApplication();
+ if (application != null) {
+ final SAML2ProtocolSupportService supportService =
+ application.getProtocolSupportService(SAML2ProtocolSupportService.PROTOCOL_ID,
+ SAML2ProtocolSupportService.class);
+ if (supportService != null) {
+ try (final ServiceableComponent<MetadataResolver> component =
+ supportService.getMetadataResolver().getServiceableComponent()) {
+ assert issuerId != null;
+ final CriteriaSet criteria = new CriteriaSet(new EntityIdCriterion(issuerId));
+ return component.getComponent().resolveSingle(criteria);
+ } catch (final ServiceException|ResolverException e) {
+ log.error("{} Error resolving metadata from service for {}", getLogPrefix(), issuerId, e);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.MESSAGE_PROC_ERROR);
+ return null;
+ }
+ }
+ }
+ }
+
+ log.error("{} Unable to access MetadataResolver", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, EventIds.MESSAGE_PROC_ERROR);
+ return null;
+ }
+
+ private void adjustTimestamps(@Nonnull final ProfileRequestContext profileRequestContext,
+ @Nonnull final EntityDescriptor entity) {
+
+ final Duration lifetime = profileConfiguration.getLifetime(profileRequestContext);
+ final Duration cacheDuration = profileConfiguration.getCacheDuration(profileRequestContext);
+
+ if (lifetime != null && !lifetime.isZero()) {
+ entity.setValidUntil(Instant.now().plus(lifetime));
+ }
+
+ if (cacheDuration != null && !cacheDuration.isZero()) {
+ entity.setCacheDuration(cacheDuration);
+ }
+ }
+
+}
\ No newline at end of file
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list