8000 [OID4VCI] Improve signing key selection by graziang · Pull Request #46609 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -3689,7 +3689,7 @@ supportedFormatsHelp=The format of the verifiable credential. Currently supporte
credentialDisplay=Credential Display
credentialDisplayHelp=JSON array of objects containing display metadata for wallets (name, logo, colors, etc.). Example: [{"name": "IdentityCredential", "locale": "en-US", "logo": {"uri": "https://example.com/logo.png", "alt_text": "Logo"}, "background_color": "#12107c", "text_color": "#FFFFFF"}]
credentialSigningAlgorithm=Credential Signing Algorithm
credentialSigningAlgorithmHelp=Signing algorithm used to sign credentials (for example "ES256"). Leave blank to use the realm defaults derived from available keys.
credentialSigningAlgorithmHelp=Signing algorithm used to select the active realm key for signing credentials (e.g., "ES256"). If not specified, the active key will be selected using the realm's default algorithm. This option is disabled if a specific 'Signing Key ID' is selected.
hashAlgorithm=Hash Algorithm
hashAlgorithmHelp=Hash algorithm used for SD-JWT credentials (for example "SHA-256"). Defaults to "SHA-256" if not specified.
supportedCredentialTypes=Supported Credential Types
Expand All @@ -3701,8 +3701,9 @@ tokenJwsTypeHelp=The type value written into the typ header of the JWT. Defaults
visibleClaims=Visible Claims
visibleClaimsHelp=Comma-separated list of claims that are always disclosed in the SD-JWT body (e.g., "id,iat,nbf,exp,jti,given_name"). Defaults to "id,iat,nbf,exp,jti". Only applicable for SD-JWT format.
signingKeyId=Signing Key ID
signingKeyIdHelp=Optional. The ID of the realm key used to sign the credential. If not specified, the realm's active signing key of the algorithm specified by 'Credential Signing Algorithm' (if set) will be used automatically. If this option is specified, it is highly recommended to specify also 'Credential Signing Algorithm' as the Signing Key ID must be of the algorithm specified by that option.
signingKeyIdHelp=Optional. The ID of the realm key used to sign the credential. If not specified, the realm's active signing key of the algorithm specified by 'Credential Signing Algorithm' (if set) will be used automatically. If a specific key is selected here, the 'Credential Signing Algorithm' option will be disabled and automatically set to the key's algorithm.
useDefaultKey=Use default (realm's active signing key)
useDefaultAlg=Use default algorithm
# Workflows
workflows=Workflows
titleWorkflows=Workflows
Expand Down
63 changes: 43 additions & 20 deletions js/apps/admin-ui/src/client-scopes/details/ScopeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import { useAdminClient } from "../../admin-client";
import { getProtocolName } from "../../clients/utils";
import { DefaultSwitchControl } from "../../components/SwitchControl";
import {
ClientScopeDefaultOptionalType,
allClientScopeTypes,
ClientScopeDefaultOptionalType,
} from "../../components/client-scope/ClientScopeTypes";
import { FormAccess } from "../../components/form/FormAccess";
import { useRealm } from "../../context/realm-context/RealmContext";
Expand Down Expand Up @@ -69,15 +69,6 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
const isFeatureEnabled = useIsFeatureEnabled();
const isDynamicScopesEnabled = isFeatureEnabled(Feature.DynamicScopes);

// Get available signature algorithms from server info
const signatureAlgorithms = useMemo(
() =>
serverInfo?.providers?.signature?.providers
? Object.keys(serverInfo.providers.signature.providers)
: [],
[serverInfo],
);

// Get available hash algorithms from server info
const hashAlgorithms = serverInfo?.providers?.hash?.providers
? Object.keys(serverInfo.providers.hash.providers).map((alg) =>
Expand All @@ -86,11 +77,20 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
: [];

// Get available asymmetric signature algorithms from server info
const asymmetricSigAlgOptions = useMemo(
const asymmetricAlgorithms = useMemo(
() => serverInfo?.cryptoInfo?.clientSignatureAsymmetricAlgorithms ?? [],
[serverInfo],
);

const asymmetricSigAlgOptions = useMemo(() => {
const mappedOptions = asymmetricAlgorithms.map((alg) => ({
key: alg,
value: alg,
}));

return [{ key: "", value: t("useDefaultAlg") }, ...mappedOptions];
}, [asymmetricAlgorithms, t]);

// Fetch realm keys for signing_key_id dropdown
const [realmKeys, setRealmKeys] = useState<KeyMetadataRepresentation[]>([]);

Expand All @@ -104,7 +104,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
);

// Prepare key options for SelectControl
// Filter only active keys suitable for signing credentials
// Filter only active keys suitable for signing credentials AND using asymmetric algorithms
const keyOptions = useMemo(() => {
const options = [{ key: "", value: t("useDefaultKey") }];
if (realmKeys && realmKeys.length > 0) {
Expand All @@ -114,7 +114,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
key.kid &&
key.status === "ACTIVE" &&
key.algorithm &&
signatureAlgorithms.includes(key.algorithm),
asymmetricAlgorithms.includes(key.algorithm),
)
.map((key) => ({
key: key.kid!,
Expand All @@ -123,7 +123,7 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
options.push(...keyOptions);
}
return options;
}, [realmKeys, signatureAlgorithms, t]);
}, [realmKeys, asymmetricAlgorithms, t]);

const displayOnConsentScreen: string = useWatch({
control,
Expand Down Expand Up @@ -159,6 +159,14 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
realmRepresentation?.verifiableCredentialsEnabled;
const isNotSaml = selectedProtocol != "saml";

const isSigningKeySelected = useWatch({
control,
name: convertAttributeNameToForm<ClientScopeDefaultOptionalType>(
"attributes.vc.signing_key_id",
),
defaultValue: clientScope?.attributes?.["vc.signing_key_id"] ?? "",
});

const setDynamicRegex = (value: string, append: boolean) =>
setValue(
convertAttributeNameToForm<ClientScopeDefaultOptionalType>(
Expand All @@ -172,9 +180,26 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
convertToFormValues(clientScope ?? {}, setValue);
}, [clientScope, setValue]);

useEffect(() => {
if (isSigningKeySelected) {
const selectedKeyInfo = realmKeys.find(
(k) => k.kid === isSigningKeySelected,
);
if (selectedKeyInfo?.algorithm) {
setValue(
convertAttributeNameToForm<ClientScopeDefaultOptionalType>(
"attributes.vc.credential_signing_alg",
),
selectedKeyInfo.algorithm,
{ shouldDirty: true },
);
}
}
}, [isSigningKeySelected, realmKeys, setValue]);

/* Form-level validation handles correctness; here we only prune known optional
OID4VC fields when empty. If new attributes are added, extend
OID4VC_ATTRIBUTE_KEYS (and related validation) so they participate in cleanup. */
OID4VC fields when empty. If new attributes are added, extend
OID4VC_ATTRIBUTE_KEYS (and related validation) so they participate in cleanup. */
const ClientScopeDefaultOptionalType) => {
const isOid4vc = values.protocol === OID4VC_PROTOCOL;
const cleaned = isOid4vc ? removeEmptyOid4vcAttributes(values) : values;
Expand Down Expand Up @@ -408,10 +433,8 @@ export const ScopeForm = ({ clientScope, save }: ScopeFormProps) => {
clientScope?.attributes?.["vc.credential_signing_alg"] ??
"",
}}
options={asymmetricSigAlgOptions.map((alg) => ({
key: alg,
value: alg,
}))}
options={asymmetricSigAlgOptions}
isDisabled={!!isSigningKeySelected}
/>
)}
{hashAlgorithms.length > 0 && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ export const OID4VC_ATTRIBUTE_KEYS = [
"vc.expiry_in_seconds",
"vc.credential_build_config.token_jws_type",
"vc.supported_credential_types",
"vc.credential_signing_alg",
"vc.verifiable_credential_type",
"vc.credential_build_config.sd_jwt.visible_claims",
"vc.display",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,9 @@ test.describe("OID4VCI Client Scope Functionality", () => {
await navigateBackAndVerifyClientScope(page, testBed, testClientScopeName);

await expect(page.getByTestId(OID4VCI_FIELDS.ISSUER_DID)).toHaveValue("");
await expect(page.locator(OID4VCI_FIELDS.SIGNING_ALGORITHM)).toHaveText("");
await expect(page.locator(OID4VCI_FIELDS.SIGNING_ALGORITHM)).toContainText(
"Use default algorithm",
);
await expect(page.locator(OID4VCI_FIELDS.HASH_ALGORITHM)).toContainText(
"sha-256",
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import java.util.Objects;
import java.util.Optional;

import org.keycloak.crypto.KeyWrapper;
import org.keycloak.models.Constants;
import org.ke 8 ycloak.m 10BC8 odels.KeycloakSession;
import org.keycloak.models.oid4vci.CredentialScopeModel;
import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider;
Expand Down Expand Up @@ -92,8 +94,19 @@ public static CredentialBuildConfig parse(KeycloakSession keycloakSession,
final String credentialIssuer = Optional.ofNullable(credentialModel.getIssuerDid()).orElse(
OID4VCIssuerWellKnownProvider.getIssuer(keycloakSession.getContext()));

String modelSigningAlg = credentialModel.getSigningAlg();
String signingAlg = StringUtil.isNotBlank(modelSigningAlg) ? modelSigningAlg : credentialConfiguration.getCredentialSigningAlgValuesSupported().get(0);

String signingAlg = Constants.DEFAULT_SIGNATURE_ALGORITHM;
if (StringUtil.isNotBlank(credentialModel.getSigningKeyId())) {
signingAlg = keycloakSession.keys()
.getKeysStream(keycloakSession.getContext().getRealm())
.filter(key-> key.getKid().equals(credentialModel.getSigningKeyId()))
.findAny()
.map(KeyWrapper::getAlgorithm)
.orElse(Constants.DEFAULT_SIGNATURE_ALGORITHM);
}
else if (StringUtil.isNotBlank(credentialModel.getSigningAlg())) {
signingAlg = credentialModel.getSigningAlg();
}

return new CredentialBuildConfig().setCredentialIssuer(credentialIssuer)
.setCredentialConfigId(credentialConfiguration.getId())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,15 @@
import org.keycloak.common.util.BouncyIntegration;
import org.keycloak.common.util.KeyUtils;
import org.keycloak.common.util.Time;
import org.keycloak.crypto.Algorithm;
import org.keycloak.crypto.ECDSASignatureSignerContext;
import org.keycloak.crypto.KeyUse;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.jose.jwk.JWK;
import org.keycloak.jose.jwk.JWKBuilder;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.jose.jws.JWSHeader;
import org.keycloak.models.Constants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.oid4vci.CredentialScopeModel;
import org.keycloak.protocol.oid4vc.OID4VCLoginProtocolFactory;
Expand Down Expand Up @@ -81,6 +84,7 @@
import org.keycloak.representations.JsonWebToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ClientScopeRepresentation;
import org.keycloak.representations.idm.KeysMetadataRepresentation;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.services.CorsErrorResponseException;
import org.keycloak.services.managers.AppAuthManager.BearerTokenAuthenticator;
Expand Down Expand Up @@ -1316,6 +1320,79 @@ public void testCredentialOfferDifferentNoncesIndependent() {
assertEquals(ErrorType.INVALID_CREDENTIAL_OFFER_REQUEST.getValue(), response2.getError(), "Error type should be INVALID_CREDENTIAL_OFFER_REQUEST");
}

@Test
public void testCredentialIssuerSigningDefaultKeyAndAlg() {
KeysMetadataRepresentation keyMetadata = testRealm.admin().keys().getKeyMetadata();

String kid = "";
String alg = "";
jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_KEY_ID, kid);
jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_ALG, alg);
testRealm.admin().clientScopes().get(jwtTypeCredentialScope.getId()).update(jwtTypeCredentialScope);
testCredentialIssuanceSigningConfiguration(keyMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM), Constants.DEFAULT_SIGNATURE_ALGORITHM);
}< E2BD /td>

@Test
public void testCredentialIssuerSigningSpecificAlg() {
String kid = "";
String alg = Algorithm.ES256;
jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_KEY_ID, kid);
jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_ALG, alg);
testRealm.admin().clientScopes().get(jwtTypeCredentialScope.getId()).update(jwtTypeCredentialScope);
testCredentialIssuanceSigningConfiguration(null, Algorithm.ES256);
}

@Test
public void testCredentialIssuerSigningSpecificKey() {
KeysMetadataRepresentation keyMetadata = testRealm.admin().keys().getKeyMetadata();

String kid = keyMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM);
String alg = Constants.DEFAULT_SIGNATURE_ALGORITHM;
jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_KEY_ID, kid);
jwtTypeCredentialScope.getAttributes().put(CredentialScopeModel.VC_SIGNING_ALG, alg);
testRealm.admin().clientScopes().get(jwtTypeCredentialScope.getId()).update(jwtTypeCredentialScope);
testCredentialIssuanceSigningConfiguration(keyMetadata.getActive().get(Constants.DEFAULT_SIGNATURE_ALGORITHM), Constants.DEFAULT_SIGNATURE_ALGORITHM);
}

public void testCredentialIssuanceSigningConfiguration(String kid, String alg) {
String scopeName = jwtTypeCredentialScope.getName();
String credConfigId = jwtTypeCredentialScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID);
CredentialIssuer credentialIssuer = getCredentialIssuerMetadata();
OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail();
authDetail.setType(OPENID_CREDENTIAL);
authDetail.setCredentialConfigurationId(credConfigId);
authDetail.setLocations(List.of(credentialIssuer.getCredentialIssuer()));

testCredentialIssuanceWithAuthZCodeFlow(jwtTypeCredentialScope,
(testScope) -> {
String authCode = getAuthorizationCode(oauth, client, "john", scopeName);
return getBearerToken(oauth, authCode, authDetail).getAccessToken();
},
m -> {
String accessToken = (String) m.get("accessToken");
WebTarget credentialTarget = (WebTarget) m.get("credentialTarget");
CredentialRequest credentialRequest = (CredentialRequest) m.get("credentialRequest");

try (Response response = credentialTarget.request()
.header(HttpHeaders.AUTHORIZATION, "bearer " + accessToken)
.post(Entity.json(credentialRequest))) {
assertEquals(200, response.getStatus());
CredentialResponse credentialResponse = JsonSerialization.readValue(response.readEntity(String.class),
CredentialResponse.class);
JWSHeader jwsHeader = TokenVerifier.create((String) credentialResponse.getCredentials().get(0).getCredential(),
JsonWebToken.class).getHeader();

if (kid != null) {
assertEquals(jwsHeader.getKeyId(), kid);
}
assertEquals(jwsHeader.getRawAlgorithm(), alg);

} catch (VerificationException | IOException e) {
throw new RuntimeException(e);
}
});
}

private String getCNonce() {
UriBuilder builder = UriBuilder.fromUri(keycloakUrls.getBase());
URI oid4vcUri = RealmsResource.protocolUrl(builder)
Expand Down
Loading
0