/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { asError, AsyncCache, Bytes, ClosedError, Construction, Crypto, Days, DerCodec, DerNode, DerTag, DerType, Diagnostic, Duration, Environment, Github, hashAlgorithmForId, Hours, ImplementationError, isObject, Logger, LogLevel, Pem, Seconds, StorageContext, StorageManager, StorageService, Time, Timer, } from "@matter/general"; import { DeviceAttestationPkiRevocationDclSchema, RevocationTypeEnum } from "@matter/types"; import { MlDsaAttestationDisabledError, Paa, Pai } from "../certificate/kinds/AttestationCertificates.js"; import { Certificate } from "../certificate/kinds/Certificate.js"; import { certificateSignatureOf, verifyCertificateSignature } from "../certificate/kinds/CertificateSignature.js"; import { DclClient, MatterDclError, MatterDclResponseError } from "./DclClient.js"; import { DclConfig, DclGithubConfig } from "./DclConfig.js"; import { DclPkiRootCertificateSubjectReference } from "./DclRestApiTypes.js"; import type { CertSeedEntry, SeedSource } from "./SeedTypes.js"; const logger = Logger.get("DclCertificateService"); /** Parse a trust store certificate with the extensions and algorithms its kind admits. */ function parseTrustStoreCertificate(der: Bytes, kind: DclCertificateService.CertificateKind) { return kind === "PAA" ? Paa.fromAsn1(der).cert : Certificate.parseAsn1Certificate(der, Certificate.REQUIRED_EXTENSIONS); } /** A certificate that needs a disabled forward feature is expected configuration, not a fault worth reporting. */ function skippedCertificateLogLevel(error: unknown) { return error instanceof MlDsaAttestationDisabledError ? LogLevel.DEBUG : LogLevel.INFO; } function statedString(value: unknown, field: string, index: number) { if (typeof value !== "string") { throw new ImplementationError(`Revocation set entry ${index} states ${field} as something other than a string`); } return value; } /** * A hex field, as the entry states it. * * An identifier or serial that is not hex matches no certificate, so a set that states one would be * installed, reported as installed, and then answer "not revoked" for everything it names. It is * refused instead. */ function statedHex(value: unknown, field: string, index: number) { const stated = statedString(value, field, index).replace(/:/g, ""); if (stated === "" || stated.length % 2 !== 0 || !/^[0-9A-Fa-f]+$/.test(stated)) { throw new ImplementationError( `Revocation set entry ${index} states ${field} as "${stated}", which is not an even number of hex digits`, ); } return stated; } function statedSerials(value: unknown, index: number) { if (!Array.isArray(value)) { throw new ImplementationError( `Revocation set entry ${index} states revoked_serial_numbers as something other than a list`, ); } return value.map((serial, position) => statedHex(serial, `revoked_serial_numbers[${position}]`, index)); } /** * The issuer name an entry states, as base64 of the DER it encodes. An entry that states none, or * states an empty one, is matched on its key identifier alone. */ function statedIssuerName(value: unknown, index: number) { if (value === undefined || value === "") { return undefined; } const stated = statedString(value, "issuer_name", index); try { Bytes.fromBase64(stated); } catch (error) { throw new ImplementationError( `Revocation set entry ${index} states an issuer_name that is not base64: ${asError(error).message}`, ); } return stated; } /** What the DCL's revocation sets state as their type, and the only kind of entry this reads. */ const REVOCATION_SET_TYPE = "revocation_set"; function statedType(value: unknown, index: number) { if (value !== undefined && value !== REVOCATION_SET_TYPE) { throw new ImplementationError( `Revocation set entry ${index} states type "${String(value)}" rather than "${REVOCATION_SET_TYPE}"`, ); } } /** The issuer name an entry states, as hex of the DER it encodes. */ function issuerDnOf(issuerName: string | undefined) { return issuerName === undefined ? undefined : Bytes.toHex(Bytes.fromBase64(issuerName)).toUpperCase(); } /** * The URI of a CRL's Issuing Distribution Point extension (RFC 5280 §5.2.5) when the extension is critical and its * distributionPoint is a fullName of exactly one uniformResourceIdentifier, as Matter Core §6.2.6.1 step 7.2 requires. */ function issuingDistributionPointUriOf(extension: DerNode): string | undefined { const [, critical, value] = extension._elements ?? []; if ( critical?._tag !== DerType.Boolean || Bytes.of(critical._bytes)[0] === 0 || value?._tag !== DerType.OctetString ) { return; } const distributionPoint = DerCodec.decode(value._bytes)._elements?.[0]; if (distributionPoint?._tag !== CONTEXT_CONSTRUCTED_0) { return; } const name = DerCodec.decode(distributionPoint._bytes); if (name._tag !== CONTEXT_CONSTRUCTED_0) { return; } const uri = DerCodec.decode(name._bytes); if (uri._tag !== URI_GENERAL_NAME || DerCodec.encode(uri).byteLength !== name._bytes.byteLength) { return; } return Bytes.toString(uri._bytes); } /** The DCL revocations of one issuer; incomplete when a distribution point failed transiently. */ interface RevocationLookup { entries: DclCertificateService.RevocationEntry[]; complete: boolean; } /** A distribution point's validated CRL signer and the authority (§6.2.6.1 step 9) its CRL speaks for. */ interface CrlAuthority { signer: Paa | Pai; /** DER of the authority's subject Name, the CertificateAuthorityName of §6.2.6.1. */ name: Bytes; } /** A distribution point Matter Core §6.2.6.1 tells to skip; unlike a download failure, retrying cannot change it. */ class CrlRejectedError extends MatterDclError {} function nameOf(certificate: Paa | Pai, field: "subject" | "issuer") { const der = field === "subject" ? certificate.cert.subjectDer : certificate.cert.issuerDer; if (der === undefined) { throw new CrlRejectedError(`CRL signer chain certificate has no parsed ${field} name`); } return der; } /** DER string types whose values RFC 5280 §7.1 compares as characters rather than as encodings. */ const DIRECTORY_STRING_TAGS = new Set([ DerType.UTF8String, DerType.PrintableString, DerType.T16String, DerType.IA5String, ]); /** * Whether two DER Names are the same name under RFC 5280 §7.1: string attributes compare ignoring case, surrounding and * repeated whitespace, and whether they are encoded as PrintableString or UTF8String, as CAs mix those. */ function sameName(a: Bytes, b: Bytes) { if (Bytes.areEqual(a, b)) { return true; } const canonical = (der: Bytes) => (DerCodec.decode(der)._elements ?? []).map(rdn => (rdn._elements ?? []) .map(attribute => { const [type, value] = attribute._elements ?? []; const text = value !== undefined && DIRECTORY_STRING_TAGS.has(value._tag) ? Bytes.toString(value._bytes).trim().replace(/\s+/g, " ").toLowerCase() : `${value?._tag}:${Bytes.toHex(value?._bytes ?? new Uint8Array())}`; return `${Bytes.toHex(type?._bytes ?? new Uint8Array())}=${text}`; }) .sort() .join("+"), ); try { const [left, right] = [canonical(a), canonical(b)]; return left.length === right.length && left.every((rdn, index) => rdn === right[index]); } catch { return false; } } /** {@link sameName} for Names as hex of their DER; a value that is not hex names nothing. */ function sameNameHex(a: string, b: string) { const isHex = (value: string) => /^(?:[0-9a-f]{2})*$/i.test(value); return isHex(a) && isHex(b) && sameName(Bytes.fromHex(a), Bytes.fromHex(b)); } /** Whether an entry for the issuer names the serial; an entry or query without an issuer name matches any issuer. */ function matchRevocation( entries: readonly DclCertificateService.RevocationEntry[] | undefined, serial: string, issuerDnDerHex: string | undefined, ) { return (entries ?? []).some( entry => (issuerDnDerHex === undefined || entry.issuerDnDerHex === undefined || sameNameHex(entry.issuerDnDerHex, issuerDnDerHex)) && entry.serials.has(serial), ); } /** Authority Key Identifier, Issuing Distribution Point and CRL Number, the CRL extensions this service reads. */ const KNOWN_CRL_EXTENSIONS = new Set(["551d23", "551d1c", "551d14"]); /** Reason code, invalidity date and certificate issuer (RFC 5280 §5.3). */ const KNOWN_CRL_ENTRY_EXTENSIONS = new Set(["551d15", "551d18", "551d1d"]); const CERTIFICATE_ISSUER_EXTENSION = "551d1d"; function isCritical(extension: DerNode) { const critical = extension._elements?.[1]; return critical?._tag === DerType.Boolean && Bytes.of(critical._bytes)[0] !== 0; } /** The single directoryName of a certificateIssuer CRL entry extension as Name DER, if it names exactly one. */ function certificateIssuerOf(extension: DerNode) { const value = extension._elements?.[extension._elements.length - 1]; if (value?._tag !== DerType.OctetString) { return; } const names = DerCodec.decode(value._bytes)._elements; if (names?.length !== 1 || names[0]._tag !== DIRECTORY_NAME) { return; } return Bytes.of(names[0]._bytes); } /** [4] EXPLICIT Name: the directoryName choice of GeneralName. */ const DIRECTORY_NAME = 0xa4; /** [0] IMPLICIT, constructed: distributionPoint and its fullName in an Issuing Distribution Point. */ const CONTEXT_CONSTRUCTED_0 = 0xa0; /** [6] IMPLICIT IA5String: the uniformResourceIdentifier choice of GeneralName. */ const URI_GENERAL_NAME = 0x86; /** * A serial number as both sides of a revocation lookup can agree on it. * * A certificate states its serial as the content octets of a DER INTEGER, which carry a leading zero * whenever the number's top bit is set, so the same serial reads as `00E1…` from a certificate and * `E1…` in a revocation set, which states the number itself. Dropping leading zero bytes leaves one * form both arrive at. */ function canonicalSerial(serial: Bytes | string) { const hex = (typeof serial === "string" ? serial.replace(/:/g, "") : Bytes.toHex(serial)).toUpperCase(); const significant = hex.replace(/^(?:00)+/, ""); return significant === "" ? "00" : significant; } /** * Implements a service to manage DCL root certificates as a singleton in the environment and so will be shared by * multiple nodes of relevant. It is mainly relevant for controller use cases. * The service supports fetching certificates from teh CSA production and test DCL instances, as well * as from a GitHub repository for development certificates. */ export class DclCertificateService { readonly #construction: Construction; readonly #crypto: Crypto; #storageManager?: StorageManager; #storage?: StorageContext; #certificateIndex = new Map(); #updateTimer?: Timer; #githubRateLimited = false; #closed = false; #options: DclCertificateService.Options; #fetchPromise?: Promise; /** Lazy CRL revocation cache: keyed by normalized AKID, fetches on-demand from DCL */ #revocationCache: AsyncCache; /** Revocation information supplied out of band rather than fetched, keyed by normalized AKID */ #installedRevocations = new Map(); constructor(environment: Environment, options: DclCertificateService.Options = {}) { environment.root.set(DclCertificateService, this); this.#crypto = environment.get(Crypto); this.#options = options; logger.info( "Initialize CertificateService", Diagnostic.dict({ prod: options.dclConfig?.url ?? DclConfig.production.url, test: options.fetchTestCertificates ? (options.testDclConfig?.url ?? DclConfig.test.url) : undefined, github: options.fetchTestCertificates && options.fetchGithubCertificates ? "yes" : undefined, flags: Diagnostic.asFlags({ acceptTest: this.acceptsTestCertificates, offline: options.offline }), }), ); if (options.revocations !== undefined) { this.installRevocations(options.revocations); } this.#construction = Construction(this, async () => { this.#storageManager = await environment.get(StorageService).open("certificates"); this.#storage = this.#storageManager.createContext("root"); await this.#loadIndex(this.#storage); if (options.seed?.paaRoots) { await this.#consumeCertSeed(options.seed.paaRoots, "PAA"); } if (options.seed?.cdSigners) { await this.#consumeCertSeed(options.seed.cdSigners, "CDSigner"); } // `update()` answers an offline service by doing nothing, so this needs no condition await this.update(); if (!options.offline && options.updateInterval !== null) { // Start periodic update timer const updateInterval = options.updateInterval ?? Days.one; this.#updateTimer = Time.getPeriodicTimer("DCL Certificate Update", updateInterval, () => this.update(), ).start(); } }); this.#revocationCache = new AsyncCache( "CRL revocation", this.#construction, (akid: string) => this.#fetchAndValidateRevocation(akid), Hours(1), ); } get construction() { return this.#construction; } /** Whether the service runs {@link DclCertificateService.Options.offline}. */ get offline() { return this.#options.offline ?? false; } /** * Normalize the subject key identifier to a consistent string format. * Accepts either Bytes or string (with or without colons). */ #normalizeSubjectKeyId(subjectKeyId: Bytes | string) { if (typeof subjectKeyId === "string") { return subjectKeyId.replace(/:/g, "").toUpperCase(); } return Bytes.toHex(subjectKeyId).toUpperCase(); } /** * Whether a stored entry is relevant under the current trust policy. Production certificates * are always relevant. Test PAAs are only relevant when the test-certificate policy allows * them. CD signer certificates are managed separately and are always relevant. */ #isRelevant( metadata: DclCertificateService.CertificateMetadata, options?: DclCertificateService.GetCertificateOptions, ) { const kind = metadata.kind ?? "PAA"; const considerTestCertificates = options?.considerTestCertificates ?? this.acceptsTestCertificates; return kind !== "PAA" || metadata.isProduction || considerTestCertificates; } /** * Get certificate metadata by subject key identifier. Returns undefined if not found or if the * entry is filtered by the effective trust policy. */ getCertificate(subjectKeyId: Bytes | string, options?: DclCertificateService.GetCertificateOptions) { this.construction.assert(); const metadata = this.#certificateIndex.get(this.#normalizeSubjectKeyId(subjectKeyId)); if (metadata === undefined || !this.#isRelevant(metadata, options)) { return undefined; } return metadata; } /** * Get all certificate metadata entries (raw enumeration, unaffected by the * `fetchTestCertificates` filter so management commands can still inspect cached test certs). */ get certificates() { this.construction.assert(); return Array.from(this.#certificateIndex.values()); } /** * Whether the service trusts test (non-production) certificates as valid trust anchors. * * Independent of {@link Options.fetchTestCertificates} (which only governs whether test certs are * downloaded). Defaults to {@link Options.acceptTestCertificates}, falling back to * `fetchTestCertificates` when the trust policy is not set explicitly. */ get acceptsTestCertificates(): boolean { return this.#options.acceptTestCertificates ?? this.#options.fetchTestCertificates ?? false; } /** * Get certificate as PEM string. * @throws {MatterDclError} if certificate not found or filtered by trust policy */ async getCertificateAsPem(subjectKeyId: Bytes | string, options?: DclCertificateService.GetCertificateOptions) { this.construction.assert(); return Pem.encode(await this.#getCertificateDer(subjectKeyId, options)); } /** * Get certificate as DER bytes. * * Self-heals a corrupted local cache: if the stored certificate no longer parses (e.g. a * truncated or mangled storage entry), make one best-effort re-fetch from DCL so a broken cache * entry cannot permanently break attestation for an otherwise-valid trust anchor. If recovery * fails the original bytes are returned unchanged, leaving the caller's normal validation to * surface the parse failure rather than masking it with a different error here. * * @throws {MatterDclError} if certificate not found or filtered by trust policy */ async getCertificateAsDer(subjectKeyId: Bytes | string, options?: DclCertificateService.GetCertificateOptions) { this.construction.assert(); const der = await this.#getCertificateDer(subjectKeyId, options); const normalizedId = this.#normalizeSubjectKeyId(subjectKeyId); const metadata = this.#certificateIndex.get(normalizedId); const parseError = this.#certificateParseError(der, metadata?.kind); if (parseError === undefined || parseError instanceof MlDsaAttestationDisabledError) { return der; } logger.notice( `Cached certificate failed to parse; attempting one re-fetch from DCL to recover`, Diagnostic.dict({ skid: normalizedId }), Diagnostic.errorMessage(parseError), ); const refetched = await this.#tryRefetchRootCertificate(normalizedId, metadata?.isProduction ?? true, options); if (refetched !== undefined) { const refetchParseError = this.#certificateParseError(refetched, metadata?.kind); if (refetchParseError === undefined) { return refetched; } logger.warn( `Re-fetched certificate also failed to parse`, Diagnostic.dict({ skid: normalizedId }), Diagnostic.errorMessage(refetchParseError), ); } return der; } /** Parse error of a DER certificate, or undefined if it parses, using the extension set for its kind. */ #certificateParseError(der: Bytes, kind?: DclCertificateService.CertificateKind): Error | undefined { try { parseTrustStoreCertificate(der, kind ?? "PAA"); return undefined; } catch (error) { return asError(error); } } /** * Parse a DER certificate and confirm its own SKID matches the id a source claims for it. * Every trust-store entry is keyed by a certificate's own SKID, so a claimed id that disagrees * with the certificate is refused rather than filed under the wrong lookup key. Returns the * parsed certificate, or undefined if it does not parse as `kind` or its SKID does not match * `statedSkid`; both cases are logged and left for the caller to skip. */ #parseAndCheckSkid(der: Bytes, kind: DclCertificateService.CertificateKind, statedSkid: string, source: string) { let parsed: ReturnType; try { parsed = parseTrustStoreCertificate(der, kind); } catch (error) { logger.log( skippedCertificateLogLevel(error), `${source}: certificate cannot be used as a ${kind}, skipped`, Diagnostic.dict({ skid: statedSkid }), Diagnostic.errorMessage(asError(error)), ); return undefined; } const skidFromDer = this.#normalizeSubjectKeyId(parsed.extensions.subjectKeyIdentifier); if (skidFromDer !== statedSkid) { logger.warn( `${source}: SKID mismatch entry=${statedSkid} der-derived=${skidFromDer}, skipped`, Diagnostic.dict({ kind }), ); return undefined; } return parsed; } /** * Best-effort force re-fetch of a single root certificate from DCL, overwriting the cached copy * to recover from a corrupted local storage entry. Never throws: returns the freshly stored DER, * or undefined if the certificate could not be re-fetched (not a root cert, absent from DCL, or * any fetch error). */ async #tryRefetchRootCertificate( normalizedId: string, isProduction: boolean, options?: DclCertificateService.GetCertificateOptions, ): Promise { if (this.#options.offline) { return undefined; } if (this.#fetchPromise !== undefined) { await this.#fetchPromise; } try { if (!(await this.#fetchAndStoreRootCertificateBySkid(normalizedId, isProduction, true, this.#options))) { return undefined; } } catch (error) { logger.warn( `Re-fetch of certificate ${normalizedId} from DCL failed`, Diagnostic.errorMessage(asError(error)), ); return undefined; } const metadata = this.#certificateIndex.get(normalizedId); if (metadata === undefined || !this.#isRelevant(metadata, options)) { return undefined; } const der = await this.#storage!.get(normalizedId); return der && der.byteLength > 0 ? Bytes.of(der) : undefined; } /** * Fetch a single root certificate from DCL by SubjectKeyIdentifier and store it. Returns true if * a matching root certificate was found and stored, false if DCL has no such root certificate or it * could not be fetched or used. Throws if the root certificate list cannot be fetched. */ async #fetchAndStoreRootCertificateBySkid( normalizedId: string, isProduction: boolean, force: boolean, options?: DclClient.Options, ): Promise { const config = isProduction ? (this.#options.dclConfig ?? DclConfig.production) : (this.#options.testDclConfig ?? DclConfig.test); const dclClient = new DclClient(config); const certRefs = await dclClient.fetchRootCertificateList(options); const skidWithColons = normalizedId .match(/.{1,2}/g) ?.join(":") .toUpperCase(); const certRef = certRefs.find(ref => ref.subjectKeyId === skidWithColons); if (!certRef) { return false; } const stored = await this.#fetchAndStoreCertificate( this.#storage!, dclClient, certRef, isProduction, force, options ?? this.#options, ); await this.#saveIndex(); return stored; } /** Internal DER retrieval without construction assert (safe during init). */ async #getCertificateDer(subjectKeyId: Bytes | string, options?: DclCertificateService.GetCertificateOptions) { const normalizedId = this.#normalizeSubjectKeyId(subjectKeyId); const metadata = this.#certificateIndex.get(normalizedId); if (!metadata || !this.#isRelevant(metadata, options)) { throw new MatterDclError(`Certificate not found`, Diagnostic.dict({ skid: normalizedId })); } const derBytes = await this.#storage!.get(normalizedId); if (!derBytes || derBytes.byteLength === 0) { throw new MatterDclError(`Certificate data not found in storage`, Diagnostic.dict({ skid: normalizedId })); } return Bytes.of(derBytes); } /** * Install revocation information that did not come from the DCL. * * The DCL is the authority on revocation: it publishes distribution points, and {@link isRevoked} * downloads and validates the CRL behind one the first time an authority is asked about. A set * installed here is trusted as it stands — no signer chain, no CRL signature — because it is * already the validated product of that process rather than an input to it. So this is for a * deployment that cannot reach the DCL, and for certification against a PKI the DCL does not * publish. Ordinary commissioning needs none of it. * * The entries live in memory for the life of this service and are never stored. A serial listed * here is revoked; every other serial still goes to the DCL, so an installed set can only add * revocations, never hide one. Installing the same set twice changes nothing. * * An entry that names no issuer is matched on its key identifier alone, which the specification's * composite key does not license and chip's own reading refuses. A key identifier is a hash of the * issuer's public key, so the widening is small, and it errs toward refusing a device rather than * admitting one. * * @see {@link MatterSpecification.v161.Core} § 6.2.4.1 */ installRevocations(entries: DclCertificateService.RevocationSetEntry[]) { // Nothing is installed until every entry has been read, so a set with a bad entry in the middle // does not leave half of itself in force const read = entries.map((entry, index) => ({ akid: this.#normalizeSubjectKeyId(statedHex(entry.issuerSubjectKeyId, "issuerSubjectKeyId", index)), issuerDnDerHex: issuerDnOf(statedIssuerName(entry.issuerName, index)), serials: entry.revokedSerialNumbers.map((serial, position) => canonicalSerial(statedHex(serial, `revokedSerialNumbers[${position}]`, index)), ), })); for (const { akid, issuerDnDerHex, serials } of read) { let installed = this.#installedRevocations.get(akid); if (installed === undefined) { this.#installedRevocations.set(akid, (installed = new Array())); } let entry = installed.find(candidate => candidate.issuerDnDerHex === issuerDnDerHex); if (entry === undefined) { installed.push((entry = { serials: new Set(), issuerDnDerHex })); } for (const serial of serials) { entry.serials.add(serial); } } if (read.length) { logger.info( "Installed revocation information from outside the DCL", Diagnostic.dict({ entries: read.length, authorities: this.#installedRevocations.size }), ); } } /** * Revocation information installed from outside the DCL, by the key identifier it was stated for. * * A copy: what this service holds can only be added to, through {@link installRevocations}. */ get installedRevocations(): ReadonlyMap { return new Map( [...this.#installedRevocations].map(([akid, entries]) => [ akid, entries.map(({ serials, issuerDnDerHex }) => ({ serials: new Set(serials), issuerDnDerHex })), ]), ); } /** * Check if a certificate is revoked by looking up its serial number in the revocation set * for the given authority key identifier. * * Lazily fetches revocation data from DCL on first access per AKID, then caches for 1 hour. * Per spec Section 6.2.6.2, the revocation set is indexed by (AuthorityKeyIdentifier, IssuerDN). * * Returns true if the certificate is revoked, false otherwise. * If revocation data is not available for the given authority, returns false. * * @throws {ClosedError} if the service is closing or closed */ async isRevoked( authorityKeyIdentifier: Bytes | string, serialNumber: Bytes | string, issuerDnDerHex?: string, ): Promise { // A closing service must not answer "not revoked" for a lookup it never ran if (this.#closed) { throw new ClosedError("DCL certificate service is closed"); } this.construction.assert(); const akid = this.#normalizeSubjectKeyId(authorityKeyIdentifier); const serialHex = typeof serialNumber === "string" ? serialNumber.replace(/:/g, "").toUpperCase() : Bytes.toHex(serialNumber).toUpperCase(); if (matchRevocation(this.#installedRevocations.get(akid), canonicalSerial(serialHex), issuerDnDerHex)) { return true; } if (this.#options.offline) { return false; } let lookup: RevocationLookup; try { lookup = await this.#revocationCache.get(akid); } catch { // A failed fetch already logged its cause; an unreachable CRL counts as not revoked return false; } // A partition that failed transiently would stay missing for the cache's lifetime if (!lookup.complete) { await this.#revocationCache.delete(akid); } return matchRevocation(lookup.entries, serialHex, issuerDnDerHex); } /** * Get certificate metadata by subject key identifier, fetching from DCL if not in local storage and the service * is not {@link DclCertificateService.Options.offline}. Returns undefined if not found or if the entry is filtered * by the effective trust policy. */ async getOrFetchCertificate( subjectKeyId: Bytes | string, options?: DclClient.Options & { isProduction?: boolean } & DclCertificateService.GetCertificateOptions, ) { this.construction.assert(); const normalizedId = this.#normalizeSubjectKeyId(subjectKeyId); const existing = this.#certificateIndex.get(normalizedId); if (existing && this.#isRelevant(existing, options)) { return existing; } if (this.#options.offline) { return undefined; } if (this.#fetchPromise !== undefined) { await this.#fetchPromise; const afterFetch = this.#certificateIndex.get(normalizedId); return afterFetch && this.#isRelevant(afterFetch, options) ? afterFetch : undefined; } try { const isProduction = options?.isProduction ?? true; if (!(await this.#fetchAndStoreRootCertificateBySkid(normalizedId, isProduction, false, options))) { logger.debug( `Certificate not found in DCL`, Diagnostic.dict({ skid: normalizedId, prod: isProduction }), ); return; } const fetched = this.#certificateIndex.get(normalizedId); if (fetched) { logger.info( `Fetched and stored certificate from DCL`, Diagnostic.dict({ skid: normalizedId, prod: isProduction }), ); } return fetched && this.#isRelevant(fetched, options) ? fetched : undefined; } catch (error) { MatterDclError.accept(error); logger.debug(`Failed to fetch certificate ${normalizedId} from DCL: ${error.message}`); } } /** * Delete a certificate from storage and index. */ async deleteCertificate(subjectKeyId: Bytes | string) { this.construction.assert(); const normalizedId = this.#normalizeSubjectKeyId(subjectKeyId); // Delete from storage await this.#storage!.delete(normalizedId); // Remove from index this.#certificateIndex.delete(normalizedId); // Update stored index await this.#saveIndex(); logger.debug(`Deleted certificate`, Diagnostic.dict({ skid: normalizedId })); } /** * Inject a certificate (PAA or CD signer) into the trust store. * * Returns `true` if the certificate was newly added, `false` if a certificate with the same * SubjectKeyIdentifier already exists (in which case the store is unchanged). * * @param derBytes DER-encoded X.509 certificate * @param kind "PAA" (self-signed root) or "CDSigner" (CMS Certification Declaration signer) * @param options.isProduction mark as production-trust; defaults to `false` */ async addCertificate( derBytes: Bytes, kind: DclCertificateService.CertificateKind, options?: { isProduction?: boolean }, ): Promise { this.construction.assert(); const cert = parseTrustStoreCertificate(derBytes, kind); const skid = this.#normalizeSubjectKeyId(cert.extensions.subjectKeyIdentifier); if (this.#certificateIndex.has(skid)) { return false; } const isProduction = options?.isProduction ?? false; const vid = (cert.subject as { vendorId?: number }).vendorId ?? 0; await this.#storeCertificate(this.#storage!, skid, Bytes.of(derBytes), { subject: (cert.subject as { commonName?: string }).commonName, subjectKeyId: skid, serialNumber: Bytes.toHex(cert.serialNumber), vid, isRoot: kind === "PAA", isProduction, kind, }); await this.#saveIndex(); logger.info(`Added ${kind} certificate`, Diagnostic.dict({ skid, isProduction })); return true; } /** * Look up a CD signer certificate by its SubjectKeyIdentifier. * * Checks the local trust store first. On miss, queries the production DCL * (`/dcl/pki/all-certificates?subjectKeyId=`) and caches the result as a * CDSigner entry with `isProduction: true`. * * Returns `undefined` if no matching CD signer can be found either locally or on DCL. */ async getOrFetchCdSigner( subjectKeyId: Bytes | string, ): Promise<{ publicKey: Bytes; isProduction: boolean } | undefined> { this.construction.assert(); const normalizedSkid = this.#normalizeSubjectKeyId(subjectKeyId); // Local lookup first const existing = this.#certificateIndex.get(normalizedSkid); if (existing !== undefined && (existing.kind ?? "PAA") === "CDSigner") { const derBytes = await this.#getCertificateDer(normalizedSkid); const cert = Certificate.parseAsn1Certificate(derBytes, Certificate.REQUIRED_EXTENSIONS); return { publicKey: cert.ellipticCurvePublicKey, isProduction: existing.isProduction }; } if (this.#options.offline) { return undefined; } // DCL fallback try { const config = this.#options.dclConfig ?? DclConfig.production; const dclClient = new DclClient(config); const certs = await dclClient.fetchCertificatesBySubjectKeyId(normalizedSkid, this.#options); if (certs.length === 0) { return undefined; } const derBytes = Pem.asDer(certs[0].pemCert); await this.addCertificate(derBytes, "CDSigner", { isProduction: true }); const cert = Certificate.parseAsn1Certificate(derBytes, Certificate.REQUIRED_EXTENSIONS); return { publicKey: cert.ellipticCurvePublicKey, isProduction: true }; } catch (error) { logger.info( `Failed to fetch CD signer ${normalizedSkid} from DCL:`, Diagnostic.errorMessage(asError(error)), ); return undefined; } } /** * Close the service and stop all timers. */ async close() { this.#closed = true; await this.#revocationCache.close(); await this.#construction.close(async () => { this.#updateTimer?.stop(); this.#updateTimer = undefined; // update() logs a failed fetch; close only waits for it to settle await Promise.allSettled([this.#fetchPromise]); await this.#storageManager?.close(); }); } /** * Load the certificate index from storage, verifying each entry exists and cleaning up orphaned data. */ async #loadIndex(storage: StorageContext) { // Get all keys in storage to detect orphaned certificate data const allKeys = new Set(await storage.keys()); allKeys.delete("index"); // Remove the index key itself const storedIndex = await storage.get("index", []); // Load and verify each certificate entry let validCount = 0; let invalidCount = 0; for (const metadata of storedIndex) { if (allKeys.delete(metadata.subjectKeyId)) { this.#certificateIndex.set(metadata.subjectKeyId, metadata); validCount++; } else { logger.warn( `Certificate referenced in index but not found in storage`, Diagnostic.dict({ skid: metadata.subjectKeyId }), ); invalidCount++; } } // Clean up orphaned certificates (in storage but not in index) if (allKeys.size > 0) { logger.debug(`Found ${allKeys.size} orphaned certificate(s) in storage, cleaning up`); for (const orphanedKey of allKeys) { await storage.delete(orphanedKey); logger.debug(`Deleted orphaned certificate: ${orphanedKey}`); } } logger.info( `Loaded ${validCount} certificates from storage${invalidCount > 0 ? ` (${invalidCount} missing)` : ""}${allKeys.size > 0 ? ` (${allKeys.size} orphaned removed)` : ""}`, ); } /** * Update certificates from DCL and GitHub. Returns true if update succeeded, false if it failed. */ async update(force = false) { if (this.#closed || !this.#storage || this.#options.offline) { return; } if (this.#fetchPromise !== undefined) { // Process already running, return this promise return this.#fetchPromise; } logger.debug(`Update certificates${force ? " (force mode)" : ""}`); try { this.#fetchPromise = this.#fetchCertificates(this.#storage, force).finally(() => { this.#fetchPromise = undefined; }); await this.#fetchPromise; } catch (error) { logger.info("Certificate update failed", Diagnostic.errorMessage(asError(error))); return false; } return true; } /** * Fetch certificates from DCL and GitHub. */ async #fetchCertificates(storage: StorageContext, force = false) { if (this.#closed) { return; } const initialSize = this.#certificateIndex.size; this.#githubRateLimited = false; // Always fetch production certificates from DCL await this.#fetchDclCertificates(storage, true, force); if (this.#closed) { return; } // Additionally fetch test certificates if requested if (this.#options.fetchTestCertificates) { await this.#fetchDclCertificates(storage, false, force); if (this.#closed) { return; } // Also fetch certificates from GitHub (unless explicitly disabled) if (this.#options.fetchGithubCertificates !== false) { await this.#fetchGitHubCertificates(storage, force); if (this.#closed) { return; } await this.#fetchGitHubCdSignerCertificates(storage, force); } } if (this.#closed) { return; } await this.#saveIndex(); const newCerts = this.#certificateIndex.size - initialSize; if (newCerts > 0) { logger.info(`Downloaded and stored ${newCerts} new certificates (total: ${this.#certificateIndex.size})`); } else { logger.info(`All certificates up to date (${this.#certificateIndex.size} total)`); } } /** Fetch certificates from DCL for the specified environment. */ async #fetchDclCertificates(storage: StorageContext, isProduction: boolean, force: boolean) { const environment = isProduction ? "production" : "test"; logger.debug(`Fetching PAA certificates from DCL (${environment})`); const config = isProduction ? (this.#options.dclConfig ?? DclConfig.production) : (this.#options.testDclConfig ?? DclConfig.test); const dclClient = new DclClient(config); const certRefs = await dclClient.fetchRootCertificateList(this.#options); logger.debug(`Found ${certRefs.length} ${environment} root certificates in DCL`); for (const certRef of certRefs) { if (this.#closed) { return; } await this.#fetchAndStoreCertificate(storage, dclClient, certRef, isProduction, force, this.#options); } } /** Save the certificate index to storage. */ #saveIndex() { if (this.#closed) { return; } if (!this.#storage) { throw new MatterDclError("Storage context not initialized"); } const indexArray = Array.from(this.#certificateIndex.values()); return this.#storage.set("index", indexArray); } /** * Fetch and store a single certificate from DCL by its subject reference. Returns whether the trust store holds a * usable certificate for it afterwards. */ async #fetchAndStoreCertificate( storage: StorageContext, dclClient: DclClient, certRef: DclPkiRootCertificateSubjectReference, isProduction: boolean, force: boolean, options?: DclClient.Options, ): Promise { try { // Strip colons from subject key ID for storage key (normalize to match GitHub format) const normalizedSubjectKeyId = this.#normalizeSubjectKeyId(certRef.subjectKeyId); // Check if certificate already exists before fetching details (skip check if force is true) if (!force && this.#certificateIndex.has(normalizedSubjectKeyId)) { // If the existing certificate was stored as test but is now found in production DCL, upgrade it const existing = this.#certificateIndex.get(normalizedSubjectKeyId)!; if (isProduction && !existing.isProduction) { existing.isProduction = true; logger.debug( `Upgraded certificate to production`, Diagnostic.dict({ skid: normalizedSubjectKeyId }), ); } else { logger.debug( `Certificate already exists, skipping`, Diagnostic.dict({ skid: normalizedSubjectKeyId }), ); } return true; } // Fetch the certificate details const certs = await dclClient.fetchRootCertificateBySubject(certRef, options); let stored = false; for (const cert of certs) { if (!cert.subjectKeyId) { logger.warn( `Certificate for subject ${cert.subject} is missing subjectKeyId, skipping`, Diagnostic.dict({ subject: cert.subject }), ); continue; } // Strip colons from subject key ID for storage key const subjectKeyId = this.#normalizeSubjectKeyId(cert.subjectKeyId); let derBytes: Bytes; try { derBytes = Pem.asDer(cert.pemCert); } catch (error) { logger.info( `DCL: certificate cannot be used as a PAA, skipped`, Diagnostic.dict({ skid: subjectKeyId }), Diagnostic.errorMessage(asError(error)), ); continue; } if (this.#parseAndCheckSkid(derBytes, "PAA", subjectKeyId, "DCL") === undefined) { continue; } const { subject, subjectAsText, serialNumber, vid, isRoot } = cert; // Store certificate with metadata (using normalized ID without colons) await this.#storeCertificate(storage, subjectKeyId, derBytes, { subject, subjectAsText, subjectKeyId, serialNumber, vid, isRoot, isProduction, kind: "PAA", }); logger.debug(`Stored certificate`, Diagnostic.dict({ skid: normalizedSubjectKeyId, vid: cert.vid })); stored ||= subjectKeyId === normalizedSubjectKeyId; } return stored; } catch (error) { logger.info( `Failed to fetch certificate ${certRef.subject}/${certRef.subjectKeyId}`, Diagnostic.errorMessage(asError(error)), ); return false; } } #hasTestCertificatesOfKind(kind: DclCertificateService.CertificateKind) { for (const metadata of this.#certificateIndex.values()) { if (!metadata.isProduction && (metadata.kind ?? "PAA") === kind) { return true; } } return false; } /** * Log a GitHub fetch failure. GitHub only serves test certificates, so a rate-limit error is only debug-worthy * once we already hold test certificates of the affected kind: the cached data remains usable, making the failed * refresh not actionable for the operator. A rate-limit response also flags the rest of the current fetch run to * skip GitHub rather than repeating the same failing request. */ #logGithubFetchFailure(message: string, error: unknown, kind: DclCertificateService.CertificateKind) { const rateLimited = error instanceof Github.HttpError && error.isRateLimit; if (rateLimited) { this.#githubRateLimited = true; } const level = rateLimited && this.#hasTestCertificatesOfKind(kind) ? LogLevel.DEBUG : LogLevel.INFO; logger.log(level, message, Diagnostic.errorMessage(asError(error))); } /** * Fetch development certificates from GitHub repository. */ async #fetchGitHubCertificates(storage: StorageContext, force: boolean) { if (this.#githubRateLimited) { logger.debug("Skipping GitHub certificate fetch, GitHub is rate-limiting this run"); return; } try { logger.debug("Fetching development certificates from GitHub"); // Create GitHub repo client with timeout option const { owner, repo, branch, certPath } = this.#options.githubConfig ?? DclGithubConfig.defaults; const repoClient = new Github.Repo(owner, repo, branch, this.#options); const certDir = await repoClient.cd(certPath); // List files in the certificate directory const files = await certDir.ls(); // Filter for .der files, excluding DCL mirror files because we load from DCL directly const certFiles = files.filter(name => name.endsWith(".der") && !name.startsWith("dcld_mirror_")); logger.debug(`Found ${certFiles.length} certificate files on GitHub`); for (const filename of certFiles) { if (this.#closed) { return; } await this.#fetchGitHubCertificate(storage, certDir, filename, force); } } catch (error) { this.#logGithubFetchFailure("Failed to fetch certificates from GitHub", error, "PAA"); } } /** * Fetch CD signer certificates from the configured GitHub directory. * Stores each as a CDSigner entry with isProduction=false (user may promote via addCertificate). */ async #fetchGitHubCdSignerCertificates(storage: StorageContext, force: boolean) { if (this.#githubRateLimited) { logger.debug("Skipping GitHub CD signer fetch, GitHub is rate-limiting this run"); return; } try { logger.debug("Fetching CD signer certificates from GitHub"); const { owner, repo, branch, cdSignerCertPath } = this.#options.githubConfig ?? DclGithubConfig.defaults; const repoClient = new Github.Repo(owner, repo, branch, this.#options); const certDir = await repoClient.cd(cdSignerCertPath); const files = await certDir.ls(); const certFiles = files.filter(name => name.endsWith(".der")); logger.debug(`Found ${certFiles.length} CD signer certificate files on GitHub`); for (const filename of certFiles) { if (this.#closed) { return; } await this.#fetchGitHubCdSignerCertificate(storage, certDir, filename, force); } } catch (error) { this.#logGithubFetchFailure("Failed to fetch CD signer certificates from GitHub", error, "CDSigner"); } } /** * Fetch a single CD signer certificate from GitHub. */ async #fetchGitHubCdSignerCertificate( storage: StorageContext, certDir: Github.Directory, filename: string, force: boolean, ) { try { const derBytes = await certDir.getBinary(filename); const cert = Certificate.parseAsn1Certificate(derBytes, Certificate.REQUIRED_EXTENSIONS); const subjectKeyId = this.#normalizeSubjectKeyId(cert.extensions.subjectKeyIdentifier); if (!force && this.#certificateIndex.has(subjectKeyId)) { logger.debug(`CD signer certificate already exists, skipping`, Diagnostic.dict({ skid: subjectKeyId })); return; } const subject = filename.replace(".der", ""); const serialNumber = Bytes.toHex(cert.serialNumber); const vid = (cert.subject as { vendorId?: number }).vendorId ?? 0; await this.#storeCertificate(storage, subjectKeyId, Bytes.of(derBytes), { subject, subjectKeyId, serialNumber, vid, isRoot: false, isProduction: false, kind: "CDSigner", }); logger.debug(`Stored GitHub CD signer certificate`, Diagnostic.dict({ skid: subjectKeyId, filename })); } catch (error) { logger.info( `Failed to fetch GitHub CD signer certificate ${filename}`, Diagnostic.errorMessage(asError(error)), ); } } /** * Fetch a single certificate from GitHub by filename. */ async #fetchGitHubCertificate( storage: StorageContext, certDir: Github.Directory, filename: string, force: boolean, ) { try { // Download DER certificate directly as binary using GitHub client const derBytes = await certDir.getBinary(filename); // Parse the certificate to extract metadata const paa = Paa.fromAsn1(derBytes); const subjectKeyId = this.#normalizeSubjectKeyId(paa.cert.extensions.subjectKeyIdentifier); // Skip if certificate already exists (unless force is true) if (!force && this.#certificateIndex.has(subjectKeyId)) { logger.debug(`Certificate already exists, skipping`, Diagnostic.dict({ skid: subjectKeyId })); return; } const subject = filename.replace(".der", ""); const serialNumber = Bytes.toHex(paa.cert.serialNumber); const vid = paa.cert.subject.vendorId ?? 0; // Store certificate with metadata await this.#storeCertificate(storage, subjectKeyId, derBytes, { subject, subjectKeyId, serialNumber, vid, isRoot: true, isProduction: false, kind: "PAA", }); logger.debug(`Stored GitHub certificate`, Diagnostic.dict({ skid: subjectKeyId, filename })); } catch (error) { logger.log( skippedCertificateLogLevel(error), `Failed to fetch GitHub certificate ${filename}`, Diagnostic.errorMessage(asError(error)), ); } } /** * Store a certificate and its metadata. */ async #storeCertificate( storage: StorageContext, subjectKeyId: string, derBytes: Bytes, metadata: DclCertificateService.CertificateMetadata, ) { // Never downgrade isProduction from true to false const existing = this.#certificateIndex.get(subjectKeyId); if (existing?.isProduction && !metadata.isProduction) { metadata = { ...metadata, isProduction: true }; } // Set fetchedAt if not already present (preserve original fetch time across updates) if (metadata.fetchedAt === undefined) { metadata = { ...metadata, fetchedAt: existing?.fetchedAt ?? Time.nowMs }; } // Store the DER certificate await storage.set(subjectKeyId, derBytes); // Add entry to certificate index this.#certificateIndex.set(subjectKeyId, metadata); } async #consumeCertSeed(source: SeedSource, certKind: DclCertificateService.CertificateKind) { const inserted = new Array(); let expiredCount = 0; const parsedBuiltAt = Date.parse(source.builtAt); const fetchedAt = Number.isNaN(parsedBuiltAt) ? Date.now() : parsedBuiltAt; const isPaa = certKind === "PAA"; try { for await (const entry of source.entries) { if (this.#closed) break; try { if ( typeof entry.subjectKeyId !== "string" || !entry.subjectKeyId || typeof entry.derHex !== "string" || !entry.derHex || (entry.kind !== "production" && entry.kind !== "test") ) { throw new MatterDclError("invalid entry shape"); } if (entry.kind === "test" && !this.#options.fetchTestCertificates) { continue; } if (entry.notAfter !== undefined && Date.parse(entry.notAfter) < Date.now()) { expiredCount++; continue; } const der = Bytes.fromHex(entry.derHex); const entrySkid = this.#normalizeSubjectKeyId(entry.subjectKeyId); const parsed = this.#parseAndCheckSkid(der, certKind, entrySkid, "seed"); if (parsed === undefined) { continue; } if (this.#certificateIndex.has(entrySkid)) { continue; } const isProduction = entry.kind === "production"; const vid = (parsed.subject as { vendorId?: number }).vendorId ?? 0; await this.#storeCertificate(this.#storage!, entrySkid, Bytes.of(der), { subject: (parsed.subject as { commonName?: string }).commonName, subjectKeyId: entrySkid, serialNumber: Bytes.toHex(parsed.serialNumber), vid, isRoot: isPaa, isProduction, kind: certKind, fetchedAt, }); inserted.push(entrySkid); } catch (err) { logger.warn("seed: malformed entry, aborting stream", Diagnostic.errorMessage(asError(err))); break; } } } catch (err) { logger.warn("seed: stream failed", Diagnostic.errorMessage(asError(err))); } if (inserted.length > 0) { await this.#saveIndex(); } if (expiredCount > 0) { logger.info(`seed: skipped ${expiredCount} expired ${certKind} certs from snapshot ${source.builtAt}`); } logger.info(`seed: consumed ${inserted.length} ${certKind} certs from snapshot ${source.builtAt}`); } /** * Fetch and validate revocation data for a single AKID on demand. * Called by AsyncCache on cache miss. Queries DCL by issuer, downloads the CRL, * validates the signer chain and CRL signature, then returns the parsed revocation entry. * * Returns the revocations of every distribution point that authenticates (cached for 1h), which is empty when * points are rejected as Matter Core §6.2.6.1 requires. Throws only when transient failures (network timeout, * server error) left nothing usable, so the result is NOT cached and the next call retries. */ async #fetchAndValidateRevocation(akid: string): Promise { const empty: RevocationLookup = { entries: [], complete: true }; const revocationTimeout = Seconds(3); const config = this.#options.dclConfig ?? DclConfig.production; const dclClient = new DclClient(config); let points: DeviceAttestationPkiRevocationDclSchema[]; try { points = await dclClient.fetchRevocationDistributionPointsByIssuer(akid, { timeout: revocationTimeout, }); } catch (error) { // gRPC NOT_FOUND (5) — the issuer simply has no CRL registered, cache the empty result if (error instanceof MatterDclResponseError && error.response.code === 5) { logger.debug(`No CRL registered in DCL for AKID ${akid}`); return empty; } // Transient failure (timeout, network error) — throw so AsyncCache does NOT cache logger.warn( `DCL revocation lookup failed for AKID ${akid} (will retry on next check):`, Diagnostic.errorMessage(asError(error)), ); throw error; } // CRL entries for exactly the issuer asked about (§11.23.11.7), whatever else the response holds const crlPoints = points.filter( p => p.revocationType === RevocationTypeEnum.Crl && this.#normalizeSubjectKeyId(p.issuerSubjectKeyId) === akid, ); if (crlPoints.length === 0) { return empty; } // Every entry contributes: an issuer may partition its revocations over several CRLs (§6.2.6.1) const entries = new Array(); let transientFailures = 0; const results = await Promise.allSettled( crlPoints.map(point => // Step 7.2 applies to entries that share both VendorID and IssuerSubjectKeyID (§11.23.11.8) this.#processRevocationPoint( point, revocationTimeout, crlPoints.filter(other => other.vid === point.vid).length > 1, ), ), ); results.forEach((result, index) => { if (result.status === "fulfilled") { entries.push(result.value); return; } const point = crlPoints[index]; const rejected = result.reason instanceof CrlRejectedError; if (!rejected) { transientFailures++; } logger.warn( `${rejected ? "Ignoring" : "Failed to process"} revocation point for ${point.issuerSubjectKeyId} at ${point.dataUrl}:`, Diagnostic.errorMessage(asError(result.reason)), ); }); // Nothing usable because of transient failures — throw so it's not cached and will retry if (entries.length === 0 && transientFailures > 0) { throw new MatterDclError(`All CRL downloads failed for AKID ${akid}`); } return { entries, complete: transientFailures === 0 }; } /** * Process a single revocation distribution point: validate the signer chain, download the CRL, authenticate it and * extract the revoked serial numbers. Throws where Matter Core §6.2.6.1 stops processing the entry. */ async #processRevocationPoint( point: DeviceAttestationPkiRevocationDclSchema, timeout: Duration, partitioned: boolean, ): Promise { let authority: CrlAuthority; try { authority = await this.#anchorCrlSigner(point); } catch (error) { throw error instanceof CrlRejectedError ? error : new CrlRejectedError("CRL signer certificate is unusable", { cause: error }); } // Download the CRL from dataUrl const response = await fetch(point.dataUrl, { signal: AbortSignal.timeout(timeout), }); if (!response.ok) { // A client error will not heal on retry; a server error, request timeout or rate limit may const transient = response.status >= 500 || response.status === 408 || response.status === 429; const Failure = transient ? MatterDclError : CrlRejectedError; throw new Failure(`Failed to fetch CRL from ${point.dataUrl}: ${response.status}`); } const crlBytes = new Uint8Array(await response.arrayBuffer()); // Verify CRL integrity against DCL metadata if available if (point.dataFileSize !== undefined) { const expectedSize = typeof point.dataFileSize === "bigint" ? Number(point.dataFileSize) : point.dataFileSize; if (expectedSize > 0 && crlBytes.length !== expectedSize) { throw new CrlRejectedError(`CRL size mismatch: expected ${expectedSize} bytes, got ${crlBytes.length}`); } } if (point.dataDigest !== undefined && point.dataDigestType !== undefined) { const algorithm = hashAlgorithmForId(point.dataDigestType); if (algorithm !== undefined) { const actualDigest = Bytes.toBase64(await this.#crypto.computeHash(crlBytes, algorithm)); if (actualDigest !== point.dataDigest) { throw new CrlRejectedError( `CRL digest mismatch: expected ${point.dataDigest}, got ${actualDigest}`, ); } } else { logger.info(`Skipping CRL digest verification: unsupported digest type ${point.dataDigestType}`); } } try { return await this.#authenticateCrl(point, crlBytes, authority, partitioned); } catch (error) { throw error instanceof CrlRejectedError ? error : new CrlRejectedError(`CRL from ${point.dataUrl} is malformed`, { cause: error }); } } /** Matter Core §6.2.6.1 steps 7-10 for a downloaded CRL. */ async #authenticateCrl( point: DeviceAttestationPkiRevocationDclSchema, crlBytes: Bytes, { signer, name }: CrlAuthority, partitioned: boolean, ): Promise { const crl = DclCertificateService.parseCrl(crlBytes, name); // RFC 5280 §6.3.3: delta CRLs are unsupported and other unknown critical extensions forbid use if (crl.unsupportedCriticalExtension !== undefined) { throw new CrlRejectedError( `CRL carries unsupported critical extension ${crl.unsupportedCriticalExtension}`, ); } // Step 7.1 const signerSkid = this.#normalizeSubjectKeyId(signer.cert.extensions.subjectKeyIdentifier); if (crl.authorityKeyId !== signerSkid) { throw new CrlRejectedError( `CRL authority key identifier ${crl.authorityKeyId ?? "(none)"} does not match CRL signer ${signerSkid}`, ); } // RFC 5280 §5.1.2.3: the CRL names the signer as its issuer if ( crl.issuerDnDerHex === undefined || !sameName(Bytes.fromHex(crl.issuerDnDerHex), nameOf(signer, "subject")) ) { throw new CrlRejectedError("CRL issuer name is not the CRL signer's subject"); } // Step 7.2 if (partitioned && crl.issuingDistributionPointUri !== point.dataUrl) { throw new CrlRejectedError( `CRL from ${point.dataUrl} is one of several for its issuer but its Issuing Distribution Point names ${crl.issuingDistributionPointUri ?? "no single URI"}`, ); } // Step 8, RFC 5280 §6.3 with the CRL signer as trust anchor const { tbsDer, signatureAlgorithm, signatureValue } = crl; if (tbsDer === undefined || signatureAlgorithm === undefined || signatureValue === undefined) { throw new CrlRejectedError(`CRL from ${point.dataUrl} carries no valid signature`); } try { await verifyCertificateSignature( this.#crypto, signer.publicKey, tbsDer, certificateSignatureOf(signatureAlgorithm, signatureValue), ); } catch (cause) { throw new CrlRejectedError("CRL signature verification failed against CRLSignerCertificate", { cause }); } // Steps 9-10: the revocations belong to the authority, whatever issuer name an indirect CRL states return { serials: crl.serials, issuerDnDerHex: Bytes.toHex(name).toUpperCase() }; } /** * Establish the CRL signer of a distribution point and the authority whose revocations it signs, per Matter Core * §6.2.6.1 steps 2-5 and 9 and the signer forms of §11.23.11.6. * * @throws CrlRejectedError if the signer is not one the entry may name */ async #anchorCrlSigner(point: DeviceAttestationPkiRevocationDclSchema): Promise { const entrySkid = this.#normalizeSubjectKeyId(point.issuerSubjectKeyId); // Step 2 const signerDer = Pem.asDer(point.crlSignerCertificate); const signer = point.isPAA ? Paa.fromAsn1(signerDer) : Pai.fromAsn1(signerDer); const delegator = point.crlSignerDelegator ? Pai.fromAsn1(Pem.asDer(point.crlSignerDelegator)) : undefined; const selfSigned = sameName(nameOf(signer, "subject"), nameOf(signer, "issuer")) && (await this.#signsItself(signer)); // RFC 5280 §6.3.3(f) and the §11.23.11.6 formats: every signer may sign CRLs, and only a PAA or PAI signs as CA if (!signer.cert.extensions.keyUsage.cRLSign) { throw new CrlRejectedError("CRL signer certificate lacks the cRLSign key usage"); } const signerIsCa = signer.cert.extensions.basicConstraints.isCa; const delegated = point.isPAA ? !selfSigned : delegator !== undefined; if (signerIsCa === delegated) { throw new CrlRejectedError( delegated ? "A delegated CRL signer must not be a CA certificate" : "A CRL signer that is not delegated must be the PAA or PAI itself", ); } if (delegator !== undefined && !delegator.cert.extensions.basicConstraints.isCa) { throw new CrlRejectedError("CRLSignerDelegator is not a PAI"); } // Steps 3-4 const vidHolder = point.isPAA ? signer : (delegator ?? signer); const vid = vidHolder.cert.subject.vendorId; // A PAA may omit its VendorID (step 3.1); a PAI states exactly one, which must match (step 4.1) if ((vid !== undefined || !point.isPAA) && vid !== point.vid) { throw new CrlRejectedError(`CRL signer VendorID ${vid} does not match entry VendorID ${point.vid}`); } const pid = vidHolder instanceof Pai ? vidHolder.cert.subject.productId : undefined; // The DCL client reads an entry's ProductID 0 as absent, and a PAI may state 0 as well if (pid !== undefined && pid !== (point.pid ?? 0)) { throw new CrlRejectedError(`CRL signer ProductID ${pid} does not match entry ProductID ${point.pid}`); } // Step 5 and the step 9 authority let authority: Paa | Pai; if (point.isPAA && selfSigned) { // An approved PAA, identified by exact byte equality const approved = await this.#trustedPaaDer( this.#normalizeSubjectKeyId(signer.cert.extensions.subjectKeyIdentifier), ); if (!Bytes.areEqual(approved, signerDer)) { throw new CrlRejectedError("Self-signed CRL signer is not an approved PAA"); } authority = signer; } else if (point.isPAA) { // PAA-delegated signer: the entry names the PAA, which must have issued it const paa = Paa.fromAsn1(await this.#trustedPaaDer(entrySkid)); await this.#assertIssuedBy(signer, paa); authority = paa; } else if (selfSigned) { throw new CrlRejectedError("Self-signed CRL signer on an entry that is not for a PAA"); } else { // A PAI, or a signer the delegating PAI issued; either way the entry names that PAI const pai = delegator ?? signer; if (delegator !== undefined) { await this.#assertIssuedBy(signer, delegator); } const paaSkid: Bytes | undefined = pai.cert.extensions.authorityKeyIdentifier; if (paaSkid === undefined) { throw new CrlRejectedError("CRL signing PAI names no authority key identifier"); } await this.#assertIssuedBy( pai, Paa.fromAsn1(await this.#trustedPaaDer(this.#normalizeSubjectKeyId(paaSkid))), ); authority = pai; } const authoritySkid = this.#normalizeSubjectKeyId(authority.cert.extensions.subjectKeyIdentifier); if (authoritySkid !== entrySkid) { throw new CrlRejectedError(`CRL authority ${authoritySkid} is not the entry's issuer ${entrySkid}`); } return { signer, name: nameOf(authority, "subject") }; } /** Whether a certificate verifies with its own key, which with equal names makes it self-signed. */ async #signsItself(certificate: Paa | Pai) { try { await certificate.verifySignature(this.#crypto, certificate.publicKey); return true; } catch { return false; } } #trustedPaaDer(skid: string) { if ((this.#certificateIndex.get(skid)?.kind ?? "PAA") !== "PAA") { throw new CrlRejectedError(`CRL signer chain names ${skid}, which is not a PAA`); } // The CRL chain honors test PAAs that the validator already accepted upstream return this.#getCertificateDer(skid, { considerTestCertificates: true }); } /** Verify that `issuer` issued `subject`: an issuer that may sign certificates, matching names and its signature. */ async #assertIssuedBy(subject: Paa | Pai, issuer: Paa | Pai) { // RFC 5280 §6.1.4(n) if (!issuer.cert.extensions.keyUsage.keyCertSign) { throw new CrlRejectedError("CRL signer chain issuer lacks the keyCertSign key usage"); } if (!sameName(nameOf(subject, "issuer"), nameOf(issuer, "subject"))) { throw new CrlRejectedError("CRL signer chain names do not match"); } try { await subject.verifySignature(this.#crypto, issuer.publicKey); } catch (cause) { throw new CrlRejectedError("CRL signer chain signature does not verify", { cause }); } } /** * Read a revocation set: the per-issuer list of revoked serial numbers that the CHIP SDK's * `generate_revocation_set.py` writes by walking the DCL's revocation distribution points and the * CRLs behind them. It is that tool's own format, not a DCL wire format. Fields beyond the ones * {@link installRevocations} needs are ignored. */ static parseRevocationSet(json: string): DclCertificateService.RevocationSetEntry[] { let parsed: unknown; try { parsed = JSON.parse(json); } catch (error) { throw new ImplementationError(`Revocation set is not JSON: ${asError(error).message}`); } if (!Array.isArray(parsed)) { throw new ImplementationError("Revocation set must be an array of entries"); } const stated: unknown[] = parsed; return stated.map((entry, index) => { if (!isObject(entry)) { throw new ImplementationError(`Revocation set entry ${index} is not an object`); } statedType(entry.type, index); return { issuerSubjectKeyId: statedHex(entry.issuer_subject_key_id, "issuer_subject_key_id", index), issuerName: statedIssuerName(entry.issuer_name, index), revokedSerialNumbers: statedSerials(entry.revoked_serial_numbers, index), }; }); } /** Result of parsing a CRL. */ static parseCrl(crlDer: Bytes, authorityName?: Bytes): DclCertificateService.CrlParseResult { const serials = new Set(); let unsupportedCriticalExtension: string | undefined; const decoded = DerCodec.decode(crlDer); const certListElements = decoded._elements; if (!certListElements || certListElements.length < 2) { return { serials }; } // CertificateList ::= SEQUENCE { tbsCertList, signatureAlgorithm, signatureValue } const tbsCertList = certListElements[0]; const tbsElements = tbsCertList._elements; if (!tbsElements) { return { serials }; } // Extract raw tbsCertList DER for signature verification const tbsDer = DerCodec.encode(tbsCertList); // Extract signatureValue (BIT STRING, last element) // signatureValue is the 3rd element (index 2) of the outer SEQUENCE let signatureValue: Bytes | undefined; if ( certListElements.length >= 3 && certListElements[2]._tag === DerType.BitString && certListElements[2]._padding === 0 ) { // BIT STRING _bytes already has padding byte stripped by DerCodec.decode signatureValue = Bytes.of(certListElements[2]._bytes); } // RFC 5280 §5.1.1.2: the algorithm outside tbsCertList must equal the one inside it let signatureAlgorithm: Bytes | undefined; const outerAlgorithm = certListElements[1]; const innerAlgorithm = tbsElements.find(element => element._tag === DerTag.Sequence); const outerAlgorithmDer = DerCodec.encode(outerAlgorithm); if (innerAlgorithm !== undefined && Bytes.areEqual(outerAlgorithmDer, DerCodec.encode(innerAlgorithm))) { signatureAlgorithm = Bytes.of(outerAlgorithmDer); } // tbsCertList fields: [version?, signature, issuer, thisUpdate, nextUpdate?, revokedCertificates?, crlExtensions?] let idx = 0; // version is optional: if present it's an INTEGER if (tbsElements[idx]?._tag === DerType.Integer) { idx++; } // signature algorithm: SEQUENCE if (tbsElements[idx]?._tag === DerTag.Sequence) { idx++; } // issuer Name: SEQUENCE — hash its raw DER bytes for use as composite revocation key let issuerDnDerHex: string | undefined; if (tbsElements[idx]?._tag === DerTag.Sequence) { const issuerNode = tbsElements[idx]; issuerDnDerHex = Bytes.toHex(DerCodec.encode(issuerNode)).toUpperCase(); idx++; } // thisUpdate: UTCTime or GeneralizedTime — skip if (tbsElements[idx]?._tag === DerType.UtcDate || tbsElements[idx]?._tag === DerType.GeneralizedTime) { idx++; } // nextUpdate: UTCTime or GeneralizedTime — parse if present let nextUpdateMs: number | undefined; if (tbsElements[idx]?._tag === DerType.UtcDate || tbsElements[idx]?._tag === DerType.GeneralizedTime) { try { const dateStr = Bytes.toString(tbsElements[idx]._bytes); // UTCTime: YYMMDDHHMMSSZ, GeneralizedTime: YYYYMMDDHHMMSSZ let year: number; let rest: string; if (tbsElements[idx]._tag === DerType.UtcDate) { const yy = parseInt(dateStr.slice(0, 2)); year = yy >= 50 ? 1900 + yy : 2000 + yy; rest = dateStr.slice(2); } else { year = parseInt(dateStr.slice(0, 4)); rest = dateStr.slice(4); } const month = parseInt(rest.slice(0, 2)) - 1; const day = parseInt(rest.slice(2, 4)); const hour = parseInt(rest.slice(4, 6)); const min = parseInt(rest.slice(6, 8)); const sec = parseInt(rest.slice(8, 10)); nextUpdateMs = Date.UTC(year, month, day, hour, min, sec); } catch { // Ignore parse errors for nextUpdate } } // Extract Authority Key Identifier from CRL extensions if present // crlExtensions is a context-tagged [0] EXPLICIT at the end of tbsCertList let authorityKeyId: string | undefined; let issuingDistributionPointUri: string | undefined; for (const element of tbsElements) { // Context-tagged [0] EXPLICIT = tag 0xa0 if (element._tag === 0xa0 && element._bytes) { // Parse the extensions SEQUENCE inside the context tag const extSequence = DerCodec.decode(element._bytes); if (extSequence._elements) { for (const ext of extSequence._elements) { if (!ext._elements || ext._elements.length < 2) continue; const oid = Bytes.toHex(ext._elements[0]._bytes); if (isCritical(ext) && !KNOWN_CRL_EXTENSIONS.has(oid)) { unsupportedCriticalExtension ??= oid; } // Issuing Distribution Point OID: 2.5.29.28 = 551d1c if (oid === "551d1c") { issuingDistributionPointUri = issuingDistributionPointUriOf(ext); continue; } // Authority Key Identifier OID: 2.5.29.35 = 551d23 if (oid === "551d23") { // The value is an OCTET STRING containing a SEQUENCE const valueIdx = ext._elements.length > 2 ? 2 : 1; const akiOctetString = ext._elements[valueIdx]; if (akiOctetString._bytes) { const akiSeq = DerCodec.decode(akiOctetString._bytes); // KeyIdentifier is context-tagged [0] inside the SEQUENCE if (akiSeq._elements) { for (const akiField of akiSeq._elements) { if (akiField._tag === 0x80) { authorityKeyId = Bytes.toHex(Bytes.of(akiField._bytes)).toUpperCase(); break; } } } } continue; } } } } } // Find the revokedCertificates sequence let revokedCertsNode: DerNode | undefined; for (const element of tbsElements) { if (element._tag === DerTag.Sequence && element._elements) { const firstChild = element._elements[0]; if ( firstChild && firstChild._tag === DerTag.Sequence && firstChild._elements && firstChild._elements[0]?._tag === DerType.Integer ) { revokedCertsNode = element; break; } } } if (!revokedCertsNode?._elements) { return { serials, issuerDnDerHex, authorityKeyId, tbsDer, signatureAlgorithm, signatureValue, issuingDistributionPointUri, unsupportedCriticalExtension, nextUpdateMs, }; } let certificateIssuer: Bytes | undefined; for (const entry of revokedCertsNode._elements) { if (entry._tag !== DerTag.Sequence || !entry._elements || entry._elements.length < 1) continue; const serialNode = entry._elements[0]; if (serialNode._tag !== DerType.Integer) continue; // §6.2.6.1 step 10.1: an indirect CRL's entry may name another issuer than the authority, which applies to // the entries after it until another certificateIssuer (RFC 5280 §5.3.3) const entryExtensions = entry._elements[2]; for (const ext of entryExtensions?._tag === DerTag.Sequence ? (entryExtensions._elements ?? []) : []) { const oid = Bytes.toHex(ext._elements?.[0]?._bytes ?? new Uint8Array()); if (oid === CERTIFICATE_ISSUER_EXTENSION) { // RFC 5280 §5.3.3: critical, naming exactly one directoryName const named = isCritical(ext) ? certificateIssuerOf(ext) : undefined; if (named === undefined) { unsupportedCriticalExtension ??= oid; } else { certificateIssuer = named; } } else if (isCritical(ext) && !KNOWN_CRL_ENTRY_EXTENSIONS.has(oid)) { unsupportedCriticalExtension ??= oid; } } if ( certificateIssuer !== undefined && authorityName !== undefined && !sameName(certificateIssuer, authorityName) ) { continue; } const serialHex = Bytes.toHex(Bytes.of(serialNode._bytes)).toUpperCase(); serials.add(serialHex); } return { serials, issuerDnDerHex, authorityKeyId, tbsDer, signatureAlgorithm, signatureValue, issuingDistributionPointUri, unsupportedCriticalExtension, nextUpdateMs, }; } /** Convenience wrapper that returns only the revoked serial numbers from a CRL. */ static parseCrlRevokedSerials(crlDer: Bytes): Set { return DclCertificateService.parseCrl(crlDer).serials; } } export namespace DclCertificateService { /** Per-call options for certificate retrieval. */ export interface GetCertificateOptions { /** * Whether the lookup should also return test (non-production) certificates. * Defaults to the service-wide `fetchTestCertificates` flag passed at construction. */ considerTestCertificates?: boolean; } export interface Options { /** Whether to fetch test certificates in addition to production ones. Default is false. */ fetchTestCertificates?: boolean; /** * Whether to trust test (non-production) certificates as valid trust anchors. Controls whether a * matched test PAA is accepted during device attestation or flagged via a * `TrustedAsTestCertificate` finding. Independent of `fetchTestCertificates`. Defaults to the value * of `fetchTestCertificates` when not set. */ acceptTestCertificates?: boolean; /** Whether to fetch development certificates from GitHub. Default is true (when fetchTestCertificates is true). */ fetchGithubCertificates?: boolean; /** * Interval for periodic certificate updates. Default is 1 day. Set to null to disable automatic certificate * updates */ updateInterval?: Duration | null; /** Timeout for DCL requests. Default is 5s. */ timeout?: Duration; /** DCL config for production endpoint. Defaults to DclConfig.production. */ dclConfig?: DclConfig; /** DCL config for test endpoint. Defaults to DclConfig.test. */ testDclConfig?: DclConfig; /** GitHub config for development certificates. Programmatic override only. Defaults to DclGithubConfig.defaults. */ githubConfig?: DclGithubConfig; /** * Pre-populate storage from snapshot before the initial network update, which still runs after unless * `offline`. */ seed?: { paaRoots?: SeedSource; cdSigners?: SeedSource; }; /** Revocation information from outside the DCL — see {@link DclCertificateService.installRevocations}. */ revocations?: RevocationSetEntry[]; /** * Reaches no network at all: no update, no CRL, no certificate fetched on demand and no re-fetch of one that * would not parse. The trust store is whatever storage from earlier runs and `seed` carried, revocation is * whatever {@link DclCertificateService.installRevocations} was given, and a certificate neither of those holds * reads as absent. * * For a deployment with no route to the ledger, and for a test that must judge attestation * against a stated PKI rather than against whatever the ledger holds today. */ offline?: boolean; } /** One authority's revoked serial numbers, as a DCL revocation set states them. */ export interface RevocationSetEntry { /** Subject key identifier of the certificate that issued the revoked ones, as hex. */ issuerSubjectKeyId: string; /** * Base64 of the DER-encoded issuer Name. With the key identifier this forms the composite key * revocation is indexed by; an entry without one matches on the key identifier alone. */ issuerName?: string; /** The revoked serial numbers, as hex. */ revokedSerialNumbers: string[]; } /** Kind of certificate stored in the trust store. */ export type CertificateKind = "PAA" | "CDSigner"; /** * Metadata for a stored certificate. */ export type CertificateMetadata = { subject?: string; subjectAsText?: string; subjectKeyId: string; serialNumber: string; vid: number; isRoot: boolean; isProduction: boolean; /** Kind of certificate. Defaults to "PAA" when absent (backward compat). */ kind?: CertificateKind; /** Epoch timestamp (ms) when this certificate was first fetched and added to the local trust store. */ fetchedAt?: number; }; /** Revocation information installed from outside the DCL, as {@link installedRevocations} reports it. */ export interface InstalledRevocation { readonly serials: ReadonlySet; readonly issuerDnDerHex?: string; } /** Cached revocation data for a single AKID. */ export interface RevocationEntry { serials: Set; issuerDnDerHex?: string; } /** Result of parsing a DER-encoded CRL. */ export interface CrlParseResult { /** Revoked serial numbers (uppercase hex). */ serials: Set; /** Hex of the DER-encoded issuer Name, for composite revocation key matching. */ issuerDnDerHex?: string; /** CRL Authority Key Identifier extension value (uppercase hex). */ authorityKeyId?: string; /** Raw DER bytes of tbsCertList for signature verification. */ tbsDer?: Bytes; /** * DER of the CRL's signature AlgorithmIdentifier; absent if it differs from the one inside tbsCertList. */ signatureAlgorithm?: Bytes; /** Raw signature value bytes from the CRL; absent unless it is a BIT STRING without unused bits. */ signatureValue?: Bytes; /** * The single URI of a critical Issuing Distribution Point extension; absent if the extension is missing, not * critical, or names anything but exactly one URI. */ issuingDistributionPointUri?: string; /** * OID (hex) of a critical CRL or CRL entry extension the parser does not support, such as a delta CRL * indicator, or of a certificateIssuer entry extension that is not critical or not a single directoryName; * RFC 5280 §6.3.3 forbids using such a CRL. */ unsupportedCriticalExtension?: string; /** Unix epoch ms of the CRL's nextUpdate field, if present. */ nextUpdateMs?: number; } }