[java-idp-plugin-vci] branch main updated: Client attestation claims validated with OP claims validator chains. Attestation login flow bug fixes. Optional list of accepted wallets, tests
Codeberg
noreply at shibboleth.net
Tue Nov 17 09:10:48 UTC 2026
This is an automated email from the git hooks/post-receive script.
codeberg pushed a commit to branch main
in repository java-idp-plugin-vci.
View the commit online:
https://codeberg.org/Shibboleth/java-idp-plugin-vci/commit/dceac2e4807d23e4e14f412dddf014eb16507155
The following commit(s) were added to refs/heads/main by this push:
new dceac2e Client attestation claims validated with OP claims validator chains. Attestation login flow bug fixes. Optional list of accepted wallets, tests
dceac2e is described below
commit dceac2e4807d23e4e14f412dddf014eb16507155
Author: Janne Lauros <janne.lauros at csc.fi>
AuthorDate: Tue Nov 17 11:09:55 2026 +0200
Client attestation claims validated with OP claims validator chains. Attestation login flow bug fixes. Optional list of accepted wallets, tests
---
README.md | 42 ++--
.../conf/authn/oauth2client-authn-config.xml | 17 --
.../ClientAttestationClaimsAuditExtractor.java | 86 +++++++
.../impl/ClientAttestationCredentialValidator.java | 252 +++++++++-----------
.../impl/ClientAttestationPresentPredicate.java | 7 +-
...ClientAttestationTypeHeaderAuditExtractor.java} | 32 ++-
.../impl/ValidateClientAuthenticationType.java | 121 +++++++---
.../authn/impl/WalletCredentialValidator.java | 51 ++--
.../ClientInstanceKeyThumbprintLookupFunction.java | 42 ++--
.../META-INF/net.shibboleth.idp/postconfig.xml | 94 +++++++-
.../OpenIDVCIClient/OpenIDVCIClient-beans.xml | 75 +++++-
.../authn/OpenIDVCIClient/OpenIDVCIClient-flow.xml | 34 ++-
.../plugin/openidvci/conf/openid-vci.properties | 8 +-
.../impl/ClientAttestationAuditExtractorTest.java | 102 ++++++++
.../ClientAttestationCredentialValidatorTest.java | 258 ++++++++++++++++++++-
.../ClientAttestationPresentPredicateTest.java | 67 ++++++
.../impl/ValidateClientAuthenticationTypeTest.java | 145 ++++++++++++
.../authn/impl/WalletCredentialValidatorTest.java | 98 ++++++++
...entInstanceKeyThumbprintLookupFunctionTest.java | 55 +++--
19 files changed, 1267 insertions(+), 319 deletions(-)
diff --git a/README.md b/README.md
index 4267ae9..106bd2d 100644
--- a/README.md
+++ b/README.md
@@ -3052,8 +3052,7 @@ SD-JWT VC or as ISO mdoc, see
This step has one of each.
This setup does not build on Steps 2–4. Start again from Step 1 and keep the general parts:
-installation, [Metadata endpoints](#metadata-endpoints),
-[Wallet authentication](#wallet-authentication) with the client `offer-caller`, the attribute
+installation, [Metadata endpoints](#metadata-endpoints), the client `offer-caller`, the attribute
definition and the [Status List](#status-list). Do not include the credential configurations, the Paradym client, or the pre-authorized code flow
wallet client, `offer-caller/wallet`. That client authenticates with `none`, whereas the wallets in this
setup authenticate with a Wallet Attestation. The diffs below show the changes to the Step 1 files.
@@ -3571,23 +3570,22 @@ In *conf/global.xml*:
A CRL applies only to the trust anchor that issued it, so the conformance suite’s attester CA
does not need one. If CRLs are configured but none can be read, the plugin rejects attestations.
-Wallet Attestation is a client authentication method, so it is added to the login flow of
-clients in *conf/authn/oauth2client-authn-config.xml*. It must come before the public-client validator from
-[Step 1](#wallet-authentication). Otherwise, an attested request matches the public-client validator
-and is authenticated without the attestation being checked:
+**openidvci.ClientAttestationAttesters** in *conf/global.xml* is optional list to tighten which wallets are accepted
+under the trust anchor when using Wallet Attestation. The key of an entry is the client ID of the wallet.
+The values are the subject names in the wallet provider certificates that sign the Wallet Attestations of that wallet.
+After defining this list wallet has to be on it to perform Wallet Attestation successfully.
```xml
-<util:list id="shibboleth.authn.OAuth2Client.Validators">
- <ref bean="shibboleth.OIDCClientInfoValidator" />
- <ref bean="shibboleth.JWTValidator" />
- <ref bean="openidvci.ClientAttestationValidator" />
- <ref bean="openidvci.PublicClientValidator" />
-</util:list>
+<util:map id="openidvci.ClientAttestationAttesters">
+ <entry key="eudiw-abca">
+ <list>
+ <value>C=EU,O=EUDI Wallet Reference Implementation,2.5.4.97=#0c0f4c454945552d313233343536373839,CN=Wallet Provider PRD 01</value>
+ </list>
+ </entry>
+</util:map>
```
-Full file: [conf/authn/oauth2client-authn-config.xml](docs/example/step-5/conf/authn/oauth2client-authn-config.xml)
-
-The VCI endpoints use this plugin’s `OpenIDVCIClient` login flow, which supports this method. The
+The VCI endpoints use this plugin’s `OpenIDVCIClient` login flow, which supports Wallet Attestation. The
PAR endpoint belongs to the OP and rejects clients that use an authentication method its login flow
does not support. Configure the OP’s OAuth endpoints to use the same flow in *conf/oidc.properties*:
@@ -5017,8 +5015,11 @@ Beans you can define or reference. Define your own beans in *conf/global.xml* or
| **openidvci.KeyAttestationTrustAnchors** | List<Credential> | | Certificates key attestations are accepted under. Needed for `key_attestations_required`. |
| **openidvci.KeyAttestationCRLs** | List<Resource> | | CRLs of the trust anchors of key attestations, read again every `openidvci.attestation.crlRefreshInterval`. |
| **openidvci.KeyAttestationClaimsValidator** | ClaimsValidator | | Validation of key attestation claims, `nonce` among them. |
-| **openidvci.ClientAttestationValidator** | CredentialValidator | built in | Authenticates a wallet with `OAuth-Client-Attestation` headers. Add to **shibboleth.authn.OAuth2Client.Validators** before **openidvci.PublicClientValidator**. |
+| **openidvci.ClientAttestationValidator** | CredentialValidator | built in | Authenticates a wallet with `OAuth-Client-Attestation` headers, the only validator of a request carrying them. |
+| **openidvci.ClientAttestationClaimsValidator** | ClaimsValidator | built in | Validation of Wallet Attestation claims: `sub`, `exp`, `iat` and `cnf` required, expiry, not before, and `iat` at most `openidvci.attestation.maxAge` old. |
+| **openidvci.ClientAttestationPoPClaimsValidator** | ClaimsValidator | built in | Validation of the claims of the proof of possession of a Wallet Attestation: `aud`, `jti` and `iat` required, `iat` at most `openidvci.attestation.proofLifetime` old, not before, expiry, `aud` the issuer and nothing else, and `jti` not seen before. |
| **openidvci.ClientAttestationTrustAnchors** | List<Credential> | | Certificates Wallet Attestations are accepted under. |
+| **openidvci.ClientAttestationAttesters** | Map<String, List<String>> | | Wallets accepted with a Wallet Attestation, keyed by the client ID of the wallet, each with the subject names of the wallet provider certificates that sign its Wallet Attestations. Without the list every wallet is accepted with every certificate under a trust anchor. |
| **openidvci.ClientAttestationCRLs** | List<Resource> | | CRLs of the trust anchors of Wallet Attestations, read again every `openidvci.attestation.crlRefreshInterval`. |
| **openidvci.AttestationTrustEvaluator** | PKIXTrustEvaluator | `CertPathPKIXTrustEvaluator` | Evaluates the certificate chains of Wallet Attestations and key attestations. |
| **openidvci.PublicClientValidator** | CredentialValidator | built in | Authenticates a public client, `none`. |
@@ -5044,6 +5045,10 @@ The file comes with the plugin and is loaded automatically.
|---|---|---|---|
| `openidvci.issuer` | String | | Issuer of credentials and Status List Tokens. Empty or `did:jwk`, `did:web`, `url`, or the identifier itself. |
| `openidvci.authn.flows` | Regex | `OpenIDVCIClient` | Login flows of the VCI endpoints. `OpenIDVCIClient` is the `OAuth2Client` flow with `attest_jwt_client_auth`. |
+| `idp.authn.OpenIDVCIClient.order` | Integer | `1000` | Order of the `OpenIDVCIClient` login flow among the login flows. |
+| `idp.authn.OpenIDVCIClient.activationCondition` | Bean ID | **shibboleth.Conditions.TRUE** | Condition for the `OpenIDVCIClient` login flow to be used. |
+| `idp.authn.OpenIDVCIClient.subjectDecorator` | Bean ID | | Decorator of the Subject of the `OpenIDVCIClient` login flow. |
+| `idp.authn.OpenIDVCIClient.supportedPrincipals` | Comma-separated | | Principals the `OpenIDVCIClient` login flow supports. |
| `openidvci.credentialTimestampPrecision` | Duration | `PT1H` | Instant of issuance is rounded down to this. Keep it shorter than the shortest lifetime. |
| `openidvci.batchSize` | Integer | `2` | Default of `batchSize`. |
| `openidvci.StorageService` | Bean ID | **shibboleth.StorageService** | Storage of Credential Offers, used only when `openidvci.preAuthorizedCode.defaultLength` is not `0`. Server side storage. |
@@ -5052,6 +5057,9 @@ The file comes with the plugin and is loaded automatically.
| `openidvci.nonce.lifetime` | Duration | `PT5M` | Lifetime of the `c_nonce` of the Nonce endpoint. |
| `openidvci.requestParser.TokenRequest` | Bean ID | | Custom parser of the Token endpoint request, a `CustomNimbusRequestParser` of the OP plugin returning an `OpenIDVCITokenRequest`. |
+The other settings of the `OpenIDVCIClient` login flow are the `idp.authn.OAuth2Client.*` properties of the
+`OAuth2Client` login flow, `idp.authn.OAuth2Client.audit.enabled` among them.
+
#### Credential Configurations
| Name | Type | Default | Function |
@@ -5114,6 +5122,8 @@ The file comes with the plugin and is loaded automatically.
| `openidvci.attestation.verifyDepth` | Integer | `5` | Largest number of intermediate certificates of an attestation chain. |
| `openidvci.attestation.clockSkew` | Duration | `PT5M` | Tolerance of the times of Wallet Attestations, their proofs of possession and key attestations. |
| `openidvci.attestation.proofLifetime` | Duration | `PT5M` | Time a proof of possession of a Wallet Attestation is accepted after its `iat`. |
+| `openidvci.attestation.maxAge` | Duration | `P365D` | Time a Wallet Attestation is accepted after its `iat`, its `exp` permitting. |
+| `openidvci.attestation.signingAlgorithms` | Comma-separated | `ES256` | Signature algorithms accepted of a Wallet Attestation and of its proof of possession. Publish the same ones as `client_attestation_signing_alg_values_supported` and `client_attestation_pop_signing_alg_values_supported`. |
#### OpenID Federation
diff --git a/docs/example/step-5/conf/authn/oauth2client-authn-config.xml b/docs/example/step-5/conf/authn/oauth2client-authn-config.xml
deleted file mode 100644
index b64b473..0000000
--- a/docs/example/step-5/conf/authn/oauth2client-authn-config.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- 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/util http://www.springframework.org/schema/util/spring-util.xsd"
- default-init-method="initialize"
- default-destroy-method="destroy">
-
- <util:list id="shibboleth.authn.OAuth2Client.Validators">
- <ref bean="shibboleth.OIDCClientInfoValidator" />
- <ref bean="shibboleth.JWTValidator" />
- <ref bean="openidvci.ClientAttestationValidator" />
- <ref bean="openidvci.PublicClientValidator" />
- </util:list>
-
-</beans>
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationClaimsAuditExtractor.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationClaimsAuditExtractor.java
new file mode 100644
index 0000000..b74b7ef
--- /dev/null
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationClaimsAuditExtractor.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2025, GÉANT
+ *
+ * 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 org.geant.shibboleth.plugin.openidvci.authn.impl;
+
+import java.text.ParseException;
+import java.util.Date;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+
+import com.nimbusds.jwt.SignedJWT;
+
+import jakarta.servlet.http.HttpServletRequest;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.Constraint;
+
+/** {@link Function} that returns a claim of the client attestation or of its proof of possession. */
+public class ClientAttestationClaimsAuditExtractor implements Function<ProfileRequestContext, String> {
+
+ /** Supplier of the servlet request the header is read from. */
+ @Nonnull
+ private final Supplier<HttpServletRequest> httpServletRequestSupplier;
+
+ /** Header carrying the JWT. */
+ @Nonnull
+ @NotEmpty
+ private final String header;
+
+ /** Claim whose value is extracted. */
+ @Nonnull
+ @NotEmpty
+ private final String key;
+
+ /**
+ * Constructor.
+ *
+ * @param supplier supplier of the servlet request
+ * @param name header carrying the JWT
+ * @param claim claim whose value is extracted
+ */
+ public ClientAttestationClaimsAuditExtractor(@Nonnull final Supplier<HttpServletRequest> supplier,
+ @Nonnull @NotEmpty final String name, @Nonnull @NotEmpty final String claim) {
+ httpServletRequestSupplier = Constraint.isNotNull(supplier, "Servlet request supplier cannot be null");
+ header = Constraint.isNotEmpty(name, "Header cannot be empty");
+ key = Constraint.isNotEmpty(claim, "Claim cannot be empty");
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable
+ public String apply(@Nullable final ProfileRequestContext input) {
+ final HttpServletRequest request = httpServletRequestSupplier.get();
+ final String jwt = request != null ? request.getHeader(header) : null;
+ if (jwt == null) {
+ return null;
+ }
+ try {
+ final Object claim = SignedJWT.parse(jwt).getJWTClaimsSet().getClaim(key);
+ if (claim instanceof Date date) {
+ return date.toInstant().toString();
+ }
+ return claim != null ? claim.toString() : null;
+ } catch (final ParseException e) {
+ return null;
+ }
+ }
+
+}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidator.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidator.java
index 0aa7eee..ffc639f 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidator.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidator.java
@@ -16,45 +16,50 @@
package org.geant.shibboleth.plugin.openidvci.authn.impl;
+import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.time.Duration;
-import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
-import java.util.Date;
import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.function.Function;
+import java.util.Set;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.security.auth.Subject;
+import javax.security.auth.x500.X500Principal;
import org.geant.shibboleth.plugin.openidvci.security.impl.CertificateChainTrust;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.profile.context.ProfileRequestContext;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.x509.PKIXTrustEvaluator;
-import org.opensaml.storage.ReplayCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
-import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.crypto.factories.DefaultJWSVerifierFactory;
import com.nimbusds.jose.jwk.AsymmetricJWK;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.oauth2.sdk.AbstractOptionallyIdentifiedRequest;
+import com.nimbusds.oauth2.sdk.AuthorizationRequest;
+import com.nimbusds.oauth2.sdk.PushedAuthorizationRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.idp.authn.AbstractCredentialValidator;
+import net.shibboleth.idp.authn.AuthnEventIds;
import net.shibboleth.idp.authn.context.AuthenticationContext;
import net.shibboleth.idp.authn.principal.UsernamePrincipal;
+import net.shibboleth.oidc.jwt.claims.ClaimsValidator;
import net.shibboleth.oidc.jwt.claims.JWTValidationException;
import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
import net.shibboleth.shared.component.ComponentInitializationException;
@@ -94,21 +99,25 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
@NonnullAfterInit
private Supplier<HttpServletRequest> httpServletRequestSupplier;
- /** Replay cache of the proofs of possession. */
+ /** Validator of the claims of a client attestation. */
@NonnullAfterInit
- private ReplayCache replayCache;
+ private ClaimsValidator attestationClaimsValidator;
- /** Strategy used to obtain the audience a proof of possession is for. */
+ /** Validator of the claims of a proof of possession. */
@NonnullAfterInit
- private Function<ProfileRequestContext, String> audienceLookupStrategy;
+ private ClaimsValidator proofClaimsValidator;
- /** Tolerance of the times of the attestation and of its proof of possession. */
+ /** Signature algorithms accepted of a client attestation and of its proof of possession. */
@Nonnull
- private Duration clockSkew = Duration.ofMinutes(5);
+ private Set<String> signatureAlgorithms = Set.of("ES256");
- /** Time a proof of possession is accepted after its issue time. */
- @Nonnull
- private Duration proofLifetime = Duration.ofMinutes(5);
+ /** Subject names of the attester certificates accepted for a client, keyed by client identifier. */
+ @Nullable
+ private Map<String, ? extends Collection<String>> attesters;
+
+ /** Parsed subject names of the attester certificates accepted for a client, null to accept any. */
+ @Nullable
+ private Map<String, Set<X500Principal>> attesterNames;
/**
* Set the credentials a chain of a client attestation is accepted under.
@@ -166,48 +175,47 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
}
/**
- * Set the replay cache of the proofs of possession.
+ * Set the validator of the claims of a client attestation.
*
- * @param cache replay cache to use
+ * @param validator claims validator
*/
- public void setReplayCache(@Nonnull final ReplayCache cache) {
+ public void setAttestationClaimsValidator(@Nonnull final ClaimsValidator validator) {
checkSetterPreconditions();
- replayCache = Constraint.isNotNull(cache, "ReplayCache cannot be null");
+ attestationClaimsValidator = Constraint.isNotNull(validator, "Attestation claims validator cannot be null");
}
/**
- * Set the strategy used to obtain the audience a proof of possession is for, the issuer of the
- * Authorization Server.
+ * Set the validator of the claims of a proof of possession.
*
- * @param strategy strategy to obtain the audience
+ * @param validator claims validator
*/
- public void setAudienceLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) {
+ public void setProofClaimsValidator(@Nonnull final ClaimsValidator validator) {
checkSetterPreconditions();
- audienceLookupStrategy = Constraint.isNotNull(strategy, "Audience lookup strategy cannot be null");
+ proofClaimsValidator = Constraint.isNotNull(validator, "Proof claims validator cannot be null");
}
/**
- * Set the tolerance of the times of the attestation and of its proof of possession.
+ * Set the signature algorithms accepted of a client attestation and of its proof of possession.
*
- * @param skew tolerance of the times
+ * @param algorithms JWS algorithm names
*/
- public void setClockSkew(@Nonnull final Duration skew) {
+ public void setSignatureAlgorithms(@Nonnull final Collection<String> algorithms) {
checkSetterPreconditions();
- clockSkew = Constraint.isNotNull(skew, "Clock skew cannot be null");
+ signatureAlgorithms = Set.copyOf(Constraint.isNotNull(algorithms, "Signature algorithms cannot be null"));
}
/**
- * Set the time a proof of possession is accepted after its issue time.
+ * Set the clients accepted and the subject names of their attester certificates, keyed by client identifier.
*
- * @param lifetime time a proof of possession is accepted
+ * @param names subject names in RFC 2253 format, keyed by client identifier, or null to accept any
*/
- public void setProofLifetime(@Nonnull final Duration lifetime) {
+ public void setAttesters(@Nullable final Map<String, ? extends Collection<String>> names) {
checkSetterPreconditions();
- proofLifetime = Constraint.isNotNull(lifetime, "Proof lifetime cannot be null");
+ attesters = names;
}
/** {@inheritDoc} */
@@ -215,14 +223,31 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
protected void doInitialize() throws ComponentInitializationException {
super.doInitialize();
+ if (attesters != null) {
+ final Map<String, Set<X500Principal>> parsed = new HashMap<>();
+ for (final Map.Entry<String, ? extends Collection<String>> entry : attesters.entrySet()) {
+ final Set<X500Principal> names = new HashSet<>();
+ for (final String name : entry.getValue()) {
+ try {
+ names.add(new X500Principal(name));
+ } catch (final IllegalArgumentException e) {
+ throw new ComponentInitializationException(
+ "Attester '" + name + "' of client '" + entry.getKey() + "' is no subject name", e);
+ }
+ }
+ parsed.put(entry.getKey(), names);
+ }
+ attesterNames = parsed;
+ }
+
if (httpServletRequestSupplier == null) {
throw new ComponentInitializationException("Servlet request supplier cannot be null");
}
- if (replayCache == null) {
- throw new ComponentInitializationException("ReplayCache cannot be null");
+ if (attestationClaimsValidator == null) {
+ throw new ComponentInitializationException("Attestation claims validator cannot be null");
}
- if (audienceLookupStrategy == null) {
- throw new ComponentInitializationException("Audience lookup strategy cannot be null");
+ if (proofClaimsValidator == null) {
+ throw new ComponentInitializationException("Proof claims validator cannot be null");
}
chainTrust.initialize();
}
@@ -244,26 +269,31 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
log.debug("{} Request carries no client attestation", getLogPrefix());
return null;
}
- if (attestationHeaders.isEmpty() || popHeaders.isEmpty()) {
- log.warn("{} Request carries only one of '{}' and '{}'", getLogPrefix(), ATTESTATION_HEADER, POP_HEADER);
- return null;
- }
+ final SignedJWT attestation;
final String clientId;
try {
+ if (attestationHeaders.isEmpty() || popHeaders.isEmpty()) {
+ throw new JWTValidationException(
+ "Request carries only one of '" + ATTESTATION_HEADER + "' and '" + POP_HEADER + "'");
+ }
if (attestationHeaders.size() > 1 || popHeaders.size() > 1) {
throw new JWTValidationException(
"Request carries more than one '" + ATTESTATION_HEADER + "' or '" + POP_HEADER + "' header");
}
- clientId = validate(profileRequestContext, SignedJWT.parse(attestationHeaders.get(0)),
- SignedJWT.parse(popHeaders.get(0)));
- validateRequestClientID(profileRequestContext, clientId);
+ attestation = SignedJWT.parse(attestationHeaders.get(0));
+ clientId = validate(profileRequestContext, attestation, SignedJWT.parse(popHeaders.get(0)));
} catch (final JWTValidationException | ParseException e) {
log.warn("{} Client attestation validation failed: {}", getLogPrefix(), e.getMessage());
+ if (errorHandler != null) {
+ errorHandler.handleError(profileRequestContext, authenticationContext, e,
+ AuthnEventIds.INVALID_CREDENTIALS);
+ }
throw e;
}
final Subject subject = new Subject();
subject.getPrincipals().add(new UsernamePrincipal(clientId));
+ subject.getPublicCredentials().add(attestation);
log.info("{} Client {} authenticated with a client attestation", getLogPrefix(), clientId);
return super.populateSubject(subject);
}
@@ -284,22 +314,30 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
}
/**
- * Validate the client identifier of the request against the one the client attestation names.
+ * Validate the client identifier of the request against the 'sub' of the client attestation.
*
* @param profileRequestContext profile request context
- * @param clientId client identifier of the attestation
+ * @param clientId 'sub' of the client attestation
*
- * @throws JWTValidationException if the request names another client
+ * @throws JWTValidationException if the request carries another client identifier
*/
private void validateRequestClientID(@Nonnull final ProfileRequestContext profileRequestContext,
@Nonnull final String clientId) throws JWTValidationException {
final MessageContext inbound = profileRequestContext.getInboundMessageContext();
final Object message = inbound != null ? inbound.getMessage() : null;
- if (message instanceof AbstractOptionallyIdentifiedRequest request && request.getClientID() != null
- && !clientId.equals(request.getClientID().getValue())) {
- throw new JWTValidationException("Request names client " + request.getClientID().getValue()
- + ", the client attestation names " + clientId);
+ final ClientID requested;
+ if (message instanceof PushedAuthorizationRequest pushed) {
+ final AuthorizationRequest authorizationRequest = pushed.getAuthorizationRequest();
+ requested = authorizationRequest != null ? authorizationRequest.getClientID() : null;
+ } else if (message instanceof AbstractOptionallyIdentifiedRequest identified) {
+ requested = identified.getClientID();
+ } else {
+ requested = null;
+ }
+ if (requested != null && !clientId.equals(requested.getValue())) {
+ throw new JWTValidationException("Request carries client " + requested.getValue()
+ + ", the 'sub' of the client attestation is " + clientId);
}
}
@@ -310,7 +348,7 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
* @param attestation client attestation
* @param pop proof of possession of the client attestation
*
- * @return the client identifier the attestation names
+ * @return the 'sub' of the client attestation
*
* @throws JWTValidationException if either is not acceptable
*/
@@ -324,25 +362,32 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
if (!POP_TYPE.equals(pop.getHeader().getType())) {
throw new JWTValidationException("typ of a proof of possession must be " + POP_TYPE);
}
- chainTrust.verify(attestation);
+ if (!signatureAlgorithms.contains(attestation.getHeader().getAlgorithm().getName())) {
+ throw new JWTValidationException(
+ "alg " + attestation.getHeader().getAlgorithm() + " of the client attestation is not accepted");
+ }
+ if (!signatureAlgorithms.contains(pop.getHeader().getAlgorithm().getName())) {
+ throw new JWTValidationException(
+ "alg " + pop.getHeader().getAlgorithm() + " of the proof of possession is not accepted");
+ }
+ final List<X509Certificate> chain = chainTrust.verify(attestation);
final JWTClaimsSet attestationClaims = claims(attestation);
- final JWTClaimsSet popClaims = claims(pop);
- validateIssueTime(attestationClaims, "client attestation", null);
- validateTimes(attestationClaims, "client attestation", true);
- validateIssueTime(popClaims, "proof of possession", proofLifetime);
- validateTimes(popClaims, "proof of possession", false);
-
- final String subject = attestationClaims.getSubject();
- if (subject == null || subject.isEmpty()) {
- throw new JWTValidationException("Client attestation carries no 'sub'");
+ attestationClaimsValidator.validate(attestationClaims, profileRequestContext);
+ if (!(attestation.getPayload().toJSONObject().get("sub") instanceof String subject) || subject.isEmpty()) {
+ throw new JWTValidationException("'sub' of the client attestation must be a non-empty string");
}
- final String audience = audienceLookupStrategy.apply(profileRequestContext);
- if (audience == null || popClaims.getAudience() == null || !popClaims.getAudience().contains(audience)) {
- throw new JWTValidationException("'aud' of the proof of possession is no " + audience);
+ if (attesterNames != null) {
+ final Set<X500Principal> accepted = attesterNames.get(subject);
+ final X500Principal attester = chain.get(0).getSubjectX500Principal();
+ if (accepted == null || !accepted.contains(attester)) {
+ throw new JWTValidationException(
+ "Attester '" + attester.getName() + "' is not listed for client " + subject);
+ }
}
+ validateRequestClientID(profileRequestContext, subject);
verifyProofOfPossession(attestationClaims, pop);
- spend(popClaims);
+ proofClaimsValidator.validate(claims(pop), profileRequestContext);
return subject;
}
@@ -362,7 +407,8 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
throw new JWTValidationException("Client attestation confirms no key in 'cnf'");
}
try {
- final JWK key = JWK.parse(new ObjectMapper().writeValueAsString(jwk));
+ @SuppressWarnings("unchecked")
+ final JWK key = JWK.parse((Map<String, Object>) jwk);
if (!(key instanceof AsymmetricJWK asymmetric)) {
throw new JWTValidationException("Key of 'cnf' is no asymmetric key");
}
@@ -380,31 +426,6 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
}
}
- /**
- * Spend the identifier of a proof of possession.
- *
- * @param popClaims claims of the proof of possession
- *
- * @throws JWTValidationException if the identifier is absent or spent already
- */
- private void spend(@Nonnull final JWTClaimsSet popClaims) throws JWTValidationException {
-
- final String jti = popClaims.getJWTID();
- if (jti == null || jti.isEmpty()) {
- throw new JWTValidationException("Proof of possession carries no 'jti'");
- }
- final Date issued = popClaims.getIssueTime();
- if (issued == null) {
- throw new JWTValidationException("Proof of possession carries no 'iat'");
- }
- final Instant expires = issued.toInstant().plus(proofLifetime).plus(clockSkew);
- final String context = getClass().getName();
- assert context != null && expires != null;
- if (!replayCache.check(context, jti, expires)) {
- throw new JWTValidationException("Replay detected of a proof of possession");
- }
- }
-
/**
* Read the claims of a JWT.
*
@@ -423,55 +444,4 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
}
}
- /**
- * Validate the issue time of a JWT.
- *
- * @param claims claims to validate
- * @param what what is validated, for the message
- * @param lifetime time the JWT is accepted after its issue time, or null for no limit
- *
- * @throws JWTValidationException if the issue time is absent or not acceptable
- */
- private void validateIssueTime(@Nonnull final JWTClaimsSet claims, @Nonnull final String what,
- @Nullable final Duration lifetime) throws JWTValidationException {
-
- final Date issued = claims.getIssueTime();
- if (issued == null) {
- throw new JWTValidationException("The " + what + " carries no 'iat'");
- }
- final Instant now = Instant.now();
- if (issued.toInstant().isAfter(now.plus(clockSkew))) {
- throw new JWTValidationException("The " + what + " is issued in the future");
- }
- if (lifetime != null && issued.toInstant().plus(lifetime).plus(clockSkew).isBefore(now)) {
- throw new JWTValidationException("The " + what + " is issued too long ago");
- }
- }
-
- /**
- * Validate the expiration and not before times of a JWT.
- *
- * @param claims claims to validate
- * @param what what is validated, for the message
- * @param expirationRequired whether the JWT must carry an expiration time
- *
- * @throws JWTValidationException if the times are not acceptable
- */
- private void validateTimes(@Nonnull final JWTClaimsSet claims, @Nonnull final String what,
- final boolean expirationRequired) throws JWTValidationException {
-
- final Instant now = Instant.now();
- final Date expires = claims.getExpirationTime();
- if (expires == null && expirationRequired) {
- throw new JWTValidationException("The " + what + " carries no 'exp'");
- }
- if (expires != null && expires.toInstant().isBefore(now.minus(clockSkew))) {
- throw new JWTValidationException("The " + what + " is expired");
- }
- final Date notBefore = claims.getNotBeforeTime();
- if (notBefore != null && notBefore.toInstant().isAfter(now.plus(clockSkew))) {
- throw new JWTValidationException("The " + what + " is not yet valid");
- }
- }
-
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java
index 78fe6e1..260378c 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java
@@ -27,7 +27,7 @@ import org.opensaml.profile.context.ProfileRequestContext;
import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.shared.logic.Constraint;
-/** Condition signaling that the request carries a Wallet Attestation. */
+/** Condition signaling that the request carries a Wallet Attestation header. */
public class ClientAttestationPresentPredicate implements Predicate<ProfileRequestContext> {
/** Supplier of the servlet request the headers are read from. */
@@ -48,9 +48,8 @@ public class ClientAttestationPresentPredicate implements Predicate<ProfileReque
public boolean test(@Nullable final ProfileRequestContext profileRequestContext) {
final HttpServletRequest request = httpServletRequestSupplier.get();
- return request != null
- && request.getHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER) != null
- && request.getHeader(ClientAttestationCredentialValidator.POP_HEADER) != null;
+ return request != null && (request.getHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER) != null
+ || request.getHeader(ClientAttestationCredentialValidator.POP_HEADER) != null);
}
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationTypeHeaderAuditExtractor.java
similarity index 56%
copy from openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java
copy to openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationTypeHeaderAuditExtractor.java
index 78fe6e1..15036c7 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicate.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationTypeHeaderAuditExtractor.java
@@ -16,7 +16,8 @@
package org.geant.shibboleth.plugin.openidvci.authn.impl;
-import java.util.function.Predicate;
+import java.text.ParseException;
+import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
@@ -24,13 +25,16 @@ import javax.annotation.Nullable;
import org.opensaml.profile.context.ProfileRequestContext;
+import com.nimbusds.jose.JOSEObjectType;
+import com.nimbusds.jwt.SignedJWT;
+
import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.shared.logic.Constraint;
-/** Condition signaling that the request carries a Wallet Attestation. */
-public class ClientAttestationPresentPredicate implements Predicate<ProfileRequestContext> {
+/** {@link Function} that returns the type header of the client attestation. */
+public class ClientAttestationTypeHeaderAuditExtractor implements Function<ProfileRequestContext, String> {
- /** Supplier of the servlet request the headers are read from. */
+ /** Supplier of the servlet request the header is read from. */
@Nonnull
private final Supplier<HttpServletRequest> httpServletRequestSupplier;
@@ -39,18 +43,26 @@ public class ClientAttestationPresentPredicate implements Predicate<ProfileReque
*
* @param supplier supplier of the servlet request
*/
- public ClientAttestationPresentPredicate(@Nonnull final Supplier<HttpServletRequest> supplier) {
+ public ClientAttestationTypeHeaderAuditExtractor(@Nonnull final Supplier<HttpServletRequest> supplier) {
httpServletRequestSupplier = Constraint.isNotNull(supplier, "Servlet request supplier cannot be null");
}
/** {@inheritDoc} */
@Override
- public boolean test(@Nullable final ProfileRequestContext profileRequestContext) {
-
+ @Nullable
+ public String apply(@Nullable final ProfileRequestContext input) {
final HttpServletRequest request = httpServletRequestSupplier.get();
- return request != null
- && request.getHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER) != null
- && request.getHeader(ClientAttestationCredentialValidator.POP_HEADER) != null;
+ final String jwt =
+ request != null ? request.getHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER) : null;
+ if (jwt == null) {
+ return null;
+ }
+ try {
+ final JOSEObjectType type = SignedJWT.parse(jwt).getHeader().getType();
+ return type != null ? type.getType() : null;
+ } catch (final ParseException e) {
+ return null;
+ }
}
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationType.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationType.java
index e28faab..d9fd33d 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationType.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationType.java
@@ -15,20 +15,21 @@
*/
/*
- * Derived from net.shibboleth.idp.plugin.oidc.op.authn.impl.ValidateClientAuthenticationType
- * of the Shibboleth OpenID Connect Provider plugin, Apache License 2.0, modified by GÉANT.
+ * Derived from net.shibboleth.oidc.authn.impl.ValidateClientAuthenticationType
+ * of the Shibboleth OIDC Common library, Apache License 2.0, modified by GÉANT.
*/
package org.geant.shibboleth.plugin.openidvci.authn.impl;
import java.util.Collections;
import java.util.Set;
-import java.util.stream.Collectors;
import java.util.function.Function;
+import java.util.function.Predicate;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.context.navigate.ChildContextLookup;
import org.opensaml.profile.action.ActionSupport;
import org.opensaml.profile.action.EventIds;
@@ -37,19 +38,20 @@ import org.opensaml.profile.context.navigate.InboundMessageContextLookup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.nimbusds.oauth2.sdk.AbstractOptionallyAuthenticatedRequest;
import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod;
+import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation;
import com.nimbusds.openid.connect.sdk.rp.OIDCClientMetadata;
-import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.idp.authn.AbstractAuthenticationAction;
import net.shibboleth.idp.authn.context.AuthenticationContext;
import net.shibboleth.oidc.authn.context.OAuth2ClientAuthenticationContext;
import net.shibboleth.oidc.metadata.context.OIDCMetadataContext;
-import net.shibboleth.oidc.profile.oauth2.config.OAuth2ClientAuthenticableProfileConfiguration;
-import net.shibboleth.profile.context.RelyingPartyContext;
+import net.shibboleth.oidc.profile.config.navigate.TokenEndpointAuthMethodLookupFunction;
import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.logic.PredicateSupport;
/**
* Validates the client authentication method of a request against the method the client registered and
@@ -75,6 +77,10 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
@Nonnull
private Function<ProfileRequestContext, Set<ClientAuthenticationMethod>> tokenEndpointAuthMethodsLookupStrategy;
+ /** Condition signaling that the request carries a client attestation. */
+ @Nonnull
+ private Predicate<ProfileRequestContext> attestationPresentCondition;
+
/** Metadata of the client. */
@Nullable
private OIDCMetadataContext oidcMetadataContext;
@@ -95,7 +101,8 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
new ChildContextLookup<>(OIDCMetadataContext.class).compose(new InboundMessageContextLookup());
assert strategy != null;
oidcMetadataContextLookupStrategy = strategy;
- tokenEndpointAuthMethodsLookupStrategy = new EnabledMethodsLookupFunction();
+ tokenEndpointAuthMethodsLookupStrategy = new TokenEndpointAuthMethodLookupFunction();
+ attestationPresentCondition = PredicateSupport.alwaysFalse();
enabledMethods = Collections.emptySet();
}
@@ -104,7 +111,7 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
*
* @param strategy lookup strategy
*/
- public void setOidcMetadataContextLookupStrategy(
+ public void setOIDCMetadataContextLookupStrategy(
@Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy) {
checkSetterPreconditions();
@@ -123,6 +130,17 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
tokenEndpointAuthMethodsLookupStrategy = Constraint.isNotNull(strategy, "Lookup strategy cannot be null");
}
+ /**
+ * Set the condition signaling that the request carries a client attestation.
+ *
+ * @param condition condition to set
+ */
+ public void setAttestationPresentCondition(@Nonnull final Predicate<ProfileRequestContext> condition) {
+ checkSetterPreconditions();
+
+ attestationPresentCondition = Constraint.isNotNull(condition, "Condition cannot be null");
+ }
+
/** {@inheritDoc} */
@Override
protected boolean doPreExecute(@Nonnull final ProfileRequestContext profileRequestContext,
@@ -148,6 +166,15 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
@Nonnull final AuthenticationContext authenticationContext) {
+ final boolean attested = attestationPresentCondition.test(profileRequestContext);
+ if (attested) {
+ final ClientAuthenticationMethod other = messageMethod(profileRequestContext);
+ if (other != null) {
+ log.warn("{} Request carries a client attestation and {}", getLogPrefix(), other);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.ACCESS_DENIED);
+ return;
+ }
+ }
ClientAuthenticationMethod registeredMethod = null;
if (oidcMetadataContext != null) {
final OIDCClientInformation clientInformation = oidcMetadataContext.getClientInformation();
@@ -158,9 +185,10 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
: ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
}
}
- final ClientAuthenticationMethod used = resolveUsedMethod();
+ final ClientAuthenticationMethod used = resolveUsedMethod(attested);
if (registeredMethod != null && !registeredMethod.equals(used)) {
- log.warn("{} Client registered {} but attempted {}", getLogPrefix(), registeredMethod, used);
+ log.warn("{} Client '{}' registered {} but attempted {}", getLogPrefix(), getClientID(),
+ registeredMethod, used);
ActionSupport.buildEvent(profileRequestContext, EventIds.ACCESS_DENIED);
return;
}
@@ -171,52 +199,71 @@ public class ValidateClientAuthenticationType extends AbstractAuthenticationActi
}
/**
- * Function reading the methods the profile configuration enables.
+ * Read the client identifier from the metadata of the client or from the client authentication.
+ *
+ * @return the client identifier, or null if neither carries one
*/
- private static class EnabledMethodsLookupFunction
- implements Function<ProfileRequestContext, Set<ClientAuthenticationMethod>> {
-
- /** Strategy used to locate the {@link RelyingPartyContext}. */
- @Nonnull
- private final Function<ProfileRequestContext, RelyingPartyContext> relyingPartyContextLookupStrategy =
- new ChildContextLookup<>(RelyingPartyContext.class);
-
- /** {@inheritDoc} */
- @Override
- @Nonnull
- public Set<ClientAuthenticationMethod> apply(@Nullable final ProfileRequestContext profileRequestContext) {
-
- final RelyingPartyContext rpCtx = relyingPartyContextLookupStrategy.apply(profileRequestContext);
- if (rpCtx == null || !(rpCtx
- .getProfileConfig() instanceof OAuth2ClientAuthenticableProfileConfiguration configuration)) {
- return Collections.emptySet();
+ @Nullable
+ private String getClientID() {
+
+ if (oidcMetadataContext != null) {
+ final OIDCClientInformation clientInformation = oidcMetadataContext.getClientInformation();
+ if (clientInformation != null) {
+ return getClientIDValue(clientInformation.getID());
}
- return configuration.getTokenEndpointAuthMethods(profileRequestContext).stream()
- .map(ClientAuthenticationMethod::new).collect(Collectors.toUnmodifiableSet());
}
+ if (clientAuthentication != null) {
+ return getClientIDValue(clientAuthentication.getClientID());
+ }
+ return null;
+ }
+ /**
+ * Get the value of a client identifier.
+ *
+ * @param clientId client identifier
+ *
+ * @return the value, or null if the client identifier is null
+ */
+ @Nullable
+ private static String getClientIDValue(@Nullable final ClientID clientId) {
+ return clientId == null ? null : clientId.getValue();
}
/**
* Read the method the request is authenticated with.
*
+ * @param attested whether the request carries a client attestation
+ *
* @return the method
*/
@Nonnull
- private ClientAuthenticationMethod resolveUsedMethod() {
+ private ClientAuthenticationMethod resolveUsedMethod(final boolean attested) {
if (clientAuthentication != null) {
final ClientAuthenticationMethod method = clientAuthentication.getMethod();
assert method != null;
return method;
}
- final HttpServletRequest request = getHttpServletRequest();
- if (request != null
- && request.getHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER) != null
- && request.getHeader(ClientAttestationCredentialValidator.POP_HEADER) != null) {
- return ATTEST_JWT_CLIENT_AUTH;
+ return attested ? ATTEST_JWT_CLIENT_AUTH : ClientAuthenticationMethod.NONE;
+ }
+
+ /**
+ * Read the client authentication method of the inbound message.
+ *
+ * @param profileRequestContext profile request context
+ *
+ * @return the method, or null if the message carries no client authentication
+ */
+ @Nullable
+ private ClientAuthenticationMethod messageMethod(@Nonnull final ProfileRequestContext profileRequestContext) {
+
+ final MessageContext inbound = profileRequestContext.getInboundMessageContext();
+ if (inbound != null && inbound.getMessage() instanceof AbstractOptionallyAuthenticatedRequest request
+ && request.getClientAuthentication() != null) {
+ return request.getClientAuthentication().getMethod();
}
- return ClientAuthenticationMethod.NONE;
+ return null;
}
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidator.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidator.java
index 92c3f05..35ef1a9 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidator.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidator.java
@@ -17,6 +17,7 @@
package org.geant.shibboleth.plugin.openidvci.authn.impl;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import javax.security.auth.Subject;
import net.shibboleth.idp.authn.AbstractCredentialValidator;
@@ -26,6 +27,7 @@ import net.shibboleth.shared.annotation.constraint.ThreadSafeAfterInit;
import net.shibboleth.shared.primitive.LoggerFactory;
import org.geant.shibboleth.plugin.openidvci.profile.context.navigate.APIRequestClientIDLookupFunction;
+import org.opensaml.messaging.context.MessageContext;
import org.opensaml.profile.context.ProfileRequestContext;
import org.slf4j.Logger;
@@ -33,13 +35,7 @@ import com.nimbusds.oauth2.sdk.AbstractOptionallyAuthenticatedRequest;
import com.nimbusds.oauth2.sdk.id.ClientID;
/**
- * With OpenID VCI code flow we have unregistered clients that access Token
- * endpoint. This Validator accepts unregistered clients locating client
- * identifier by {@link APIRequestClientIDLookupFunction} but discarding non
- * public clients.
- *
- * TODO! Using this Validator may not withstand daylight in the long run. Care
- * has to be taken when this is applied.
+ * Credential validator of a public client, located by {@link APIRequestClientIDLookupFunction}.
*/
@ThreadSafeAfterInit
public class WalletCredentialValidator extends AbstractCredentialValidator {
@@ -48,35 +44,32 @@ public class WalletCredentialValidator extends AbstractCredentialValidator {
@Nonnull
private final Logger log = LoggerFactory.getLogger(WalletCredentialValidator.class);
+ /** Strategy used to locate the client identifier of the request. */
+ @Nonnull
+ private final APIRequestClientIDLookupFunction clientIdLookupStrategy = new APIRequestClientIDLookupFunction();
+
/** {@inheritDoc} */
@Override
- protected Subject doValidate(final ProfileRequestContext profileRequestContext,
- final AuthenticationContext authenticationContext, final WarningHandler warningHandler,
- final ErrorHandler errorHandler)
- throws Exception {
+ @Nullable
+ protected Subject doValidate(@Nonnull final ProfileRequestContext profileRequestContext,
+ @Nonnull final AuthenticationContext authenticationContext, @Nullable final WarningHandler warningHandler,
+ @Nullable final ErrorHandler errorHandler) throws Exception {
- final APIRequestClientIDLookupFunction apiRequestClientIDLookupFunction =
- new APIRequestClientIDLookupFunction();
- // TODO Auto-generated method stub
- final Subject subject = new Subject();
- final ClientID clientId = apiRequestClientIDLookupFunction
- .apply(profileRequestContext.getInboundMessageContext());
- if (clientId == null) {
- log.info("No client id located");
+ final MessageContext inbound = profileRequestContext.getInboundMessageContext();
+ final ClientID clientId = clientIdLookupStrategy.apply(inbound);
+ final String clientIdValue = clientId != null ? clientId.getValue() : null;
+ if (inbound == null || clientIdValue == null) {
+ log.debug("{} No client identifier found", getLogPrefix());
return null;
}
- if (profileRequestContext.getInboundMessageContext()
- .getMessage() instanceof AbstractOptionallyAuthenticatedRequest msg
- && msg.getClientAuthentication() != null) {
- // We validate only public clients
- log.debug("Not a public client");
+ if (inbound.getMessage() instanceof AbstractOptionallyAuthenticatedRequest message
+ && message.getClientAuthentication() != null) {
+ log.debug("{} Client '{}' is not a public client", getLogPrefix(), clientIdValue);
return null;
}
- final String clientIdValue = clientId.getValue();
- if (clientIdValue != null) {
- subject.getPrincipals().add(new UsernamePrincipal(clientIdValue));
- }
- log.info("Public client validated");
+ final Subject subject = new Subject();
+ subject.getPrincipals().add(new UsernamePrincipal(clientIdValue));
+ log.info("{} Login by '{}' succeeded", getLogPrefix(), clientIdValue);
return super.populateSubject(subject);
}
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunction.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunction.java
index aea0284..403f036 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunction.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunction.java
@@ -19,12 +19,12 @@ package org.geant.shibboleth.plugin.openidvci.profile.context.navigate;
import java.text.ParseException;
import java.util.Map;
import java.util.function.Function;
-import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationCredentialValidator;
+import org.opensaml.messaging.context.navigate.ChildContextLookup;
import org.opensaml.profile.context.ProfileRequestContext;
import org.slf4j.Logger;
@@ -32,13 +32,14 @@ import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jwt.SignedJWT;
-import jakarta.servlet.http.HttpServletRequest;
+import net.shibboleth.idp.authn.AuthenticationResult;
+import net.shibboleth.idp.authn.context.AuthenticationContext;
import net.shibboleth.shared.logic.Constraint;
import net.shibboleth.shared.primitive.LoggerFactory;
/**
- * Function returning the JWK thumbprint of the client instance key, the 'cnf' key of the client attestation of the
- * request.
+ * Function returning the JWK thumbprint of the client instance key, the 'cnf' key of the client attestation the
+ * client was authenticated with.
*/
public class ClientInstanceKeyThumbprintLookupFunction implements Function<ProfileRequestContext, String> {
@@ -46,33 +47,46 @@ public class ClientInstanceKeyThumbprintLookupFunction implements Function<Profi
@Nonnull
private final Logger log = LoggerFactory.getLogger(ClientInstanceKeyThumbprintLookupFunction.class);
- /** Supplier of the servlet request the client attestation is read from. */
+ /** Strategy used to locate the {@link AuthenticationContext}. */
@Nonnull
- private final Supplier<HttpServletRequest> httpServletRequestSupplier;
+ private Function<ProfileRequestContext, AuthenticationContext> authenticationContextLookupStrategy;
/**
* Constructor.
+ */
+ public ClientInstanceKeyThumbprintLookupFunction() {
+ authenticationContextLookupStrategy = new ChildContextLookup<>(AuthenticationContext.class);
+ }
+
+ /**
+ * Set the strategy used to locate the {@link AuthenticationContext}.
*
- * @param supplier supplier of the servlet request
+ * @param strategy lookup strategy
*/
- public ClientInstanceKeyThumbprintLookupFunction(@Nonnull final Supplier<HttpServletRequest> supplier) {
- httpServletRequestSupplier = Constraint.isNotNull(supplier, "Servlet request supplier cannot be null");
+ public void setAuthenticationContextLookupStrategy(
+ @Nonnull final Function<ProfileRequestContext, AuthenticationContext> strategy) {
+ authenticationContextLookupStrategy = Constraint.isNotNull(strategy, "Lookup strategy cannot be null");
}
/** {@inheritDoc} */
@Override
@Nullable
public String apply(@Nullable final ProfileRequestContext profileRequestContext) {
- final HttpServletRequest request = httpServletRequestSupplier.get();
- if (request == null) {
+ final AuthenticationContext authenticationContext =
+ authenticationContextLookupStrategy.apply(profileRequestContext);
+ final AuthenticationResult result =
+ authenticationContext != null ? authenticationContext.getAuthenticationResult() : null;
+ if (result == null) {
return null;
}
- final String attestation = request.getHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER);
- if (attestation == null || attestation.isEmpty()) {
+ final SignedJWT attestation = result.getSubject().getPublicCredentials(SignedJWT.class).stream()
+ .filter(jwt -> ClientAttestationCredentialValidator.ATTESTATION_TYPE.equals(jwt.getHeader().getType()))
+ .findFirst().orElse(null);
+ if (attestation == null) {
return null;
}
try {
- final Object confirmation = SignedJWT.parse(attestation).getJWTClaimsSet().getClaim("cnf");
+ final Object confirmation = attestation.getJWTClaimsSet().getClaim("cnf");
if (!(confirmation instanceof Map<?, ?> cnf) || !(cnf.get("jwk") instanceof Map<?, ?> jwk)) {
return null;
}
diff --git a/openid-vci-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml b/openid-vci-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml
index 4e69adf..2b8a790 100644
--- a/openid-vci-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml
+++ b/openid-vci-impl/src/main/resources/META-INF/net.shibboleth.idp/postconfig.xml
@@ -99,18 +99,100 @@
p:CRLRefreshInterval="%{openidvci.attestation.crlRefreshInterval:PT1H}"
p:trustEvaluator="#{getObject('openidvci.AttestationTrustEvaluator') ?: getObject('openidvci.DefaultAttestationTrustEvaluator')}"
p:httpServletRequestSupplier-ref="shibboleth.HttpServletRequestSupplier"
- p:replayCache-ref="shibboleth.ReplayCache"
- p:audienceLookupStrategy="#{T(net.shibboleth.shared.logic.FunctionSupport).constant(getObject('shibboleth.oidc.issuer'))}"
- p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}"
- p:proofLifetime="%{openidvci.attestation.proofLifetime:PT5M}" />
+ p:attesters="#{getObject('openidvci.ClientAttestationAttesters')}"
+ p:attestationClaimsValidator="#{getObject('openidvci.ClientAttestationClaimsValidator') ?: getObject('openidvci.DefaultClientAttestationClaimsValidator')}"
+ p:proofClaimsValidator="#{getObject('openidvci.ClientAttestationPoPClaimsValidator') ?: getObject('openidvci.DefaultClientAttestationPoPClaimsValidator')}">
+ <property name="signatureAlgorithms">
+ <bean parent="shibboleth.CommaDelimStringArray"
+ c:_0="#{'%{openidvci.attestation.signingAlgorithms:ES256}'.trim()}" />
+ </property>
+ </bean>
+
+ <bean id="openidvci.DefaultClientAttestationClaimsValidator" lazy-init="true"
+ class="net.shibboleth.oidc.security.jwt.claims.impl.ChainingJWTClaimsValidator"
+ p:id="openidvci.DefaultClientAttestationClaimsValidator">
+ <property name="claimValidators">
+ <list>
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.RequiredClaimsValidator"
+ p:id="openidvci.ClientAttestation.RequiredClaimsValidator">
+ <property name="requiredClaims">
+ <list>
+ <value>sub</value>
+ <value>exp</value>
+ <value>iat</value>
+ <value>cnf</value>
+ </list>
+ </property>
+ </bean>
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.ExpiryClaimsValidator"
+ p:id="openidvci.ClientAttestation.ExpiryClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}" />
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.NotBeforeClaimsValidator"
+ p:id="openidvci.ClientAttestation.NotBeforeClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}" />
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.IssuedAtClaimsValidator"
+ p:id="openidvci.ClientAttestation.IssuedAtClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}"
+ p:messageLifetime="%{openidvci.attestation.maxAge:P365D}"
+ p:requiredRule="true" />
+ </list>
+ </property>
+ </bean>
+
+ <bean id="openidvci.DefaultClientAttestationPoPClaimsValidator" lazy-init="true"
+ class="net.shibboleth.oidc.security.jwt.claims.impl.ChainingJWTClaimsValidator"
+ p:id="openidvci.DefaultClientAttestationPoPClaimsValidator">
+ <property name="claimValidators">
+ <list>
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.RequiredClaimsValidator"
+ p:id="openidvci.ClientAttestationPoP.RequiredClaimsValidator">
+ <property name="requiredClaims">
+ <list>
+ <value>aud</value>
+ <value>jti</value>
+ <value>iat</value>
+ </list>
+ </property>
+ </bean>
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.IssuedAtClaimsValidator"
+ p:id="openidvci.ClientAttestationPoP.IssuedAtClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}"
+ p:messageLifetime="%{openidvci.attestation.proofLifetime:PT5M}"
+ p:requiredRule="true" />
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.NotBeforeClaimsValidator"
+ p:id="openidvci.ClientAttestationPoP.NotBeforeClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}" />
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.ExpiryClaimsValidator"
+ p:id="openidvci.ClientAttestationPoP.ExpiryClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}" />
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.AudienceClaimsValidator"
+ p:id="openidvci.ClientAttestationPoP.AudienceClaimsValidator"
+ p:extraAudienceValidation="true">
+ <property name="audienceLookupStrategy">
+ <bean class="net.shibboleth.shared.logic.BiFunctionSupport" factory-method="forFunctionOfFirstArg"
+ c:_0="#{T(net.shibboleth.shared.logic.FunctionSupport).constant(getObject('shibboleth.oidc.issuer'))}" />
+ </property>
+ </bean>
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.JWTIdentifierClaimsValidator"
+ p:id="openidvci.ClientAttestationPoP.JWTIdentifierClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}"
+ p:replayCache-ref="shibboleth.ReplayCache"
+ p:replayCacheRecordLifetime="#{T(java.time.Duration).parse('%{openidvci.attestation.proofLifetime:PT5M}').plus(T(java.time.Duration).parse('%{openidvci.attestation.clockSkew:PT5M}').multipliedBy(2))}"
+ p:maxReplayCacheRecordLifetime="#{T(java.time.Duration).parse('%{openidvci.attestation.proofLifetime:PT5M}').plus(T(java.time.Duration).parse('%{openidvci.attestation.clockSkew:PT5M}').multipliedBy(2))}">
+ <property name="replayCacheKeyCalculationStrategy">
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.CalculateSha256DigestForLongKeyFunction" />
+ </property>
+ </bean>
+ </list>
+ </property>
+ </bean>
<bean id="openidvci.TokenManipulationStrategy"
class="org.geant.shibboleth.plugin.openidvci.profile.logic.OpenIDVCITokenManipulationStrategy"
p:clientInstanceKeyLookupStrategy-ref="openidvci.ClientInstanceKeyThumbprintLookup" />
<bean id="openidvci.ClientInstanceKeyThumbprintLookup"
- class="org.geant.shibboleth.plugin.openidvci.profile.context.navigate.ClientInstanceKeyThumbprintLookupFunction"
- c:supplier-ref="shibboleth.HttpServletRequestSupplier" />
+ class="org.geant.shibboleth.plugin.openidvci.profile.context.navigate.ClientInstanceKeyThumbprintLookupFunction" />
<bean id="openidvci.AllowedCredentialConfigurationsLookup" lazy-init="true"
class="org.geant.shibboleth.plugin.openidvci.profile.logic.AllowedCredentialConfigurationsLookupFunction"
diff --git a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-beans.xml b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-beans.xml
index 6a0469b..827ef7a 100644
--- a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-beans.xml
+++ b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-beans.xml
@@ -1,13 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Actions of this plugin for the authn/OpenIDVCIClient flow. Every other bean of the flow is
- the one of authn/OAuth2Client of the OpenID Connect Provider plugin, imported as it is.
+ Beans of this plugin for the authn/OpenIDVCIClient flow. Every other bean of the flow is
+ the one of authn/OAuth2Client of the Shibboleth OIDC Common library, imported as it is.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
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"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
default-init-method="initialize"
default-destroy-method="destroy">
@@ -18,6 +20,71 @@
<bean id="OpenIDVCIValidateClientAuthenticationType"
class="org.geant.shibboleth.plugin.openidvci.authn.impl.ValidateClientAuthenticationType" scope="prototype"
- p:httpServletRequestSupplier-ref="shibboleth.HttpServletRequestSupplier" />
+ p:attestationPresentCondition-ref="OpenIDVCIClientAttestationPresent" />
+
+ <bean id="OpenIDVCIValidateClientAttestation" parent="ValidateCredentials" scope="prototype"
+ p:populateAuditContextAction="#{%{idp.authn.OAuth2Client.audit.enabled:%{idp.authn.audit.enabled:false}} ? getObject('OpenIDVCIClientAttestation.PopulateAuditContext') : null}">
+ <property name="validators">
+ <list>
+ <ref bean="openidvci.ClientAttestationValidator" />
+ </list>
+ </property>
+ </bean>
+
+ <bean id="OpenIDVCIClientAttestation.PopulateAuditContext" parent="shibboleth.authn.AbstractPopulateAuditContext"
+ lazy-init="true" p:fieldExtractors-ref="OpenIDVCIClientAttestation.AuditExtractors" />
+
+ <bean id="OpenIDVCIClientAttestation.AuditExtractors" parent="shibboleth.authn.DefaultAuditExtractors"
+ lazy-init="true" class="org.springframework.beans.factory.config.MapFactoryBean">
+ <property name="sourceMap">
+ <map merge="true">
+ <entry>
+ <key>
+ <util:constant static-field="net.shibboleth.idp.saml.profile.SAMLAuditFields.REQUEST_ID"/>
+ </key>
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation-PoP"
+ c:claim="jti" />
+ </entry>
+ <entry>
+ <key>
+ <util:constant static-field="net.shibboleth.idp.saml.profile.SAMLAuditFields.REQUEST_ISSUE_INSTANT"/>
+ </key>
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation-PoP"
+ c:claim="iat" />
+ </entry>
+ <entry key="aud">
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation-PoP"
+ c:claim="aud" />
+ </entry>
+ <entry key="iss">
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation"
+ c:claim="iss" />
+ </entry>
+ <entry key="sub">
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation"
+ c:claim="sub" />
+ </entry>
+ <entry key="exp">
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation"
+ c:claim="exp" />
+ </entry>
+ <entry key="iat">
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationClaimsAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" c:name="OAuth-Client-Attestation"
+ c:claim="iat" />
+ </entry>
+ <entry key="typ">
+ <bean class="org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationTypeHeaderAuditExtractor"
+ c:supplier-ref="shibboleth.HttpServletRequestSupplier" />
+ </entry>
+ </map>
+ </property>
+ </bean>
</beans>
diff --git a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-flow.xml b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-flow.xml
index 8d9cd92..2ad924f 100644
--- a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-flow.xml
+++ b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/authn/OpenIDVCIClient/OpenIDVCIClient-flow.xml
@@ -1,22 +1,22 @@
<!--
Derived from META-INF/net/shibboleth/idp/flows/authn/OAuth2Client/OAuth2Client-flow.xml
- of the Shibboleth OpenID Connect Provider plugin, Apache License 2.0, modified by GÉANT.
+ of the Shibboleth OIDC Common library, Apache License 2.0, modified by GÉANT.
-->
<!--
- The authn/OAuth2Client flow of the OpenID Connect Provider plugin with the Wallet Attestation
- of OpenID4VCI as a client authentication method. Idea is to merge this flow and the one of
- the OP to one at some point in future.
+ The authn/OAuth2Client flow of the Shibboleth OIDC Common library with the Wallet Attestation
+ of OpenID4VCI as a client authentication method.
- The beans of the OP are imported as they are and referred to by their id, the actions of this
- plugin are the two below.
+ The beans of that flow are imported as they are and referred to by their id, the actions of this
+ plugin are the ones below.
ADDED
- CheckClientAttestation state branches a request carrying the attestation headers aside
- AttestedClient state that branch, no client authentication of the OP to extract
+ CheckClientAttestation state branches a request carrying an attestation header aside
+ AttestedClient state that branch, validated by the client attestation only
OpenIDVCIValidateClientAuthenticationType reads 'attest_jwt_client_auth' as the method
+ OpenIDVCIValidateClientAttestation ValidateCredentials of the client attestation
REPLACED
- ValidateClientAuthenticationType of the OP, by the action above
+ ValidateClientAuthenticationType of that flow, by the action above
-->
<flow xmlns="http://www.springframework.org/schema/webflow"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
@@ -37,21 +37,18 @@
<action-state id="StandardClient">
<evaluate expression="ExtractClientAuthenticationFromRequest" />
+ <evaluate expression="OpenIDVCIValidateClientAuthenticationType" />
+ <evaluate expression="ValidateJWTSignature"/>
+ <evaluate expression="ValidateCredentials" />
+ <evaluate expression="PopulateSubjectCanonicalizationContext" />
<evaluate expression="'proceed'" />
- <transition on="proceed" to="ValidateClient" />
+ <transition on="proceed" to="CallSubjectCanonicalization" />
</action-state>
<action-state id="AttestedClient">
- <evaluate expression="'proceed'" />
-
- <transition on="proceed" to="ValidateClient" />
- </action-state>
-
- <action-state id="ValidateClient">
<evaluate expression="OpenIDVCIValidateClientAuthenticationType" />
- <evaluate expression="ValidateJWTSignature"/>
- <evaluate expression="ValidateCredentials" />
+ <evaluate expression="OpenIDVCIValidateClientAttestation" />
<evaluate expression="PopulateSubjectCanonicalizationContext" />
<evaluate expression="'proceed'" />
@@ -70,6 +67,7 @@
<transition on="InvalidCredentials" to="ReselectFlow" />
<transition on="RequestUnsupported" to="ReselectFlow" />
<transition on="UnknownUsername" to="ReselectFlow" />
+ <transition on="AccessDenied" to="ReselectFlow" />
</global-transitions>
<bean-import resource="classpath:/META-INF/net/shibboleth/idp/flows/authn/OAuth2Client/OAuth2Client-beans.xml" />
diff --git a/openid-vci-impl/src/main/resources/org/geant/shibboleth/plugin/openidvci/conf/openid-vci.properties b/openid-vci-impl/src/main/resources/org/geant/shibboleth/plugin/openidvci/conf/openid-vci.properties
index e2bcc2b..bb84f25 100644
--- a/openid-vci-impl/src/main/resources/org/geant/shibboleth/plugin/openidvci/conf/openid-vci.properties
+++ b/openid-vci-impl/src/main/resources/org/geant/shibboleth/plugin/openidvci/conf/openid-vci.properties
@@ -11,8 +11,8 @@
openidvci.issuer =
# Regular expression matching OpenID VCI login flows to enable.
-# For most deployments, the default is sufficient to accomodate a variety of methods
-#openidvci.authn.flows = OAuth2Client
+# For most deployments, the default is sufficient to accommodate a variety of methods
+#openidvci.authn.flows = OpenIDVCIClient
# Storage for Credential Offers when pre-authorized codes are stored. Requires server-side storage
#openidvci.StorageService = shibboleth.StorageService
@@ -148,6 +148,10 @@ openidvci.status-list.index.permutationKey = change_this_to_secret
#openidvci.attestation.clockSkew = PT5M
# Time a proof of possession of a Wallet Attestation is accepted after its 'iat'
#openidvci.attestation.proofLifetime = PT5M
+# Time a Wallet Attestation is accepted after its 'iat', its 'exp' permitting
+#openidvci.attestation.maxAge = P365D
+# Signature algorithms accepted of a Wallet Attestation and of its proof of possession, comma-separated
+#openidvci.attestation.signingAlgorithms = ES256
# Settings for the loggingId of each flow
#openidvci.logging.credentials = OpenID.VCI.Credentials
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationAuditExtractorTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationAuditExtractorTest.java
new file mode 100644
index 0000000..fe58aa4
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationAuditExtractorTest.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2025, GÉANT
+ *
+ * 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 org.geant.shibboleth.plugin.openidvci.authn.impl;
+
+import java.util.Date;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.jose.JWSAlgorithm;
+import com.nimbusds.jose.JWSHeader;
+import com.nimbusds.jose.crypto.ECDSASigner;
+import com.nimbusds.jose.jwk.Curve;
+import com.nimbusds.jose.jwk.ECKey;
+import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.SignedJWT;
+
+/** Unit tests for {@link ClientAttestationClaimsAuditExtractor} and {@link ClientAttestationTypeHeaderAuditExtractor}.
+ */
+public class ClientAttestationAuditExtractorTest {
+
+ private MockHttpServletRequest request;
+
+ private ECKey key;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ request = new MockHttpServletRequest();
+ key = new ECKeyGenerator(Curve.P_256).generate();
+ }
+
+ private String jwt(final JWSHeader header, final JWTClaimsSet claims) throws Exception {
+ final SignedJWT jwt = new SignedJWT(header, claims);
+ jwt.sign(new ECDSASigner(key));
+ return jwt.serialize();
+ }
+
+ private ClientAttestationClaimsAuditExtractor extractor(final String header, final String claim) {
+ return new ClientAttestationClaimsAuditExtractor(() -> request, header, claim);
+ }
+
+ @Test
+ public void testClaims() throws Exception {
+ final Date issued = new Date(1_700_000_000_000L);
+ final JWSHeader.Builder header = new JWSHeader.Builder(JWSAlgorithm.ES256);
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER,
+ jwt(header.type(ClientAttestationCredentialValidator.ATTESTATION_TYPE).build(),
+ new JWTClaimsSet.Builder().subject("wallet").issueTime(issued).build()));
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER,
+ jwt(header.type(ClientAttestationCredentialValidator.POP_TYPE).build(),
+ new JWTClaimsSet.Builder().jwtID("pop-1").build()));
+ final ProfileRequestContext prc = new ProfileRequestContext();
+ Assert.assertEquals(extractor(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "sub").apply(prc),
+ "wallet");
+ Assert.assertEquals(extractor(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "iat").apply(prc),
+ issued.toInstant().toString());
+ Assert.assertEquals(extractor(ClientAttestationCredentialValidator.POP_HEADER, "jti").apply(prc), "pop-1");
+ Assert.assertNull(extractor(ClientAttestationCredentialValidator.POP_HEADER, "aud").apply(prc));
+ Assert.assertEquals(new ClientAttestationTypeHeaderAuditExtractor(() -> request).apply(prc),
+ ClientAttestationCredentialValidator.ATTESTATION_TYPE.getType());
+ }
+
+ @Test
+ public void testNoHeader() {
+ final ProfileRequestContext prc = new ProfileRequestContext();
+ Assert.assertNull(extractor(ClientAttestationCredentialValidator.POP_HEADER, "jti").apply(prc));
+ Assert.assertNull(new ClientAttestationTypeHeaderAuditExtractor(() -> request).apply(prc));
+ }
+
+ @Test
+ public void testNotJWT() {
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "not-a-jwt");
+ final ProfileRequestContext prc = new ProfileRequestContext();
+ Assert.assertNull(extractor(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "sub").apply(prc));
+ Assert.assertNull(new ClientAttestationTypeHeaderAuditExtractor(() -> request).apply(prc));
+ }
+
+ @Test
+ public void testNoRequest() {
+ Assert.assertNull(new ClientAttestationClaimsAuditExtractor(() -> null,
+ ClientAttestationCredentialValidator.POP_HEADER, "jti").apply(new ProfileRequestContext()));
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidatorTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidatorTest.java
index 75a1192..6ef2db0 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidatorTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationCredentialValidatorTest.java
@@ -17,12 +17,16 @@
package org.geant.shibboleth.plugin.openidvci.authn.impl;
import java.io.InputStream;
+import java.net.URI;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
+import java.time.Duration;
import java.time.Instant;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@@ -47,11 +51,30 @@ import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
-
+import com.nimbusds.oauth2.sdk.AuthorizationCode;
+import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant;
+import com.nimbusds.oauth2.sdk.AuthorizationRequest;
+import com.nimbusds.oauth2.sdk.PushedAuthorizationRequest;
+import com.nimbusds.oauth2.sdk.ResponseType;
+import com.nimbusds.oauth2.sdk.TokenRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+
+import net.shibboleth.idp.authn.AuthnEventIds;
+import net.shibboleth.idp.authn.CredentialValidator.ErrorHandler;
import net.shibboleth.idp.authn.context.AuthenticationContext;
import net.shibboleth.idp.authn.principal.UsernamePrincipal;
+import net.shibboleth.oidc.jwt.claims.AbstractClaimsValidator;
+import net.shibboleth.oidc.jwt.claims.ClaimsValidator;
import net.shibboleth.oidc.jwt.claims.JWTValidationException;
+import net.shibboleth.oidc.security.jwt.claims.impl.AudienceClaimsValidator;
+import net.shibboleth.oidc.security.jwt.claims.impl.ChainingJWTClaimsValidator;
+import net.shibboleth.oidc.security.jwt.claims.impl.ExpiryClaimsValidator;
+import net.shibboleth.oidc.security.jwt.claims.impl.IssuedAtClaimsValidator;
+import net.shibboleth.oidc.security.jwt.claims.impl.JWTIdentifierClaimsValidator;
+import net.shibboleth.oidc.security.jwt.claims.impl.NotBeforeClaimsValidator;
+import net.shibboleth.oidc.security.jwt.claims.impl.RequiredClaimsValidator;
import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.component.ComponentInitializationException;
/** Unit tests for {@link ClientAttestationCredentialValidator}. */
public class ClientAttestationCredentialValidatorTest {
@@ -60,6 +83,8 @@ public class ClientAttestationCredentialValidatorTest {
private static final String AUDIENCE = "https://issuer.example.org";
+ private static final Duration SKEW = Duration.ofMinutes(5);
+
private X509Certificate signerCertificate;
private PrivateKey signerKey;
@@ -74,6 +99,8 @@ public class ClientAttestationCredentialValidatorTest {
private ClientAttestationCredentialValidator validator;
+ private Set<String> seen;
+
private X509Certificate read(final String name) throws Exception {
try (InputStream in = getClass().getResourceAsStream("/credentials/" + name)) {
return X509Support.decodeCertificate(in.readAllBytes());
@@ -90,16 +117,67 @@ public class ClientAttestationCredentialValidatorTest {
request = new MockHttpServletRequest();
prc = new ProfileRequestContext();
authnContext = new AuthenticationContext();
- final Set<String> seen = new HashSet<>();
+ seen = new HashSet<>();
validator = new ClientAttestationCredentialValidator();
validator.setId("test");
validator.setTrustAnchors(CollectionSupport.listOf(new BasicX509Credential(read("attestation-ca.crt"))));
validator.setHttpServletRequestSupplier(() -> request);
- validator.setReplayCache((context, key, expires) -> seen.add(context + key));
- validator.setAudienceLookupStrategy(context -> AUDIENCE);
+ validator.setAttestationClaimsValidator(chain(required("sub", "exp", "iat", "cnf"), expiry(), notBefore(),
+ issuedAt(Duration.ofDays(365))));
+ final AudienceClaimsValidator audience = new AudienceClaimsValidator();
+ audience.setAudienceLookupStrategy((context, claims) -> AUDIENCE);
+ audience.setExtraAudienceValidation(true);
+ final JWTIdentifierClaimsValidator identifier = new JWTIdentifierClaimsValidator();
+ identifier.setClockSkew(SKEW);
+ identifier.setReplayCache((context, key, expires) -> seen.add(context + key));
+ identifier.setReplayCacheRecordLifetime(Duration.ofMinutes(15));
+ validator.setProofClaimsValidator(chain(required("aud", "jti", "iat"), issuedAt(Duration.ofMinutes(5)),
+ notBefore(), expiry(), init(audience), init(identifier)));
validator.initialize();
}
+ private static <T extends AbstractClaimsValidator> T init(final T claimsValidator)
+ throws ComponentInitializationException {
+ claimsValidator.setId(claimsValidator.getClass().getSimpleName());
+ claimsValidator.initialize();
+ return claimsValidator;
+ }
+
+ private static ClaimsValidator chain(final ClaimsValidator... validators)
+ throws ComponentInitializationException {
+ final ChainingJWTClaimsValidator chain = new ChainingJWTClaimsValidator();
+ chain.setId("chain");
+ chain.setClaimValidators(new ArrayList<>(List.of(validators)));
+ chain.initialize();
+ return chain;
+ }
+
+ private static RequiredClaimsValidator required(final String... claims) throws ComponentInitializationException {
+ final RequiredClaimsValidator required = new RequiredClaimsValidator();
+ required.setRequiredClaims(List.of(claims));
+ return init(required);
+ }
+
+ private static ExpiryClaimsValidator expiry() throws ComponentInitializationException {
+ final ExpiryClaimsValidator expiry = new ExpiryClaimsValidator();
+ expiry.setClockSkew(SKEW);
+ return init(expiry);
+ }
+
+ private static NotBeforeClaimsValidator notBefore() throws ComponentInitializationException {
+ final NotBeforeClaimsValidator notBefore = new NotBeforeClaimsValidator();
+ notBefore.setClockSkew(SKEW);
+ return init(notBefore);
+ }
+
+ private static IssuedAtClaimsValidator issuedAt(final Duration lifetime) throws ComponentInitializationException {
+ final IssuedAtClaimsValidator issuedAt = new IssuedAtClaimsValidator();
+ issuedAt.setClockSkew(SKEW);
+ issuedAt.setMessageLifetime(lifetime);
+ issuedAt.setRequiredRule(true);
+ return init(issuedAt);
+ }
+
private String attestation(final JWTClaimsSet.Builder claims) throws Exception {
final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.ES256)
.type(ClientAttestationCredentialValidator.ATTESTATION_TYPE)
@@ -139,6 +217,15 @@ public class ClientAttestationCredentialValidatorTest {
Assert.assertTrue(subject.getPrincipals().contains(new UsernamePrincipal(CLIENT_ID)));
}
+ @Test
+ public void testAttestationInPublicCredentials() throws Exception {
+ final Subject subject = validate(attestation(attestationClaims()), pop(popClaims()));
+ final Set<SignedJWT> credentials = subject.getPublicCredentials(SignedJWT.class);
+ Assert.assertEquals(credentials.size(), 1);
+ Assert.assertEquals(credentials.iterator().next().getHeader().getType(),
+ ClientAttestationCredentialValidator.ATTESTATION_TYPE);
+ }
+
@Test
public void testIssuersAndExpiration() throws Exception {
final Subject subject = validate(attestation(attestationClaims().issuer("https://wallet-provider.example.org")),
@@ -151,6 +238,18 @@ public class ClientAttestationCredentialValidatorTest {
Assert.assertNull(validator.validate(prc, authnContext, null, null));
}
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testAttestationHeaderOnly() throws Exception {
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, attestation(attestationClaims()));
+ validator.validate(prc, authnContext, null, null);
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testPopHeaderOnly() throws Exception {
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, pop(popClaims()));
+ validator.validate(prc, authnContext, null, null);
+ }
+
@Test(expectedExceptions = JWTValidationException.class)
public void testProofWithoutIssueTime() throws Exception {
validate(attestation(attestationClaims()), pop(popClaims().issueTime(null)));
@@ -179,6 +278,157 @@ public class ClientAttestationCredentialValidatorTest {
validate(attestation(attestationClaims()), pop(popClaims().audience("https://other.example.org")));
}
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testProofSeveralAudiences() throws Exception {
+ validate(attestation(attestationClaims()),
+ pop(popClaims().audience(List.of(AUDIENCE, "https://other.example.org"))));
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testAttestationTooOld() throws Exception {
+ validate(attestation(attestationClaims().issueTime(Date.from(Instant.now().minus(Duration.ofDays(400))))),
+ pop(popClaims()));
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testPushedAuthorizationRequestOfAnotherClient() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(pushed("other-client"));
+ validate(attestation(attestationClaims()), pop(popClaims()));
+ }
+
+ @Test
+ public void testPushedAuthorizationRequestOfTheClient() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(pushed(CLIENT_ID));
+ Assert.assertNotNull(validate(attestation(attestationClaims()), pop(popClaims())));
+ }
+
+ @Test
+ public void testIdentifierNotSpentForAnotherClient() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(pushed("other-client"));
+ try {
+ validate(attestation(attestationClaims()), pop(popClaims()));
+ Assert.fail("Validation must fail");
+ } catch (final JWTValidationException e) {
+ Assert.assertTrue(seen.isEmpty());
+ }
+ }
+
+ private ClientAttestationCredentialValidator withAttesters(final Map<String, List<String>> names)
+ throws Exception {
+ final ClientAttestationCredentialValidator pinned = new ClientAttestationCredentialValidator();
+ pinned.setId("pinned");
+ pinned.setTrustAnchors(CollectionSupport.listOf(new BasicX509Credential(read("attestation-ca.crt"))));
+ pinned.setHttpServletRequestSupplier(() -> request);
+ pinned.setAttestationClaimsValidator(chain(required("sub")));
+ pinned.setProofClaimsValidator(chain(required("aud")));
+ pinned.setAttesters(names);
+ pinned.initialize();
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, attestation(attestationClaims()));
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, pop(popClaims()));
+ return pinned;
+ }
+
+ @Test
+ public void testAttesterOfClient() throws Exception {
+ Assert.assertNotNull(withAttesters(Map.of(CLIENT_ID, List.of("O=Other", "cn=Wallet Provider, o=Test")))
+ .validate(prc, authnContext, null, null));
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testOtherAttesterOfClient() throws Exception {
+ withAttesters(Map.of(CLIENT_ID, List.of("CN=Other Provider,O=Test"))).validate(prc, authnContext, null, null);
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testClientNotListed() throws Exception {
+ withAttesters(Map.of("other-client", List.of("CN=Wallet Provider,O=Test")))
+ .validate(prc, authnContext, null, null);
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testNoClientListed() throws Exception {
+ withAttesters(Map.of()).validate(prc, authnContext, null, null);
+ }
+
+ @Test
+ public void testAttestersNotDefined() throws Exception {
+ Assert.assertNotNull(withAttesters(null).validate(prc, authnContext, null, null));
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testNoAttestersOfClient() throws Exception {
+ withAttesters(Map.of(CLIENT_ID, List.of())).validate(prc, authnContext, null, null);
+ }
+
+ @Test(expectedExceptions = ComponentInitializationException.class)
+ public void testAttesterNoSubjectName() throws Exception {
+ withAttesters(Map.of(CLIENT_ID, List.of("not a subject name")));
+ }
+
+ @Test
+ public void testAttesterWithObjectIdentifier() throws Exception {
+ Assert.assertNotNull(withAttesters(Map.of("other-client",
+ List.of("C=EU,O=Test,2.5.4.97=#0c0f4c454945552d313233343536373839,CN=Wallet Provider PRD 01"))));
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testSubjectNotString() throws Exception {
+ validate(attestation(attestationClaims().claim("sub", 12345)), pop(popClaims()));
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testAlgorithmNotAccepted() throws Exception {
+ final ClientAttestationCredentialValidator strict = new ClientAttestationCredentialValidator();
+ strict.setId("strict");
+ strict.setTrustAnchors(CollectionSupport.listOf(new BasicX509Credential(read("attestation-ca.crt"))));
+ strict.setHttpServletRequestSupplier(() -> request);
+ strict.setAttestationClaimsValidator(chain(required("sub")));
+ strict.setProofClaimsValidator(chain(required("aud")));
+ strict.setSignatureAlgorithms(Set.of("ES384"));
+ strict.initialize();
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, attestation(attestationClaims()));
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, pop(popClaims()));
+ strict.validate(prc, authnContext, null, null);
+ }
+
+ @Test(expectedExceptions = JWTValidationException.class)
+ public void testTokenRequestOfAnotherClient() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(new TokenRequest(new URI("https://issuer.example.org/token"),
+ new ClientID("other-client"), new AuthorizationCodeGrant(new AuthorizationCode("code"),
+ new URI("https://wallet.example.org/cb"))));
+ validate(attestation(attestationClaims()), pop(popClaims()));
+ }
+
+ @Test
+ public void testFailureReportedAsInvalidCredentials() throws Exception {
+ final List<String> events = new ArrayList<>();
+ final ErrorHandler handler = new ErrorHandler() {
+ public void handleError(final ProfileRequestContext profileRequestContext,
+ final AuthenticationContext authenticationContext, final Exception e, final String eventId) {
+ events.add(eventId);
+ }
+
+ public void handleError(final ProfileRequestContext profileRequestContext,
+ final AuthenticationContext authenticationContext, final String message, final String eventId) {
+ events.add(eventId);
+ }
+ };
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, attestation(attestationClaims()));
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER,
+ pop(popClaims().audience("https://other.example.org")));
+ try {
+ validator.validate(prc, authnContext, null, handler);
+ Assert.fail("Validation must fail");
+ } catch (final JWTValidationException e) {
+ Assert.assertEquals(events, List.of(AuthnEventIds.INVALID_CREDENTIALS));
+ }
+ }
+
+ private PushedAuthorizationRequest pushed(final String clientId) throws Exception {
+ return new PushedAuthorizationRequest(new URI("https://issuer.example.org/par"),
+ new AuthorizationRequest.Builder(new ResponseType("code"), new ClientID(clientId)).build());
+ }
+
@Test(expectedExceptions = JWTValidationException.class)
public void testProofReplayed() throws Exception {
final String attestation = attestation(attestationClaims());
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicateTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicateTest.java
new file mode 100644
index 0000000..e089f29
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ClientAttestationPresentPredicateTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2025, GÉANT
+ *
+ * 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 org.geant.shibboleth.plugin.openidvci.authn.impl;
+
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/** Unit tests for {@link ClientAttestationPresentPredicate}. */
+public class ClientAttestationPresentPredicateTest {
+
+ private MockHttpServletRequest request;
+
+ private ClientAttestationPresentPredicate predicate;
+
+ @BeforeMethod
+ protected void setUp() {
+ request = new MockHttpServletRequest();
+ predicate = new ClientAttestationPresentPredicate(() -> request);
+ }
+
+ @Test
+ public void testNoHeaders() {
+ Assert.assertFalse(predicate.test(new ProfileRequestContext()));
+ }
+
+ @Test
+ public void testBothHeaders() {
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "attestation");
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, "pop");
+ Assert.assertTrue(predicate.test(new ProfileRequestContext()));
+ }
+
+ @Test
+ public void testAttestationHeaderOnly() {
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "attestation");
+ Assert.assertTrue(predicate.test(new ProfileRequestContext()));
+ }
+
+ @Test
+ public void testPopHeaderOnly() {
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, "pop");
+ Assert.assertTrue(predicate.test(new ProfileRequestContext()));
+ }
+
+ @Test
+ public void testNoRequest() {
+ Assert.assertFalse(new ClientAttestationPresentPredicate(() -> null).test(new ProfileRequestContext()));
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationTypeTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationTypeTest.java
new file mode 100644
index 0000000..44e9d0b
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/ValidateClientAuthenticationTypeTest.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2025, GÉANT
+ *
+ * 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 org.geant.shibboleth.plugin.openidvci.authn.impl;
+
+import java.net.URI;
+import java.util.Date;
+import java.util.Set;
+
+import org.opensaml.profile.action.EventIds;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.webflow.execution.Event;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.oauth2.sdk.AuthorizationCode;
+import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant;
+import com.nimbusds.oauth2.sdk.TokenRequest;
+import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod;
+import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
+import com.nimbusds.oauth2.sdk.auth.Secret;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+import com.nimbusds.openid.connect.sdk.rp.OIDCClientInformation;
+import com.nimbusds.openid.connect.sdk.rp.OIDCClientMetadata;
+
+import net.shibboleth.idp.authn.context.AuthenticationContext;
+import net.shibboleth.idp.profile.context.navigate.WebflowRequestContextProfileRequestContextLookup;
+import net.shibboleth.idp.profile.testing.ActionTestingSupport;
+import net.shibboleth.idp.profile.testing.RequestContextBuilder;
+import net.shibboleth.oidc.metadata.context.OIDCMetadataContext;
+
+/** Unit tests for {@link ValidateClientAuthenticationType}. */
+public class ValidateClientAuthenticationTypeTest {
+
+ private static final ClientID CLIENT_ID = new ClientID("wallet");
+
+ private MockHttpServletRequest request;
+
+ private Set<ClientAuthenticationMethod> enabledMethods;
+
+ private ValidateClientAuthenticationType action;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ request = new MockHttpServletRequest();
+ enabledMethods = Set.of(ValidateClientAuthenticationType.ATTEST_JWT_CLIENT_AUTH);
+ action = new ValidateClientAuthenticationType();
+ action.setAttestationPresentCondition(new ClientAttestationPresentPredicate(() -> request));
+ action.setTokenEndpointAuthMethodsLookupStrategy(prc -> enabledMethods);
+ action.initialize();
+ }
+
+ private TokenRequest message(final boolean withSecret) throws Exception {
+ final AuthorizationCodeGrant grant =
+ new AuthorizationCodeGrant(new AuthorizationCode("code"), new URI("https://wallet.example.org/cb"));
+ final URI endpoint = new URI("https://issuer.example.org/token");
+ return withSecret ? new TokenRequest(endpoint, new ClientSecretBasic(CLIENT_ID, new Secret("secret")), grant)
+ : new TokenRequest(endpoint, CLIENT_ID, grant);
+ }
+
+ private Event execute(final TokenRequest message, final ClientAuthenticationMethod registered)
+ throws Exception {
+ final RequestContext rc = new RequestContextBuilder().setInboundMessage(message).buildRequestContext();
+ final ProfileRequestContext prc = new WebflowRequestContextProfileRequestContextLookup().apply(rc);
+ prc.addSubcontext(new AuthenticationContext());
+ if (registered != null) {
+ final OIDCClientMetadata metadata = new OIDCClientMetadata();
+ metadata.setTokenEndpointAuthMethod(registered);
+ final OIDCMetadataContext oidcContext = new OIDCMetadataContext();
+ oidcContext.setClientInformation(new OIDCClientInformation(CLIENT_ID, new Date(), metadata, null));
+ prc.ensureInboundMessageContext().addSubcontext(oidcContext);
+ }
+ return action.execute(rc);
+ }
+
+ private void attest() {
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "attestation");
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, "pop");
+ }
+
+ @Test
+ public void testAttestation() throws Exception {
+ attest();
+ ActionTestingSupport.assertProceedEvent(
+ execute(message(false), ValidateClientAuthenticationType.ATTEST_JWT_CLIENT_AUTH));
+ }
+
+ @Test
+ public void testAttestationHeaderOnly() throws Exception {
+ request.addHeader(ClientAttestationCredentialValidator.ATTESTATION_HEADER, "attestation");
+ ActionTestingSupport.assertProceedEvent(execute(message(false), null));
+ }
+
+ @Test
+ public void testPopHeaderOnly() throws Exception {
+ request.addHeader(ClientAttestationCredentialValidator.POP_HEADER, "pop");
+ ActionTestingSupport.assertProceedEvent(execute(message(false), null));
+ }
+
+ @Test
+ public void testAttestationNotEnabled() throws Exception {
+ attest();
+ enabledMethods = Set.of(ClientAuthenticationMethod.NONE);
+ ActionTestingSupport.assertEvent(execute(message(false), null), EventIds.ACCESS_DENIED);
+ }
+
+ @Test
+ public void testAttestationNotRegistered() throws Exception {
+ attest();
+ enabledMethods = Set.of(ValidateClientAuthenticationType.ATTEST_JWT_CLIENT_AUTH,
+ ClientAuthenticationMethod.NONE);
+ ActionTestingSupport.assertEvent(execute(message(false), ClientAuthenticationMethod.NONE),
+ EventIds.ACCESS_DENIED);
+ }
+
+ @Test
+ public void testAttestationAndSecret() throws Exception {
+ attest();
+ enabledMethods = Set.of(ValidateClientAuthenticationType.ATTEST_JWT_CLIENT_AUTH,
+ ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
+ ActionTestingSupport.assertEvent(execute(message(true), null), EventIds.ACCESS_DENIED);
+ }
+
+ @Test
+ public void testNoneWithoutHeaders() throws Exception {
+ enabledMethods = Set.of(ClientAuthenticationMethod.NONE);
+ ActionTestingSupport.assertProceedEvent(execute(message(false), ClientAuthenticationMethod.NONE));
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidatorTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidatorTest.java
new file mode 100644
index 0000000..27afe1a
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/authn/impl/WalletCredentialValidatorTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2025, GÉANT
+ *
+ * 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 org.geant.shibboleth.plugin.openidvci.authn.impl;
+
+import java.net.URI;
+
+import javax.security.auth.Subject;
+
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.common.contenttype.ContentType;
+import com.nimbusds.oauth2.sdk.AuthorizationCode;
+import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant;
+import com.nimbusds.oauth2.sdk.TokenRequest;
+import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
+import com.nimbusds.oauth2.sdk.auth.Secret;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+
+import net.shibboleth.idp.authn.context.AuthenticationContext;
+import net.shibboleth.idp.authn.principal.UsernamePrincipal;
+
+/** Unit tests for {@link WalletCredentialValidator}. */
+public class WalletCredentialValidatorTest {
+
+ private ProfileRequestContext prc;
+
+ private WalletCredentialValidator validator;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ prc = new ProfileRequestContext();
+ validator = new WalletCredentialValidator();
+ validator.setId("test");
+ validator.initialize();
+ }
+
+ private HTTPRequest request(final String body) throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("https://issuer.example.org"));
+ httpRequest.setContentType(ContentType.APPLICATION_URLENCODED.toString());
+ httpRequest.setBody(body);
+ return httpRequest;
+ }
+
+ private Subject validate() throws Exception {
+ return validator.validate(prc, new AuthenticationContext(), null, null);
+ }
+
+ @Test
+ public void testPublicClient() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(OpenIDVCITokenRequest
+ .parse(request("client_id=wallet&grant_type=refresh_token&refresh_token=abc&scope=openid")));
+ final Subject subject = validate();
+ Assert.assertNotNull(subject);
+ Assert.assertTrue(subject.getPrincipals().contains(new UsernamePrincipal("wallet")));
+ }
+
+ @Test
+ public void testAuthenticatedClient() throws Exception {
+ final HTTPRequest httpRequest = request("grant_type=client_credentials&scope=read");
+ httpRequest.setAuthorization(
+ new ClientSecretBasic(new ClientID("wallet"), new Secret("secret")).toHTTPAuthorizationHeader());
+ prc.ensureInboundMessageContext().setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ Assert.assertNull(validate());
+ }
+
+ @Test
+ public void testOtherMessage() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(new TokenRequest(new URI("https://issuer.example.org"),
+ new ClientID("wallet"), new AuthorizationCodeGrant(new AuthorizationCode("code"),
+ new URI("https://wallet.example.org/cb"))));
+ Assert.assertNull(validate());
+ }
+
+ @Test
+ public void testNoInboundMessageContext() throws Exception {
+ Assert.assertNull(validate());
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunctionTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunctionTest.java
index d0313df..cc95af7 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunctionTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/ClientInstanceKeyThumbprintLookupFunctionTest.java
@@ -16,8 +16,11 @@
package org.geant.shibboleth.plugin.openidvci.profile.context.navigate;
+import java.text.ParseException;
+
+import javax.security.auth.Subject;
+
import org.opensaml.profile.context.ProfileRequestContext;
-import org.springframework.mock.web.MockHttpServletRequest;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -27,50 +30,68 @@ import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import com.nimbusds.jose.util.Base64URL;
+import com.nimbusds.jwt.SignedJWT;
+
+import net.shibboleth.idp.authn.AuthenticationResult;
+import net.shibboleth.idp.authn.context.AuthenticationContext;
/**
* Tests for {@link ClientInstanceKeyThumbprintLookupFunction}.
*/
public class ClientInstanceKeyThumbprintLookupFunctionTest {
- private MockHttpServletRequest request;
+ private ProfileRequestContext prc;
+
+ private Subject subject;
private ClientInstanceKeyThumbprintLookupFunction lookup;
@BeforeMethod
public void setUp() {
- request = new MockHttpServletRequest();
- lookup = new ClientInstanceKeyThumbprintLookupFunction(() -> request);
+ prc = new ProfileRequestContext();
+ subject = new Subject();
+ prc.ensureSubcontext(AuthenticationContext.class)
+ .setAuthenticationResult(new AuthenticationResult("authn/OpenIDVCIClient", subject));
+ lookup = new ClientInstanceKeyThumbprintLookupFunction();
+ }
+
+ private static SignedJWT jwt(final String type, final String payload) throws ParseException {
+ return SignedJWT.parse(Base64URL.encode("{\"alg\":\"ES256\",\"typ\":\"" + type + "\"}") + "."
+ + Base64URL.encode(payload) + "." + Base64URL.encode("signature"));
}
- private static String attestation(final String payload) {
- return Base64URL.encode("{\"alg\":\"ES256\",\"typ\":\"oauth-client-attestation+jwt\"}") + "."
- + Base64URL.encode(payload) + "." + Base64URL.encode("signature");
+ private static String cnf(final ECKey key) {
+ return "{\"sub\":\"wallet\",\"cnf\":{\"jwk\":" + key.toPublicJWK().toJSONString() + "}}";
}
@Test
- public void thumbprintOfCnfKey() throws JOSEException {
+ public void thumbprintOfCnfKey() throws JOSEException, ParseException {
final ECKey key = new ECKeyGenerator(Curve.P_256).generate();
- request.addHeader("OAuth-Client-Attestation", attestation(
- "{\"sub\":\"wallet\",\"cnf\":{\"jwk\":" + key.toPublicJWK().toJSONString() + "}}"));
- Assert.assertEquals(lookup.apply(new ProfileRequestContext()), key.computeThumbprint().toString());
+ subject.getPublicCredentials().add(jwt("oauth-client-attestation+jwt", cnf(key)));
+ Assert.assertEquals(lookup.apply(prc), key.computeThumbprint().toString());
+ }
+
+ @Test
+ public void otherJWTIgnored() throws JOSEException, ParseException {
+ final ECKey key = new ECKeyGenerator(Curve.P_256).generate();
+ subject.getPublicCredentials().add(jwt("JWT", cnf(key)));
+ Assert.assertNull(lookup.apply(prc));
}
@Test
public void noAttestation() {
- Assert.assertNull(lookup.apply(new ProfileRequestContext()));
+ Assert.assertNull(lookup.apply(prc));
}
@Test
- public void noCnf() {
- request.addHeader("OAuth-Client-Attestation", attestation("{\"sub\":\"wallet\"}"));
+ public void noAuthenticationResult() {
Assert.assertNull(lookup.apply(new ProfileRequestContext()));
}
@Test
- public void unparseable() {
- request.addHeader("OAuth-Client-Attestation", "not a jwt");
- Assert.assertNull(lookup.apply(new ProfileRequestContext()));
+ public void noCnf() throws ParseException {
+ subject.getPublicCredentials().add(jwt("oauth-client-attestation+jwt", "{\"sub\":\"wallet\"}"));
+ Assert.assertNull(lookup.apply(prc));
}
}
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list