[java-idp-plugin-vci] 01/01: Token endpoint review, OP conventions, request parsing and pre-authorized code fixes, use_fresh_attestation
Codeberg
noreply at shibboleth.net
Wed Nov 25 16:08:22 UTC 2026
This is an automated email from the git hooks/post-receive script.
codeberg pushed a commit to branch dev/REVIEWTOKEN
in repository java-idp-plugin-vci.
View the commit online:
https://codeberg.org/Shibboleth/java-idp-plugin-vci/commit/5c12e682d0deae25de6454706fe8a301d96f2b3d
commit 5c12e682d0deae25de6454706fe8a301d96f2b3d
Author: Janne Lauros <janne.lauros at csc.fi>
AuthorDate: Wed Nov 25 18:07:54 2026 +0200
Token endpoint review, OP conventions, request parsing and pre-authorized code fixes, use_fresh_attestation
---
README.md | 8 +-
.../openidvci/messaging/error/OpenIDVCIError.java | 25 +--
.../openidvci/profile/OpenIDVCIEventIds.java | 7 +
.../impl/ClientAttestationCredentialValidator.java | 49 +++++
.../impl/OpenIDVCITokenRequestDecoder.java | 4 +-
.../AuthorizationDetailsLookupFunction.java | 20 +-
.../messaging/impl/OpenIDVCITokenRequest.java | 156 ++++++-------
.../impl/DefaultOpenIDVCITokenConfiguration.java | 6 +
.../navigate/APIRequestClientIDLookupFunction.java | 103 +--------
.../profile/impl/ConsumeCredentialOffer.java | 29 ++-
.../profile/impl/FilterPotentialCredentials.java | 6 +-
.../OpenIDVCIBuildTokenErrorResponseFromEvent.java | 69 ++++++
.../SetAuthorizationDetailsToResponseContext.java | 18 +-
.../profile/impl/UnwrapPreAuthorizedCode.java | 129 +++++------
.../profile/impl/ValidatePreAuthorizedCode.java | 6 +-
.../openidvci/profile/impl/ValidateTxCode.java | 18 +-
.../logic/OpenIDVCITokenManipulationStrategy.java | 2 +-
.../openidvci/storage/CredentialOfferCache.java | 80 +++----
.../META-INF/net.shibboleth.idp/postconfig.xml | 22 +-
.../idp/flows/openid/vci/token/token-beans.xml | 24 +-
.../idp/flows/openid/vci/token/token-flow.xml | 2 +-
.../ClientAttestationCredentialValidatorTest.java | 61 +++++-
.../impl/OpenIDVCITokenRequestDecoderTest.java | 24 ++
.../AuthorizationDetailsLookupFunctionTest.java | 57 +++++
.../messaging/impl/OpenIDVCITokenRequestTest.java | 191 ++++++++++------
.../APIRequestClientIDLookupFunctionTest.java | 104 +++++++++
.../profile/impl/ConsumeCredentialOfferTest.java | 134 +++++++++++
.../impl/FilterPotentialCredentialsTest.java | 34 +++
...nIDVCIBuildTokenErrorResponseFromEventTest.java | 82 +++++++
...tAuthorizationDetailsToResponseContextTest.java | 17 ++
.../profile/impl/UnwrapPreAuthorizedCodeTest.java | 244 +++++++++++++++++++++
.../impl/ValidatePreAuthorizedCodeTest.java | 110 ++++++++++
.../openidvci/profile/impl/ValidateTxCodeTest.java | 101 +++++++++
.../storage/CredentialOfferCacheTest.java | 34 +--
34 files changed, 1522 insertions(+), 454 deletions(-)
diff --git a/README.md b/README.md
index 58e8437..cfd827a 100644
--- a/README.md
+++ b/README.md
@@ -4578,8 +4578,7 @@ The strategy carries the `authorization_details` of the grant into the refresh t
refreshed access token is limited to the same credentials as the first one. For a client that
authenticates with a Wallet Attestation the refresh token works only for the same wallet instance, as
[Attestation-Based Client Authentication 10.3](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-attestation-based-client-auth-12#section-10.3)
-requires. A refresh from another instance, or without an attestation, is refused with
-`invalid_grant`.
+requires.
The lifetimes and rotation are the OP settings of **OpenID.VCI.Token**:
@@ -5023,7 +5022,8 @@ Beans you can define or reference. Define your own beans in *conf/global.xml* or
| **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, 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.ClientAttestationClaimsValidator** | ClaimsValidator | built in | Validation of Wallet Attestation claims: `sub`, `exp`, `iat` and `cnf` required, not before, and `iat` not in the future. |
+| **openidvci.ClientAttestationFreshnessValidator** | ClaimsValidator | built in | Validation of Wallet Attestation freshness: expiry, 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. |
@@ -5036,7 +5036,7 @@ Beans you can define or reference. Define your own beans in *conf/global.xml* or
| **openidvci.jwtVcIssuer.TemplateContext** | Map | as above | The same for JWT VC issuer metadata. |
| **openidvci.authorizationServer.TemplateContext** | Map | as above | The same for authorization server metadata. |
| **openidvci.credentials.MappedErrors** | Map | built in | Events of the credential endpoint mapped to error responses. |
-| **openidvci.token.MappedErrors** | Map | built in | Events of the token endpoint mapped to error responses. |
+| **openidvci.token.MappedErrors** | Map | built in | Events of the token endpoint mapped to error responses, in place of the built-in map. |
### Properties
diff --git a/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/error/OpenIDVCIError.java b/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/error/OpenIDVCIError.java
index 6c1b098..a24be60 100644
--- a/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/error/OpenIDVCIError.java
+++ b/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/error/OpenIDVCIError.java
@@ -24,18 +24,6 @@ import com.nimbusds.oauth2.sdk.http.HTTPResponse;
*/
public final class OpenIDVCIError {
- /**
- * Configuration Error.
- */
- public static final ErrorObject CONF_ERROR = new ErrorObject("configuration_error", "Configuration error.",
- HTTPResponse.SC_SERVER_ERROR);
-
- /**
- * The pre-authorized code is expired.
- */
- public static final ErrorObject NO_CREDENTIAL_OFFER = new ErrorObject("no_credential_offer",
- "No active credential offer per pre-authorized code", HTTPResponse.SC_BAD_REQUEST);
-
/**
* The Credential Request is missing a required parameter, includes an unsupported parameter or parameter
* value, repeats the same parameter, or is otherwise malformed.
@@ -43,6 +31,14 @@ public final class OpenIDVCIError {
public static final ErrorObject INVALID_CREDENTIAL_REQUEST = new ErrorObject("invalid_credential_request",
"The credential request is malformed", HTTPResponse.SC_BAD_REQUEST);
+ /** The authorization details of the Token Request are not granted, RFC 9396 section 6. */
+ public static final ErrorObject INVALID_AUTHORIZATION_DETAILS = new ErrorObject("invalid_authorization_details",
+ "The requested authorization details are not granted", HTTPResponse.SC_BAD_REQUEST);
+
+ /** The Wallet Attestation is not fresh enough, Attestation-Based Client Authentication section 7.4. */
+ public static final ErrorObject USE_FRESH_ATTESTATION = new ErrorObject("use_fresh_attestation",
+ "The client attestation is not fresh enough", HTTPResponse.SC_BAD_REQUEST);
+
/** Requested Credential Configuration is unknown. */
public static final ErrorObject UNKNOWN_CREDENTIAL_CONFIGURATION = new ErrorObject(
"unknown_credential_configuration", "Requested credential configuration is unknown",
@@ -64,11 +60,6 @@ public final class OpenIDVCIError {
public static final ErrorObject INVALID_NONCE = new ErrorObject("invalid_nonce",
"The nonce of a key proof is invalid", HTTPResponse.SC_BAD_REQUEST);
- /** The encryption parameters of the Credential Request are invalid or missing. */
- public static final ErrorObject INVALID_ENCRYPTION_PARAMETERS = new ErrorObject(
- "invalid_encryption_parameters", "The encryption parameters of the request are invalid or missing",
- HTTPResponse.SC_BAD_REQUEST);
-
/**
* The Credential Request has not been accepted by the Credential Issuer. The Wallet is to treat this as
* unrecoverable, the credential cannot be issued.
diff --git a/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/OpenIDVCIEventIds.java b/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/OpenIDVCIEventIds.java
index e7670b7..fe3946d 100644
--- a/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/OpenIDVCIEventIds.java
+++ b/openid-vci-api/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/OpenIDVCIEventIds.java
@@ -120,6 +120,13 @@ public final class OpenIDVCIEventIds {
@NotEmpty
public static final String INVALID_TX_CODE = "InvalidTxCode";
+ /**
+ * Tx code missing although the offer requires one, or present although the offer requires none.
+ */
+ @Nonnull
+ @NotEmpty
+ public static final String TX_CODE_PRESENCE = "TxCodePresence";
+
/**
* Constructor.
*/
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 ffc639f..567de1c 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
@@ -58,6 +58,7 @@ 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.context.AuthenticationErrorContext;
import net.shibboleth.idp.authn.principal.UsernamePrincipal;
import net.shibboleth.oidc.jwt.claims.ClaimsValidator;
import net.shibboleth.oidc.jwt.claims.JWTValidationException;
@@ -87,6 +88,10 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
@Nonnull
public static final JOSEObjectType POP_TYPE = new JOSEObjectType("oauth-client-attestation-pop+jwt");
+ /** Classified authentication error of a client attestation that is not fresh enough. */
+ @Nonnull
+ public static final String USE_FRESH_ATTESTATION = "UseFreshAttestation";
+
/** Class logger. */
@Nonnull
private final Logger log = LoggerFactory.getLogger(ClientAttestationCredentialValidator.class);
@@ -103,6 +108,10 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
@NonnullAfterInit
private ClaimsValidator attestationClaimsValidator;
+ /** Validator of the freshness of a client attestation. */
+ @NonnullAfterInit
+ private ClaimsValidator attestationFreshnessValidator;
+
/** Validator of the claims of a proof of possession. */
@NonnullAfterInit
private ClaimsValidator proofClaimsValidator;
@@ -185,6 +194,18 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
attestationClaimsValidator = Constraint.isNotNull(validator, "Attestation claims validator cannot be null");
}
+ /**
+ * Set the validator of the freshness of a client attestation.
+ *
+ * @param validator claims validator
+ */
+ public void setAttestationFreshnessValidator(@Nonnull final ClaimsValidator validator) {
+ checkSetterPreconditions();
+
+ attestationFreshnessValidator =
+ Constraint.isNotNull(validator, "Attestation freshness validator cannot be null");
+ }
+
/**
* Set the validator of the claims of a proof of possession.
*
@@ -246,6 +267,9 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
if (attestationClaimsValidator == null) {
throw new ComponentInitializationException("Attestation claims validator cannot be null");
}
+ if (attestationFreshnessValidator == null) {
+ throw new ComponentInitializationException("Attestation freshness validator cannot be null");
+ }
if (proofClaimsValidator == null) {
throw new ComponentInitializationException("Proof claims validator cannot be null");
}
@@ -284,6 +308,10 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
clientId = validate(profileRequestContext, attestation, SignedJWT.parse(popHeaders.get(0)));
} catch (final JWTValidationException | ParseException e) {
log.warn("{} Client attestation validation failed: {}", getLogPrefix(), e.getMessage());
+ if (e instanceof StaleAttestationException) {
+ authenticationContext.ensureSubcontext(AuthenticationErrorContext.class)
+ .addClassifiedError(USE_FRESH_ATTESTATION);
+ }
if (errorHandler != null) {
errorHandler.handleError(profileRequestContext, authenticationContext, e,
AuthnEventIds.INVALID_CREDENTIALS);
@@ -374,6 +402,11 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
final JWTClaimsSet attestationClaims = claims(attestation);
attestationClaimsValidator.validate(attestationClaims, profileRequestContext);
+ try {
+ attestationFreshnessValidator.validate(attestationClaims, profileRequestContext);
+ } catch (final JWTValidationException e) {
+ throw new StaleAttestationException(e);
+ }
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");
}
@@ -444,4 +477,20 @@ public class ClientAttestationCredentialValidator extends AbstractCredentialVali
}
}
+ /** Validation failure of a client attestation that is not fresh enough. */
+ private static final class StaleAttestationException extends JWTValidationException {
+
+ /** Serial version UID. */
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Constructor.
+ *
+ * @param cause failure of the freshness validation
+ */
+ StaleAttestationException(@Nonnull final JWTValidationException cause) {
+ super(cause.getMessage(), cause);
+ }
+ }
+
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoder.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoder.java
index e64135c..e72cbce 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoder.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoder.java
@@ -94,10 +94,8 @@ public class OpenIDVCITokenRequestDecoder extends OIDCTokenRequestDecoder {
}
return MoreObjects.toStringHelper(this).omitNullValues()
.add("grant_type", request.getGrantType())
- .add("code", request.getCode())
- .add("code_verifier", request.getCodeVerifier())
.add("pre-authorized_code", request.getPreAuthorizedCode())
- .add("tx_code", request.getTxCode())
+ .add("tx_code", request.getTxCode() != null ? "present" : null)
.add("authorizationGrant", RequestUtil.getAuthorizationGrantLog(request.getAuthorizationGrant()))
.add("client_authentication", RequestUtil.getClientAuthenticationLog(request.getClientAuthentication()))
.add("client_id", request.getClientID() != null ? request.getClientID().getValue() : null)
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunction.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunction.java
index d859b63..4a2618a 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunction.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunction.java
@@ -40,9 +40,9 @@ import net.shibboleth.idp.plugin.oidc.op.messaging.context.OIDCAuthenticationRes
/**
* A function that returns list of {@link OpenIDVCIAuthorizationDetail} parsed
- * from from 1. {@link AuthorizationRequest} or its request object, 2.
- * {@link OpenIDVCITokenRequest} or from claim encoded to 3. authorization code
- * grant.
+ * from 1. {@link AuthorizationRequest} or its request object, 2.
+ * {@link OpenIDVCITokenRequest} or from claim encoded to 3. the authorization grant.
+ * With grant only set, a token request gives the authorization details of the grant alone.
*/
public class AuthorizationDetailsLookupFunction
implements ContextDataLookupFunction<ProfileRequestContext, List<OpenIDVCIAuthorizationDetail>> {
@@ -55,6 +55,18 @@ public class AuthorizationDetailsLookupFunction
@Nonnull
private final Logger log = LoggerFactory.getLogger(AuthorizationDetailsLookupFunction.class);
+ /** Whether a token request gives the authorization details of the grant alone. */
+ private boolean grantOnly;
+
+ /**
+ * Set whether a token request gives the authorization details of the grant alone.
+ *
+ * @param flag whether to read the grant alone
+ */
+ public void setGrantOnly(final boolean flag) {
+ grantOnly = flag;
+ }
+
// Checkstyle: CyclomaticComplexity|ReturnCount OFF
/** {@inheritDoc} */
@Override
@@ -75,7 +87,7 @@ public class AuthorizationDetailsLookupFunction
}
}
if (input.getInboundMessageContext().getMessage() instanceof OpenIDVCITokenRequest tokenRequest) {
- if (tokenRequest.getCredentialAuthorizationDetails() != null
+ if (!grantOnly && tokenRequest.getCredentialAuthorizationDetails() != null
&& !tokenRequest.getCredentialAuthorizationDetails().isEmpty()) {
return tokenRequest.getCredentialAuthorizationDetails();
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequest.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequest.java
index 155891e..d08f5ed 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequest.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequest.java
@@ -30,6 +30,7 @@ import com.nimbusds.common.contenttype.ContentType;
import com.nimbusds.oauth2.sdk.AuthorizationCode;
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant;
import com.nimbusds.oauth2.sdk.AuthorizationGrant;
+import com.nimbusds.oauth2.sdk.ErrorObject;
import com.nimbusds.oauth2.sdk.OAuth2Error;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.Scope;
@@ -95,29 +96,6 @@ public class OpenIDVCITokenRequest extends TokenRequest {
private final List<OpenIDVCIAuthorizationDetail> authorizationDetails;
// Checkstyle: ParameterNumber OFF
- /**
- * Constructor.
- *
- * @param uri The URI of the endpoint (HTTP or HTTPS) for which
- * the request is intended, {@code null} if not
- * specified (if, for example, the
- * {@link #toHTTPRequest()} method will not be used).
- * @param clientAuth The client authentication, {@code null} if none.
- * @param grantType Grant type.
- * @param preAuthorizedCode The pre-authorized code
- * @param code Authorization code
- * @param txCode The tx-code in pre-authorized flow
- * @param codeVerifier The PKCE code verifier
- * @param authorizationDetails Authorization details of the request
- */
- public OpenIDVCITokenRequest(@Nullable final URI uri, @Nullable final ClientAuthentication clientAuth,
- @Nonnull final String grantType, @Nullable final String preAuthorizedCode, @Nullable final String code,
- @Nullable final String txCode, @Nullable final String codeVerifier,
- @Nullable final List<OpenIDVCIAuthorizationDetail> authorizationDetails) {
- this(uri, clientAuth, grantType, preAuthorizedCode, code, txCode, codeVerifier, null, null,
- authorizationDetails);
- }
-
/**
* Constructor.
*
@@ -130,16 +108,18 @@ public class OpenIDVCITokenRequest extends TokenRequest {
* @param code Authorization code
* @param txCode The tx-code in pre-authorized flow
* @param codeVerifier The PKCE code verifier
+ * @param redirectURI The redirection URI of the authorization code grant, {@code null} if not specified.
* @param scope The requested scope, {@code null} if not specified.
* @param resources The resource URIs, {@code null} if not specified.
* @param authorizationDetails Authorization details of the request
*/
public OpenIDVCITokenRequest(@Nullable final URI uri, @Nullable final ClientAuthentication clientAuth,
@Nonnull final String grantType, @Nullable final String preAuthorizedCode, @Nullable final String code,
- @Nullable final String txCode, @Nullable final String codeVerifier, @Nullable final Scope scope,
- @Nullable final List<URI> resources,
+ @Nullable final String txCode, @Nullable final String codeVerifier, @Nullable final URI redirectURI,
+ @Nullable final Scope scope, @Nullable final List<URI> resources,
@Nullable final List<OpenIDVCIAuthorizationDetail> authorizationDetails) {
- super(uri, clientAuth, toAuthorizationGrant(grantType, preAuthorizedCode, code, txCode, codeVerifier),
+ super(uri, clientAuth,
+ toAuthorizationGrant(grantType, preAuthorizedCode, code, txCode, codeVerifier, redirectURI),
scope, resources, (Map<String, List<String>>) null);
this.grantType = grantType;
this.preAuthorizedCode = preAuthorizedCode;
@@ -149,31 +129,6 @@ public class OpenIDVCITokenRequest extends TokenRequest {
this.authorizationDetails = authorizationDetails;
}
- /**
- * Constructor.
- *
- * @param uri The URI of the endpoint (HTTP or HTTPS) for which
- * the request is intended, {@code null} if not
- * specified (if, for example, the
- * {@link #toHTTPRequest()} method will not be used).
- * @param clientID The client identifier, {@code null} if not
- * specified.
- * @param grantType Grant type.
- * @param preAuthorizedCode The pre-authorized code
- * @param code Authorization code
- * @param txCode The tx-code in pre-authorized flow
- * @param codeVerifier The PKCE code verifier
- * @param authorizationDetails Authorization details of the request
- */
- public OpenIDVCITokenRequest(@Nullable final URI uri, @Nullable final ClientID clientID,
- @Nonnull final String grantType,
- @Nullable final String preAuthorizedCode, @Nullable final String code, @Nullable final String txCode,
- @Nullable final String codeVerifier,
- @Nullable final List<OpenIDVCIAuthorizationDetail> authorizationDetails) {
- this(uri, clientID, grantType, preAuthorizedCode, code, txCode, codeVerifier, null, null,
- authorizationDetails);
- }
-
/**
* Constructor.
*
@@ -187,6 +142,7 @@ public class OpenIDVCITokenRequest extends TokenRequest {
* @param code Authorization code
* @param txCode The tx-code in pre-authorized flow
* @param codeVerifier The PKCE code verifier
+ * @param redirectURI The redirection URI of the authorization code grant, {@code null} if not specified.
* @param scope The requested scope, {@code null} if not specified.
* @param resources The resource URIs, {@code null} if not specified.
* @param authorizationDetails Authorization details of the request
@@ -194,9 +150,11 @@ public class OpenIDVCITokenRequest extends TokenRequest {
public OpenIDVCITokenRequest(@Nullable final URI uri, @Nullable final ClientID clientID,
@Nonnull final String grantType,
@Nullable final String preAuthorizedCode, @Nullable final String code, @Nullable final String txCode,
- @Nullable final String codeVerifier, @Nullable final Scope scope, @Nullable final List<URI> resources,
+ @Nullable final String codeVerifier, @Nullable final URI redirectURI, @Nullable final Scope scope,
+ @Nullable final List<URI> resources,
@Nullable final List<OpenIDVCIAuthorizationDetail> authorizationDetails) {
- super(uri, clientID, toAuthorizationGrant(grantType, preAuthorizedCode, code, txCode, codeVerifier),
+ super(uri, clientID,
+ toAuthorizationGrant(grantType, preAuthorizedCode, code, txCode, codeVerifier, redirectURI),
scope, resources, (RefreshToken) null, (Map<String, List<String>>) null);
this.grantType = grantType;
this.preAuthorizedCode = preAuthorizedCode;
@@ -324,13 +282,14 @@ public class OpenIDVCITokenRequest extends TokenRequest {
* @param code authorization code, or null
* @param txCode transaction code, or null
* @param codeVerifier PKCE code verifier, or null
+ * @param redirectURI redirection URI of the authorization code grant, or null
*
* @return the grant
*/
@Nonnull
private static AuthorizationGrant toAuthorizationGrant(@Nonnull final String grantType,
@Nullable final String preAuthorizedCode, @Nullable final String code, @Nullable final String txCode,
- @Nullable final String codeVerifier) {
+ @Nullable final String codeVerifier, @Nullable final URI redirectURI) {
if (codeVerifier != null && codeVerifier.length() < 43) {
throw new IllegalArgumentException("The code verifier must be at least 43 characters");
@@ -346,7 +305,7 @@ public class OpenIDVCITokenRequest extends TokenRequest {
if (code == null || code.isEmpty()) {
throw new IllegalArgumentException("code must not be null or empty for authorization_code grant");
}
- return new AuthorizationCodeGrant(new AuthorizationCode(code), null,
+ return new AuthorizationCodeGrant(new AuthorizationCode(code), redirectURI,
codeVerifier != null ? new CodeVerifier(codeVerifier) : null);
}
throw new IllegalArgumentException("Grant type must be either 'authorization_code' or "
@@ -362,8 +321,7 @@ public class OpenIDVCITokenRequest extends TokenRequest {
}
/**
- * Read the client identifier a client attestation names, the 'sub' of the
- * 'OAuth-Client-Attestation' header.
+ * Read the 'sub' of the 'OAuth-Client-Attestation' header, the client identifier of an attested request.
*
* @param httpRequest request to read
* @return the client identifier, or null if the request carries no readable attestation
@@ -398,7 +356,8 @@ public class OpenIDVCITokenRequest extends TokenRequest {
clientAuth = ClientAuthentication.parse(httpRequest);
} catch (final ParseException e) {
throw new ParseException(e.getMessage(),
- OAuth2Error.INVALID_REQUEST.appendDescription(": " + e.getMessage()));
+ OAuth2Error.INVALID_REQUEST
+ .appendDescription(": " + ErrorObject.removeIllegalChars(e.getMessage())));
}
final Map<String, List<String>> params = httpRequest.getQueryParameters();
if (clientAuth instanceof ClientSecretBasic) {
@@ -415,36 +374,41 @@ public class OpenIDVCITokenRequest extends TokenRequest {
throw new ParseException(e.getMessage(),
OAuth2Error.INVALID_REQUEST.appendDescription(": authorization_details could not be parsed"));
}
- final String grantType = MultivaluedMapUtils.getFirstValue(params, "grant_type");
+ final String grantType = singleValue(params, "grant_type");
if (!GRANT_TYPE_VALUE_PRE_AUTH.equals(grantType) && !GRANT_TYPE_VALUE_CODE.equals(grantType)) {
return wrap(TokenRequest.parse(httpRequest), authorizationDetails, httpRequest);
}
final Scope scope = Scope.parse(MultivaluedMapUtils.getFirstValue(params, "scope"));
final List<URI> resources = parseResources(params);
- final String preAuthorizedCode = MultivaluedMapUtils.getFirstValue(params, "pre-authorized_code");
- final String code = MultivaluedMapUtils.getFirstValue(params, "code");
- final String txCode = MultivaluedMapUtils.getFirstValue(params, "tx_code");
- final String codeVerifier = MultivaluedMapUtils.getFirstValue(params, "code_verifier");
+ final String preAuthorizedCode = singleValue(params, "pre-authorized_code");
+ final String code = singleValue(params, "code");
+ final String txCode = singleValue(params, "tx_code");
+ final String codeVerifier = singleValue(params, "code_verifier");
+ final URI redirectURI = parseRedirectURI(singleValue(params, "redirect_uri"));
final URI uri;
try {
uri = httpRequest.getURL().toURI();
} catch (final URISyntaxException e) {
throw new ParseException(e.getMessage(), e);
}
- if (clientAuth != null) {
- return new OpenIDVCITokenRequest(uri, clientAuth, grantType, preAuthorizedCode, code, txCode, codeVerifier,
- scope, resources, authorizationDetails);
- }
String clientIDString = MultivaluedMapUtils.getFirstValue(params, "client_id");
- if (StringUtils.isBlank(clientIDString)) {
+ if (clientAuth == null && StringUtils.isBlank(clientIDString)) {
clientIDString = attestedClientID(httpRequest);
}
- if (StringUtils.isBlank(clientIDString)) {
- return new OpenIDVCITokenRequest(uri, (ClientID) null, grantType, preAuthorizedCode, code, txCode,
- codeVerifier, scope, resources, authorizationDetails);
+ try {
+ if (clientAuth != null) {
+ return new OpenIDVCITokenRequest(uri, clientAuth, grantType, preAuthorizedCode, code, txCode,
+ codeVerifier, redirectURI, scope, resources, authorizationDetails);
+ }
+ return new OpenIDVCITokenRequest(uri,
+ StringUtils.isBlank(clientIDString) ? (ClientID) null : new ClientID(clientIDString), grantType,
+ preAuthorizedCode, code, txCode, codeVerifier, redirectURI, scope, resources,
+ authorizationDetails);
+ } catch (final IllegalArgumentException e) {
+ throw new ParseException(e.getMessage(),
+ OAuth2Error.INVALID_REQUEST
+ .appendDescription(": " + ErrorObject.removeIllegalChars(e.getMessage())));
}
- return new OpenIDVCITokenRequest(uri, new ClientID(clientIDString), grantType, preAuthorizedCode, code, txCode,
- codeVerifier, scope, resources, authorizationDetails);
}
// Checkstyle: CyclomaticComplexity|MethodLength|ReturnCount ON
@@ -475,6 +439,48 @@ public class OpenIDVCITokenRequest extends TokenRequest {
request.getCustomParameters(), authorizationDetails);
}
+ /**
+ * Get the value of a parameter that may appear at most once. A parameter without a value is treated as absent.
+ *
+ * @param params parameters of the request
+ * @param name name of the parameter
+ * @return the value, or null if the parameter is absent or has no value
+ * @throws ParseException if the parameter is included more than once
+ */
+ @Nullable
+ private static String singleValue(@Nonnull final Map<String, List<String>> params, @Nonnull final String name)
+ throws ParseException {
+ final List<String> values = params.get(name);
+ if (values == null || values.isEmpty()) {
+ return null;
+ }
+ if (values.size() > 1) {
+ final String msg = "Parameter " + name + " included more than once";
+ throw new ParseException(msg, OAuth2Error.INVALID_REQUEST.appendDescription(": " + msg));
+ }
+ return values.get(0) == null || values.get(0).isEmpty() ? null : values.get(0);
+ }
+
+ /**
+ * Parse the 'redirect_uri' parameter of a request.
+ *
+ * @param value value of the parameter, or null
+ * @return the redirection URI, or null if there is none
+ * @throws ParseException if the value is not a URI
+ */
+ @Nullable
+ private static URI parseRedirectURI(@Nullable final String value) throws ParseException {
+ if (value == null) {
+ return null;
+ }
+ try {
+ return new URI(value);
+ } catch (final URISyntaxException e) {
+ throw new ParseException("Illegal redirect_uri parameter: " + value,
+ OAuth2Error.INVALID_REQUEST.appendDescription(": illegal redirect_uri"));
+ }
+ }
+
/**
* Parse the 'resource' parameters of a request.
*
@@ -495,11 +501,11 @@ public class OpenIDVCITokenRequest extends TokenRequest {
resource = new URI(value);
} catch (final URISyntaxException e) {
throw new ParseException("Illegal resource parameter: " + value,
- OAuth2Error.INVALID_TARGET.appendDescription(": " + value));
+ OAuth2Error.INVALID_TARGET.appendDescription(": " + ErrorObject.removeIllegalChars(value)));
}
if (!resource.isAbsolute() || resource.getFragment() != null) {
throw new ParseException("Illegal resource parameter: " + value,
- OAuth2Error.INVALID_TARGET.appendDescription(": " + value));
+ OAuth2Error.INVALID_TARGET.appendDescription(": " + ErrorObject.removeIllegalChars(value)));
}
resources.add(resource);
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/config/impl/DefaultOpenIDVCITokenConfiguration.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/config/impl/DefaultOpenIDVCITokenConfiguration.java
index a543ae3..37ad6d8 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/config/impl/DefaultOpenIDVCITokenConfiguration.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/config/impl/DefaultOpenIDVCITokenConfiguration.java
@@ -18,16 +18,22 @@ package org.geant.shibboleth.plugin.openidvci.profile.config.impl;
import java.util.List;
+import javax.annotation.Nonnull;
+
import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
import org.geant.shibboleth.plugin.openidvci.profile.config.OpenIDVCIConfiguration;
import com.nimbusds.oauth2.sdk.GrantType;
import net.shibboleth.oidc.profile.oauth2.config.impl.DefaultOAuth2TokenConfiguration;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
/** Profile configuration for the Token endpoint. */
public class DefaultOpenIDVCITokenConfiguration extends DefaultOAuth2TokenConfiguration {
+ /** Token profile counter name. */
+ @Nonnull @NotEmpty public static final String PROFILE_COUNTER = "net.shibboleth.idp.profiles.openid.vci.token";
+
/** Constructor. */
public DefaultOpenIDVCITokenConfiguration() {
super(OpenIDVCIConfiguration.PROFILE_ID_TOKEN);
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunction.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunction.java
index a9565dd..2dacc3c 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunction.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunction.java
@@ -16,119 +16,38 @@
package org.geant.shibboleth.plugin.openidvci.profile.context.navigate;
-import java.io.IOException;
-
-import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
-import org.geant.shibboleth.plugin.openidvci.messaging.impl.CredentialOfferRequest;
import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
-import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferCache;
import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferObject;
-import org.geant.shibboleth.plugin.openidvci.token.support.CredentialOfferClaimsSet;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.messaging.context.navigate.ContextDataLookupFunction;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.nimbusds.oauth2.sdk.AbstractOptionallyAuthenticatedRequest;
-import com.nimbusds.oauth2.sdk.AbstractOptionallyIdentifiedRequest;
import com.nimbusds.oauth2.sdk.id.ClientID;
-import net.minidev.json.parser.ParseException;
-import net.shibboleth.shared.logic.Constraint;
-import net.shibboleth.shared.security.DataSealer;
-import net.shibboleth.shared.security.DataSealerException;
-
/**
- * Locates client firstly by oauth2 authentication, secondly by pre-authorized
- * code and thirdly by client_id request parameter. Client id is the client id
- * of client that created the code appended with /wallet in the case
- * pre-authorized code is used.
+ * Locates the client of a token request: firstly by client authentication, secondly by the Credential Offer of
+ * the pre-authorized code in {@link TokenContext}, as the client id of the offer caller appended with /wallet, and
+ * thirdly by the client_id request parameter.
*/
public class APIRequestClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> {
- /** Class logger. */
- @Nonnull
- private final Logger log = LoggerFactory.getLogger(APIRequestClientIDLookupFunction.class);
-
- /** Cache for credential offers. */
- @Nullable
- private CredentialOfferCache credentialOfferCache;
-
- /** Data sealer for unwrapping pre-authorized code. */
- private DataSealer dataSealer;
-
- /**
- * Set the data sealer instance to use.
- *
- * @param sealer sealer to use
- */
- public void setDataSealer(@Nonnull final DataSealer sealer) {
- dataSealer = Constraint.isNotNull(sealer, "DataSealer cannot be null");
- }
-
- /**
- * Set cache for Credential Offers.
- *
- * @param cache Cache for device codes
- */
- public void setCredentialOfferCache(@Nonnull final CredentialOfferCache cache) {
- credentialOfferCache = Constraint.isNotNull(cache, "CredentialOfferCache cannot be null");
- }
-
-// Checkstyle: CyclomaticComplexity OFF
/** {@inheritDoc} */
@Nullable
public ClientID apply(@Nullable final MessageContext input) {
- if (input == null) {
- return null;
- }
- final Object message = input.getMessage();
- if (!(message instanceof CredentialOfferRequest) && !(message instanceof OpenIDVCITokenRequest)) {
+ if (input == null || !(input.getMessage() instanceof OpenIDVCITokenRequest message)) {
return null;
}
- if (message instanceof AbstractOptionallyAuthenticatedRequest msg && msg.getClientAuthentication() != null
- && msg.getClientAuthentication().getClientID() != null) {
- return msg.getClientAuthentication().getClientID();
+ if (message.getClientAuthentication() != null && message.getClientAuthentication().getClientID() != null) {
+ return message.getClientAuthentication().getClientID();
}
- if (message instanceof OpenIDVCITokenRequest) {
- final TokenContext tokenContext = input.getSubcontext(TokenContext.class);
- final CredentialOfferObject offer = tokenContext != null ? tokenContext.getCredentialOfferObject() : null;
- if (offer != null && offer.getClientID() != null) {
- return new ClientID(offer.getClientID().getValue() + "/wallet");
- }
+ final TokenContext tokenContext = input.getSubcontext(TokenContext.class);
+ final CredentialOfferObject offer = tokenContext != null ? tokenContext.getCredentialOfferObject() : null;
+ if (offer != null && offer.getClientID() != null) {
+ return new ClientID(offer.getClientID().getValue() + "/wallet");
}
- if (message instanceof OpenIDVCITokenRequest msg && msg.getPreAuthorizedCode() != null
- && credentialOfferCache != null) {
- try {
- final CredentialOfferObject offer = credentialOfferCache.getCredentialOffer(msg.getPreAuthorizedCode());
- if (offer != null) {
- return new ClientID(offer.getClientID().getValue() + "/wallet");
- }
- } catch (final IOException | ParseException e) {
- log.error("Unexpected error", e);
- }
- }
- if (message instanceof OpenIDVCITokenRequest msg && msg.getPreAuthorizedCode() != null && dataSealer != null) {
- final CredentialOfferClaimsSet credentialOffer;
- try {
- credentialOffer = CredentialOfferClaimsSet.parse(msg.getPreAuthorizedCode(), dataSealer);
- return new ClientID(
- CredentialOfferObject.parse(credentialOffer.getSubject()).getClientID().getValue() + "/wallet");
- } catch (final java.text.ParseException | DataSealerException | JsonProcessingException
- | com.nimbusds.oauth2.sdk.ParseException e) {
- log.error("Unexpected error", e);
- }
- }
- if (message instanceof AbstractOptionallyIdentifiedRequest msg && msg.getClientID() != null) {
- return msg.getClientID();
- }
-
- return null;
+ return message.getClientID();
}
-// Checkstyle: CyclomaticComplexity ON
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOffer.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOffer.java
index 926c0ec..6ad12fe 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOffer.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOffer.java
@@ -19,7 +19,9 @@ import java.io.IOException;
import javax.annotation.Nonnull;
+import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds;
import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferCache;
import org.opensaml.profile.action.ActionSupport;
import org.opensaml.profile.action.EventIds;
@@ -34,19 +36,12 @@ import net.shibboleth.shared.logic.Constraint;
import net.shibboleth.shared.primitive.LoggerFactory;
/**
- * Action that spends the Credential Offer a pre-authorized code was redeemed
- * for, making the code single use.
+ * Action that removes the stored Credential Offer a pre-authorized code was redeemed for, making the code single
+ * use. The offer must still be stored: a request that finds it already removed fails.
*
* <p>
- * Runs once the tokens are built. Both the client of the request and the
- * subject of the access token are resolved from the stored offer, so the offer
- * outlives the actions reading it and is removed only after the last of them.
- * </p>
- *
- * <p>
- * Nothing is done for the authorization code flow, which carries no
- * pre-authorized code, nor for a self-contained pre-authorized code, which has
- * no stored offer to remove.
+ * Nothing is done for a request without a pre-authorized code, nor for a sealed pre-authorized code, which has no
+ * stored offer.
* </p>
*/
public class ConsumeCredentialOffer extends AbstractProfileAction {
@@ -94,6 +89,12 @@ public class ConsumeCredentialOffer extends AbstractProfileAction {
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_PROFILE_CTX);
return false;
}
+ final TokenContext tokenContext =
+ profileRequestContext.getInboundMessageContext().getSubcontext(TokenContext.class);
+ if (tokenContext != null && tokenContext.getCredentialOfferClaimsSet() != null) {
+ log.debug("{} Sealed pre-authorized code, no stored Credential Offer to consume", getLogPrefix());
+ return false;
+ }
if (profileRequestContext.getInboundMessageContext().getMessage() instanceof OpenIDVCITokenRequest request) {
preAuthorizedCode = request.getPreAuthorizedCode();
}
@@ -108,7 +109,11 @@ public class ConsumeCredentialOffer extends AbstractProfileAction {
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
try {
- credentialOfferCache.removeCredentialOffer(preAuthorizedCode);
+ if (!credentialOfferCache.removeCredentialOffer(preAuthorizedCode)) {
+ log.warn("{} Credential Offer of the pre-authorized code already consumed", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.NO_CREDENTIAL_OFFER);
+ return;
+ }
log.debug("{} Credential Offer of the pre-authorized code consumed", getLogPrefix());
} catch (final IOException e) {
log.error("{} Removing Credential Offer of the pre-authorized code failed", getLogPrefix(), e);
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentials.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentials.java
index 262545e..d537bb8 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentials.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentials.java
@@ -45,7 +45,7 @@ import net.shibboleth.shared.primitive.LoggerFactory;
/**
* Action that limits {@link TokenContext#getPotentialCredentials()} to the credential configurations authorized
* for the grant, those whose 'scope' is in the granted scope of {@link OIDCAuthenticationResponseContext#getScope()}
- * and those requested with 'authorization_details'.
+ * and those in the 'authorization_details' of the grant.
*
* @event {@link EventIds#PROCEED_EVENT_ID}
* @event {@link EventIds#INVALID_PROFILE_CTX}
@@ -73,7 +73,9 @@ public class FilterPotentialCredentials extends AbstractCredentialValidationActi
* Constructor.
*/
public FilterPotentialCredentials() {
- authorizationDetailsStrategy = new AuthorizationDetailsLookupFunction();
+ final AuthorizationDetailsLookupFunction grantDetails = new AuthorizationDetailsLookupFunction();
+ grantDetails.setGrantOnly(true);
+ authorizationDetailsStrategy = grantDetails;
}
/**
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/OpenIDVCIBuildTokenErrorResponseFromEvent.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/OpenIDVCIBuildTokenErrorResponseFromEvent.java
new file mode 100644
index 0000000..363ad4d
--- /dev/null
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/OpenIDVCIBuildTokenErrorResponseFromEvent.java
@@ -0,0 +1,69 @@
+/*
+ * 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.profile.impl;
+
+import java.util.Collection;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationCredentialValidator;
+import org.geant.shibboleth.plugin.openidvci.messaging.error.OpenIDVCIError;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.nimbusds.oauth2.sdk.ErrorObject;
+import com.nimbusds.oauth2.sdk.TokenErrorResponse;
+
+import net.shibboleth.idp.authn.context.AuthenticationContext;
+import net.shibboleth.idp.authn.context.AuthenticationErrorContext;
+import net.shibboleth.idp.plugin.oidc.op.profile.TokenErrorObjectMapping;
+import net.shibboleth.idp.plugin.oidc.op.profile.impl.BuildTokenErrorResponseFromEvent;
+
+/**
+ * Action that builds the token error response from the current event, answering 'use_fresh_attestation' for a
+ * client attestation that is not fresh enough.
+ */
+public class OpenIDVCIBuildTokenErrorResponseFromEvent extends BuildTokenErrorResponseFromEvent {
+
+ /**
+ * Constructor.
+ *
+ * @param freeObjects autowired error mappings
+ */
+ @Autowired
+ public OpenIDVCIBuildTokenErrorResponseFromEvent(@Nullable final Collection<TokenErrorObjectMapping> freeObjects) {
+ super(freeObjects);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ protected TokenErrorResponse buildErrorResponse(@Nonnull final ErrorObject error,
+ @Nonnull final ProfileRequestContext profileRequestContext) {
+ final AuthenticationContext authenticationContext =
+ profileRequestContext.getSubcontext(AuthenticationContext.class);
+ final AuthenticationErrorContext errorContext = authenticationContext != null
+ ? authenticationContext.getSubcontext(AuthenticationErrorContext.class)
+ : null;
+ if (errorContext != null && errorContext.getClassifiedErrors()
+ .contains(ClientAttestationCredentialValidator.USE_FRESH_ATTESTATION)) {
+ return super.buildErrorResponse(OpenIDVCIError.USE_FRESH_ATTESTATION, profileRequestContext);
+ }
+ return super.buildErrorResponse(error, profileRequestContext);
+ }
+
+}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContext.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContext.java
index 4a4a78c..92605ee 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContext.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContext.java
@@ -84,6 +84,7 @@ public class SetAuthorizationDetailsToResponseContext extends AbstractProfileAct
*/
public void setAuthorizationDetailsLookupStrategy(
@Nonnull final Function<ProfileRequestContext, List<OpenIDVCIAuthorizationDetail>> strategy) {
+ checkSetterPreconditions();
authorizationDetailsStrategy = Constraint.isNotNull(strategy,
"AuthorizationDetailsLookupStrategy lookup strategy cannot be null");
}
@@ -121,8 +122,8 @@ public class SetAuthorizationDetailsToResponseContext extends AbstractProfileAct
try {
potentialCredentials = tokenContext.getPotentialCredentials().toJWTClaimsSet().toJSONObject();
} catch (final ParseException e) {
- log.error("{} Parsing exception. Not able to match request to offering", getLogPrefix(), e);
- ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.NO_CREDENTIALS_FOR_REQUEST);
+ log.error("{} Potential credentials not parsed", getLogPrefix(), e);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_PROFILE_CTX);
return;
}
final Set<String> requested = new LinkedHashSet<>();
@@ -132,12 +133,13 @@ public class SetAuthorizationDetailsToResponseContext extends AbstractProfileAct
final List<OpenIDVCIAuthorizationDetail> responseDetails = new ArrayList<>();
final Map<String, Object> issued = new LinkedHashMap<>();
for (final String configurationId : requested) {
- addDetail(configurationId, datasetsOf(potentialCredentials, configurationId), responseDetails, issued);
- }
- if (!requested.isEmpty() && responseDetails.isEmpty()) {
- log.error("{} No credentials available for request", getLogPrefix());
- ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.NO_CREDENTIALS_FOR_REQUEST);
- return;
+ final List<CredentialDataset> datasets = datasetsOf(potentialCredentials, configurationId);
+ if (datasets == null || datasets.isEmpty()) {
+ log.warn("{} Requested credential configuration {} is not granted", getLogPrefix(), configurationId);
+ ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.NO_CREDENTIALS_FOR_REQUEST);
+ return;
+ }
+ addDetail(configurationId, datasets, responseDetails, issued);
}
for (final String configurationId : potentialCredentials.keySet()) {
if (requested.contains(configurationId)) {
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCode.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCode.java
index 61717bd..1865aee 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCode.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCode.java
@@ -31,22 +31,21 @@ import javax.annotation.Nonnull;
import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
import org.geant.shibboleth.plugin.openidvci.messaging.impl.AbstractOpenIDVCITokenResponseAction;
import org.geant.shibboleth.plugin.openidvci.messaging.impl.CredentialDataset;
-import org.geant.shibboleth.plugin.openidvci.messaging.impl.PreAuthorizedCodeGrant;
+import org.geant.shibboleth.plugin.openidvci.profile.config.impl.AbstractOpenIDVCIConfiguration;
import org.geant.shibboleth.plugin.openidvci.profile.context.navigate.APIRequestClientIDLookupFunction;
import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferCache;
import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferObject;
import org.geant.shibboleth.plugin.openidvci.token.support.CredentialOfferClaimsSet;
import org.opensaml.profile.action.ActionSupport;
+import org.opensaml.profile.action.EventIds;
import org.opensaml.profile.context.ProfileRequestContext;
import org.opensaml.profile.context.navigate.InboundMessageContextLookup;
import org.slf4j.Logger;
import com.fasterxml.jackson.core.JsonProcessingException;
-import com.nimbusds.oauth2.sdk.AuthorizationGrant;
import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.openid.connect.sdk.claims.ClaimsSet;
-import net.shibboleth.idp.plugin.oidc.op.token.support.TokenClaimsSet;
import net.shibboleth.oidc.profile.core.OidcEventIds;
import net.shibboleth.shared.annotation.ParameterName;
import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
@@ -95,9 +94,8 @@ public class UnwrapPreAuthorizedCode extends AbstractOpenIDVCITokenResponseActio
*/
public UnwrapPreAuthorizedCode(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer) {
dataSealer = Constraint.isNotNull(sealer, "DataSealer cannot be null");
- final APIRequestClientIDLookupFunction lookup = new APIRequestClientIDLookupFunction();
- lookup.setDataSealer(sealer);
- clientIDLookupStrategy = FunctionSupport.compose(lookup, new InboundMessageContextLookup());
+ clientIDLookupStrategy =
+ FunctionSupport.compose(new APIRequestClientIDLookupFunction(), new InboundMessageContextLookup());
}
/**
@@ -134,85 +132,60 @@ public class UnwrapPreAuthorizedCode extends AbstractOpenIDVCITokenResponseActio
/** {@inheritDoc} */
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
- final AuthorizationGrant grant = getTokenRequest().getAuthorizationGrant();
- log.debug("{} Unwrapping grant type: {}", getLogPrefix(), grant.getType());
- if (PreAuthorizedCodeGrant.GRANT_TYPE.equals(grant.getType())) {
- final String code = getOpenIDVCITokenRequest().getPreAuthorizedCode();
- log.info("{} Unwrapping pre-authorization code", getLogPrefix());
-
- final CredentialOfferObject storedOffer;
- try {
- storedOffer = credentialOfferCache.getCredentialOffer(code);
- } catch (final IOException | net.minidev.json.parser.ParseException e) {
- log.error("{} Validating pre-authorized code failed", getLogPrefix(), e);
- ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
- return;
- }
- if (storedOffer != null) {
- final TokenContext tokenContext = profileRequestContext.getInboundMessageContext()
- .ensureSubcontext(TokenContext.class);
- tokenContext.setCredentialOfferObject(storedOffer);
- setPotentialCredentials(tokenContext);
- // Subject and auth time set for access token creation. TODO make sure what
- // content to use.
- getOidcResponseContext().setSubject(clientIDLookupStrategy.apply(profileRequestContext).getValue());
- getOidcResponseContext().setAuthTime(Instant.now());
- return;
- }
- log.debug("{} No stored Credential Offer for the pre-authorized code, unwrapping it as a sealed code",
- getLogPrefix());
-
- try {
- final CredentialOfferClaimsSet credentialOffer = CredentialOfferClaimsSet.parse(code, dataSealer);
- assert credentialOffer != null;
- final String jti = credentialOffer.getID();
- if (jti == null) {
- log.warn("{} Invalid contents in the pre-authorized grant: no JTI", getLogPrefix());
- ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
- return;
- }
- log.debug("{} pre-authorized grant unwrapped {}", getLogPrefix(), credentialOffer.serialize());
- validateTokenClaimsSet(profileRequestContext, credentialOffer);
- final TokenContext tokenContext = profileRequestContext.getInboundMessageContext()
- .ensureSubcontext(TokenContext.class);
- tokenContext.setCredentialOfferObject(CredentialOfferObject.parse(credentialOffer.getSubject()));
- tokenContext.setCredentialOfferClaimsSet(credentialOffer);
- getOidcResponseContext().setAuthTime(Instant.now());
- setPotentialCredentials(tokenContext);
- // Subject and auth time set for access token creation. TODO make sure what
- // content to use.
- getOidcResponseContext().setSubject(clientIDLookupStrategy.apply(profileRequestContext).getValue());
- getOidcResponseContext().setAuthTime(Instant.now());
- return;
- } catch (final DataSealerException | JsonProcessingException | com.nimbusds.oauth2.sdk.ParseException
- | ParseException e) {
- log.warn("{} Unwrapping pre-authorized code failed, not a stored Credential Offer and not a sealed "
- + "one, expired or already redeemed: {}", getLogPrefix(), e.getMessage());
- }
+ final String code = getOpenIDVCITokenRequest().getPreAuthorizedCode();
+ log.info("{} Unwrapping pre-authorization code", getLogPrefix());
+
+ final CredentialOfferObject storedOffer;
+ try {
+ storedOffer = credentialOfferCache.getCredentialOffer(code);
+ } catch (final IOException e) {
+ log.error("{} Reading the stored Credential Offer failed", getLogPrefix(), e);
+ ActionSupport.buildEvent(profileRequestContext, EventIds.IO_ERROR);
+ return;
}
- ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
-
- }
-// Checkstyle: CyclomaticComplexity|MethodLength ON
-
- /**
- * Validate the claims of an unwrapped grant.
- *
- * @param profileRequestContext profile request context
- * @param tokenClaimsSet claims of the unwrapped grant
- */
- private void validateTokenClaimsSet(@Nonnull final ProfileRequestContext profileRequestContext,
- final TokenClaimsSet tokenClaimsSet) {
- if (tokenClaimsSet == null) {
- log.warn("{} Grant type not supported", getLogPrefix());
+ if (storedOffer != null) {
+ final TokenContext tokenContext = profileRequestContext.getInboundMessageContext()
+ .ensureSubcontext(TokenContext.class);
+ tokenContext.setCredentialOfferObject(storedOffer);
+ setPotentialCredentials(tokenContext);
+ getOidcResponseContext().setSubject(clientIDLookupStrategy.apply(profileRequestContext).getValue());
+ getOidcResponseContext().setAuthTime(Instant.now());
+ return;
+ }
+ if (code.length() <= AbstractOpenIDVCIConfiguration.MAX_PRE_AUTHORIZED_CODE_LENGTH) {
+ log.warn("{} No stored Credential Offer for the pre-authorized code: unknown, expired or redeemed",
+ getLogPrefix());
ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
return;
}
- if (!tokenClaimsSet.isTimeValid()) {
- log.warn("{} Token is expired or not yet valid", getLogPrefix());
+ log.debug("{} No stored Credential Offer for the pre-authorized code, unwrapping it as a sealed code",
+ getLogPrefix());
+
+ try {
+ final CredentialOfferClaimsSet credentialOffer = CredentialOfferClaimsSet.parse(code, dataSealer);
+ assert credentialOffer != null;
+ final String jti = credentialOffer.getID();
+ log.debug("{} Pre-authorized grant {} unwrapped", getLogPrefix(), jti);
+ if (!credentialOffer.isTimeValid()) {
+ log.warn("{} Pre-authorized grant {} is expired or not yet valid", getLogPrefix(), jti);
+ ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
+ return;
+ }
+ final TokenContext tokenContext = profileRequestContext.getInboundMessageContext()
+ .ensureSubcontext(TokenContext.class);
+ tokenContext.setCredentialOfferObject(CredentialOfferObject.parse(credentialOffer.getSubject()));
+ tokenContext.setCredentialOfferClaimsSet(credentialOffer);
+ setPotentialCredentials(tokenContext);
+ getOidcResponseContext().setSubject(clientIDLookupStrategy.apply(profileRequestContext).getValue());
+ getOidcResponseContext().setAuthTime(Instant.now());
+ } catch (final DataSealerException | JsonProcessingException | com.nimbusds.oauth2.sdk.ParseException
+ | ParseException e) {
+ log.warn("{} Unwrapping pre-authorized code failed, not a sealed Credential Offer: {}", getLogPrefix(),
+ e.getMessage());
ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
}
}
+// Checkstyle: CyclomaticComplexity|MethodLength ON
/**
* Set the credentials the grant may be redeemed for.
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCode.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCode.java
index b2c7200..02f4b8c 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCode.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCode.java
@@ -119,11 +119,7 @@ public class ValidatePreAuthorizedCode extends AbstractProfileAction {
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
final String jti = credentialOffer.getID();
- if (jti == null) {
- log.warn("{} Invalid contents in the pre-authorized grant: no JTI", getLogPrefix());
- ActionSupport.buildEvent(profileRequestContext, OidcEventIds.INVALID_GRANT);
- return;
- }
+ assert jti != null;
final String cacheContext = getClass().getName();
assert cacheContext != null;
if (!replayCache.check(cacheContext, jti, credentialOffer.getExp())) {
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCode.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCode.java
index edafa08..cb0e488 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCode.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCode.java
@@ -78,7 +78,12 @@ public class ValidateTxCode extends AbstractProfileAction {
}
requiredTxCode = tokenContext.getCredentialOfferObject().getCredentialOfferTxCode();
if (requiredTxCode == null) {
- log.debug("{} No TX Code set for pre-auth flow, nothing to do", getLogPrefix());
+ if (providedTxCode != null) {
+ log.warn("{} Transaction Code presented, the Credential Offer requires none", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.TX_CODE_PRESENCE);
+ return false;
+ }
+ log.debug("{} No Transaction Code required by the Credential Offer", getLogPrefix());
return false;
}
return true;
@@ -87,12 +92,17 @@ public class ValidateTxCode extends AbstractProfileAction {
/** {@inheritDoc} */
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
- log.info("{} Validating tx-code", getLogPrefix());
+ if (providedTxCode == null) {
+ log.warn("{} No Transaction Code presented, the Credential Offer requires one", getLogPrefix());
+ ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.TX_CODE_PRESENCE);
+ return;
+ }
if (!requiredTxCode.getValue().equals(providedTxCode)) {
- log.error("{} Provided tx code did not match the required one.", getLogPrefix());
+ log.warn("{} Presented Transaction Code does not match the Credential Offer", getLogPrefix());
ActionSupport.buildEvent(profileRequestContext, OpenIDVCIEventIds.INVALID_TX_CODE);
+ return;
}
-
+ log.debug("{} Transaction Code validated", getLogPrefix());
}
}
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/logic/OpenIDVCITokenManipulationStrategy.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/logic/OpenIDVCITokenManipulationStrategy.java
index 68b95d4..74ac44a 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/logic/OpenIDVCITokenManipulationStrategy.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/profile/logic/OpenIDVCITokenManipulationStrategy.java
@@ -125,7 +125,7 @@ public class OpenIDVCITokenManipulationStrategy
claims.put(AUTH_DETAILS, new ObjectMapper().writeValueAsString(details));
}
} catch (final JsonProcessingException e) {
- log.warn("{} Failed parsing", e);
+ log.warn("Failed serializing authorization_details", e);
}
}
final TokenContext tokenContext =
diff --git a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCache.java b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCache.java
index e3de35e..698a7ed 100644
--- a/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCache.java
+++ b/openid-vci-impl/src/main/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCache.java
@@ -19,8 +19,8 @@ package org.geant.shibboleth.plugin.openidvci.storage;
import java.io.IOException;
import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
-import net.minidev.json.parser.ParseException;
import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
import net.shibboleth.shared.annotation.constraint.NotEmpty;
import net.shibboleth.shared.annotation.constraint.ThreadSafeAfterInit;
@@ -32,11 +32,9 @@ import org.apache.commons.codec.digest.DigestUtils;
import org.opensaml.storage.StorageCapabilities;
import org.opensaml.storage.StorageRecord;
import org.opensaml.storage.StorageService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
- * Cache for storing {@link CredentialOfferObject} per pre-authorization code.
+ * Cache for storing {@link CredentialOfferObject} per pre-authorized code, keyed by the SHA-256 of the code.
*/
@ThreadSafeAfterInit
public class CredentialOfferCache extends AbstractIdentifiableInitializableComponent {
@@ -48,10 +46,11 @@ public class CredentialOfferCache extends AbstractIdentifiableInitializableCompo
@NotEmpty
public static final String CONTEXT_CREDENTIAL_OFFER = CredentialOfferCache.class.getName();
- /** Logger. */
- private final Logger log = LoggerFactory.getLogger(CredentialOfferCache.class);
+ /** Length of the storage key, the SHA-256 of a pre-authorized code in hex. */
+ private static final int KEY_SIZE = 64;
/** Backing storage for the cache. */
+ @NonnullAfterInit
private StorageService storage;
/**
@@ -77,6 +76,8 @@ public class CredentialOfferCache extends AbstractIdentifiableInitializableCompo
Constraint.isTrue(caps.isServerSide(), "StorageService cannot be client-side");
Constraint.isTrue(CONTEXT_CREDENTIAL_OFFER.length() <= caps.getContextSize(), "Context "
+ CONTEXT_CREDENTIAL_OFFER.length() + " too long for StorageService " + caps.getContextSize());
+ Constraint.isTrue(KEY_SIZE <= caps.getKeySize(), "Key size " + caps.getKeySize() + " of StorageService below "
+ + KEY_SIZE);
}
/** {@inheritDoc} */
@@ -89,73 +90,60 @@ public class CredentialOfferCache extends AbstractIdentifiableInitializableCompo
}
/**
- * Adjusts the key to smaller size if needed.
+ * Get the storage key of a pre-authorized code.
*
- * @param key key to adjust
- * @return key, either original or adjusted.
+ * @param code pre-authorized code
+ * @return SHA-256 of the code in hex
*/
- private String adjustKey(@Nonnull final String key) {
- final StorageCapabilities caps = storage.getCapabilities();
- return key.length() > caps.getKeySize() ? DigestUtils.sha256Hex(key) : key;
+ @Nonnull
+ private static String storageKey(@Nonnull final String code) {
+ return DigestUtils.sha256Hex(code);
}
/**
- * Stores CredentialOfferObject keyed with pre-authorization code.
+ * Stores CredentialOfferObject keyed with pre-authorized code.
*
- * @param object CredentialOfferObject to store.
- * @param code Pre-Authorizatio code for storing the
- * CredentialOfferObject.
- * @param expiration lifetime in milliseconds.
+ * @param object CredentialOfferObject to store.
+ * @param code Pre-authorized code for storing the CredentialOfferObject.
+ * @param lifetime lifetime in milliseconds.
* @return true if stored successfully.
* @throws IOException if something went wrong with storage.
*/
- public boolean storeCredentialOffer(@Nonnull final CredentialOfferObject object,
- @Nonnull final String code,
- final long expiration) throws IOException {
- final String preAuthorizationKey = adjustKey(code);
- if (!storage.create(CONTEXT_CREDENTIAL_OFFER, preAuthorizationKey, object.serialize(),
- System.currentTimeMillis() + expiration)) {
- log.debug("Pre-authorized code collision");
- return false;
- }
- return true;
+ public boolean storeCredentialOffer(@Nonnull final CredentialOfferObject object, @Nonnull final String code,
+ final long lifetime) throws IOException {
+ return storage.create(CONTEXT_CREDENTIAL_OFFER, storageKey(code), object.serialize(),
+ System.currentTimeMillis() + lifetime);
}
/**
- * Get CredentialOfferObject keyed with pre-authorization code.
+ * Get CredentialOfferObject keyed with pre-authorized code.
*
* @param code key to CredentialOfferObject.
- * @return CredentialOfferObject keyed with pre-authorization code. Null if not
- * located.
- * @throws IOException if something went wrong with storage.
- * @throws ParseException if CredentialOfferObject was not parsed successfully.
+ * @return CredentialOfferObject keyed with pre-authorized code. Null if not located.
+ * @throws IOException if something went wrong with storage or the stored CredentialOfferObject is not parsed.
*/
- @SuppressWarnings("rawtypes")
- public synchronized CredentialOfferObject getCredentialOffer(@Nonnull final String code)
- throws IOException, ParseException {
- final String key = adjustKey(code);
- final StorageRecord entry = storage.read(CONTEXT_CREDENTIAL_OFFER, key);
+ @Nullable
+ public CredentialOfferObject getCredentialOffer(@Nonnull final String code) throws IOException {
+ final StorageRecord<?> entry = storage.read(CONTEXT_CREDENTIAL_OFFER, storageKey(code));
if (entry == null) {
return null;
}
try {
- final CredentialOfferObject result = CredentialOfferObject.parse(entry.getValue());
- return result;
+ return CredentialOfferObject.parse(entry.getValue());
} catch (final com.nimbusds.oauth2.sdk.ParseException e) {
- log.error("Failed parsing CredentialOfferObject", e);
+ throw new IOException("Stored CredentialOfferObject not parsed", e);
}
- return null;
}
/**
- * Remove CredentialOfferObject keyed with pre-authorization code.
+ * Remove CredentialOfferObject keyed with pre-authorized code.
*
* @param code key to CredentialOfferObject.
+ * @return true if the CredentialOfferObject was removed, false if there was none.
* @throws IOException if something went wrong with storage.
*/
- public synchronized void removeCredentialOffer(@Nonnull final String code) throws IOException {
- final String key = adjustKey(code);
- storage.delete(CONTEXT_CREDENTIAL_OFFER, key);
+ public boolean removeCredentialOffer(@Nonnull final String code) throws IOException {
+ return storage.delete(CONTEXT_CREDENTIAL_OFFER, storageKey(code));
}
-}
\ No newline at end of file
+}
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 5add70f..12ab95a 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
@@ -98,6 +98,7 @@
p:httpServletRequestSupplier-ref="shibboleth.HttpServletRequestSupplier"
p:attesters="#{getObject('openidvci.ClientAttestationAttesters')}"
p:attestationClaimsValidator="#{getObject('openidvci.ClientAttestationClaimsValidator') ?: getObject('openidvci.DefaultClientAttestationClaimsValidator')}"
+ p:attestationFreshnessValidator="#{getObject('openidvci.ClientAttestationFreshnessValidator') ?: getObject('openidvci.DefaultClientAttestationFreshnessValidator')}"
p:proofClaimsValidator="#{getObject('openidvci.ClientAttestationPoPClaimsValidator') ?: getObject('openidvci.DefaultClientAttestationPoPClaimsValidator')}">
<property name="signatureAlgorithms">
<bean parent="shibboleth.CommaDelimStringArray"
@@ -121,12 +122,27 @@
</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}" />
+ <!-- iat not in the future. -->
+ <bean class="net.shibboleth.oidc.security.jwt.claims.impl.IssuedAtClaimsValidator"
+ p:id="openidvci.ClientAttestation.IssuedAtFutureClaimsValidator"
+ p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}"
+ p:messageLifetime="P36500D"
+ p:requiredRule="true" />
+ </list>
+ </property>
+ </bean>
+
+ <bean id="openidvci.DefaultClientAttestationFreshnessValidator" lazy-init="true"
+ class="net.shibboleth.oidc.security.jwt.claims.impl.ChainingJWTClaimsValidator"
+ p:id="openidvci.DefaultClientAttestationFreshnessValidator">
+ <property name="claimValidators">
+ <list>
+ <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.IssuedAtClaimsValidator"
p:id="openidvci.ClientAttestation.IssuedAtClaimsValidator"
p:clockSkew="%{openidvci.attestation.clockSkew:PT5M}"
diff --git a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-beans.xml b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-beans.xml
index 75984df..3b4ed91 100644
--- a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-beans.xml
+++ b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-beans.xml
@@ -17,11 +17,16 @@
<!-- Beans named by openid/vci/abstract-api. -->
- <bean id="openidvci.profileId" class="java.lang.String" c:_0="http://geant.org/ns/profiles/openid/vci/token"/>
+ <bean id="openidvci.profileId" class="java.lang.String"
+ c:_0="#{T(org.geant.shibboleth.plugin.openidvci.profile.config.OpenIDVCIConfiguration).PROFILE_ID_TOKEN}"/>
<bean id="openidvci.loggingId" class="java.lang.String"
c:_0="%{openidvci.logging.token:OpenID.VCI.Token}"/>
+ <!-- REPLACED shibboleth.metrics.ProfileCounter, keeping the bean id. -->
+ <util:constant id="shibboleth.metrics.ProfileCounter"
+ static-field="org.geant.shibboleth.plugin.openidvci.profile.config.impl.DefaultOpenIDVCITokenConfiguration.PROFILE_COUNTER"/>
+
<!-- In place of DecodeMessage, with OpenIDVCITokenRequestDecoder in place of OIDCTokenRequestDecoder. -->
<bean id="OpenIDVCIDecodeMessage" class="org.opensaml.profile.action.impl.DecodeMessage" scope="prototype">
<constructor-arg>
@@ -36,11 +41,12 @@
<bean id="OpenIDVCIFormOutboundMessage"
class="org.geant.shibboleth.plugin.openidvci.profile.impl.FormOutboundTokenResponseMessage" scope="prototype" />
- <!-- In place of BuildErrorResponseFromEvent, with the error map of this plugin. -->
+ <!-- In place of BuildErrorResponseFromEvent, with the error map of this plugin and use_fresh_attestation. -->
<bean id="OpenIDVCIBuildErrorResponseFromEvent"
- class="net.shibboleth.idp.plugin.oidc.op.profile.impl.BuildTokenErrorResponseFromEvent" scope="prototype"
+ class="org.geant.shibboleth.plugin.openidvci.profile.impl.OpenIDVCIBuildTokenErrorResponseFromEvent"
+ scope="prototype"
p:httpServletResponseSupplier-ref="shibboleth.HttpServletResponseSupplier"
- p:mappedErrors="#{getObject('shibboleth.oidc.token.MappedErrors') ?: getObject('openidvci.token.MappedErrors')}">
+ p:mappedErrors="#{getObject('openidvci.token.MappedErrors') ?: getObject('openidvci.token.DefaultMappedErrors')}">
<property name="eventContextLookupStrategy">
<bean class="net.shibboleth.idp.profile.context.navigate.WebFlowCurrentEventLookupFunction" />
</property>
@@ -51,9 +57,7 @@
APIRequestClientIDLookupFunction in place of TokenRequestClientIDLookupFunction.
-->
<bean id="shibboleth.ClientIDLookupStrategy"
- class="org.geant.shibboleth.plugin.openidvci.profile.context.navigate.APIRequestClientIDLookupFunction"
- p:credentialOfferCache-ref="openidvci.CredentialOfferCache"
- p:dataSealer-ref="#{'%{idp.oidc.tokenSealer:shibboleth.oidc.TokenSealer}'.trim()}" />
+ class="org.geant.shibboleth.plugin.openidvci.profile.context.navigate.APIRequestClientIDLookupFunction" />
<!-- Beans of this flow in place of beans of oidc/token. -->
@@ -189,12 +193,16 @@
p:customObject-ref="OpenIDVCICredentialIssuerIdentifierLookup" />
<!-- Error map of this plugin, extending the map of the OP. -->
- <bean id="openidvci.token.MappedErrors" parent="shibboleth.oidc.DefaultApiMappedErrors"
+ <bean id="openidvci.token.DefaultMappedErrors" parent="shibboleth.oidc.DefaultApiMappedErrors"
class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map merge="true" value-type="com.nimbusds.oauth2.sdk.ErrorObject">
<entry key="#{T(org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds).INVALID_TX_CODE}"
value="#{T(com.nimbusds.oauth2.sdk.OAuth2Error).INVALID_GRANT}" />
+ <entry key="#{T(org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds).TX_CODE_PRESENCE}"
+ value="#{T(com.nimbusds.oauth2.sdk.OAuth2Error).INVALID_REQUEST}" />
+ <entry key="#{T(org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds).NO_CREDENTIALS_FOR_REQUEST}"
+ value="#{T(org.geant.shibboleth.plugin.openidvci.messaging.error.OpenIDVCIError).INVALID_AUTHORIZATION_DETAILS}" />
<entry key="#{T(org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds).NO_CREDENTIAL_OFFER}"
value="#{T(com.nimbusds.oauth2.sdk.OAuth2Error).INVALID_GRANT}" />
<!-- Both are of PKCE validation, RFC 7636 section 4.6. -->
diff --git a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-flow.xml b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-flow.xml
index 543bbfd..1e7bbf4 100644
--- a/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-flow.xml
+++ b/openid-vci-impl/src/main/resources/META-INF/net/shibboleth/idp/flows/openid/vci/token/token-flow.xml
@@ -149,7 +149,7 @@
<transition on="proceed" to="OpenIDVCIBuildTokensForCredentialsAccess" />
</action-state>
- <!-- ADDED. Token building of both grants of this endpoint. -->
+ <!-- ADDED. The opaque access token of the pre-authorized code grant. -->
<action-state id="OpenIDVCIBuildTokensForCredentialsAccess">
<evaluate expression="OpenIDVCISetAuthorizationDetailsToResponseContext" />
<evaluate expression="OpenIDVCISetCredentialsAudienceToResponseContext" />
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 6ef2db0..b6b3f8d 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
@@ -62,6 +62,7 @@ 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.context.AuthenticationErrorContext;
import net.shibboleth.idp.authn.principal.UsernamePrincipal;
import net.shibboleth.oidc.jwt.claims.AbstractClaimsValidator;
import net.shibboleth.oidc.jwt.claims.ClaimsValidator;
@@ -122,8 +123,9 @@ public class ClientAttestationCredentialValidatorTest {
validator.setId("test");
validator.setTrustAnchors(CollectionSupport.listOf(new BasicX509Credential(read("attestation-ca.crt"))));
validator.setHttpServletRequestSupplier(() -> request);
- validator.setAttestationClaimsValidator(chain(required("sub", "exp", "iat", "cnf"), expiry(), notBefore(),
- issuedAt(Duration.ofDays(365))));
+ validator.setAttestationClaimsValidator(
+ chain(required("sub", "exp", "iat", "cnf"), notBefore(), issuedAt(Duration.ofDays(36500))));
+ validator.setAttestationFreshnessValidator(chain(expiry(), issuedAt(Duration.ofDays(365))));
final AudienceClaimsValidator audience = new AudienceClaimsValidator();
audience.setAudienceLookupStrategy((context, claims) -> AUDIENCE);
audience.setExtraAudienceValidation(true);
@@ -290,6 +292,59 @@ public class ClientAttestationCredentialValidatorTest {
pop(popClaims()));
}
+ private void assertUseFreshAttestation(final JWTClaimsSet.Builder claims) throws Exception {
+ try {
+ validate(attestation(claims), pop(popClaims()));
+ Assert.fail("Validation must fail");
+ } catch (final JWTValidationException e) {
+ final AuthenticationErrorContext errorContext =
+ authnContext.getSubcontext(AuthenticationErrorContext.class);
+ Assert.assertNotNull(errorContext);
+ Assert.assertTrue(errorContext.getClassifiedErrors()
+ .contains(ClientAttestationCredentialValidator.USE_FRESH_ATTESTATION));
+ }
+ }
+
+ @Test
+ public void testAttestationTooOldClassified() throws Exception {
+ assertUseFreshAttestation(
+ attestationClaims().issueTime(Date.from(Instant.now().minus(Duration.ofDays(400)))));
+ }
+
+ @Test
+ public void testAttestationExpiredClassified() throws Exception {
+ assertUseFreshAttestation(
+ attestationClaims().expirationTime(Date.from(Instant.now().minus(Duration.ofHours(1)))));
+ }
+
+ @Test
+ public void testAttestationIssuedInFutureNotClassified() throws Exception {
+ try {
+ validate(attestation(attestationClaims().issueTime(Date.from(Instant.now().plus(Duration.ofHours(1))))
+ .expirationTime(Date.from(Instant.now().plus(Duration.ofHours(2))))), pop(popClaims()));
+ Assert.fail("Validation must fail");
+ } catch (final JWTValidationException e) {
+ final AuthenticationErrorContext errorContext =
+ authnContext.getSubcontext(AuthenticationErrorContext.class);
+ Assert.assertTrue(errorContext == null || !errorContext.getClassifiedErrors()
+ .contains(ClientAttestationCredentialValidator.USE_FRESH_ATTESTATION));
+ }
+ }
+
+ @Test
+ public void testOtherFailureNotClassified() throws Exception {
+ prc.ensureInboundMessageContext().setMessage(pushed("other-client"));
+ try {
+ validate(attestation(attestationClaims()), pop(popClaims()));
+ Assert.fail("Validation must fail");
+ } catch (final JWTValidationException e) {
+ final AuthenticationErrorContext errorContext =
+ authnContext.getSubcontext(AuthenticationErrorContext.class);
+ Assert.assertTrue(errorContext == null || !errorContext.getClassifiedErrors()
+ .contains(ClientAttestationCredentialValidator.USE_FRESH_ATTESTATION));
+ }
+ }
+
@Test(expectedExceptions = JWTValidationException.class)
public void testPushedAuthorizationRequestOfAnotherClient() throws Exception {
prc.ensureInboundMessageContext().setMessage(pushed("other-client"));
@@ -320,6 +375,7 @@ public class ClientAttestationCredentialValidatorTest {
pinned.setTrustAnchors(CollectionSupport.listOf(new BasicX509Credential(read("attestation-ca.crt"))));
pinned.setHttpServletRequestSupplier(() -> request);
pinned.setAttestationClaimsValidator(chain(required("sub")));
+ pinned.setAttestationFreshnessValidator(chain(required("sub")));
pinned.setProofClaimsValidator(chain(required("aud")));
pinned.setAttesters(names);
pinned.initialize();
@@ -383,6 +439,7 @@ public class ClientAttestationCredentialValidatorTest {
strict.setTrustAnchors(CollectionSupport.listOf(new BasicX509Credential(read("attestation-ca.crt"))));
strict.setHttpServletRequestSupplier(() -> request);
strict.setAttestationClaimsValidator(chain(required("sub")));
+ strict.setAttestationFreshnessValidator(chain(required("sub")));
strict.setProofClaimsValidator(chain(required("aud")));
strict.setSignatureAlgorithms(Set.of("ES384"));
strict.initialize();
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoderTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoderTest.java
index a0dfbb7..0047334 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoderTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/decoding/impl/OpenIDVCITokenRequestDecoderTest.java
@@ -112,4 +112,28 @@ public class OpenIDVCITokenRequestDecoderTest {
Assert.assertEquals(request.getResources().get(0).toString(), "urn:shibboleth.oidc.op.resource:api");
}
+ @Test
+ public void testTxCodeNotLogged() throws MessageDecodingException {
+ httpRequest.addParameter("tx_code", "493536");
+ decoder.decode();
+ final OpenIDVCITokenRequest request = (OpenIDVCITokenRequest) decoder.getMessageContext().getMessage();
+ Assert.assertEquals(request.getTxCode(), "493536");
+ final String logged = decoder.getMessageToLog(request);
+ Assert.assertFalse(logged.contains("493536"), logged);
+ Assert.assertTrue(logged.contains("tx_code="), logged);
+ }
+
+ @Test
+ public void testCodeLoggedOnce() throws MessageDecodingException {
+ httpRequest.removeParameter("pre-authorized_code");
+ httpRequest.setParameter("grant_type", "authorization_code");
+ httpRequest.addParameter("code", "codeValue1");
+ httpRequest.addParameter("code_verifier", "wzYAXaFZTuabNSWQUDPZuvAzmwVETLFyNJmtJGDWheU");
+ decoder.decode();
+ final String logged = decoder.getMessageToLog(
+ (OpenIDVCITokenRequest) decoder.getMessageContext().getMessage());
+ Assert.assertEquals(logged.split("codeValue1", -1).length - 1, 1, logged);
+ Assert.assertTrue(logged.split("wzYAXaFZTuabNSWQUDPZuvAzmwVETLFyNJmtJGDWheU", -1).length - 1 <= 1, logged);
+ }
+
}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunctionTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunctionTest.java
index cb0b7b4..04ff55a 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunctionTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/context/navigate/AuthorizationDetailsLookupFunctionTest.java
@@ -17,23 +17,31 @@
package org.geant.shibboleth.plugin.openidvci.messaging.context.navigate;
import java.net.URI;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCIAuthorizationDetail;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.profile.logic.OpenIDVCITokenManipulationStrategy;
import org.opensaml.messaging.context.MessageContext;
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.jwt.JWTClaimsSet;
import com.nimbusds.jwt.PlainJWT;
import com.nimbusds.oauth2.sdk.AuthorizationRequest;
import com.nimbusds.oauth2.sdk.ResponseType;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
import com.nimbusds.oauth2.sdk.id.ClientID;
import net.shibboleth.idp.plugin.oidc.op.messaging.context.OIDCAuthenticationResponseContext;
+import net.shibboleth.idp.plugin.oidc.op.token.support.AccessTokenClaimsSet;
/**
* Unit tests for {@link AuthorizationDetailsLookupFunction}.
@@ -114,4 +122,53 @@ public class AuthorizationDetailsLookupFunctionTest {
Assert.assertNull(lookup.apply(profileRequestCtx));
}
+ private void setTokenRequest(final String requestDetails, final String grantDetails) throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, URI.create("http://example.com"));
+ httpRequest.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ httpRequest.setBody("client_id=client&grant_type=authorization_code&code=123456"
+ + (requestDetails != null ? "&authorization_details="
+ + URLEncoder.encode(requestDetails, StandardCharsets.UTF_8) : ""));
+ profileRequestCtx.getInboundMessageContext().setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ final AccessTokenClaimsSet.Builder builder = new AccessTokenClaimsSet.Builder();
+ builder.setJWTID("jti").setClientID(new ClientID("client")).setIssuer("issuer").setPrincipal("principal")
+ .setSubject("subject").setIssuedAt(Instant.now()).setExpiresAt(Instant.now().plusSeconds(60))
+ .setAuthenticationTime(Instant.now());
+ if (grantDetails != null) {
+ builder.addCustomClaim(OpenIDVCITokenManipulationStrategy.AUTH_DETAILS, grantDetails);
+ }
+ profileRequestCtx.getOutboundMessageContext().ensureSubcontext(OIDCAuthenticationResponseContext.class)
+ .setAuthorizationGrantClaimsSet(builder.build());
+ }
+
+ private static final String OTHER =
+ "[{\"type\":\"openid_credential\",\"credential_configuration_id\":\"OtherCredential\"}]";
+
+ @Test
+ public void testTokenRequestDetails() throws Exception {
+ setTokenRequest(OTHER, DETAILS);
+ Assert.assertEquals(lookup.apply(profileRequestCtx).get(0).getCredentialConfigurationId(), "OtherCredential");
+ }
+
+ @Test
+ public void testGrantDetails() throws Exception {
+ setTokenRequest(null, DETAILS);
+ Assert.assertEquals(lookup.apply(profileRequestCtx).get(0).getCredentialConfigurationId(),
+ "GeantIncubatorDiploma");
+ }
+
+ @Test
+ public void testGrantOnly() throws Exception {
+ setTokenRequest(OTHER, DETAILS);
+ lookup.setGrantOnly(true);
+ Assert.assertEquals(lookup.apply(profileRequestCtx).get(0).getCredentialConfigurationId(),
+ "GeantIncubatorDiploma");
+ }
+
+ @Test
+ public void testGrantOnlyNoGrantDetails() throws Exception {
+ setTokenRequest(OTHER, null);
+ lookup.setGrantOnly(true);
+ Assert.assertNull(lookup.apply(profileRequestCtx));
+ }
+
}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequestTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequestTest.java
index eb9d817..e415055 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequestTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/messaging/impl/OpenIDVCITokenRequestTest.java
@@ -19,8 +19,7 @@ package org.geant.shibboleth.plugin.openidvci.messaging.impl;
import java.net.URI;
import java.net.URISyntaxException;
-import org.opensaml.messaging.decoder.MessageDecodingException;
-import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -32,7 +31,6 @@ import com.nimbusds.oauth2.sdk.GrantType;
import com.nimbusds.oauth2.sdk.OAuth2Error;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.RefreshTokenGrant;
-import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
import com.nimbusds.oauth2.sdk.auth.Secret;
import com.nimbusds.oauth2.sdk.http.HTTPRequest;
@@ -47,75 +45,6 @@ public class OpenIDVCITokenRequestTest {
private OpenIDVCITokenRequest message;
private HTTPRequest httpRequest;
- // @BeforeMethod
- protected void setUp() throws Exception {
- httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
- httpRequest.setContentType(ContentType.APPLICATION_URLENCODED.toString());
- httpRequest.setBody(
- "client_id=clientID&grant_type=urn:ietf:params:oauth:grant-type:pre-authorized_code&pre-authorized_code=123456&tx_code=txCodeValue&code_verifier=wzYAXaFZTuabNSWQUDPZuvAzmwVETLFyNJmtJGDWheU&authorization_details=[{\"type\":\"openid_credential\",\"credential_configuration_id\":\"UniversityDegreeCredential\",\"claims\":[{\"path\":[\"credentialSubject\",\"given_name\"],\"mandatory\":true},{\"path\":[\"credentialSubject\",\"family_name\"]},{\"path\":[\"credentialSubject\",\"de [...]
-
- message = OpenIDVCITokenRequest.parse(httpRequest);
- }
-
- // @Test
- public void testGetters() throws MessageDecodingException {
- Assert.assertEquals("clientID", message.getClientID().getValue());
- Assert.assertEquals("123456", message.getPreAuthorizedCode());
- Assert.assertEquals(OpenIDVCITokenRequest.GRANT_TYPE_VALUE_PRE_AUTH, message.getGrantType());
- Assert.assertNull(message.getClientAuthentication());
- Assert.assertEquals("http://example.com", message.getEndpointURI().toString());
- Assert.assertEquals("txCodeValue", message.getTxCode());
- Assert.assertEquals("CodeVerifier", message.getCodeVerifier());
- Assert.assertEquals(message.getCredentialAuthorizationDetails().size(), 1);
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getType(), "openid_credential");
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getCredentialConfigurationId(),
- "UniversityDegreeCredential");
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().size(), 3);
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().get(0).getPath().get(0),
- "credentialSubject");
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().get(0).getPath().get(1),
- "given_name");
- Assert.assertTrue(message.getCredentialAuthorizationDetails().get(0).getClaims().get(0).getMandatory());
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().get(1).getPath().get(0),
- "credentialSubject");
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().get(1).getPath().get(1),
- "family_name");
- Assert.assertFalse(message.getCredentialAuthorizationDetails().get(0).getClaims().get(1).getMandatory());
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().get(2).getPath().get(0),
- "credentialSubject");
- Assert.assertEquals(message.getCredentialAuthorizationDetails().get(0).getClaims().get(2).getPath().get(1),
- "degree");
- Assert.assertFalse(message.getCredentialAuthorizationDetails().get(0).getClaims().get(2).getMandatory());
- Assert.assertTrue(message.getAuthorizationGrant() instanceof PreAuthorizedCodeGrant);
- Assert.assertEquals(message.getAuthorizationGrant().getType(), PreAuthorizedCodeGrant.GRANT_TYPE);
- Assert.assertEquals(((PreAuthorizedCodeGrant) message.getAuthorizationGrant()).getPreAuthorizedCode(),
- "123456");
- }
-
- // @Test(expectedExceptions = IllegalArgumentException.class)
- public void testInvalidGrantType() throws MessageDecodingException, URISyntaxException {
- message = new OpenIDVCITokenRequest(new URI("http://example.com"), new ClientID("clientID"), "none", "123456",
- null, null, null, null);
- }
-
- // @Test(expectedExceptions = IllegalArgumentException.class)
- public void testMissingCode() throws MessageDecodingException, URISyntaxException {
- message = new OpenIDVCITokenRequest(new URI("http://example.com"), new ClientID("clientID"),
- OpenIDVCITokenRequest.GRANT_TYPE_VALUE_PRE_AUTH, null, null, null, null, null);
- }
-
- // @Test
- public void testClientAuthnGetters() throws MessageDecodingException, ParseException, URISyntaxException {
- ClientAuthentication clientAuth = new ClientSecretBasic(new ClientID("clientID"), new Secret());
- message = new OpenIDVCITokenRequest(new URI("http://example.com"), clientAuth,
- OpenIDVCITokenRequest.GRANT_TYPE_VALUE_PRE_AUTH, "123456", null, null, null, null);
- Assert.assertNull(message.getClientID());
- Assert.assertEquals("123456", message.getPreAuthorizedCode());
- Assert.assertEquals(OpenIDVCITokenRequest.GRANT_TYPE_VALUE_PRE_AUTH, message.getGrantType());
- Assert.assertEquals("clientID", message.getClientAuthentication().getClientID().getValue());
- Assert.assertEquals("http://example.com", message.getEndpointURI().toString());
- }
-
@Test
public void parseCodeGrant() throws ParseException, JsonProcessingException, URISyntaxException {
httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
@@ -196,4 +125,122 @@ public class OpenIDVCITokenRequestTest {
Assert.assertEquals(e.getErrorObject().getCode(), OAuth2Error.INVALID_REQUEST.getCode());
}
+ private static final String VERIFIER = "wzYAXaFZTuabNSWQUDPZuvAzmwVETLFyNJmtJGDWheU";
+
+ private static final String PRE_AUTH = "grant_type=urn:ietf:params:oauth:grant-type:pre-authorized_code";
+
+ private static final String CODE = "client_id=clientID&grant_type=authorization_code&code=123456";
+
+ private static void parseFails(final String body) throws URISyntaxException {
+ final HTTPRequest request = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ request.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ request.setBody(body);
+ final ParseException e = Assert.expectThrows(ParseException.class, () -> OpenIDVCITokenRequest.parse(request));
+ Assert.assertEquals(e.getErrorObject().getCode(), OAuth2Error.INVALID_REQUEST.getCode());
+ }
+
+ @Test
+ public void parsePreAuthMissingCode() throws URISyntaxException {
+ parseFails(PRE_AUTH + "&tx_code=1234");
+ }
+
+ @Test
+ public void parsePreAuthEmptyCode() throws URISyntaxException {
+ parseFails(PRE_AUTH + "&pre-authorized_code=");
+ }
+
+ @Test
+ public void parseCodeGrantMissingCode() throws URISyntaxException {
+ parseFails("client_id=clientID&grant_type=authorization_code&code_verifier=" + VERIFIER);
+ }
+
+ @Test
+ public void parseShortCodeVerifier() throws URISyntaxException {
+ parseFails(CODE + "&code_verifier=" + VERIFIER.substring(1));
+ }
+
+ @Test
+ public void parseLongCodeVerifier() throws URISyntaxException {
+ parseFails(CODE + "&code_verifier=" + VERIFIER + VERIFIER + VERIFIER.substring(0, 43));
+ }
+
+ @Test
+ public void parseCodeGrantRedirectURI() throws ParseException, URISyntaxException {
+ httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setContentType(ContentType.APPLICATION_URLENCODED.toString());
+ httpRequest.setBody(CODE + "&redirect_uri=https%3A%2F%2Fwallet.example.org%2Fcb");
+ message = OpenIDVCITokenRequest.parse(httpRequest);
+ Assert.assertEquals(((AuthorizationCodeGrant) message.getAuthorizationGrant()).getRedirectionURI(),
+ new URI("https://wallet.example.org/cb"));
+ }
+
+ @Test
+ public void parseCodeGrantMalformedRedirectURI() throws URISyntaxException {
+ parseFails(CODE + "&redirect_uri=https%3A%2F%2Fwallet.example.org%2Fc%20b");
+ }
+
+ @DataProvider
+ public Object[][] repeatedParameters() {
+ return new Object[][] {
+ {PRE_AUTH + "&pre-authorized_code=1&grant_type=authorization_code"},
+ {PRE_AUTH + "&pre-authorized_code=1&pre-authorized_code=2"},
+ {PRE_AUTH + "&pre-authorized_code=1&tx_code=1234&tx_code=5678"},
+ {CODE + "&code=654321"},
+ {CODE + "&code_verifier=" + VERIFIER + "&code_verifier=" + VERIFIER},
+ {CODE + "&redirect_uri=https%3A%2F%2Fa.example.org&redirect_uri=https%3A%2F%2Fb.example.org"},
+ };
+ }
+
+ @Test(dataProvider = "repeatedParameters")
+ public void parseRepeatedParameter(final String body) throws URISyntaxException {
+ parseFails(body);
+ }
+
+ private static OpenIDVCITokenRequest parse(final String body) throws Exception {
+ final HTTPRequest request = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ request.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ request.setBody(body);
+ return OpenIDVCITokenRequest.parse(request);
+ }
+
+ private static void parseFailsWith(final String body, final String code) throws URISyntaxException {
+ final HTTPRequest request = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ request.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ request.setBody(body);
+ final ParseException e = Assert.expectThrows(ParseException.class, () -> OpenIDVCITokenRequest.parse(request));
+ Assert.assertEquals(e.getErrorObject().getCode(), code);
+ }
+
+ @Test
+ public void parseCodeGrantWithoutClient() throws URISyntaxException {
+ parseFailsWith("grant_type=authorization_code&code=123456&code_verifier=" + VERIFIER,
+ OAuth2Error.INVALID_REQUEST.getCode());
+ }
+
+ @Test
+ public void parseResourceWithQuote() throws URISyntaxException {
+ parseFailsWith(CODE + "&resource=https%3A%2F%2Fexample.org%2F%22a", OAuth2Error.INVALID_TARGET.getCode());
+ }
+
+ @Test
+ public void parseResourceWithNonAsciiCharacter() throws URISyntaxException {
+ parseFailsWith(CODE + "&resource=%C3%A4", OAuth2Error.INVALID_TARGET.getCode());
+ }
+
+ @Test
+ public void parseEmptyTxCode() throws Exception {
+ Assert.assertNull(parse(PRE_AUTH + "&pre-authorized_code=1&tx_code=").getTxCode());
+ }
+
+ @Test
+ public void parseEmptyRedirectURI() throws Exception {
+ Assert.assertNull(((AuthorizationCodeGrant) parse(CODE + "&redirect_uri=").getAuthorizationGrant())
+ .getRedirectionURI());
+ }
+
+ @Test
+ public void parseEmptyCodeVerifier() throws Exception {
+ Assert.assertNull(parse(CODE + "&code_verifier=").getCodeVerifier());
+ }
+
}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunctionTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunctionTest.java
new file mode 100644
index 0000000..5343072
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/context/navigate/APIRequestClientIDLookupFunctionTest.java
@@ -0,0 +1,104 @@
+/*
+ * 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.profile.context.navigate;
+
+import java.net.URI;
+
+import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.CredentialOfferRequest;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferObject;
+import org.opensaml.messaging.context.MessageContext;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.nimbusds.common.contenttype.ContentType;
+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;
+
+/**
+ * Unit tests for {@link APIRequestClientIDLookupFunction}.
+ */
+public class APIRequestClientIDLookupFunctionTest {
+
+ private static final String PRE_AUTH = "grant_type=urn:ietf:params:oauth:grant-type:pre-authorized_code"
+ + "&pre-authorized_code=storedCode0123456789";
+
+ private final APIRequestClientIDLookupFunction lookup = new APIRequestClientIDLookupFunction();
+
+ private static MessageContext tokenRequest(final String body, final ClientSecretBasic auth) throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ if (auth != null) {
+ httpRequest.setAuthorization(auth.toHTTPAuthorizationHeader());
+ }
+ httpRequest.setBody(body);
+ final MessageContext messageContext = new MessageContext();
+ messageContext.setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ return messageContext;
+ }
+
+ private static void setOffer(final MessageContext messageContext) {
+ messageContext.ensureSubcontext(TokenContext.class)
+ .setCredentialOfferObject(new CredentialOfferObject(new ClientID("offer-caller"), null, null, null));
+ }
+
+ @Test
+ public void testClientAuthentication() throws Exception {
+ final MessageContext messageContext =
+ tokenRequest(PRE_AUTH, new ClientSecretBasic(new ClientID("authenticated"), new Secret("secret")));
+ setOffer(messageContext);
+ Assert.assertEquals(lookup.apply(messageContext).getValue(), "authenticated");
+ }
+
+ @Test
+ public void testOffer() throws Exception {
+ final MessageContext messageContext = tokenRequest(PRE_AUTH + "&client_id=wallet", null);
+ setOffer(messageContext);
+ Assert.assertEquals(lookup.apply(messageContext).getValue(), "offer-caller/wallet");
+ }
+
+ @Test
+ public void testRequestClientID() throws Exception {
+ Assert.assertEquals(lookup.apply(tokenRequest(PRE_AUTH + "&client_id=wallet", null)).getValue(), "wallet");
+ }
+
+ @Test
+ public void testNoClientID() throws Exception {
+ Assert.assertNull(lookup.apply(tokenRequest(PRE_AUTH, null)));
+ }
+
+ @Test
+ public void testCredentialOfferRequest() throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setAuthorization("Basic dGVzdDp0ZXN0");
+ httpRequest.setContentType("application/json");
+ httpRequest.setBody("{\"preAuthorizedCredentials\":{\"GeantIncubatorSdJwt2\":"
+ + "[{\"path\":[\"mail\"],\"value\":\"incubatorUser at example.org\"}]}}");
+ final MessageContext messageContext = new MessageContext();
+ messageContext.setMessage(CredentialOfferRequest.parse(httpRequest));
+ Assert.assertNull(lookup.apply(messageContext));
+ }
+
+ @Test
+ public void testNoInput() {
+ Assert.assertNull(lookup.apply(null));
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOfferTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOfferTest.java
new file mode 100644
index 0000000..730dd1f
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ConsumeCredentialOfferTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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.profile.impl;
+
+import java.net.URI;
+import java.time.Instant;
+
+import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds;
+import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferCache;
+import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferObject;
+import org.geant.shibboleth.plugin.openidvci.token.support.CredentialOfferClaimsSet;
+import org.opensaml.messaging.context.MessageContext;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.storage.impl.MemoryStorageService;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.common.contenttype.ContentType;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+
+import net.shibboleth.idp.profile.context.navigate.WebflowRequestContextProfileRequestContextLookup;
+import net.shibboleth.idp.profile.testing.ActionTestingSupport;
+import net.shibboleth.idp.profile.testing.RequestContextBuilder;
+
+/**
+ * Unit tests for {@link ConsumeCredentialOffer}.
+ */
+public class ConsumeCredentialOfferTest {
+
+ private static final String CODE = "storedCode0123456789";
+
+ private RequestContext requestCtx;
+
+ private TokenContext tokenContext;
+
+ private CountingStorageService storageService;
+
+ private CredentialOfferCache cache;
+
+ private CredentialOfferObject offer;
+
+ private ConsumeCredentialOffer action;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ storageService = new CountingStorageService();
+ storageService.setId("test");
+ storageService.initialize();
+ cache = new CredentialOfferCache();
+ cache.setStorage(storageService);
+ cache.initialize();
+ offer = new CredentialOfferObject(new ClientID("offer-caller"), null, null, null);
+
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ httpRequest.setBody("grant_type=urn:ietf:params:oauth:grant-type:pre-authorized_code&pre-authorized_code="
+ + CODE);
+ requestCtx = new RequestContextBuilder().buildRequestContext();
+ final ProfileRequestContext profileRequestCtx =
+ new WebflowRequestContextProfileRequestContextLookup().apply(requestCtx);
+ profileRequestCtx.setInboundMessageContext(new MessageContext());
+ profileRequestCtx.getInboundMessageContext().setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ tokenContext = profileRequestCtx.getInboundMessageContext().ensureSubcontext(TokenContext.class);
+ tokenContext.setCredentialOfferObject(offer);
+
+ action = new ConsumeCredentialOffer();
+ action.setCredentialOfferCache(cache);
+ action.initialize();
+ }
+
+ @AfterMethod
+ protected void tearDown() {
+ cache.destroy();
+ storageService.destroy();
+ }
+
+ @Test
+ public void testConsumed() throws Exception {
+ cache.storeCredentialOffer(offer, CODE, 600000);
+
+ ActionTestingSupport.assertProceedEvent(action.execute(requestCtx));
+ Assert.assertNull(cache.getCredentialOffer(CODE));
+ }
+
+ @Test
+ public void testAlreadyConsumed() throws Exception {
+ ActionTestingSupport.assertEvent(action.execute(requestCtx), OpenIDVCIEventIds.NO_CREDENTIAL_OFFER);
+ }
+
+ @Test
+ public void testSealedCodeNotDeleted() throws Exception {
+ tokenContext.setCredentialOfferClaimsSet(new CredentialOfferClaimsSet.Builder()
+ .setIssuer("https://issuer.example.org").setClientID(new ClientID("offer-caller"))
+ .setJWTID("jti").setIssuedAt(Instant.now()).setAuthenticationTime(Instant.now())
+ .setSubject(offer.serialize()).setExpiresAt(Instant.now().plusSeconds(600)).build());
+
+ ActionTestingSupport.assertProceedEvent(action.execute(requestCtx));
+ Assert.assertEquals(storageService.deleteCalls, 0);
+ }
+
+ /** Storage counting the delete calls. */
+ private static class CountingStorageService extends MemoryStorageService {
+
+ private int deleteCalls;
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean delete(final String context, final String key) throws java.io.IOException {
+ deleteCalls++;
+ return super.delete(context, key);
+ }
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentialsTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentialsTest.java
index da75128..cbfb8d5 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentialsTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/FilterPotentialCredentialsTest.java
@@ -17,10 +17,14 @@
package org.geant.shibboleth.plugin.openidvci.profile.impl;
import java.util.List;
+import java.net.URI;
+import java.time.Instant;
import org.geant.shibboleth.plugin.openidvci.credential.impl.FilesystemCredentialConfigurationsResolver;
import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCIAuthorizationDetail;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.profile.logic.OpenIDVCITokenManipulationStrategy;
import org.opensaml.messaging.context.MessageContext;
import org.opensaml.profile.context.ProfileRequestContext;
import org.springframework.core.io.ClassPathResource;
@@ -30,9 +34,13 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.nimbusds.oauth2.sdk.Scope;
+import com.nimbusds.common.contenttype.ContentType;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.openid.connect.sdk.claims.ClaimsSet;
import net.shibboleth.idp.plugin.oidc.op.messaging.context.OIDCAuthenticationResponseContext;
+import net.shibboleth.idp.plugin.oidc.op.token.support.AccessTokenClaimsSet;
import net.shibboleth.idp.profile.context.navigate.WebflowRequestContextProfileRequestContextLookup;
import net.shibboleth.idp.profile.testing.ActionTestingSupport;
import net.shibboleth.idp.profile.testing.RequestContextBuilder;
@@ -113,4 +121,30 @@ public class FilterPotentialCredentialsTest {
Assert.assertTrue(tokenContext.getPotentialCredentials().toJSONObject().isEmpty());
}
+ @Test
+ public void testGrantLimitsTokenRequestDetails() throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ httpRequest.setBody("client_id=client&grant_type=authorization_code&code=123456&authorization_details="
+ + "%5B%7B%22type%22%3A%22openid_credential%22%2C%22credential_configuration_id%22%3A"
+ + "%22OtherCredential%22%7D%5D");
+ final ProfileRequestContext profileRequestCtx =
+ new WebflowRequestContextProfileRequestContextLookup().apply(requestCtx);
+ profileRequestCtx.getInboundMessageContext().setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ final AccessTokenClaimsSet.Builder builder = new AccessTokenClaimsSet.Builder();
+ builder.setJWTID("jti").setClientID(new ClientID("client")).setIssuer("issuer").setPrincipal("principal")
+ .setSubject("subject").setIssuedAt(Instant.now()).setExpiresAt(Instant.now().plusSeconds(60))
+ .setAuthenticationTime(Instant.now());
+ builder.addCustomClaim(OpenIDVCITokenManipulationStrategy.AUTH_DETAILS,
+ "[{\"type\":\"openid_credential\",\"credential_configuration_id\":\"UnscopedCredential\"}]");
+ responseCtx.setAuthorizationGrantClaimsSet(builder.build());
+
+ final FilterPotentialCredentials action = new FilterPotentialCredentials();
+ action.setCredentialConfigurationsResolver(resolver);
+ action.initialize();
+ ActionTestingSupport.assertProceedEvent(action.execute(requestCtx));
+ Assert.assertEquals(tokenContext.getPotentialCredentials().toJSONObject().keySet(),
+ java.util.Set.of("UnscopedCredential"));
+ }
+
}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/OpenIDVCIBuildTokenErrorResponseFromEventTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/OpenIDVCIBuildTokenErrorResponseFromEventTest.java
new file mode 100644
index 0000000..3971053
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/OpenIDVCIBuildTokenErrorResponseFromEventTest.java
@@ -0,0 +1,82 @@
+/*
+ * 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.profile.impl;
+
+import java.util.Map;
+
+import org.geant.shibboleth.plugin.openidvci.authn.impl.ClientAttestationCredentialValidator;
+import org.opensaml.messaging.context.MessageContext;
+import org.opensaml.profile.context.EventContext;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.oauth2.sdk.OAuth2Error;
+import com.nimbusds.oauth2.sdk.TokenErrorResponse;
+
+import net.shibboleth.idp.authn.AuthnEventIds;
+import net.shibboleth.idp.authn.context.AuthenticationContext;
+import net.shibboleth.idp.authn.context.AuthenticationErrorContext;
+
+/**
+ * Unit tests for {@link OpenIDVCIBuildTokenErrorResponseFromEvent}.
+ */
+public class OpenIDVCIBuildTokenErrorResponseFromEventTest {
+
+ private ProfileRequestContext prc;
+
+ private OpenIDVCIBuildTokenErrorResponseFromEvent action;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ prc = new ProfileRequestContext();
+ prc.setOutboundMessageContext(new MessageContext());
+ prc.ensureSubcontext(EventContext.class).setEvent(AuthnEventIds.INVALID_CREDENTIALS);
+ action = new OpenIDVCIBuildTokenErrorResponseFromEvent(null);
+ action.setMappedErrors(Map.of(AuthnEventIds.INVALID_CREDENTIALS, OAuth2Error.INVALID_CLIENT));
+ action.initialize();
+ }
+
+ private TokenErrorResponse response() {
+ return (TokenErrorResponse) prc.getOutboundMessageContext().getMessage();
+ }
+
+ @Test
+ public void testUseFreshAttestation() throws Exception {
+ prc.ensureSubcontext(AuthenticationContext.class).ensureSubcontext(AuthenticationErrorContext.class)
+ .addClassifiedError(ClientAttestationCredentialValidator.USE_FRESH_ATTESTATION);
+ action.execute(prc);
+ Assert.assertEquals(response().getErrorObject().getCode(), "use_fresh_attestation");
+ Assert.assertEquals(response().getErrorObject().getHTTPStatusCode(), 400);
+ }
+
+ @Test
+ public void testInvalidClient() throws Exception {
+ prc.ensureSubcontext(AuthenticationContext.class).ensureSubcontext(AuthenticationErrorContext.class)
+ .addClassifiedError(AuthnEventIds.INVALID_CREDENTIALS);
+ action.execute(prc);
+ Assert.assertEquals(response().getErrorObject().getCode(), OAuth2Error.INVALID_CLIENT.getCode());
+ }
+
+ @Test
+ public void testNoAuthentication() throws Exception {
+ action.execute(prc);
+ Assert.assertEquals(response().getErrorObject().getCode(), OAuth2Error.INVALID_CLIENT.getCode());
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContextTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContextTest.java
index c468ef4..6894656 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContextTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/SetAuthorizationDetailsToResponseContextTest.java
@@ -36,6 +36,7 @@ import com.nimbusds.openid.connect.sdk.claims.ClaimsSet;
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.shared.component.UnmodifiableComponentException;
/**
* Unit tests for {@link SetAuthorizationDetailsToResponseContext}.
@@ -123,4 +124,20 @@ public class SetAuthorizationDetailsToResponseContextTest {
OpenIDVCIEventIds.NO_CREDENTIALS_FOR_REQUEST);
}
+ @Test
+ public void testRequestedPartlyAvailable() throws Exception {
+ potentialCredentials.setClaim("GeantIncubatorDiploma", CONTENT);
+ final List<OpenIDVCIAuthorizationDetail> details =
+ List.of(new OpenIDVCIAuthorizationDetail("openid_credential", "GeantIncubatorDiploma", null, null),
+ new OpenIDVCIAuthorizationDetail("openid_credential", "GeantIncubatorDiploma2", null, null));
+ ActionTestingSupport.assertEvent(actionOf(details).execute(requestCtx),
+ OpenIDVCIEventIds.NO_CREDENTIALS_FOR_REQUEST);
+ Assert.assertNull(tokenContext.getResponseAuthorizationDetails());
+ }
+
+ @Test(expectedExceptions = UnmodifiableComponentException.class)
+ public void testStrategyAfterInitialize() throws Exception {
+ actionOf(null).setAuthorizationDetailsLookupStrategy(prc -> null);
+ }
+
}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCodeTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCodeTest.java
new file mode 100644
index 0000000..4822e79
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/UnwrapPreAuthorizedCodeTest.java
@@ -0,0 +1,244 @@
+/*
+ * 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.profile.impl;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+
+import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.CredentialOfferRequest;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferCache;
+import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferObject;
+import org.geant.shibboleth.plugin.openidvci.token.support.CredentialOfferClaimsSet;
+import org.opensaml.messaging.context.MessageContext;
+import org.opensaml.profile.action.EventIds;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.storage.impl.MemoryStorageService;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.common.contenttype.ContentType;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+
+import net.shibboleth.idp.plugin.oidc.op.messaging.context.OIDCAuthenticationResponseContext;
+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.profile.core.OidcEventIds;
+import net.shibboleth.shared.collection.Pair;
+import net.shibboleth.shared.security.DataSealer;
+import net.shibboleth.shared.security.DataSealerException;
+import net.shibboleth.shared.security.DataSealerKeyStrategy;
+
+/**
+ * Unit tests for {@link UnwrapPreAuthorizedCode}.
+ */
+public class UnwrapPreAuthorizedCodeTest {
+
+ private RequestContext requestCtx;
+
+ private ProfileRequestContext profileRequestCtx;
+
+ private MemoryStorageService storageService;
+
+ private CredentialOfferCache cache;
+
+ private CountingSealer sealer;
+
+ private CredentialOfferObject offer;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ final HTTPRequest offerRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ offerRequest.setAuthorization("Basic dGVzdDp0ZXN0");
+ offerRequest.setContentType("application/json");
+ offerRequest.setBody("{\"preAuthorizedCredentials\":{\"GeantIncubatorSdJwt2\":"
+ + "[{\"path\":[\"mail\"],\"value\":\"incubatorUser at example.org\"}]}}");
+ offer = new CredentialOfferObject(new ClientID("offer-caller"),
+ CredentialOfferRequest.parse(offerRequest).getPreAuthorizedCredentials(), null, null);
+
+ storageService = new MemoryStorageService();
+ storageService.setId("test");
+ storageService.initialize();
+ cache = new CredentialOfferCache();
+ cache.setStorage(storageService);
+ cache.initialize();
+
+ final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
+ keyGenerator.init(128);
+ sealer = new CountingSealer();
+ sealer.setKeyStrategy(new FixedKeyStrategy(keyGenerator.generateKey()));
+ sealer.initialize();
+ }
+
+ @AfterMethod
+ protected void tearDown() {
+ cache.destroy();
+ storageService.destroy();
+ sealer.destroy();
+ }
+
+ private void setTokenRequest(final String code) throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ httpRequest.setBody("grant_type=urn:ietf:params:oauth:grant-type:pre-authorized_code&pre-authorized_code="
+ + URLEncoder.encode(code, StandardCharsets.UTF_8));
+ requestCtx = new RequestContextBuilder().buildRequestContext();
+ profileRequestCtx = new WebflowRequestContextProfileRequestContextLookup().apply(requestCtx);
+ profileRequestCtx.setInboundMessageContext(new MessageContext());
+ profileRequestCtx.getInboundMessageContext().setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ profileRequestCtx.setOutboundMessageContext(new MessageContext());
+ profileRequestCtx.getOutboundMessageContext().ensureSubcontext(OIDCAuthenticationResponseContext.class);
+ }
+
+ private UnwrapPreAuthorizedCode newAction(final CredentialOfferCache offerCache) throws Exception {
+ final UnwrapPreAuthorizedCode action = new UnwrapPreAuthorizedCode(sealer);
+ action.setCredentialOfferCache(offerCache);
+ action.initialize();
+ return action;
+ }
+
+ private CredentialOfferClaimsSet claimsSet(final Instant expiresAt) throws Exception {
+ return new CredentialOfferClaimsSet.Builder()
+ .setIssuer("https://issuer.example.org").setClientID(new ClientID("offer-caller"))
+ .setJWTID("jti").setIssuedAt(Instant.now().minusSeconds(120))
+ .setAuthenticationTime(Instant.now().minusSeconds(120)).setSubject(offer.serialize())
+ .setExpiresAt(expiresAt).build();
+ }
+
+ private void assertOffer() {
+ final TokenContext tokenContext = profileRequestCtx.getInboundMessageContext()
+ .getSubcontext(TokenContext.class);
+ Assert.assertEquals(tokenContext.getCredentialOfferObject().getClientID().getValue(), "offer-caller");
+ Assert.assertNotNull(tokenContext.getPotentialCredentials().getClaim("GeantIncubatorSdJwt2"));
+ final OIDCAuthenticationResponseContext responseCtx = profileRequestCtx.getOutboundMessageContext()
+ .getSubcontext(OIDCAuthenticationResponseContext.class);
+ Assert.assertEquals(responseCtx.getSubject(), "offer-caller/wallet");
+ Assert.assertNotNull(responseCtx.getAuthTime());
+ }
+
+ @Test
+ public void testStoredCode() throws Exception {
+ final String code = "storedCode0123456789";
+ cache.storeCredentialOffer(offer, code, 600000);
+ setTokenRequest(code);
+
+ ActionTestingSupport.assertProceedEvent(newAction(cache).execute(requestCtx));
+ assertOffer();
+ }
+
+ @Test
+ public void testSealedCode() throws Exception {
+ setTokenRequest(claimsSet(Instant.now().plusSeconds(600)).serialize(sealer));
+
+ ActionTestingSupport.assertProceedEvent(newAction(cache).execute(requestCtx));
+ assertOffer();
+ Assert.assertEquals(profileRequestCtx.getInboundMessageContext().getSubcontext(TokenContext.class)
+ .getCredentialOfferClaimsSet().getID(), "jti");
+ }
+
+ @Test
+ public void testUnknownCode() throws Exception {
+ setTokenRequest("unknownCode0123456789");
+
+ ActionTestingSupport.assertEvent(newAction(cache).execute(requestCtx), OidcEventIds.INVALID_GRANT);
+ Assert.assertNull(profileRequestCtx.getInboundMessageContext().getSubcontext(TokenContext.class));
+ Assert.assertEquals(sealer.unwrapCalls, 0);
+ }
+
+ @Test
+ public void testExpiredSealedCode() throws Exception {
+ setTokenRequest(sealer.wrap(claimsSet(Instant.now().minusSeconds(60)).serialize(),
+ Instant.now().plusSeconds(600)));
+
+ ActionTestingSupport.assertEvent(newAction(cache).execute(requestCtx), OidcEventIds.INVALID_GRANT);
+ final TokenContext tokenContext = profileRequestCtx.getInboundMessageContext()
+ .getSubcontext(TokenContext.class);
+ Assert.assertTrue(tokenContext == null || tokenContext.getCredentialOfferObject() == null);
+ }
+
+ @Test
+ public void testStorageFailure() throws Exception {
+ setTokenRequest("storedCode0123456789");
+
+ ActionTestingSupport.assertEvent(newAction(new FailingCache()).execute(requestCtx), EventIds.IO_ERROR);
+ }
+
+ /** Sealer counting the unwrap calls. */
+ private static class CountingSealer extends DataSealer {
+
+ private int unwrapCalls;
+
+ /** {@inheritDoc} */
+ @Override
+ public String unwrap(final String wrapped) throws DataSealerException {
+ unwrapCalls++;
+ return super.unwrap(wrapped);
+ }
+ }
+
+ /** Cache failing every read. */
+ private static class FailingCache extends CredentialOfferCache {
+
+ /** {@inheritDoc} */
+ @Override
+ public synchronized CredentialOfferObject getCredentialOffer(final String code) throws IOException {
+ throw new IOException("Storage failure");
+ }
+ }
+
+ /** Key strategy of one fixed key. */
+ private static class FixedKeyStrategy implements DataSealerKeyStrategy {
+
+ private final SecretKey key;
+
+ FixedKeyStrategy(final SecretKey secretKey) {
+ key = secretKey;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @SuppressWarnings("removal")
+ public Pair<String, SecretKey> getDefaultKey() {
+ return new Pair<>("default", key);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public NamedKey getDefaultKeyRecord() {
+ return new NamedKey("default", key);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public SecretKey getKey(final String name) {
+ return key;
+ }
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCodeTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCodeTest.java
new file mode 100644
index 0000000..c82fc76
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidatePreAuthorizedCodeTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.profile.impl;
+
+import java.time.Instant;
+
+import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
+import org.geant.shibboleth.plugin.openidvci.token.support.CredentialOfferClaimsSet;
+import org.opensaml.messaging.context.MessageContext;
+import org.opensaml.profile.action.EventIds;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.opensaml.storage.impl.MemoryStorageService;
+import org.opensaml.storage.impl.StorageServiceReplayCache;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.nimbusds.oauth2.sdk.id.ClientID;
+
+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.profile.core.OidcEventIds;
+
+/**
+ * Unit tests for {@link ValidatePreAuthorizedCode}.
+ */
+public class ValidatePreAuthorizedCodeTest {
+
+ private MemoryStorageService storageService;
+
+ private StorageServiceReplayCache replayCache;
+
+ @BeforeMethod
+ protected void setUp() throws Exception {
+ storageService = new MemoryStorageService();
+ storageService.setId("test");
+ storageService.initialize();
+ replayCache = new StorageServiceReplayCache();
+ replayCache.setStorage(storageService);
+ replayCache.initialize();
+ }
+
+ @AfterMethod
+ protected void tearDown() {
+ replayCache.destroy();
+ storageService.destroy();
+ }
+
+ private static RequestContext requestContext(final TokenContext tokenContext) throws Exception {
+ final RequestContext requestCtx = new RequestContextBuilder().buildRequestContext();
+ final ProfileRequestContext profileRequestCtx =
+ new WebflowRequestContextProfileRequestContextLookup().apply(requestCtx);
+ profileRequestCtx.setInboundMessageContext(new MessageContext());
+ if (tokenContext != null) {
+ profileRequestCtx.getInboundMessageContext().addSubcontext(tokenContext);
+ }
+ return requestCtx;
+ }
+
+ private static TokenContext sealed(final String jti) {
+ final TokenContext tokenContext = new TokenContext();
+ tokenContext.setCredentialOfferClaimsSet(new CredentialOfferClaimsSet.Builder()
+ .setIssuer("https://issuer.example.org").setClientID(new ClientID("offer-caller"))
+ .setJWTID(jti).setIssuedAt(Instant.now()).setAuthenticationTime(Instant.now())
+ .setSubject("{}").setExpiresAt(Instant.now().plusSeconds(600)).build());
+ return tokenContext;
+ }
+
+ private ValidatePreAuthorizedCode newAction() throws Exception {
+ final ValidatePreAuthorizedCode action = new ValidatePreAuthorizedCode();
+ action.setReplayCache(replayCache);
+ action.initialize();
+ return action;
+ }
+
+ @Test
+ public void testSpentOnce() throws Exception {
+ ActionTestingSupport.assertProceedEvent(newAction().execute(requestContext(sealed("jti1"))));
+ ActionTestingSupport.assertEvent(newAction().execute(requestContext(sealed("jti1"))),
+ OidcEventIds.INVALID_GRANT);
+ ActionTestingSupport.assertProceedEvent(newAction().execute(requestContext(sealed("jti2"))));
+ }
+
+ @Test
+ public void testStoredCode() throws Exception {
+ ActionTestingSupport.assertProceedEvent(newAction().execute(requestContext(new TokenContext())));
+ }
+
+ @Test
+ public void testNoTokenContext() throws Exception {
+ ActionTestingSupport.assertEvent(newAction().execute(requestContext(null)), EventIds.INVALID_PROFILE_CTX);
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCodeTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCodeTest.java
new file mode 100644
index 0000000..f487c68
--- /dev/null
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/profile/impl/ValidateTxCodeTest.java
@@ -0,0 +1,101 @@
+/*
+ * 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.profile.impl;
+
+import java.net.URI;
+
+import org.geant.shibboleth.plugin.openidvci.messaging.context.TokenContext;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.CredentialOfferTxCode;
+import org.geant.shibboleth.plugin.openidvci.messaging.impl.OpenIDVCITokenRequest;
+import org.geant.shibboleth.plugin.openidvci.profile.OpenIDVCIEventIds;
+import org.geant.shibboleth.plugin.openidvci.storage.CredentialOfferObject;
+import org.opensaml.messaging.context.MessageContext;
+import org.opensaml.profile.context.ProfileRequestContext;
+import org.springframework.webflow.execution.RequestContext;
+import org.testng.annotations.Test;
+
+import com.nimbusds.common.contenttype.ContentType;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+
+import net.shibboleth.idp.profile.context.navigate.WebflowRequestContextProfileRequestContextLookup;
+import net.shibboleth.idp.profile.testing.ActionTestingSupport;
+import net.shibboleth.idp.profile.testing.RequestContextBuilder;
+
+/**
+ * Unit tests for {@link ValidateTxCode}.
+ */
+public class ValidateTxCodeTest {
+
+ private static final String PRE_AUTH = "grant_type=urn:ietf:params:oauth:grant-type:pre-authorized_code"
+ + "&pre-authorized_code=storedCode0123456789";
+
+ private static RequestContext requestContext(final String body, final CredentialOfferTxCode txCode)
+ throws Exception {
+ final HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URI("http://example.com"));
+ httpRequest.setEntityContentType(ContentType.APPLICATION_URLENCODED);
+ httpRequest.setBody(body);
+ final RequestContext requestCtx = new RequestContextBuilder().buildRequestContext();
+ final ProfileRequestContext profileRequestCtx =
+ new WebflowRequestContextProfileRequestContextLookup().apply(requestCtx);
+ profileRequestCtx.setInboundMessageContext(new MessageContext());
+ profileRequestCtx.getInboundMessageContext().setMessage(OpenIDVCITokenRequest.parse(httpRequest));
+ profileRequestCtx.getInboundMessageContext().ensureSubcontext(TokenContext.class).setCredentialOfferObject(
+ new CredentialOfferObject(new ClientID("offer-caller"), null, null, txCode));
+ return requestCtx;
+ }
+
+ private static ValidateTxCode newAction() throws Exception {
+ final ValidateTxCode action = new ValidateTxCode();
+ action.initialize();
+ return action;
+ }
+
+ private static CredentialOfferTxCode txCode() {
+ return new CredentialOfferTxCode("numeric", 6, null, "493536");
+ }
+
+ @Test
+ public void testCorrectTxCode() throws Exception {
+ ActionTestingSupport.assertProceedEvent(
+ newAction().execute(requestContext(PRE_AUTH + "&tx_code=493536", txCode())));
+ }
+
+ @Test
+ public void testNoTxCodeExpected() throws Exception {
+ ActionTestingSupport.assertProceedEvent(newAction().execute(requestContext(PRE_AUTH, null)));
+ }
+
+ @Test
+ public void testWrongTxCode() throws Exception {
+ ActionTestingSupport.assertEvent(newAction().execute(requestContext(PRE_AUTH + "&tx_code=000000", txCode())),
+ OpenIDVCIEventIds.INVALID_TX_CODE);
+ }
+
+ @Test
+ public void testMissingTxCode() throws Exception {
+ ActionTestingSupport.assertEvent(newAction().execute(requestContext(PRE_AUTH, txCode())),
+ OpenIDVCIEventIds.TX_CODE_PRESENCE);
+ }
+
+ @Test
+ public void testUnexpectedTxCode() throws Exception {
+ ActionTestingSupport.assertEvent(newAction().execute(requestContext(PRE_AUTH + "&tx_code=493536", null)),
+ OpenIDVCIEventIds.TX_CODE_PRESENCE);
+ }
+
+}
diff --git a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCacheTest.java b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCacheTest.java
index d69283b..79c708b 100644
--- a/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCacheTest.java
+++ b/openid-vci-impl/src/test/java/org/geant/shibboleth/plugin/openidvci/storage/CredentialOfferCacheTest.java
@@ -105,8 +105,9 @@ public class CredentialOfferCacheTest {
Assert.assertTrue(credentialOfferCache.storeCredentialOffer(credentialOfferObject, preAuthorizationCode, 200));
CredentialOfferObject credentialOfferFromStore = credentialOfferCache.getCredentialOffer(preAuthorizationCode);
Assert.assertEquals(credentialOfferObject.serialize(), credentialOfferFromStore.serialize());
- credentialOfferCache.removeCredentialOffer(preAuthorizationCode);
+ Assert.assertTrue(credentialOfferCache.removeCredentialOffer(preAuthorizationCode));
Assert.assertNull(credentialOfferCache.getCredentialOffer(preAuthorizationCode));
+ Assert.assertFalse(credentialOfferCache.removeCredentialOffer(preAuthorizationCode));
}
@Test
@@ -118,22 +119,21 @@ public class CredentialOfferCacheTest {
}
@Test
- public void testCodeLongerThanKeySize() throws Exception {
- final MemoryStorageService smallKeys = new MemoryStorageService();
- smallKeys.setId("small");
- smallKeys.setKeySize(32);
- smallKeys.initialize();
- final CredentialOfferCache cache = new CredentialOfferCache();
- cache.setStorage(smallKeys);
- cache.initialize();
- final String code = "0123456789".repeat(10);
-
- Assert.assertTrue(cache.storeCredentialOffer(credentialOfferObject, code, 200000));
- Assert.assertEquals(cache.getCredentialOffer(code).serialize(), credentialOfferObject.serialize());
- Assert.assertNotNull(
- smallKeys.read(CredentialOfferCache.CONTEXT_CREDENTIAL_OFFER, DigestUtils.sha256Hex(code)));
- cache.destroy();
- smallKeys.destroy();
+ public void testStoredUnderCodeHash() throws Exception {
+ Assert.assertTrue(credentialOfferCache.storeCredentialOffer(credentialOfferObject, preAuthorizationCode,
+ 200000));
+ Assert.assertNull(storageService.read(CredentialOfferCache.CONTEXT_CREDENTIAL_OFFER, preAuthorizationCode));
+ Assert.assertNotNull(storageService.read(CredentialOfferCache.CONTEXT_CREDENTIAL_OFFER,
+ DigestUtils.sha256Hex(preAuthorizationCode)));
+ Assert.assertEquals(credentialOfferCache.getCredentialOffer(preAuthorizationCode).serialize(),
+ credentialOfferObject.serialize());
+ }
+
+ @Test
+ public void testCorruptRecord() throws Exception {
+ storageService.create(CredentialOfferCache.CONTEXT_CREDENTIAL_OFFER,
+ DigestUtils.sha256Hex(preAuthorizationCode), "not json", System.currentTimeMillis() + 200000);
+ Assert.expectThrows(IOException.class, () -> credentialOfferCache.getCredentialOffer(preAuthorizationCode));
}
@Test
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list