8000 [OID4VP] Enforce DCQL binding on verified presentations by dominikschlosser · Pull Request #55621 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 48 additions & 13 deletions services/src/main/java/org/keycloak/broker/oid4vp/DcqlQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,18 @@
import java.util.Map;
import java.util.stream.Stream;

import org.keycloak.OID4VCConstants;
import org.keycloak.broker.oid4vp.mappers.ClaimPath;
import org.keycloak.broker.oid4vp.mappers.DcqlQueryContributor;
import org.keycloak.broker.provider.IdentityProviderMapper;
import org.keycloak.common.VerificationException;
import org.keycloak.models.IdentityProviderMapperModel;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.sdjwt.consumer.PresentationRequirements;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import org.jboss.logging.Logger;

/**
Expand All @@ -54,8 +59,33 @@ public record CredentialQuery(
Meta meta,
@JsonProperty("trusted_authorities") List<TrustedAuthoritiesQuery> trustedAuthorities,
@JsonProperty("require_cryptographic_holder_binding") Boolean requireCryptographicHolderBinding,
List<ClaimsQuery> claims,
@JsonProperty("claim_sets") List<List<String>> claimSets) {
// Claims are optional, but a present claims array must not be empty (OID4VP 1.0 §6.1).
// Without claims only the always disclosed claims are presented.
@JsonInclude(JsonInclude.Include.NON_EMPTY) List<ClaimsQuery> claims,
@JsonProperty("claim_sets") List<List<String>> claimSets) implements PresentationRequirements {

/**
* Requires the presented credential to have one of the requested types and to disclose the
* requested claims (OID4VP 1.0 §6.4.1).
*
* @see <a href="https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#section-8.6">OID4VP 1.0 §8.6 — VP Token Validation</a>
*/
@Override
public void checkIfSatisfiedBy(JsonNode disclosedPayload) throws VerificationException {
JsonNode type = disclosedPayload.get(OID4VCConstants.CLAIM_NAME_VCT);
String vct = type != null && type.isTextual() ? type.textValue() : null;
if (!meta.vctValues().contains(vct)) {
throw new VerificationException("The credential '" + id + "' has the type '" + vct
+ "', which is not requested");
}
// TODO once claim sets are requested, require the claims of one claim set option instead of all claims.
for (ClaimsQuery claim : claims) {
if (!claim.isDisclosedIn(disclosedPayload)) {
throw new VerificationException("The credential '" + id + "' does not disclose the requested claim '"
+ claim.path() + "'");
}
}
}
}

/**
Expand All @@ -74,13 +104,20 @@ public record TrustedAuthoritiesQuery(String type, List<String> values) {
}

/**
* Each path element is a string for an object member, null for all array elements or a non
* negative integer for an array index (OID4VP 1.0 §7).
* The path is serialized as a DCQL claims path pointer (OID4VP 1.0 §7).
*
* @see <a href="https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#section-6.3">OID4VP 1.0 §6.3 — Claims Query</a>
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public record ClaimsQuery(String id, List<Object> path, List<Object> values) {
public record ClaimsQuery(String id, ClaimPath path, List<Object> values) {

/**
* Whether the path selects at least one claim of the disclosed payload (OID4VP 1.0 §7.1.1).
* A null value or an element of the wrong kind selects nothing, as in {@link ClaimPath#select}.
*/
public boolean isDisclosedIn(JsonNode disclosedPayload) {
return !path.select(disclosedPayload).isEmpty();
}
}

/**
Expand All @@ -99,7 +136,7 @@ public record CredentialSetQuery(List<List<String>> options, Boolean required) {
public static DcqlQuery fromMappers(KeycloakSessionFactory sessionFactory,
Stream<IdentityProviderMapperModel> mappers, RequestedCredentials requested) {
// A claim must not be requested twice (OID4VP 1.0 §6.1), even if several mappers read it.
Map<String, Map<List<Object>, ClaimsQuery>> claimsByCredential = new LinkedHashMap<>();
Map<String, Map<List<ClaimPath.Step>, ClaimsQuery>> claimsByCredential = new LinkedHashMap<>();
requested.credentials().forEach(credential -> claimsByCredential.put(credential.id(), new LinkedHashMap<>()));
mappers.sorted(Comparator.comparing(IdentityProviderMapperModel::getName)).forEach(mapper -> {
IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory
Expand All @@ -109,26 +146,24 @@ public static DcqlQuery fromMappers(KeycloakSessionFactory sessionFactory,
if (requestedClaims.isEmpty()) {
return;
}
Map<List<Object>, ClaimsQuery> claims = claimsByCredential.get(contributor.credentialId(mapper));
Map<List<ClaimPath.Step>, ClaimsQuery> claims = claimsByCredential.get(contributor.credentialId(mapper));
if (claims == null) {
logger.warnf("Skipping the mapper '%s', which refers to the credential '%s' that is not requested",
mapper.getName(), contributor.credentialId(mapper));
return;
}
requestedClaims.forEach(claim -> claims.putIfAbsent(claim.path(), claim));
requestedClaims.forEach(claim -> claims.putIfAbsent(claim.path().steps(), claim));
}
});
List<Object> principalPath = requested.principal().claimPath().toClaimsPathPointer();
ClaimPath principalPath = requested.principal().claimPath();
claimsByCredential.get(requested.principal().credential())
.putIfAbsent(principalPath, new ClaimsQuery(null, principalPath, null));
.putIfAbsent(principalPath.steps(), new ClaimsQuery(null, principalPath, null));

List<CredentialQuery> credentials = requested.credentials().stream()
.map(credential -> {
Collection<ClaimsQuery> claims = claimsByCredential.get(credential.id()).values();
// An empty claims array is not allowed. Without claims only the always disclosed claims are presented.
return new CredentialQuery(credential.id(), credential.format(), null,
new Meta(List.copyOf(credential.types())), null, null,
claims.isEmpty() ? null : List.copyOf(claims), null);
new Meta(List.copyOf(credential.types())), null, null, List.copyOf(claims), null);
})
.toList();
List<CredentialSetQuery> credentialSets = requested.credentialSets() == null ? null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.FormParam;
Expand Down Expand Up @@ -53,7 +56,6 @@
import org.keycloak.representations.IDToken;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.sdjwt.IssuerSignedJwtVerificationOpts;
import org.keycloak.sdjwt.consumer.PresentationRequirements;
import org.keycloak.sdjwt.consumer.SdJwtPresentationConsumer;
import org.keycloak.sdjwt.consumer.TrustedSdJwtIssuer;
import org.keycloak.sdjwt.vp.KeyBindingJWT;
Expand Down Expand Up @@ -418,8 +420,8 @@ protected DecryptedResponse decryptResponse(String response) throws Verification
}

/**
* Verifies the presentation of each presented credential and requires the presented credentials
* to satisfy the required credential sets.
* Verifies the presentation of each presented credential against its credential query.
* The presented credentials must satisfy the required credential sets.
*
* @return the disclosed claims of the presented credentials by credential id
*/
Expand All @@ -430,24 +432,23 @@ protected ObjectNode verifyPresentations(String vpToken, String nonce) throws Ve
throw new VerificationException("vp_token does not contain the required credentials, presented were "
+ presentations.keySet());
}
Map<String, DcqlQuery.CredentialQuery> queries = dcqlQuery().credentials().stream()
.collect(Collectors.toMap(DcqlQuery.CredentialQuery::id, Function.identity()));
ObjectNode claims = JsonSerialization.mapper.createObjectNode();
for (RequestedCredentials.Credential credential : requested.credentials()) {
String presentation = presentations.get(credential.id());
if (presentation == null) {
continue;
}
SdJwtVpVerificationResult result = verifyPresentation(credential, presentation, nonce);
if (!credential.types().contains(result.getCredentialType())) {
throw new VerificationException("The credential '" + credential.id() + "' has the type '"
+ result.getCredentialType() + "', which is not requested");
}
SdJwtVpVerificationResult result = verifyPresentation(credential, Objects.requireNonNull(queries.get(credential.id())),
presentation, nonce);
claims.set(credential.id(), result.getClaims());
}
return claims;
}

protected SdJwtVpVerificationResult verifyPresentation(RequestedCredentials.Credential credential,
String presentation, String nonce) throws VerificationException {
DcqlQuery.CredentialQuery query, String presentation, String nonce) throws VerificationException {
SdJwtVP sdJwtVP;
try {
sdJwtVP = SdJwtVP.of(presentation);
Expand Down Expand Up @@ -479,16 +480,10 @@ protected SdJwtVpVerificationResult verifyPresentation(RequestedCredentials.Cred
.withNonceCheck(nonce)
.build();

// TODO require the claims the DCQL query requests for this credential: derive
// PresentationRequirements from the query and enforce them here. The principal check in
// requirePrincipalClaim then becomes just another requested claim.
// https://github.com/keycloak/keycloak/issues/50657
PresentationRequirements noAdditionalRequirements = disclosedPayload -> {
};
TrustedSdJwtIssuer trustedIssuer = provider.trustedIssuerResolver(credential)
.resolve(sdJwtVP.getIssuerSignedJWT());
return new SdJwtPresentationConsumer().verifySdJwtPresentation(
sdJwtVP, noAdditionalRequirements, List.of(trustedIssuer), issuerOpts, kbOpts);
sdJwtVP, query, List.of(trustedIssuer), issuerOpts, kbOpts);
}

private static void requireAcceptedAlgorithm(String algorithm, String jwt) throws VerificationException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public List<DcqlQuery.ClaimsQuery> requestedClaims(IdentityProviderMapperModel m
if (path == null) {
return List.of();
}
return List.of(new DcqlQuery.ClaimsQuery(null, path.toClaimsPathPointer(), null));
return List.of(new DcqlQuery.ClaimsQuery(null, path, null));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import org.keycloak.utils.JsonUtils;

import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.JsonNode;

/**
Expand Down Expand Up @@ -71,6 +72,7 @@ public List<Step> steps() {
* The path in DCQL notation, for example {@code ["address", "locality"]} for
* {@code address.locality} and {@code ["nationalities", null]} for {@code nationalities[]}.
*/
@JsonValue
public List<Object> toClaimsPathPointer() {
List<Object> pointer = new ArrayList<>();
for (Step step : steps) {
Expand All @@ -83,6 +85,27 @@ public List<Object> toClaimsPathPointer() {
return pointer;
}

/**
* The path in dot notation, for example {@code degrees[].type}.
*/
@Override
public String toString() {
StringBuilder path = new StringBuilder();
for (Step step : steps) {
switch (step.kind()) {
case FIELD -> {
if (!path.isEmpty()) {
path.append('.');
}
path.append(step.field().replace(".", "\\."));
}
case ALL_ELEMENTS -> path.append("[]");
case FIRST_ELEMENT -> path.append("[0]");
}
}
return path.toString();
}

/**
* Parses the dot notation path, returning {@code null} if it is not well formed.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ public void convertsToClaimsPathPointer() {
assertEquals(List.of("org.example"), ClaimPath.parse("org\\.example").toClaimsPathPointer());
}

@Test
public void printsTheParsedDotNotation() {
for (String path : List.of("email", "address.locality", "degrees[].type", "nationalities[0]", "matrix[][]",
"org\\.example")) {
assertEquals(path, ClaimPath.parse(path).toString());
}
}

@Test
public void serializesAsClaimsPathPointer() throws Exception {
assertEquals("[\"degrees\",null,\"type\"]",
JsonSerialization.writeValueAsString(ClaimPath.parse("degrees[].type")));
}

@Test
public void rejectsMalformedPaths() {
assertNull(ClaimPath.parse(null));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -289,12 +289,16 @@ public Proofs generateJwtProofs(OID4VCTestContext ctx, String nonce, KeyWrapper.
* binding JWT signed by {@code holderKey} and bound to the verifier ({@code audience}, {@code nonce}).
*/
public String present(String sdJwtVc, KeyWrapper holderKey, String audience, String nonce) {
return SdJwtVP.of(sdJwtVc)
.present(null, true, keyBindingClaims(audience, nonce), new ECDSASignatureSignerContext(holderKey));
}

private static ObjectNode keyBindingClaims(String audience, String nonce) {
ObjectNode keyBindingClaims = JsonSerialization.mapper.createObjectNode();
keyBindingClaims.put("aud", audience);
keyBindingClaims.put("nonce", nonce);
keyBindingClaims.put("iat", Time.currentTimeSeconds());
return SdJwtVP.of(sdJwtVc)
.present(null, true, keyBindingClaims, new ECDSASignatureSignerContext(holderKey));
return keyBindingClaims;
}

public String requestUri(String walletUrl) {
Expand Down Expand Up @@ -326,6 +330,31 @@ public String presentation(OID4VCTestContext ctx, JsonNode request, String nonce
return present(sdJwtVc, getECKeyPair(ctx), request.path("client_id").asText(), nonce);
}

/**
* Builds a presentation that discloses the requested claims of a credential and leaves out the
* withheld ones. The requested claims are those of the DCQL credential query with the id
* {@code credentialId}. Claims are matched by name, so a nested claim goes with its top level
* claim. Always disclosed claims like vct cannot be withheld.
*/
public String presentationOfRequestedClaims(OID4VCTestContext ctx, JsonNode request, String credentialId,
String... withheldClaims) {
Set<String> disclosed = new HashSet<>();
for (JsonNode credential : request.path("dcql_query").path("credentials")) {
if (credential.path("id").asText().equals(credentialId)) {
credential.path("claims").forEach(claim -> claim.path("path").forEach(component -> {
if (component.isTextual()) {
disclosed.add(component.textValue());
}
}));
}
}
disclosed.removeAll(List.of(withheldClaims));
String sdJwtVc = (String) ctx.getCredentialResponse().getCredentials().get(0).getCredential();
return SdJwtVP.of(sdJwtVc).presentWithSpecifiedClaims(List.copyOf(disclosed), false,
keyBindingClaims(request.path("client_id").asText(), request.path("nonce").asText()),
new ECDSASignatureSignerContext(getECKeyPair(ctx)));
}

/**
* Wraps a presentation into a vp_token keyed by the id of the first credential the DCQL query
* of the request asks for.
Expand Down
Loading
Loading
0