From fb913d1d406e20b832a98de3ca203aaa47398e9e Mon Sep 17 00:00:00 2001 From: Dominik Schlosser Date: Mon, 2 Nov 2026 00:57:54 +0100 Subject: [PATCH] [OID4VC] Support ETSI Lists of Trusted Entities Signed-off-by: Dominik Schlosser --- .../server_admin/topics/oid4vci/proofs.adoc | 28 +- .../admin/messages/messages_en.properties | 2 +- .../add/AddEtsiTrustList.tsx | 96 ++++ .../identity-providers/add/DetailSettings.tsx | 31 +- .../add/EtsiTrustListSettings.tsx | 38 ++ .../admin-ui/src/identity-providers/routes.ts | 2 + .../routes/IdentityProviderEtsiTrustList.tsx | 26 + .../broker/provider/X509TrustMaterial.java | 13 +- .../broker/oid4vp/OID4VPIdentityProvider.java | 1 - .../DefaultTrustIdentityProviderConfig.java | 2 +- .../etsi/EtsiTrustListIdentityProvider.java | 115 +++++ .../EtsiTrustListIdentityProviderConfig.java | 113 +++++ .../EtsiTrustListIdentityProviderFactory.java | 99 ++++ .../etsi/EtsiTrustListPublicKeyLoader.java | 156 ++++++ .../trust/etsi/ListOfTrustedEntities.java | 61 +++ .../admin/IdentityProviderResource.java | 5 +- ...ak.broker.provider.IdentityProviderFactory | 1 + .../EtsiTrustListIdentityProviderTest.java | 477 ++++++++++++++++++ .../broker/trust/TrustListTestSupport.java | 192 +++++++ .../signing/OID4VCKeyAttestationTest.java | 6 +- .../broker/trust/wallet-providers-list.json | 186 +++++++ 21 files changed, 1626 insertions(+), 24 deletions(-) create mode 100644 js/apps/admin-ui/src/identity-providers/add/AddEtsiTrustList.tsx create mode 100644 js/apps/admin-ui/src/identity-providers/add/EtsiTrustListSettings.tsx create mode 100644 js/apps/admin-ui/src/identity-providers/routes/IdentityProviderEtsiTrustList.tsx create mode 100644 services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProvider.java create mode 100644 services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderConfig.java create mode 100644 services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderFactory.java create mode 100644 services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListPublicKeyLoader.java create mode 100644 services/src/main/java/org/keycloak/broker/trust/etsi/ListOfTrustedEntities.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/broker/trust/EtsiTrustListIdentityProviderTest.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/broker/trust/TrustListTestSupport.java create mode 100644 tests/base/src/test/resources/org/keycloak/tests/broker/trust/wallet-providers-list.json diff --git a/docs/documentation/server_admin/topics/oid4vci/proofs.adoc b/docs/documentation/server_admin/topics/oid4vci/proofs.adoc index 502e75c221f0..ee5dc6ffb175 100644 --- a/docs/documentation/server_admin/topics/oid4vci/proofs.adoc +++ b/docs/documentation/server_admin/topics/oid4vci/proofs.adoc @@ -107,9 +107,10 @@ Trusted attester keys are configured per client because different wallets can re ===== Admin Console -. Create or configure a trust-material identity provider, such as **Default Trust**, that exposes the trusted attester public keys or X.509 trust anchors. +. Create or configure a trust-material identity provider, such as **Default Trust** or **ETSI Trust List**, that exposes the trusted attester public keys or X.509 trust anchors. ** For `kid`-based attestations, configure a JWKS URL or validating public key. -** For `x5c`-based attestations, enable **Use X.509 attestation trust**, provide a PEM bundle containing only self-signed device-vendor attestation CA roots, and configure **Required extended key usages** with the accepted Extended Key Usage (EKU) OIDs. When at least one OID is configured, the attestation end-entity certificate must contain an EKU extension with at least one OID that exactly matches a configured value; otherwise, validation fails. When the list is empty, no EKU restriction is applied and the trust anchors alone decide trust. +** For trust from an ETSI TS 119 602 List of Trusted Entities (LoTE), see <<_oid4vci_etsi_trust_list,ETSI trust lists>>. +** For `x5c`-based attestations, enable **Use X.509 attestation trust**, provide a PEM bundle containing the device-vendor attestation CA certificates, and configure **Required extended key usages** with the accepted Extended Key Usage (EKU) OIDs. When at least one OID is configured, the attestation end-entity certificate must contain an EKU extension with at least one OID that exactly matches a configured value; otherwise, validation fails. When the list is empty, no EKU restriction is applied and the trust anchors alone decide trust. . Go to *Clients* and select the wallet client that requests credentials. . Open the *Advanced* tab. . In the *OpenID Verifiable Credentials* section, enable **Enable OID4VCI**. @@ -118,12 +119,31 @@ Trusted attester keys are configured per client because different wallets can re OID4VCI does not define a universal EKU OID for key attestation. Use the OID specified by the device vendor or the applicable attestation trust framework. For example, a private test PKI could place `1.3.6.1.4.1.32473.1.1` in both the certificate and the configuration to demonstrate exact matching. The `32473` private enterprise number is reserved for documentation and must not be used in production. -WARNING: The built-in OIDC identity provider exposes only JWK trust material and cannot provide X.509 trust anchors for `x5c`-based attestations. Use **Default Trust**, or a custom trust-material identity provider that implements X.509 trust resolution, for `x5c`-based attestations. +WARNING: The built-in OIDC identity provider exposes only JWK trust material and cannot provide X.509 trust anchors for `x5c`-based attestations. Use **Default Trust**, **ETSI Trust List**, or a custom trust-material identity provider that implements X.509 trust resolution, for `x5c`-based attestations. WARNING: Certificate revocation checking is not currently supported for `x5c` key-attestation certificate chains. Before trusting an attestation CA, ensure that revoked attestation certificates are rejected by a mandatory revocation mechanism outside {project_name}. The **OID4VCI Attester Trust Identity Providers** option is only shown when **Enable OID4VCI** is enabled for the client. It accepts only trust-material identity providers from the current realm. If no trust-material identity provider is configured, the dropdown has no values to select. +[[_oid4vci_etsi_trust_list]] +===== ETSI trust lists + +The **ETSI Trust List** identity provider derives trust from a signed ETSI TS 119 602 V1.1.1 List of Trusted Entities (LoTE), such as the Wallet Providers list of the EUDI Wallet ecosystem. Configure these settings: + +Trust list URL:: The URL of the signed list in its JSON Web Signature form. +Trust list signing certificates:: A PEM bundle of the certificates allowed to sign the list. A list is used only when one of these certificates verifies its signature. To rotate the signing key, configure the old and the new certificate. +LoTE type:: The required type of the list, for example `+http://uri.etsi.org/19602/LoTEType/EUWalletProvidersList+`. {project_name} rejects a list whose `LoTEType` value does not match. +Service types:: The service type identifiers whose certificates are trusted, for example `+http://uri.etsi.org/19602/SvcType/WalletSolution/Issuance+`. +Service statuses:: Services with one of these statuses are trusted. Services without a status are always trusted. When no status is configured, only services without a status are trusted. +Refresh interval:: The maximum number of seconds between two downloads, 3600 by default. This value decides how soon a withdrawn certificate stops being trusted. + +An attestation must include its signing certificate in the `x5c` header, and that certificate must chain to a CA certificate on the list. Attestations without `x5c` are rejected, and a key cannot be selected by `kid`. End entity certificates on the list are ignored. + +{project_name} downloads the list when it is needed and reuses it until the refresh interval or its `NextUpdate` time has passed. When the list cannot be downloaded or verified, trust decisions that depend on it fail until a valid list is available. A list without a `NextUpdate` value has been discontinued by its operator, so none of its certificates are trusted. + +{project_name} uses the configured certificates as the only trust source for the list. It does not follow pointers to other lists. +{project_name} checks the list signature as a JSON Web Signature against the configured certificates and does not perform full JAdES Baseline B validation. + ===== Client Attribute [cols="1,1,2", options="header"] @@ -167,7 +187,7 @@ Attestation JWT JOSE header Default Trust identity provider --------------------------- ------------------------------- x5c[0]: attestation leaf certificate Trusted certificates: - signs the attestation JWT device-vendor root CA - - must be an end-entity certificate (self-signed trust anchor) + - must be an end-entity certificate (trust anchor, may be a subordinate CA) - contains an allowed EKU x5c[1..n]: intermediate CA certificates Allowed attestation extended diff --git a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties index 19eaf381ff4c..b9e6d515226c 100644 --- a/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties +++ b/js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties @@ -2030,7 +2030,7 @@ useJwksUrl=Use JWKS URL useX509AttestationTrust=Use X.509 attestation trust useX509AttestationTrustHelp=Validate key-attestation certificate chains against dedicated trusted attestation roots instead of resolving a JWK. trustedAttestationCertificates=Trusted attestation certificates -trustedAttestationCertificatesHelp=PEM bundle containing only self-signed device-vendor attestation CA root certificates. Do not use the general TLS trust store. +trustedAttestationCertificatesHelp=PEM bundle containing the device-vendor attestation CA certificates. Do not use the general TLS trust store. requiredExtendedKeyUsages=Required extended key usages requiredExtendedKeyUsagesHelp=Comma-separated object identifiers (OIDs). The leaf certificate's Extended Key Usage extension must contain at least one of them. When empty, no extended key usage restriction is applied. wantAssertionsSigned=Want Assertions signed diff --git a/js/apps/admin-ui/src/identity-providers/add/AddEtsiTrustList.tsx b/js/apps/admin-ui/src/identity-providers/add/AddEtsiTrustList.tsx new file mode 100644 index 000000000000..7f2ae99b6d84 --- /dev/null +++ b/js/apps/admin-ui/src/identity-providers/add/AddEtsiTrustList.tsx @@ -0,0 +1,96 @@ +import type IdentityProviderRepresentation from "@keycloak/keycloak-admin-client/lib/defs/identityProviderRepresentation"; +import { + ActionGroup, + AlertVariant, + Button, + PageSection, +} from "@patternfly/react-core"; +import { FormProvider, useForm } from "react-hook-form"; +import { useTranslation } from "react-i18next"; +import { Link, useNavigate } from "react-router-dom"; +import { useAdminClient } from "../../admin-client"; +import { useAlerts } from "@keycloak/keycloak-ui-shared"; +import { FormAccess } from "../../components/form/FormAccess"; +import { ViewHeader } from "../../components/view-header/ViewHeader"; +import { useRealm } from "../../context/realm-context/RealmContext"; +import { toIdentityProvider } from "../routes/IdentityProvider"; +import { toIdentityProviders } from "../routes/IdentityProviders"; +import EtsiTrustListSettings from "./EtsiTrustListSettings"; + +export default function AddEtsiTrustList() { + const { adminClient } = useAdminClient(); + const { t } = useTranslation(); + const navigate = useNavigate(); + const id = "etsi-trust-list"; + + const form = useForm({ + defaultValues: { alias: id }, + mode: "onChange", + }); + const { + handleSubmit, + formState: { isDirty }, + } = form; + + const { addAlert, addError } = useAlerts(); + const { realm } = useRealm(); + + const onSubmit = async (provider: IdentityProviderRepresentation) => { + try { + await adminClient.identityProviders.create({ + ...provider, + providerId: id, + }); + addAlert(t("createIdentityProviderSuccess"), AlertVariant.success); + void navigate( + toIdentityProvider({ + realm, + providerId: id, + alias: provider.alias!, + tab: "settings", + }), + ); + } catch (error) { + addError("createIdentityProviderError", error); + } + }; + + return ( + <> + + + + + + + + + + + + + + + ); +} diff --git a/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx b/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx index 04862dd1f45c..b5c825756cb6 100644 --- a/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx +++ b/js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx @@ -83,6 +83,7 @@ import { JWTAuthorizationGrantAssertionSettings } from "./JWTAuthorizationGrantA import JWTAuthorizationGrantSettings from "./JWTAuthorizationGrantSettings"; import { DefaultSwitchControl } from "../../components/SwitchControl"; import DefaultTrustSettings from "./DefaultTrustSettings"; +import EtsiTrustListSettings from "./EtsiTrustListSettings"; import { IdpDomainsTab } from "./IdpDomainsTab"; import { IdpOrganizationsTab } from "./IdpOrganizationsTab"; import Oid4VpSettings from "./Oid4VpSettings"; @@ -504,6 +505,7 @@ export default function DetailSettings() { "jwt-authorization-grant", ); const isDefaultTrust = provider.providerId === "default-trust"; + const isEtsiTrustList = provider.providerId === "etsi-trust-list"; const isOid4vp = provider.providerId === "oid4vp"; const isSocial = !isOIDC && !isSAML && !isOAuth2; const isJWTAuthorizationGrantSupported = @@ -544,6 +546,7 @@ export default function DetailSettings() { isKubernetes || isJWTAuthorizationGrant || isDefaultTrust || + isEtsiTrustList || isOid4vp, panel: ( ), }, + { + title: t("generalSettings"), + isHidden: !isEtsiTrustList, + panel: ( +
+ + + + ), + }, { title: t("samlSettings"), isHidden: !isSAML, @@ -726,7 +748,11 @@ export default function DetailSettings() { { title: t("advancedSettings"), isHidden: - isSPIFFE || isKubernetes || isJWTAuthorizationGrant || isDefaultTrust, + isSPIFFE || + isKubernetes || + isJWTAuthorizationGrant || + isDefaultTrust || + isEtsiTrustList, panel: ( {t("mappers")}} diff --git a/js/apps/admin-ui/src/identity-providers/add/EtsiTrustListSettings.tsx b/js/apps/admin-ui/src/identity-providers/add/EtsiTrustListSettings.tsx new file mode 100644 index 000000000000..c7c38a2f5126 --- /dev/null +++ b/js/apps/admin-ui/src/identity-providers/add/EtsiTrustListSettings.tsx @@ -0,0 +1,38 @@ +import { TextControl } from "@keycloak/keycloak-ui-shared"; +import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; +import { useParams } from "react-router-dom"; +import { DynamicComponents } from "../../components/dynamic/DynamicComponents"; +import { useServerInfo } from "../../context/server-info/ServerInfoProvider"; +import type { IdentityProviderParams } from "../routes/IdentityProvider"; + +const PROVIDER_ID = "etsi-trust-list"; + +export default function EtsiTrustListSettings() { + const { t } = useTranslation(); + const { tab } = useParams(); + const serverInfo = useServerInfo(); + + const properties = useMemo( + () => + serverInfo.componentTypes?.[ + "org.keycloak.broker.provider.IdentityProvider" + ]?.find(({ id }) => id === PROVIDER_ID)?.properties ?? [], + [serverInfo], + ); + + return ( + <> + + + + ); +} diff --git a/js/apps/admin-ui/src/identity-providers/routes.ts b/js/apps/admin-ui/src/identity-providers/routes.ts index b27ba76769e1..241359fe1b52 100644 --- a/js/apps/admin-ui/src/identity-providers/routes.ts +++ b/js/apps/admin-ui/src/identity-providers/routes.ts @@ -7,6 +7,7 @@ import { IdentityProviderSpiffeRoute } from "./routes/IdentityProviderSpiffe"; import { IdentityProviderKubernetesRoute } from "./routes/IdentityProviderKubernetes"; import { IdentityProviderDefaultTrustRoute } from "./routes/IdentityProviderDefaultTrust"; import { IdentityProviderOid4VpRoute } from "./routes/IdentityProviderOid4Vp"; +import { IdentityProviderEtsiTrustListRoute } from "./routes/IdentityProviderEtsiTrustList"; import { IdentityProvidersRoute } from "./routes/IdentityProviders"; import { IdentityProviderAddMapperRoute } from "./routes/AddMapper"; import { IdentityProviderEditMapperRoute } from "./routes/EditMapper"; @@ -25,6 +26,7 @@ const routes: AppRouteObject[] = [ IdentityProviderKubernetesRoute, IdentityProviderDefaultTrustRoute, IdentityProviderOid4VpRoute, + IdentityProviderEtsiTrustListRoute, IdentityProviderKeycloakOidcRoute, IdentityProviderCreateRoute, IdentityProviderRoute, diff --git a/js/apps/admin-ui/src/identity-providers/routes/IdentityProviderEtsiTrustList.tsx b/js/apps/admin-ui/src/identity-providers/routes/IdentityProviderEtsiTrustList.tsx new file mode 100644 index 000000000000..5bf6f5971500 --- /dev/null +++ b/js/apps/admin-ui/src/identity-providers/routes/IdentityProviderEtsiTrustList.tsx @@ -0,0 +1,26 @@ +import { lazy } from "react"; +import type { Path } from "react-router-dom"; +import { generateEncodedPath } from "../../utils/generateEncodedPath"; +import type { AppRouteObject } from "../../routes"; + +export type IdentityProviderEtsiTrustListParams = { realm: string }; + +const AddEtsiTrustList = lazy(() => import("../add/AddEtsiTrustList")); + +export const IdentityProviderEtsiTrustListRoute: AppRouteObject = { + path: "/:realm/identity-providers/etsi-trust-list/add", + element: , + handle: { + access: "manage-identity-providers", + breadcrumb: (t) => t("addProvider"), + }, +}; + +export const toIdentityProviderEtsiTrustList = ( + params: IdentityProviderEtsiTrustListParams, +): Partial => ({ + pathname: generateEncodedPath( + IdentityProviderEtsiTrustListRoute.path, + params, + ), +}); diff --git a/server-spi-private/src/main/java/org/keycloak/broker/provider/X509TrustMaterial.java b/server-spi-private/src/main/java/org/keycloak/broker/provider/X509TrustMaterial.java index dca271f40bc8..a80e2887ab68 100644 --- a/server-spi-private/src/main/java/org/keycloak/broker/provider/X509TrustMaterial.java +++ b/server-spi-private/src/main/java/org/keycloak/broker/provider/X509TrustMaterial.java @@ -24,7 +24,8 @@ /** * X.509 trust material and validation policy exposed by a trust material identity provider. * - * @param trustAnchors self signed CA roots for one trust domain + * @param trustAnchors CA certificates for one trust domain. Path validation ends at a listed + * certificate, so a subordinate CA is a valid anchor * @param requiredExtendedKeyUsages extended key usage OIDs of which the end entity certificate must * contain at least one, an empty list imposes no restriction */ @@ -49,15 +50,5 @@ private static void validateTrustAnchor(X509Certificate certificate) { if (keyUsage != null && (keyUsage.length <= 5 || !keyUsage[5])) { throw new IllegalArgumentException("X.509 trust anchors must be valid for certificate signing"); } - - if (!certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) { - throw new IllegalArgumentException("X.509 trust anchors must be self-issued root certificates"); - } - - try { - certificate.verify(certificate.getPublicKey()); - } catch (Exception e) { - throw new IllegalArgumentException("X.509 trust anchors must be self-signed root certificates", e); - } } } diff --git a/services/src/main/java/org/keycloak/broker/oid4vp/OID4VPIdentityProvider.java b/services/src/main/java/org/keycloak/broker/oid4vp/OID4VPIdentityProvider.java index 1014547e5a1c..f6721dcd19fd 100644 --- a/services/src/main/java/org/keycloak/broker/oid4vp/OID4VPIdentityProvider.java +++ b/services/src/main/java/org/keycloak/broker/oid4vp/OID4VPIdentityProvider.java @@ -182,7 +182,6 @@ public Stream resolveX509Trust(TrustMaterialRequest request) // How trusted issuer material is resolved for a presented credential. The provider acts as its // own trust material, either delegating to the configured trust material identity providers or // serving the inline trusted issuer JWKS. - // TODO add a trust list backed resolver (e.g. ETSI), selected from configuration. protected TrustedSdJwtIssuerResolver trustedIssuerResolver() { return new TrustMaterialSdJwtIssuerResolver(this); } diff --git a/services/src/main/java/org/keycloak/broker/trust/DefaultTrustIdentityProviderConfig.java b/services/src/main/java/org/keycloak/broker/trust/DefaultTrustIdentityProviderConfig.java index 4267ff8b67f6..8ae28c55a774 100644 --- a/services/src/main/java/org/keycloak/broker/trust/DefaultTrustIdentityProviderConfig.java +++ b/services/src/main/java/org/keycloak/broker/trust/DefaultTrustIdentityProviderConfig.java @@ -74,7 +74,7 @@ public void validate(RealmModel realm) { getRequiredExtendedKeyUsages()); } catch (RuntimeException e) { throw new IllegalArgumentException( - "Trusted X.509 certificates must be a valid PEM bundle of self-signed CA roots", e); + "Trusted X.509 certificates must be a valid PEM bundle of CA certificates", e); } } else { if (hasTrustedCertificates) { diff --git a/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProvider.java b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProvider.java new file mode 100644 index 000000000000..2cc901e3e11b --- /dev/null +++ b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProvider.java @@ -0,0 +1,115 @@ +package org.keycloak.broker.trust.etsi; + +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Stream; + +import org.keycloak.broker.provider.TrustMaterialIdentityProvider; +import org.keycloak.broker.provider.TrustMaterialRequest; +import org.keycloak.broker.provider.X509TrustMaterial; +import org.keycloak.crypto.KeyWrapper; +import org.keycloak.jose.jwk.JWK; +import org.keycloak.keys.PublicKeyStorageProvider; +import org.keycloak.keys.PublicKeyStorageUtils; +import org.keycloak.models.KeycloakSession; + +import org.jboss.logging.Logger; + +/** + * Exposes the CA certificates of an ETSI TS 119 602 List of Trusted Entities as X.509 trust anchors. + * HAIP requires the signing certificate in x5c and keeps the trust anchor out of it, so an artifact + * needs a chain to a listed CA. No key can be selected by kid and listed end entity certificates are + * ignored. + */ +public class EtsiTrustListIdentityProvider implements TrustMaterialIdentityProvider { + + private static final Logger logger = Logger.getLogger(EtsiTrustListIdentityProvider.class); + + // Index of the keyCertSign bit in the key usage extension, see RFC 5280 clause 4.2.1.3 + private static final int KEY_CERT_SIGN = 5; + + private final KeycloakSession session; + private final EtsiTrustListIdentityProviderConfig config; + + public EtsiTrustListIdentityProvider(KeycloakSession session, EtsiTrustListIdentityProviderConfig config) { + this.session = session; + this.config = config; + } + + @Override + public EtsiTrustListIdentityProviderConfig getConfig() { + return config; + } + + @Override + public Stream resolveKeys(TrustMaterialRequest request) { + return Stream.empty(); + } + + @Override + public Stream resolveX509Trust(TrustMaterialRequest request) { + Set trustAnchors = new LinkedHashSet<>(listedCertificates().stream() + .filter(EtsiTrustListIdentityProvider::isCaCertificate) + .filter(EtsiTrustListIdentityProvider::isWithinValidityPeriod) + .toList()); + if (trustAnchors.isEmpty()) { + return Stream.empty(); + } + return Stream.of(new X509TrustMaterial(trustAnchors, List.of())); + } + + @Override + public boolean reloadKeys() { + if (!config.isEnabled()) { + return false; + } + return session.getProvider(PublicKeyStorageProvider.class) + .reloadKeys(modelKey(), new EtsiTrustListPublicKeyLoader(session, config)); + } + + @Override + public void close() { + } + + private List listedCertificates() { + List keys; + try { + keys = session.getProvider(PublicKeyStorageProvider.class) + .getKeys(modelKey(), new EtsiTrustListPublicKeyLoader(session, config)); + } catch (RuntimeException e) { + // Other trust providers of the client still work while this list is unavailable + logger.warnf(e, "Failed to load the trust list of identity provider '%s'", config.getAlias()); + return List.of(); + } + return keys.stream() + .map(KeyWrapper::getCertificate) + .filter(Objects::nonNull) + .toList(); + } + + private String modelKey() { + return PublicKeyStorageUtils.getIdpModelCacheKey(session.getContext().getRealm().getId(), config.getInternalId()); + } + + private static boolean isCaCertificate(X509Certificate certificate) { + boolean[] keyUsage = certificate.getKeyUsage(); + boolean ca = certificate.getBasicConstraints() >= 0 && (keyUsage == null || (keyUsage.length > KEY_CERT_SIGN && keyUsage[KEY_CERT_SIGN])); + if (!ca) { + logger.debugf("Ignoring listed certificate '%s', it is not a CA certificate", certificate.getSubjectX500Principal()); + } + return ca; + } + + private static boolean isWithinValidityPeriod(X509Certificate certificate) { + try { + certificate.checkValidity(); + return true; + } catch (CertificateException e) { + return false; + } + } +} diff --git a/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderConfig.java b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderConfig.java new file mode 100644 index 000000000000..1e2442ae9e6b --- /dev/null +++ b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderConfig.java @@ -0,0 +1,113 @@ +package org.keycloak.broker.trust.etsi; + +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.List; + +import org.keycloak.common.util.PemUtils; +import org.keycloak.models.IdentityProviderModel; +import org.keycloak.models.RealmModel; +import org.keycloak.util.Strings; + +import static org.keycloak.common.util.UriUtils.checkUrl; + +public class EtsiTrustListIdentityProviderConfig extends IdentityProviderModel { + + public static final String TRUST_LIST_URL = "trustListUrl"; + public static final String SIGNING_CERTIFICATES = "trustListSigningCertificates"; + public static final String LOTE_TYPE = "trustListLoteType"; + public static final String SERVICE_TYPES = "trustListServiceTypes"; + public static final String SERVICE_STATUSES = "trustListServiceStatuses"; + public static final String REFRESH_INTERVAL = "trustListRefreshInterval"; + + public static final int DEFAULT_REFRESH_INTERVAL = 3600; + + public EtsiTrustListIdentityProviderConfig() { + } + + public EtsiTrustListIdentityProviderConfig(IdentityProviderModel model) { + super(model); + } + + @Override + public Boolean isHideOnLogin() { + return true; + } + + @Override + public void validate(RealmModel realm) { + super.validate(realm); + if (Strings.isEmpty(getTrustListUrl())) { + throw new IllegalArgumentException("The trust list URL is required"); + } + checkUrl(realm.getSslRequired(), getTrustListUrl(), TRUST_LIST_URL); + if (Strings.isEmpty(getLoteType())) { + throw new IllegalArgumentException("The trust list LoTE type is required"); + } + if (getServiceTypes().isEmpty()) { + throw new IllegalArgumentException("At least one trust list service type is required"); + } + List signingCertificates; + try { + signingCertificates = getSigningCertificates(); + } catch (RuntimeException e) { + throw new IllegalArgumentException("The trust list signing certificates must be a valid PEM bundle", e); + } + if (signingCertificates.isEmpty()) { + throw new IllegalArgumentException("At least one trust list signing certificate is required"); + } + int refreshInterval; + try { + refreshInterval = getRefreshInterval(); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("The trust list refresh interval must be a number of seconds", e); + } + if (refreshInterval <= 0) { + throw new IllegalArgumentException("The trust list refresh interval must be a positive number of seconds"); + } + } + + public String getTrustListUrl() { + return getConfig().get(TRUST_LIST_URL); + } + + public List getSigningCertificates() { + String certificates = getConfig().get(SIGNING_CERTIFICATES); + if (Strings.isEmpty(certificates)) { + return List.of(); + } + return List.of(PemUtils.decodeCertificates(certificates)); + } + + public String getLoteType() { + return getConfig().get(LOTE_TYPE); + } + + public int getRefreshInterval() { + String refreshInterval = getConfig().get(REFRESH_INTERVAL); + if (Strings.isEmpty(refreshInterval)) { + return DEFAULT_REFRESH_INTERVAL; + } + return Integer.parseInt(refreshInterval.trim()); + } + + public List getServiceTypes() { + return getList(SERVICE_TYPES); + } + + public List getServiceStatuses() { + return getList(SERVICE_STATUSES); + } + + private List getList(String key) { + String configured = getConfig().get(key); + if (Strings.isEmpty(configured)) { + return List.of(); + } + return Arrays.stream(configured.split(",")) + .map(String::trim) + .filter(value -> !value.isEmpty()) + .distinct() + .toList(); + } +} diff --git a/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderFactory.java b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderFactory.java new file mode 100644 index 000000000000..ae4e520b99df --- /dev/null +++ b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListIdentityProviderFactory.java @@ -0,0 +1,99 @@ +package org.keycloak.broker.trust.etsi; + +import java.util.List; +import java.util.Map; + +import org.keycloak.Config; +import org.keycloak.broker.provider.AbstractIdentityProviderFactory; +import org.keycloak.common.Profile; +import org.keycloak.models.IdentityProviderModel; +import org.keycloak.models.KeycloakSession; +import org.keycloak.provider.EnvironmentDependentProviderFactory; +import org.keycloak.provider.ProviderConfigProperty; +import org.keycloak.provider.ProviderConfigurationBuilder; + +public class EtsiTrustListIdentityProviderFactory extends AbstractIdentityProviderFactory + implements EnvironmentDependentProviderFactory { + + public static final String PROVIDER_ID = "etsi-trust-list"; + + private static final List CONFIG_PROPERTIES = ProviderConfigurationBuilder.create() + .property() + .name(EtsiTrustListIdentityProviderConfig.TRUST_LIST_URL) + .label("Trust list URL") + .helpText("URL of the signed ETSI TS 119 602 List of Trusted Entities (LoTE).") + .type(ProviderConfigProperty.STRING_TYPE) + .required(true) + .add() + .property() + .name(EtsiTrustListIdentityProviderConfig.SIGNING_CERTIFICATES) + .label("Trust list signing certificates") + .helpText("PEM bundle of the certificates allowed to sign the trust list. Configure several certificates for a key rotation.") + .type(ProviderConfigProperty.TEXT_TYPE) + .required(true) + .add() + .property() + .name(EtsiTrustListIdentityProviderConfig.LOTE_TYPE) + .label("LoTE type") + .helpText("Required LoTE type of the trust list, for example http://uri.etsi.org/19602/LoTEType/EUWalletProvidersList.") + .type(ProviderConfigProperty.STRING_TYPE) + .required(true) + .add() + .property() + .name(EtsiTrustListIdentityProviderConfig.SERVICE_TYPES) + .label("Service types") + .helpText("Comma-separated service type identifiers whose certificates are trusted, for example http://uri.etsi.org/19602/SvcType/WalletSolution/Issuance.") + .type(ProviderConfigProperty.STRING_TYPE) + .required(true) + .add() + .property() + .name(EtsiTrustListIdentityProviderConfig.SERVICE_STATUSES) + .label("Service statuses") + .helpText("Comma-separated service statuses. Services with one of these statuses are trusted. Services without a status are always trusted. When no status is configured, only services without a status are trusted.") + .type(ProviderConfigProperty.STRING_TYPE) + .add() + .property() + .name(EtsiTrustListIdentityProviderConfig.REFRESH_INTERVAL) + .label("Refresh interval") + .helpText("Maximum number of seconds between two downloads of the trust list. This value decides how soon a withdrawn certificate stops being trusted.") + .type(ProviderConfigProperty.STRING_TYPE) + .defaultValue(String.valueOf(EtsiTrustListIdentityProviderConfig.DEFAULT_REFRESH_INTERVAL)) + .add() + .build(); + + @Override + public String getName() { + return "ETSI Trust List"; + } + + @Override + public EtsiTrustListIdentityProvider create(KeycloakSession session, IdentityProviderModel model) { + return new EtsiTrustListIdentityProvider(session, new EtsiTrustListIdentityProviderConfig(model)); + } + + @Override + public Map parseConfig(KeycloakSession session, String config) { + throw new UnsupportedOperationException(); + } + + @Override + public IdentityProviderModel createConfig() { + return new EtsiTrustListIdentityProviderConfig(); + } + + @Override + public List getConfigProperties() { + return CONFIG_PROPERTIES; + } + + @Override + public String getId() { + return PROVIDER_ID; + } + + @Override + public boolean isSupported(Config.Scope config) { + return Profile.isFeatureEnabled(Profile.Feature.OID4VC_VCI) || Profile.isFeatureEnabled(Profile.Feature.OID4VC_VP) + || Profile.isFeatureEnabled(Profile.Feature.CLIENT_AUTH_ABCA); + } +} diff --git a/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListPublicKeyLoader.java b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListPublicKeyLoader.java new file mode 100644 index 000000000000..8640170cbe4f --- /dev/null +++ b/services/src/main/java/org/keycloak/broker/trust/etsi/EtsiTrustListPublicKeyLoader.java @@ -0,0 +1,156 @@ +package org.keycloak.broker.trust.etsi; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.RSAPublicKey; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import org.keycloak.common.crypto.CryptoIntegration; +import org.keycloak.common.util.Time; +import org.keycloak.crypto.KeyType; +import org.keycloak.crypto.KeyUse; +import org.keycloak.crypto.KeyWrapper; +import org.keycloak.crypto.PublicKeysWrapper; +import org.keycloak.crypto.SignatureProvider; +import org.keycloak.http.simple.SimpleHttp; +import org.keycloak.jose.jws.JWSInput; +import org.keycloak.jose.jws.JWSInputException; +import org.keycloak.keys.PublicKeyLoader; +import org.keycloak.models.KeycloakSession; +import org.keycloak.util.JsonSerialization; +import org.keycloak.util.Strings; + +import org.apache.http.HttpHeaders; +import org.jboss.logging.Logger; + +/** + * Loads the certificates of the configured service types from a signed ETSI TS 119 602 V1.1.1 trust + * list. The list is accepted only if one of the configured certificates verifies its signature. + */ +public class EtsiTrustListPublicKeyLoader implements PublicKeyLoader { + + private static final Logger logger = Logger.getLogger(EtsiTrustListPublicKeyLoader.class); + + private final KeycloakSession session; + private final EtsiTrustListIdentityProviderConfig config; + + public EtsiTrustListPublicKeyLoader(KeycloakSession session, EtsiTrustListIdentityProviderConfig config) { + this.session = session; + this.config = config; + } + + @Override + public PublicKeysWrapper loadKeys() throws Exception { + JWSInput jws = new JWSInput(SimpleHttp.create(session).doGet(config.getTrustListUrl()) + .header(HttpHeaders.ACCEPT, "application/jwt") + .asString().trim()); + verifySignature(jws); + + ListOfTrustedEntities list = parse(jws); + if (!config.getLoteType().equals(list.schemeInformation().type())) { + throw new IllegalStateException("Unexpected LoTE type: " + list.schemeInformation().type()); + } + + long now = Time.currentTimeMillis(); + long refreshAt = now + config.getRefreshInterval() * 1000L; + // ETSI TS 119 602 V1.1.1 clause 6.3.15 uses a null NextUpdate for a discontinued list + if (Strings.isEmpty(list.schemeInformation().nextUpdate())) { + logger.warnf("Trust list of identity provider '%s' has no NextUpdate and is discontinued", config.getAlias()); + return new PublicKeysWrapper(List.of(), refreshAt); + } + + long nextUpdate = Instant.parse(list.schemeInformation().nextUpdate()).toEpochMilli(); + if (nextUpdate <= now) { + throw new IllegalStateException("Trust list expired at " + list.schemeInformation().nextUpdate()); + } + return new PublicKeysWrapper(toKeys(list), Math.min(refreshAt, nextUpdate)); + } + + // The signer is pinned by configuration, so the subject C and O are not matched against + // SchemeTerritory and SchemeOperatorName although clause 6.8.0 of ETSI TS 119 602 V1.1.1 requires it + private void verifySignature(JWSInput jws) throws JWSInputException { + String algorithm = jws.getHeader().getRawAlgorithm(); + SignatureProvider signatureProvider = Strings.isEmpty(algorithm) ? null : session.getProvider(SignatureProvider.class, algorithm); + if (signatureProvider == null || !signatureProvider.isAsymmetricAlgorithm()) { + throw new IllegalStateException("Unsupported trust list signature algorithm: " + algorithm); + } + + byte[] signedData = jws.getEncodedSignatureInput().getBytes(StandardCharsets.UTF_8); + for (X509Certificate certificate : config.getSigningCertificates()) { + if (verifies(signatureProvider, certificate, algorithm, signedData, jws.getSignature())) { + return; + } + } + throw new IllegalStateException("Trust list signature does not match any configured signing certificate"); + } + + private boolean verifies(SignatureProvider signatureProvider, X509Certificate certificate, String algorithm, + byte[] signedData, byte[] signature) { + try { + certificate.checkValidity(); + KeyWrapper key = toKey(certificate); + key.setAlgorithm(algorithm); + return signatureProvider.verifier(key).verify(signedData, signature); + } catch (Exception e) { + logger.debugf("Signing certificate '%s' does not verify the trust list: %s", certificate.getSubjectX500Principal(), e.getMessage()); + return false; + } + } + + private ListOfTrustedEntities parse(JWSInput jws) throws IOException { + ListOfTrustedEntities.Document document = JsonSerialization.readValue(jws.getContent(), ListOfTrustedEntities.Document.class); + if (document.list() == null || document.list().schemeInformation() == null) { + throw new IllegalStateException("Trust list payload has no LoTE object"); + } + return document.list(); + } + + private List toKeys(ListOfTrustedEntities list) { + List serviceTypes = config.getServiceTypes(); + List serviceStatuses = config.getServiceStatuses(); + List keys = new ArrayList<>(); + list.services() + .filter(service -> service != null && serviceTypes.contains(service.type())) + .filter(service -> service.status() == null || serviceStatuses.contains(service.status())) + .flatMap(ListOfTrustedEntities.ServiceInformation::encodedCertificates) + .forEach(encoded -> addKey(encoded, keys)); + return List.copyOf(keys); + } + + private void addKey(String encodedCertificate, List keys) { + try { + CertificateFactory factory = CryptoIntegration.getProvider().getX509CertFactory(); + X509Certificate certificate = (X509Certificate) factory.generateCertificate( + new ByteArrayInputStream(Base64.getMimeDecoder().decode(encodedCertificate))); + keys.add(toKey(certificate)); + } catch (GeneralSecurityException | IllegalArgumentException e) { + logger.warnf("Ignoring certificate in trust list of identity provider '%s': %s", config.getAlias(), e.getMessage()); + } + } + + private static KeyWrapper toKey(X509Certificate certificate) throws CertificateException { + PublicKey publicKey = certificate.getPublicKey(); + KeyWrapper key = new KeyWrapper(); + key.setUse(KeyUse.SIG); + key.setPublicKey(publicKey); + key.setCertificate(certificate); + if (publicKey instanceof ECPublicKey) { + key.setType(KeyType.EC); + } else if (publicKey instanceof RSAPublicKey) { + key.setType(KeyType.RSA); + } else { + throw new CertificateException("Unsupported public key type: " + publicKey.getAlgorithm()); + } + return key; + } +} diff --git a/services/src/main/java/org/keycloak/broker/trust/etsi/ListOfTrustedEntities.java b/services/src/main/java/org/keycloak/broker/trust/etsi/ListOfTrustedEntities.java new file mode 100644 index 000000000000..88c8a3f13add --- /dev/null +++ b/services/src/main/java/org/keycloak/broker/trust/etsi/ListOfTrustedEntities.java @@ -0,0 +1,61 @@ +package org.keycloak.broker.trust.etsi; + +import java.util.List; +import java.util.stream.Stream; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The parts of an ETSI TS 119 602 V1.1.1 List of Trusted Entities in its JSON binding that trust + * decisions depend on. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +record ListOfTrustedEntities(@JsonProperty("ListAndSchemeInformation") SchemeInformation schemeInformation, + @JsonProperty("TrustedEntitiesList") List trustedEntities) { + + Stream services() { + return (trustedEntities == null ? Stream.empty() : trustedEntities.stream()) + .flatMap(TrustedEntity::servicesInformation); + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record Document(@JsonProperty("LoTE") ListOfTrustedEntities list) { + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record SchemeInformation(@JsonProperty("LoTEType") String type, + @JsonProperty("NextUpdate") String nextUpdate) { + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record TrustedEntity(@JsonProperty("TrustedEntityServices") List services) { + + Stream servicesInformation() { + return services == null ? Stream.empty() : services.stream().map(TrustedEntityService::information); + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record TrustedEntityService(@JsonProperty("ServiceInformation") ServiceInformation information) { + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record ServiceInformation(@JsonProperty("ServiceTypeIdentifier") String type, + @JsonProperty("ServiceStatus") String status, + @JsonProperty("ServiceDigitalIdentity") DigitalIdentity digitalIdentity) { + + Stream encodedCertificates() { + return digitalIdentity == null || digitalIdentity.certificates() == null ? Stream.empty() + : digitalIdentity.certificates().stream().map(X509CertificateEntry::value); + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record DigitalIdentity(@JsonProperty("X509Certificates") List certificates) { + } + + @JsonIgnoreProperties(ignoreUnknown = true) + record X509CertificateEntry(@JsonProperty("val") String value) { + } +} diff --git a/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java b/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java index 682fda07f1d4..a72bd73e73c7 100644 --- a/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java @@ -559,7 +559,10 @@ public boolean reloadKeys() { throw new jakarta.ws.rs.NotFoundException(); } - IdentityProvider provider = IdentityBrokerService.getIdentityProvider(session, identityProviderModel.getAlias()); + IdentityProvider provider = IdentityBrokerService.getIdentityProvider(session, identityProviderModel, IdentityProvider.class); + if (provider == null) { + throw new NotFoundException(); + } return provider.reloadKeys(); } diff --git a/services/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderFactory b/services/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderFactory index 6c100450f3e3..957d38303686 100755 --- a/services/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderFactory +++ b/services/src/main/resources/META-INF/services/org.keycloak.broker.provider.IdentityProviderFactory @@ -24,3 +24,4 @@ org.keycloak.broker.kubernetes.KubernetesIdentityProviderFactory org.keycloak.broker.jwtauthorizationgrant.JWTAuthorizationGrantIdentityProviderFactory org.keycloak.broker.trust.DefaultTrustIdentityProviderFactory org.keycloak.broker.oid4vp.OID4VPIdentityProviderFactory +org.keycloak.broker.trust.etsi.EtsiTrustListIdentityProviderFactory diff --git a/tests/base/src/test/java/org/keycloak/tests/broker/trust/EtsiTrustListIdentityProviderTest.java b/tests/base/src/test/java/org/keycloak/tests/broker/trust/EtsiTrustListIdentityProviderTest.java new file mode 100644 index 000000000000..602080ab191e --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/broker/trust/EtsiTrustListIdentityProviderTest.java @@ -0,0 +1,477 @@ +package org.keycloak.tests.broker.trust; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import jakarta.ws.rs.core.Response; + +import org.keycloak.broker.provider.TrustMaterialIdentityProvider; +import org.keycloak.broker.provider.TrustMaterialRequest; +import org.keycloak.broker.provider.TrustMaterialResolver; +import org.keycloak.broker.provider.X509TrustMaterial; +import org.keycloak.broker.trust.etsi.EtsiTrustListIdentityProviderConfig; +import org.keycloak.broker.trust.etsi.EtsiTrustListIdentityProviderFactory; +import org.keycloak.common.Profile; +import org.keycloak.common.VerificationException; +import org.keycloak.common.util.KeyUtils; +import org.keycloak.common.util.PemUtils; +import org.keycloak.crypto.Algorithm; +import org.keycloak.jose.jwk.JWK; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.representations.idm.ErrorRepresentation; +import org.keycloak.representations.idm.IdentityProviderRepresentation; +import org.keycloak.services.resources.IdentityBrokerService; +import org.keycloak.testframework.annotations.InjectHttpServer; +import org.keycloak.testframework.annotations.InjectRealm; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.testframework.realm.ManagedRealm; +import org.keycloak.testframework.remote.runonserver.InjectRunOnServer; +import org.keycloak.testframework.remote.runonserver.RunOnServerClient; +import org.keycloak.testframework.remote.timeoffset.InjectTimeOffSet; +import org.keycloak.testframework.remote.timeoffset.TimeOffSet; +import org.keycloak.testframework.server.KeycloakServerConfig; +import org.keycloak.testframework.server.KeycloakServerConfigBuilder; +import org.keycloak.tests.broker.trust.TrustListTestSupport.PublishedTrustList; + +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.Test; + +import static org.keycloak.tests.broker.trust.TrustListTestSupport.ISSUANCE_SERVICE; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.LOTE_TYPE; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.REVOCATION_SERVICE; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.caCertificate; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.caCertificateWithoutCertificateSigning; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.ecKeyPair; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.encode; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.endEntityCertificate; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.expiredCaCertificate; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.publish; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.service; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.serviceWithStatus; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.signTrustList; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.subordinateCaCertificate; +import static org.keycloak.tests.broker.trust.TrustListTestSupport.trustList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@KeycloakIntegrationTest(config = EtsiTrustListIdentityProviderTest.TrustListServerConfig.class) +public class EtsiTrustListIdentityProviderTest { + + private static final int REFRESH_INTERVAL_SECONDS = 600; + private static final String REJECTED = "rejected"; + private static final String PUB_EAA_LOTE_TYPE = "http://uri.etsi.org/19602/LoTEType/EUPubEAAProvidersList"; + private static final String PUB_EAA_ISSUANCE_SERVICE = "http://uri.etsi.org/19602/SvcType/PubEAA/Issuance"; + private static final String NOTIFIED = "http://uri.etsi.org/19602/PubEAAProvidersList/SvcStatus/notified"; + private static final String WITHDRAWN = "http://uri.etsi.org/19602/PubEAAProvidersList/SvcStatus/withdrawn"; + private static final String SCHEME_ACTIVE = "https://scheme.example.test/status/active"; + + private static final AtomicInteger IDS = new AtomicInteger(); + + @InjectRunOnServer + RunOnServerClient runOnServer; + + @InjectHttpServer + HttpServer httpServer; + + @InjectRealm + ManagedRealm realm; + + @InjectTimeOffSet + TimeOffSet timeOffSet; + + private PublishedTrustList published; + + @Test + public void listedCaCertificatesBecomeTrustAnchors() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + List x5c = List.of(encode(Pki.LEAF)); + + assertEquals(1, trustAnchorCount(alias)); + assertEquals(KeyUtils.createKeyId(Pki.LEAF_KEY.getPublic()), validatedLeafKeyId(alias, x5c)); + } + + @Test + public void chainOfAnUnlistedCaIsRejected() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + + assertChainRejected(alias, List.of(encode(Pki.LISTED_LEAF))); + } + + @Test + public void listedEndEntityCertificatesAreIgnored() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.LISTED_LEAF))); + + assertTrustsNothing(alias); + assertNull(validatedLeafKeyId(alias, List.of(encode(Pki.LISTED_LEAF)))); + assertNull(validatedLeafKeyId(alias, null)); + } + + @Test + public void renewedCaCertificateSurvivesItsExpiredPredecessor() { + KeyPair caKey = ecKeyPair(); + X509Certificate renewed = caCertificate(caKey, "Renewed CA"); + X509Certificate expired = expiredCaCertificate(caKey, "Renewed CA"); + KeyPair leafKey = ecKeyPair(); + X509Certificate leaf = endEntityCertificate(leafKey.getPublic(), "Renewed CA Leaf", renewed, caKey); + String alias = createProvider(validList(service(ISSUANCE_SERVICE, renewed, expired))); + + assertEquals(1, trustAnchorCount(alias)); + assertEquals(KeyUtils.createKeyId(leafKey.getPublic()), validatedLeafKeyId(alias, List.of(encode(leaf)))); + } + + @Test + public void caCertificateWithoutCertificateSigningDoesNotDisableTheList() { + X509Certificate unusable = caCertificateWithoutCertificateSigning(ecKeyPair(), "CRL Only CA"); + String alias = createProvider(validList(service(ISSUANCE_SERVICE, unusable, Pki.SUBORDINATE_CA))); + + assertEquals(1, trustAnchorCount(alias)); + } + + @Test + public void listMixingCertificatesTrustsOnlyItsCaCertificates() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA, Pki.LISTED_LEAF))); + + assertEquals(KeyUtils.createKeyId(Pki.LEAF_KEY.getPublic()), validatedLeafKeyId(alias, List.of(encode(Pki.LEAF)))); + assertChainRejected(alias, List.of(encode(Pki.LISTED_LEAF))); + assertChainRejected(alias, null); + } + + @Test + public void onlyConfiguredServiceTypesAreInScope() { + String alias = createProvider(validList( + service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA), + service(REVOCATION_SERVICE, Pki.ROOT))); + + assertEquals(1, trustAnchorCount(alias)); + assertChainRejected(alias, List.of(encode(Pki.LISTED_LEAF))); + } + + @Test + public void withdrawnPubEaaServicesAreIgnored() { + String alias = createProvider(pubEaaList(), Map.of( + EtsiTrustListIdentityProviderConfig.LOTE_TYPE, PUB_EAA_LOTE_TYPE, + EtsiTrustListIdentityProviderConfig.SERVICE_TYPES, PUB_EAA_ISSUANCE_SERVICE, + EtsiTrustListIdentityProviderConfig.SERVICE_STATUSES, NOTIFIED)); + + assertEquals(1, trustAnchorCount(alias)); + assertChainRejected(alias, List.of(encode(Pki.LISTED_LEAF))); + } + + @Test + public void servicesWithAStatusAreIgnoredWithoutConfiguredStatuses() { + String alias = createProvider(pubEaaList(), Map.of( + EtsiTrustListIdentityProviderConfig.LOTE_TYPE, PUB_EAA_LOTE_TYPE, + EtsiTrustListIdentityProviderConfig.SERVICE_TYPES, PUB_EAA_ISSUANCE_SERVICE)); + + assertTrustsNothing(alias); + } + + @Test + public void onlyConfiguredServiceStatusesAreInScope() { + String alias = createProvider(validList( + serviceWithStatus(ISSUANCE_SERVICE, SCHEME_ACTIVE, Pki.SUBORDINATE_CA), + serviceWithStatus(ISSUANCE_SERVICE, NOTIFIED, Pki.ROOT)), + Map.of(EtsiTrustListIdentityProviderConfig.SERVICE_STATUSES, SCHEME_ACTIVE)); + + assertEquals(1, trustAnchorCount(alias)); + assertChainRejected(alias, List.of(encode(Pki.LISTED_LEAF))); + } + + @Test + public void listOfAnotherLoteTypeIsRejected() { + String alias = createProvider(trustList(Pki.SIGNER_KEY, "http://uri.etsi.org/19602/LoTEType/EUPIDProvidersList", + nextUpdate(), List.of(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA)))); + + assertTrustsNothing(alias); + } + + @Test + public void listWithoutTheConfiguredSignatureIsRejected() { + KeyPair attacker = ecKeyPair(); + String alias = createProvider(trustList(attacker, LOTE_TYPE, nextUpdate(), List.of(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA)))); + + assertTrustsNothing(alias); + } + + @Test + public void listWithoutNextUpdateTrustsNothing() { + String alias = createProvider(trustList(Pki.SIGNER_KEY, LOTE_TYPE, null, List.of(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA)))); + + assertTrustsNothing(alias); + } + + @Test + public void listPastNextUpdateIsRejected() { + String alias = createProvider(trustList(Pki.SIGNER_KEY, LOTE_TYPE, Instant.now().minusSeconds(60), + List.of(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA)))); + + assertTrustsNothing(alias); + } + + @Test + public void listInThePublishedJsonShapeIsParsed() { + String alias = createProvider(signTrustList(Pki.SIGNER_KEY, walletProvidersList())); + + assertEquals(1, trustAnchorCount(alias)); + assertEquals(KeyUtils.createKeyId(Pki.LEAF_KEY.getPublic()), validatedLeafKeyId(alias, List.of(encode(Pki.LEAF)))); + } + + @Test + public void refreshDropsAWithdrawnCertificate() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + assertEquals(1, trustAnchorCount(alias)); + + published.replace(validList(service(ISSUANCE_SERVICE, Pki.LISTED_LEAF))); + assertEquals(1, trustAnchorCount(alias)); + + timeOffSet.set(REFRESH_INTERVAL_SECONDS + 1); + assertEquals(0, trustAnchorCount(alias)); + } + + @Test + public void reloadKeysDropsAWithdrawnCertificateBeforeTheRefreshInterval() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + assertEquals(1, trustAnchorCount(alias)); + + published.replace(validList(service(ISSUANCE_SERVICE, Pki.LISTED_LEAF))); + // Infinispan allows a reload 10 seconds after the last download by default + timeOffSet.set(11); + assertEquals(1, trustAnchorCount(alias)); + assertTrue(realm.admin().identityProviders().get(alias).reloadKeys()); + assertEquals(0, trustAnchorCount(alias)); + } + + @Test + public void failedRefreshRejectsTheListUntilAValidListIsAvailable() { + String alias = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + assertEquals(1, trustAnchorCount(alias)); + + published.replace("not a trust list"); + timeOffSet.set(REFRESH_INTERVAL_SECONDS + 1); + assertTrustsNothing(alias); + + published.replace(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + assertEquals(1, trustAnchorCount(alias)); + } + + @Test + public void failedDownloadIsRetried() { + String alias = createProvider("not a trust list"); + assertTrustsNothing(alias); + + published.replace(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + assertEquals(1, trustAnchorCount(alias)); + } + + @Test + public void unavailableListDoesNotBlockOtherTrustProviders() { + String unavailable = createProvider("not a trust list"); + String available = createProvider(validList(service(ISSUANCE_SERVICE, Pki.SUBORDINATE_CA))); + String aliases = unavailable + "," + available; + List x5c = new ArrayList<>(List.of(encode(Pki.LEAF))); + + assertEquals(1, runOnServer.fetch(session -> (int) new TrustMaterialResolver() + .resolveX509Trust(session, aliases, request()).count(), Integer.class)); + assertEquals(KeyUtils.createKeyId(Pki.LEAF_KEY.getPublic()), runOnServer.fetchString(session -> { + try { + return new TrustMaterialResolver().validateX509Chain(session, aliases, request(), x5c, Algorithm.ES256).getKeyId(); + } catch (VerificationException e) { + return REJECTED; + } + })); + } + + @Test + public void adminApiRejectsIncompleteConfiguration() { + String signingCertificates = PemUtils.addCertificateBeginEnd(encode(Pki.SIGNER)); + Map valid = Map.of( + EtsiTrustListIdentityProviderConfig.TRUST_LIST_URL, "https://lists.example.test/wallet.jwt", + EtsiTrustListIdentityProviderConfig.SIGNING_CERTIFICATES, signingCertificates, + EtsiTrustListIdentityProviderConfig.LOTE_TYPE, LOTE_TYPE, + EtsiTrustListIdentityProviderConfig.SERVICE_TYPES, ISSUANCE_SERVICE); + + assertEquals(201, createWithConfig("etsi-valid", valid)); + for (String key : valid.keySet()) { + Map incomplete = new HashMap<>(valid); + incomplete.remove(key); + assertEquals(400, createWithConfig("etsi-without-" + key.toLowerCase(), incomplete), key); + } + + Map invalidInterval = new HashMap<>(valid); + invalidInterval.put(EtsiTrustListIdentityProviderConfig.REFRESH_INTERVAL, "0"); + assertEquals("The trust list refresh interval must be a positive number of seconds", + creationError("etsi-invalid-interval", invalidInterval)); + + Map unparseableInterval = new HashMap<>(valid); + unparseableInterval.put(EtsiTrustListIdentityProviderConfig.REFRESH_INTERVAL, "abc"); + assertEquals("The trust list refresh interval must be a number of seconds", + creationError("etsi-unparseable-interval", unparseableInterval)); + + Map invalidCertificates = new HashMap<>(valid); + invalidCertificates.put(EtsiTrustListIdentityProviderConfig.SIGNING_CERTIFICATES, "not a certificate"); + assertEquals("The trust list signing certificates must be a valid PEM bundle", + creationError("etsi-invalid-certificates", invalidCertificates)); + + Map emptyCertificates = new HashMap<>(valid); + emptyCertificates.put(EtsiTrustListIdentityProviderConfig.SIGNING_CERTIFICATES, ""); + assertEquals("At least one trust list signing certificate is required", + creationError("etsi-empty-certificates", emptyCertificates)); + } + + @SafeVarargs + private static String validList(Map... services) { + return trustList(Pki.SIGNER_KEY, LOTE_TYPE, nextUpdate(), List.of(services)); + } + + private static String pubEaaList() { + return trustList(Pki.SIGNER_KEY, PUB_EAA_LOTE_TYPE, nextUpdate(), List.of( + serviceWithStatus(PUB_EAA_ISSUANCE_SERVICE, NOTIFIED, Pki.SUBORDINATE_CA), + serviceWithStatus(PUB_EAA_ISSUANCE_SERVICE, WITHDRAWN, Pki.ROOT))); + } + + // Shaped like a published Wallet Providers list, with the certificates and dates of this test + private static String walletProvidersList() { + try (InputStream list = EtsiTrustListIdentityProviderTest.class.getResourceAsStream("wallet-providers-list.json")) { + String filled = new String(list.readAllBytes(), StandardCharsets.UTF_8) + .replace("${SIGNER}", encode(Pki.SIGNER)) + .replace("${ISSUANCE_CA}", encode(Pki.SUBORDINATE_CA)) + .replace("${REVOCATION_CA}", encode(Pki.ROOT)) + .replace("${LIST_ISSUE_DATE_TIME}", Instant.now().toString()) + .replace("${NEXT_UPDATE}", nextUpdate().toString()); + assertFalse(filled.contains("${"), "Unknown placeholder in the list fixture"); + return filled; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static Instant nextUpdate() { + return Instant.now().plus(Duration.ofHours(2)); + } + + private int createWithConfig(String alias, Map config) { + try (Response response = realm.admin().identityProviders().create(representation(alias, config))) { + if (response.getStatus() == 201) { + realm.cleanup().add(r -> r.identityProviders().get(alias).remove()); + } + return response.getStatus(); + } + } + + private String creationError(String alias, Map config) { + try (Response response = realm.admin().identityProviders().create(representation(alias, config))) { + if (response.getStatus() == 201) { + realm.cleanup().add(r -> r.identityProviders().get(alias).remove()); + } + assertEquals(400, response.getStatus()); + return response.readEntity(ErrorRepresentation.class).getErrorMessage(); + } + } + + private static IdentityProviderRepresentation representation(String alias, Map config) { + IdentityProviderRepresentation representation = new IdentityProviderRepresentation(); + representation.setAlias(alias); + representation.setProviderId(EtsiTrustListIdentityProviderFactory.PROVIDER_ID); + representation.setEnabled(true); + representation.setConfig(config); + return representation; + } + + private String createProvider(String initialList) { + return createProvider(initialList, Map.of()); + } + + private String createProvider(String initialList, Map configOverrides) { + String alias = "etsi-trust-list-" + IDS.incrementAndGet(); + published = publish(httpServer, "/" + alias, initialList); + Map config = new HashMap<>(Map.of( + EtsiTrustListIdentityProviderConfig.TRUST_LIST_URL, published.url(), + EtsiTrustListIdentityProviderConfig.SIGNING_CERTIFICATES, PemUtils.addCertificateBeginEnd(encode(Pki.SIGNER)), + EtsiTrustListIdentityProviderConfig.LOTE_TYPE, LOTE_TYPE, + EtsiTrustListIdentityProviderConfig.SERVICE_TYPES, ISSUANCE_SERVICE, + EtsiTrustListIdentityProviderConfig.REFRESH_INTERVAL, String.valueOf(REFRESH_INTERVAL_SECONDS))); + config.putAll(configOverrides); + assertEquals(201, createWithConfig(alias, config)); + return alias; + } + + private void assertTrustsNothing(String alias) { + assertEquals(0, trustAnchorCount(alias)); + assertEquals(0, keyCount(alias)); + } + + private int trustAnchorCount(String alias) { + return runOnServer.fetch(session -> provider(session, alias).resolveX509Trust(request()) + .map(X509TrustMaterial::trustAnchors) + .mapToInt(Set::size) + .sum(), Integer.class); + } + + private int keyCount(String alias) { + return runOnServer.fetch(session -> (int) provider(session, alias).resolveKeys(request()).count(), Integer.class); + } + + private String validatedLeafKeyId(String alias, List x5c) { + List chain = x5c == null ? null : new ArrayList<>(x5c); + return runOnServer.fetchString(session -> { + try { + JWK key = provider(session, alias).validateX509Chain(request(), chain, Algorithm.ES256); + return key == null ? null : key.getKeyId(); + } catch (VerificationException e) { + return REJECTED; + } + }); + } + + private void assertChainRejected(String alias, List x5c) { + assertEquals(REJECTED, validatedLeafKeyId(alias, x5c)); + } + + private static TrustMaterialRequest request() { + return TrustMaterialRequest.builder().kid("wallet-chosen-kid").algorithm(Algorithm.ES256).build(); + } + + private static TrustMaterialIdentityProvider provider(KeycloakSession session, String alias) { + RealmModel realm = session.getContext().getRealm(); + return IdentityBrokerService.getIdentityProvider(session, realm.getIdentityProviderByAlias(alias), TrustMaterialIdentityProvider.class); + } + + // Kept apart from the test class, because code run on the server initializes the test class. + private static final class Pki { + + private static final KeyPair SIGNER_KEY = ecKeyPair(); + private static final X509Certificate SIGNER = caCertificate(SIGNER_KEY, "LoTE Signer"); + private static final KeyPair ROOT_KEY = ecKeyPair(); + private static final X509Certificate ROOT = caCertificate(ROOT_KEY, "Wallet Provider Root"); + private static final KeyPair CA_KEY = ecKeyPair(); + private static final X509Certificate SUBORDINATE_CA = subordinateCaCertificate(CA_KEY.getPublic(), "Wallet Provider CA", ROOT, ROOT_KEY); + private static final KeyPair LEAF_KEY = ecKeyPair(); + private static final X509Certificate LEAF = endEntityCertificate(LEAF_KEY.getPublic(), "Wallet Provider Leaf", SUBORDINATE_CA, CA_KEY); + private static final KeyPair LISTED_KEY = ecKeyPair(); + private static final X509Certificate LISTED_LEAF = endEntityCertificate(LISTED_KEY.getPublic(), "Listed Leaf", ROOT, ROOT_KEY); + } + + public static class TrustListServerConfig implements KeycloakServerConfig { + + @Override + public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) { + return config.features(Profile.Feature.CLIENT_AUTH_ABCA); + } + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/broker/trust/TrustListTestSupport.java b/tests/base/src/test/java/org/keycloak/tests/broker/trust/TrustListTestSupport.java new file mode 100644 index 000000000000..f3c220cbea46 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/broker/trust/TrustListTestSupport.java @@ -0,0 +1,192 @@ +package org.keycloak.tests.broker.trust; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.keycloak.common.crypto.CryptoIntegration; +import org.keycloak.common.util.KeyUtils; +import org.keycloak.crypto.Algorithm; +import org.keycloak.crypto.ECDSASignatureSignerContext; +import org.keycloak.crypto.KeyWrapper; +import org.keycloak.crypto.def.DefaultCryptoProvider; +import org.keycloak.jose.jws.JWSBuilder; +import org.keycloak.testframework.util.HttpServerUtil; + +import com.sun.net.httpserver.HttpServer; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; + +/** + * Creates test certificates and signed ETSI TS 119 602 trust lists, and publishes those lists on + * the HTTP server of the test, so tests depend on no external trust list provider. + */ +public final class TrustListTestSupport { + + public static final String LOTE_TYPE = "http://uri.etsi.org/19602/LoTEType/EUWalletProvidersList"; + public static final String ISSUANCE_SERVICE = "http://uri.etsi.org/19602/SvcType/WalletSolution/Issuance"; + public static final String REVOCATION_SERVICE = "http://uri.etsi.org/19602/SvcType/WalletSolution/Revocation"; + + private static final String TRUST_LIST_TYPE = "trustlist+jwt"; + + private TrustListTestSupport() { + } + + public static KeyPair ecKeyPair() { + if (!CryptoIntegration.isInitialised()) { + CryptoIntegration.setProvider(new DefaultCryptoProvider()); + } + return KeyUtils.generateEcKeyPair("secp256r1"); + } + + public static X509Certificate caCertificate(KeyPair key, String name) { + return certificate(key.getPublic(), name, name, key, true, KeyUsage.keyCertSign | KeyUsage.cRLSign); + } + + public static X509Certificate expiredCaCertificate(KeyPair key, String name) { + return certificate(key.getPublic(), name, name, key, true, KeyUsage.keyCertSign | KeyUsage.cRLSign, Instant.now().minus(1, ChronoUnit.HOURS)); + } + + public static X509Certificate caCertificateWithoutCertificateSigning(KeyPair key, String name) { + return certificate(key.getPublic(), name, name, key, true, KeyUsage.cRLSign); + } + + public static X509Certificate subordinateCaCertificate(PublicKey key, String name, X509Certificate issuer, KeyPair issuerKey) { + return certificate(key, name, commonName(issuer), issuerKey, true, KeyUsage.keyCertSign | KeyUsage.cRLSign); + } + + public static X509Certificate endEntityCertificate(PublicKey key, String name, X509Certificate issuer, KeyPair issuerKey) { + return certificate(key, name, commonName(issuer), issuerKey, false, KeyUsage.digitalSignature); + } + + public static String encode(X509Certificate certificate) { + try { + return Base64.getEncoder().encodeToString(certificate.getEncoded()); + } catch (CertificateEncodingException e) { + throw new IllegalStateException(e); + } + } + + public static Map service(String serviceType, X509Certificate... certificates) { + return Map.of("ServiceInformation", Map.of( + "ServiceTypeIdentifier", serviceType, + "ServiceDigitalIdentity", digitalIdentity(certificates))); + } + + public static Map serviceWithStatus(String serviceType, String status, X509Certificate... certificates) { + return Map.of("ServiceInformation", Map.of( + "ServiceTypeIdentifier", serviceType, + "ServiceStatus", status, + "ServiceDigitalIdentity", digitalIdentity(certificates))); + } + + private static Map digitalIdentity(X509Certificate... certificates) { + return Map.of("X509Certificates", List.of(certificates).stream() + .map(certificate -> Map.of("val", encode(certificate))) + .toList()); + } + + /** + * Publishes the list at the path and returns its URL. The list can be replaced by publishing + * to the same path again through the returned holder. + */ + public static PublishedTrustList publish(HttpServer httpServer, String path, String trustList) { + PublishedTrustList published = new PublishedTrustList( + "http://" + httpServer.getAddress().getHostString() + ":" + httpServer.getAddress().getPort() + path, trustList); + httpServer.createContext(path, exchange -> HttpServerUtil.sendResponse(exchange, 200, + Map.of("Content-Type", List.of("application/jwt")), published.content)); + return published; + } + + public static final class PublishedTrustList { + + private final String url; + private volatile String content; + + private PublishedTrustList(String url, String content) { + this.url = url; + this.content = content; + } + + public String url() { + return url; + } + + public void replace(String content) { + this.content = content; + } + } + + public static String trustList(KeyPair signer, String loteType, Instant nextUpdate, List> services) { + Map scheme = new HashMap<>(); + scheme.put("LoTEType", loteType); + if (nextUpdate != null) { + scheme.put("NextUpdate", nextUpdate.toString()); + } + + return new JWSBuilder() + .type(TRUST_LIST_TYPE) + .jsonContent(Map.of("LoTE", Map.of( + "ListAndSchemeInformation", scheme, + "TrustedEntitiesList", List.of(Map.of("TrustedEntityServices", services))))) + .sign(signerContext(signer)); + } + + public static String signTrustList(KeyPair signer, String list) { + return new JWSBuilder() + .type(TRUST_LIST_TYPE) + .content(list.getBytes(StandardCharsets.UTF_8)) + .sign(signerContext(signer)); + } + + private static ECDSASignatureSignerContext signerContext(KeyPair signer) { + KeyWrapper signingKey = new KeyWrapper(); + signingKey.setAlgorithm(Algorithm.ES256); + signingKey.setPrivateKey(signer.getPrivate()); + return new ECDSASignatureSignerContext(signingKey); + } + + private static String commonName(X509Certificate certificate) { + return certificate.getSubjectX500Principal().getName().substring("CN=".length()); + } + + private static X509Certificate certificate(PublicKey key, String subject, String issuer, KeyPair issuerKey, boolean ca, int keyUsage) { + return certificate(key, subject, issuer, issuerKey, ca, keyUsage, Instant.now().plus(1, ChronoUnit.DAYS)); + } + + private static X509Certificate certificate(PublicKey key, String subject, String issuer, KeyPair issuerKey, boolean ca, int keyUsage, Instant notAfter) { + try { + Instant now = Instant.now(); + X509v3CertificateBuilder builder = new X509v3CertificateBuilder( + new X500Name("CN=" + issuer), + new BigInteger(64, new SecureRandom()), + Date.from(now.minus(1, ChronoUnit.DAYS)), + Date.from(notAfter), + new X500Name("CN=" + subject), + SubjectPublicKeyInfo.getInstance(key.getEncoded())); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage)); + return new JcaX509CertificateConverter().getCertificate(builder.build( + new JcaContentSignerBuilder("SHA256withECDSA").build(issuerKey.getPrivate()))); + } catch (Exception e) { + throw new IllegalStateException("Failed to create the test certificate", e); + } + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCKeyAttestationTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCKeyAttestationTest.java index 4f9673b70496..c23afa788beb 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCKeyAttestationTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCKeyAttestationTest.java @@ -523,15 +523,15 @@ public void testAttestationWithCaCertificateAsLeafIsRejected() { } @Test - public void testX509TrustMaterialRejectsNonRootAnchors() { + public void testX509TrustMaterialRequiresCaAnchors() { X509Certificate leafCertificate = PemUtils.decodeCertificate(X5C_TEST_CERTIFICATE_CHAIN.leafCertificatePem()); X509Certificate intermediateCertificate = PemUtils.decodeCertificate( X5C_TEST_CERTIFICATE_CHAIN.caSignerCertificatePem()); assertThrows(IllegalArgumentException.class, () -> new X509TrustMaterial(Set.of(leafCertificate), List.of(TEST_ATTESTATION_EKU))); - assertThrows(IllegalArgumentException.class, - () -> new X509TrustMaterial(Set.of(intermediateCertificate), List.of(TEST_ATTESTATION_EKU))); + assertEquals(Set.of(intermediateCertificate), + new X509TrustMaterial(Set.of(intermediateCertificate), List.of(TEST_ATTESTATION_EKU)).trustAnchors()); } @Test diff --git a/tests/base/src/test/resources/org/keycloak/tests/broker/trust/wallet-providers-list.json b/tests/base/src/test/resources/org/keycloak/tests/broker/trust/wallet-providers-list.json new file mode 100644 index 000000000000..2360f4523a8d --- /dev/null +++ b/tests/base/src/test/resources/org/keycloak/tests/broker/trust/wallet-providers-list.json @@ -0,0 +1,186 @@ +{ + "LoTE": { + "ListAndSchemeInformation": { + "LoTEVersionIdentifier": 1, + "LoTESequenceNumber": 5, + "LoTEType": "http://uri.etsi.org/19602/LoTEType/EUWalletProvidersList", + "SchemeInformationURI": [ + { + "lang": "en", + "uriValue": "https://lists.example.test/" + }, + { + "lang": "en", + "uriValue": "https://lists.example.test/wallet-provider/" + } + ], + "StatusDeterminationApproach": "http://uri.etsi.org/19602/WalletProvidersList/StatusDetn/EU", + "SchemeTypeCommunityRules": [ + { + "lang": "en", + "uriValue": "http://uri.etsi.org/19602/WalletProvidersList/schemerules/EU" + } + ], + "SchemeTerritory": "BE", + "SchemeOperatorName": [ + { + "lang": "en", + "value": "Example Scheme Operator" + } + ], + "SchemeOperatorAddress": { + "SchemeOperatorPostalAddress": [ + { + "lang": "en", + "StreetAddress": "Example Street 1", + "Locality": "Example City", + "PostalCode": "12345", + "Country": "BE" + } + ], + "SchemeOperatorElectronicAddress": [ + { + "lang": "en", + "uriValue": "mailto:operator@example.test" + } + ] + }, + "SchemeName": [ + { + "lang": "en", + "value": "BE:Example Wallet Providers list" + } + ], + "PolicyOrLegalNotice": [ + { + "LoTEPolicy": { + "lang": "en", + "uriValue": "https://lists.example.test/policy" + } + } + ], + "PointersToOtherLoTE": [ + { + "LoTELocation": "https://lists.example.test/wallet-provider.jwt", + "ServiceDigitalIdentities": [ + { + "X509Certificates": [ + { + "val": "${SIGNER}" + } + ] + } + ], + "LoTEQualifiers": [ + { + "LoTEType": "http://uri.etsi.org/19602/LoTEType/EUWalletProvidersList", + "SchemeOperatorName": [ + { + "lang": "en", + "value": "Example Scheme Operator" + } + ], + "SchemeTypeCommunityRules": [ + { + "lang": "en", + "uriValue": "http://uri.etsi.org/19602/WalletProvidersList/schemerules/EU" + } + ], + "SchemeTerritory": "BE", + "MimeType": "application/jwt" + } + ] + } + ], + "ListIssueDateTime": "${LIST_ISSUE_DATE_TIME}", + "NextUpdate": "${NEXT_UPDATE}" + }, + "TrustedEntitiesList": [ + { + "TrustedEntityInformation": { + "TEInformationURI": [ + { + "lang": "en", + "uriValue": "http://uri.etsi.org/19602/ListOfTrustedEntities/WalletProvider/BE" + }, + { + "lang": "en", + "uriValue": "https://wallet.example.test/about" + } + ], + "TEName": [ + { + "lang": "en", + "value": "Example Wallet Provider" + } + ], + "TETradeName": [ + { + "lang": "en", + "value": "VATBE-0000000000" + } + ], + "TEAddress": { + "TEPostalAddress": [ + { + "lang": "en", + "StreetAddress": "Example Street 2", + "Locality": "Example City", + "PostalCode": "12345", + "Country": "BE" + } + ], + "TEElectronicAddress": [ + { + "lang": "en", + "uriValue": "mailto:wallet@example.test" + }, + { + "lang": "en", + "uriValue": "tel:+3200000000" + } + ] + } + }, + "TrustedEntityServices": [ + { + "ServiceInformation": { + "ServiceTypeIdentifier": "http://uri.etsi.org/19602/SvcType/WalletSolution/Issuance", + "ServiceName": [ + { + "lang": "en", + "value": "Example Wallet" + } + ], + "ServiceDigitalIdentity": { + "X509Certificates": [ + { + "val": "${ISSUANCE_CA}" + } + ] + } + } + }, + { + "ServiceInformation": { + "ServiceTypeIdentifier": "http://uri.etsi.org/19602/SvcType/WalletSolution/Revocation", + "ServiceName": [ + { + "lang": "en", + "value": "Example Wallet" + } + ], + "ServiceDigitalIdentity": { + "X509Certificates": [ + { + "val": "${REVOCATION_CA}" + } + ] + } + } + } + ] + } + ] + } +}