@pagopa/io-react-native-wallet 2.0.0-next.0 → 2.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/lib/commonjs/credential/issuance/02-evaluate-issuer-trust.js +2 -2
  2. package/lib/commonjs/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
  3. package/lib/commonjs/credential/presentation/02-evaluate-rp-trust.js +2 -2
  4. package/lib/commonjs/credential/presentation/02-evaluate-rp-trust.js.map +1 -1
  5. package/lib/commonjs/credential/presentation/05-verify-request-object.js.map +1 -1
  6. package/lib/commonjs/credential/presentation/08-send-authorization-response.js.map +1 -1
  7. package/lib/commonjs/trust/README.md +147 -0
  8. package/lib/commonjs/trust/build-chain.js +252 -0
  9. package/lib/commonjs/trust/build-chain.js.map +1 -0
  10. package/lib/commonjs/trust/errors.js +24 -1
  11. package/lib/commonjs/trust/errors.js.map +1 -1
  12. package/lib/commonjs/trust/index.js +11 -276
  13. package/lib/commonjs/trust/index.js.map +1 -1
  14. package/lib/commonjs/trust/utils.js +30 -1
  15. package/lib/commonjs/trust/utils.js.map +1 -1
  16. package/lib/commonjs/trust/{chain.js → verify-chain.js} +87 -15
  17. package/lib/commonjs/trust/verify-chain.js.map +1 -0
  18. package/lib/commonjs/utils/errors.js.map +1 -1
  19. package/lib/module/credential/issuance/02-evaluate-issuer-trust.js +1 -1
  20. package/lib/module/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
  21. package/lib/module/credential/presentation/02-evaluate-rp-trust.js +1 -1
  22. package/lib/module/credential/presentation/02-evaluate-rp-trust.js.map +1 -1
  23. package/lib/module/credential/presentation/05-verify-request-object.js.map +1 -1
  24. package/lib/module/credential/presentation/08-send-authorization-response.js +1 -1
  25. package/lib/module/credential/presentation/08-send-authorization-response.js.map +1 -1
  26. package/lib/module/trust/README.md +147 -0
  27. package/lib/module/trust/build-chain.js +235 -0
  28. package/lib/module/trust/build-chain.js.map +1 -0
  29. package/lib/module/trust/errors.js +23 -2
  30. package/lib/module/trust/errors.js.map +1 -1
  31. package/lib/module/trust/index.js +5 -262
  32. package/lib/module/trust/index.js.map +1 -1
  33. package/lib/module/trust/utils.js +27 -0
  34. package/lib/module/trust/utils.js.map +1 -1
  35. package/lib/module/trust/{chain.js → verify-chain.js} +85 -14
  36. package/lib/module/trust/verify-chain.js.map +1 -0
  37. package/lib/module/utils/errors.js +1 -1
  38. package/lib/module/utils/errors.js.map +1 -1
  39. package/lib/typescript/credential/issuance/02-evaluate-issuer-trust.d.ts.map +1 -1
  40. package/lib/typescript/credential/presentation/02-evaluate-rp-trust.d.ts.map +1 -1
  41. package/lib/typescript/credential/presentation/05-verify-request-object.d.ts +1 -1
  42. package/lib/typescript/credential/presentation/05-verify-request-object.d.ts.map +1 -1
  43. package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts +2 -2
  44. package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts.map +1 -1
  45. package/lib/typescript/credential/status/types.d.ts +6 -6
  46. package/lib/typescript/sd-jwt/index.d.ts +12 -12
  47. package/lib/typescript/sd-jwt/types.d.ts +6 -6
  48. package/lib/typescript/trust/build-chain.d.ts +1284 -0
  49. package/lib/typescript/trust/build-chain.d.ts.map +1 -0
  50. package/lib/typescript/trust/errors.d.ts +22 -0
  51. package/lib/typescript/trust/errors.d.ts.map +1 -1
  52. package/lib/typescript/trust/index.d.ts +5 -1299
  53. package/lib/typescript/trust/index.d.ts.map +1 -1
  54. package/lib/typescript/trust/types.d.ts +54 -54
  55. package/lib/typescript/trust/utils.d.ts +10 -0
  56. package/lib/typescript/trust/utils.d.ts.map +1 -1
  57. package/lib/typescript/trust/verify-chain.d.ts +39 -0
  58. package/lib/typescript/trust/verify-chain.d.ts.map +1 -0
  59. package/lib/typescript/utils/errors.d.ts +2 -2
  60. package/lib/typescript/utils/errors.d.ts.map +1 -1
  61. package/lib/typescript/wallet-instance-attestation/types.d.ts +21 -21
  62. package/package.json +2 -2
  63. package/src/credential/issuance/02-evaluate-issuer-trust.ts +1 -1
  64. package/src/credential/presentation/02-evaluate-rp-trust.ts +1 -1
  65. package/src/credential/presentation/05-verify-request-object.ts +1 -1
  66. package/src/credential/presentation/08-send-authorization-response.ts +4 -4
  67. package/src/trust/README.md +147 -0
  68. package/src/trust/build-chain.ts +395 -0
  69. package/src/trust/errors.ts +32 -1
  70. package/src/trust/index.ts +5 -435
  71. package/src/trust/utils.ts +35 -0
  72. package/src/trust/{chain.ts → verify-chain.ts} +132 -16
  73. package/src/utils/errors.ts +4 -4
  74. package/lib/commonjs/trust/chain.js.map +0 -1
  75. package/lib/module/trust/chain.js.map +0 -1
  76. package/lib/typescript/trust/chain.d.ts +0 -21
  77. package/lib/typescript/trust/chain.d.ts.map +0 -1
@@ -0,0 +1,147 @@
1
+ # Trust Chain Validation
2
+
3
+ This module implements **Trust Chain validation** for Entity Configurations and Entity Statements in line with the [IT Wallet Federation Specifications](https://italia.github.io/eid-wallet-it-docs/). It ensures that an entity's metadata is trusted by validating a chain of signed JWTs up to a known Trust Anchor.
4
+
5
+ The validation covers:
6
+
7
+ * JWT signature verification (using the next entity's JWKS)
8
+ * Trust chain ordering (leaf → parent → Trust Anchor)
9
+ * Optional X.509 CRL-based certificate validation
10
+
11
+ ## Sequence Diagram
12
+
13
+ ```mermaid
14
+ sequenceDiagram
15
+ autonumber
16
+ participant A as Leaf Entity
17
+ participant B as Intermediate (Federation Authority)
18
+ participant C as Trust Anchor
19
+
20
+ A->>A: Self-issued Entity Configuration (JWT)
21
+ B->>A: Signed Entity Statement (JWT)
22
+ C->>B: Signed Entity Statement (JWT or self-issued EC)
23
+
24
+ Note over A,C: Each JWT is validated with the next issuer's public keys
25
+ ```
26
+
27
+ ## Errors
28
+
29
+ | Error | Description |
30
+ | ----------------------------- | ------------------------------------------------------------------ |
31
+ | `TrustChainEmptyError` | The input chain is empty. |
32
+ | `TrustChainTokenMissingError` | One of the JWTs in the chain is missing. |
33
+ | `X509ValidationError` | X.509 certificate validation failed (e.g. revocation, expiration). |
34
+ | `FederationError` | Generic federation processing error. |
35
+
36
+ ## Usage
37
+
38
+ ### Validate a trust chain
39
+
40
+ ```ts
41
+ import { validateTrustChain } from "./trust";
42
+ import { trustAnchorEntityConfiguration } from "./your-data";
43
+ import { chain } from "./your-data"; // array of JWTs, starting from leaf
44
+
45
+ const result = await validateTrustChain(trustAnchorEntityConfiguration, chain, {
46
+ connectTimeout: 3000,
47
+ readTimeout: 3000,
48
+ requireCrl: false,
49
+ });
50
+ ```
51
+
52
+ * The `chain` must be an array of signed JWT strings.
53
+ * The first JWT must be a self-issued `EntityConfiguration`.
54
+ * The last JWT must be an `EntityStatement` or a self-issued Trust Anchor `EntityConfiguration`.
55
+
56
+ ### Renew a trust chain
57
+
58
+ ```ts
59
+ import { renewTrustChain } from "./trust";
60
+
61
+ const newChain = await renewTrustChain(chain);
62
+ ```
63
+
64
+ This will fetch updated JWTs from each authority in the chain.
65
+
66
+ ### Build a trust chain
67
+
68
+ ```ts
69
+ import { buildTrustChain } from "./trust";
70
+
71
+ const chain = await buildTrustChain({
72
+ leaf: "https://example-leaf",
73
+ trustAnchor: trustAnchorEntityConfiguration,
74
+ });
75
+ ```
76
+
77
+ * **leaf**: the entity URL of the subject to be trusted.
78
+ * **trustAnchor**: the known trust anchor configuration.
79
+ * Returns a list of JWT strings ordered from leaf to trust anchor.
80
+
81
+
82
+ ## Trust Chain Structure
83
+
84
+ | Position | JWT Type | Requirements |
85
+ | -------- | ----------------------------------- |-------------------------------|
86
+ | First | Entity Configuration | `iss === sub` (self-issued) |
87
+ | Middle | Entity Statement | `iss ≠ sub`, signed by parent |
88
+ | Last | Entity Statement or Trust Anchor EC | Trust Anchor must be known |
89
+
90
+ ### Build and Validate Example
91
+
92
+ ```ts
93
+ import {
94
+ buildTrustChain,
95
+ validateTrustChain,
96
+ } from "./trust";
97
+ import { trustAnchorEntityConfiguration } from "./your-data";
98
+
99
+ const chain = await buildTrustChain({
100
+ leaf: "https://example-leaf",
101
+ trustAnchor: trustAnchorEntityConfiguration,
102
+ });
103
+
104
+ const result = await validateTrustChain(trustAnchorEntityConfiguration, chain, {
105
+ connectTimeout: 3000,
106
+ readTimeout: 3000,
107
+ requireCrl: true,
108
+ });
109
+ ```
110
+
111
+ * This example fetches and builds the full trust chain dynamically, then validates it end-to-end.
112
+
113
+ ## Example Trust Chain
114
+
115
+ ```ts
116
+ [
117
+ {
118
+ header: { alg: "ES256", kid: "leaf-kid" },
119
+ payload: { iss: "https://leaf", sub: "https://leaf", jwks: { keys: [...] } }
120
+ },
121
+ {
122
+ header: { alg: "ES256", kid: "intermediate-kid" },
123
+ payload: { iss: "https://intermediate", sub: "https://leaf", jwks: { keys: [...] } }
124
+ },
125
+ {
126
+ header: { alg: "ES256", kid: "ta-kid" },
127
+ payload: { iss: "https://ta", sub: "https://ta", jwks: { keys: [...] } }
128
+ }
129
+ ]
130
+ ```
131
+
132
+ ## Mocking in Tests
133
+
134
+ If you're testing in Node (not in React Native), you need to mock X.509 and crypto-native dependencies:
135
+
136
+ ```ts
137
+ jest.mock("@pagopa/io-react-native-crypto", () => ({
138
+ verifyCertificateChain: jest.fn().mockResolvedValue({
139
+ isValid: true,
140
+ validationStatus: "VALID",
141
+ errorMessage: undefined,
142
+ }),
143
+ generate: jest.fn().mockResolvedValue({ ... }),
144
+ }));
145
+ ```
146
+
147
+ Ensure mocked `JWK`s contain an `x5c` array to trigger certificate validation logic during tests.
@@ -0,0 +1,395 @@
1
+ import type { JWK } from "../utils/jwk";
2
+ import {
3
+ BuildTrustChainError,
4
+ FederationListParseError,
5
+ MissingFederationFetchEndpointError,
6
+ RelyingPartyNotAuthorizedError,
7
+ TrustAnchorKidMissingError,
8
+ } from "./errors";
9
+ import { decode, verify } from "./utils";
10
+ import {
11
+ CredentialIssuerEntityConfiguration,
12
+ EntityConfiguration,
13
+ EntityStatement,
14
+ FederationListResponse,
15
+ RelyingPartyEntityConfiguration,
16
+ TrustAnchorEntityConfiguration,
17
+ WalletProviderEntityConfiguration,
18
+ } from "./types";
19
+ import { hasStatusOrThrow } from "../utils/misc";
20
+ import { decode as decodeJwt } from "@pagopa/io-react-native-jwt";
21
+
22
+ /**
23
+ * Fetch and parse the entity configuration document for a given federation entity.
24
+ * This is an inner method to serve public interfaces.
25
+ *
26
+ * To add another entity configuration type (example: Foo entity type):
27
+ * - create its zod schema and type by inherit from the base type (example: FooEntityConfiguration = BaseEntityConfiguration.and(...))
28
+ * - add such type to EntityConfiguration union
29
+ * - add an overload to this function
30
+ * - create a public function which use such type (example: getFooEntityConfiguration = (url, options) => Promise<FooEntityConfiguration>)
31
+ *
32
+ * @param entityBaseUrl The base url of the entity.
33
+ * @param schema The expected schema of the entity configuration, according to the kind of entity we are fetching from.
34
+ * @param options An optional object with additional options.
35
+ * @param options.appFetch An optional instance of the http client to be used.
36
+ * @returns The parsed entity configuration object
37
+ * @throws {IoWalletError} If the http request fails
38
+ * @throws Parse error if the document is not in the expected shape.
39
+ */
40
+ async function fetchAndParseEntityConfiguration(
41
+ entityBaseUrl: string,
42
+ schema: typeof WalletProviderEntityConfiguration,
43
+ options?: {
44
+ appFetch?: GlobalFetch["fetch"];
45
+ }
46
+ ): Promise<WalletProviderEntityConfiguration>;
47
+ async function fetchAndParseEntityConfiguration(
48
+ entityBaseUrl: string,
49
+ schema: typeof RelyingPartyEntityConfiguration,
50
+ options?: {
51
+ appFetch?: GlobalFetch["fetch"];
52
+ }
53
+ ): Promise<RelyingPartyEntityConfiguration>;
54
+ async function fetchAndParseEntityConfiguration(
55
+ entityBaseUrl: string,
56
+ schema: typeof TrustAnchorEntityConfiguration,
57
+ options?: {
58
+ appFetch?: GlobalFetch["fetch"];
59
+ }
60
+ ): Promise<TrustAnchorEntityConfiguration>;
61
+ async function fetchAndParseEntityConfiguration(
62
+ entityBaseUrl: string,
63
+ schema: typeof CredentialIssuerEntityConfiguration,
64
+ options?: {
65
+ appFetch?: GlobalFetch["fetch"];
66
+ }
67
+ ): Promise<CredentialIssuerEntityConfiguration>;
68
+ async function fetchAndParseEntityConfiguration(
69
+ entityBaseUrl: string,
70
+ schema: typeof EntityConfiguration,
71
+ options?: {
72
+ appFetch?: GlobalFetch["fetch"];
73
+ }
74
+ ): Promise<EntityConfiguration>;
75
+ async function fetchAndParseEntityConfiguration(
76
+ entityBaseUrl: string,
77
+ schema: /* FIXME: why is it different from "typeof EntityConfiguration"? */
78
+ | typeof CredentialIssuerEntityConfiguration
79
+ | typeof WalletProviderEntityConfiguration
80
+ | typeof RelyingPartyEntityConfiguration
81
+ | typeof TrustAnchorEntityConfiguration
82
+ | typeof EntityConfiguration,
83
+ {
84
+ appFetch = fetch,
85
+ }: {
86
+ appFetch?: GlobalFetch["fetch"];
87
+ } = {}
88
+ ) {
89
+ const responseText = await getSignedEntityConfiguration(entityBaseUrl, {
90
+ appFetch,
91
+ });
92
+
93
+ const responseJwt = decodeJwt(responseText);
94
+ return schema.parse({
95
+ header: responseJwt.protectedHeader,
96
+ payload: responseJwt.payload,
97
+ });
98
+ }
99
+
100
+ export const getWalletProviderEntityConfiguration = (
101
+ entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
102
+ options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
103
+ ) =>
104
+ fetchAndParseEntityConfiguration(
105
+ entityBaseUrl,
106
+ WalletProviderEntityConfiguration,
107
+ options
108
+ );
109
+
110
+ export const getCredentialIssuerEntityConfiguration = (
111
+ entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
112
+ options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
113
+ ) =>
114
+ fetchAndParseEntityConfiguration(
115
+ entityBaseUrl,
116
+ CredentialIssuerEntityConfiguration,
117
+ options
118
+ );
119
+
120
+ export const getTrustAnchorEntityConfiguration = (
121
+ entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
122
+ options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
123
+ ) =>
124
+ fetchAndParseEntityConfiguration(
125
+ entityBaseUrl,
126
+ TrustAnchorEntityConfiguration,
127
+ options
128
+ );
129
+
130
+ export const getRelyingPartyEntityConfiguration = (
131
+ entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
132
+ options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
133
+ ) =>
134
+ fetchAndParseEntityConfiguration(
135
+ entityBaseUrl,
136
+ RelyingPartyEntityConfiguration,
137
+ options
138
+ );
139
+
140
+ export const getEntityConfiguration = (
141
+ entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
142
+ options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
143
+ ) =>
144
+ fetchAndParseEntityConfiguration(entityBaseUrl, EntityConfiguration, options);
145
+
146
+ /**
147
+ * Fetch and parse the entity statement document for a given federation entity.
148
+ *
149
+ * @param accreditationBodyBaseUrl The base url of the accreditation body which holds and signs the required entity statement
150
+ * @param subordinatedEntityBaseUrl The url that identifies the subordinate entity
151
+ * @param appFetch An optional instance of the http client to be used.
152
+ * @returns The parsed entity configuration object
153
+ * @throws {IoWalletError} If the http request fails
154
+ */
155
+ export async function getEntityStatement(
156
+ accreditationBodyBaseUrl: string,
157
+ subordinatedEntityBaseUrl: string,
158
+ {
159
+ appFetch = fetch,
160
+ }: {
161
+ appFetch?: GlobalFetch["fetch"];
162
+ } = {}
163
+ ) {
164
+ const responseText = await getSignedEntityStatement(
165
+ accreditationBodyBaseUrl,
166
+ subordinatedEntityBaseUrl,
167
+ {
168
+ appFetch,
169
+ }
170
+ );
171
+
172
+ const responseJwt = decodeJwt(responseText);
173
+ return EntityStatement.parse({
174
+ header: responseJwt.protectedHeader,
175
+ payload: responseJwt.payload,
176
+ });
177
+ }
178
+
179
+ /**
180
+ * Fetch the signed entity configuration token for an entity
181
+ *
182
+ * @param entityBaseUrl The url of the entity to fetch
183
+ * @param appFetch (optional) fetch api implementation
184
+ * @returns The signed Entity Configuration token
185
+ */
186
+ export async function getSignedEntityConfiguration(
187
+ entityBaseUrl: string,
188
+ {
189
+ appFetch = fetch,
190
+ }: {
191
+ appFetch?: GlobalFetch["fetch"];
192
+ } = {}
193
+ ): Promise<string> {
194
+ const wellKnownUrl = `${entityBaseUrl}/.well-known/openid-federation`;
195
+
196
+ return await appFetch(wellKnownUrl, {
197
+ method: "GET",
198
+ })
199
+ .then(hasStatusOrThrow(200))
200
+ .then((res) => res.text());
201
+ }
202
+
203
+ /**
204
+ * Fetch the entity statement document for a given federation entity.
205
+ *
206
+ * @param federationFetchEndpoint The exact endpoint provided by the parent EC's metadata.
207
+ * @param subordinatedEntityBaseUrl The url that identifies the subordinate entity.
208
+ * @param appFetch An optional instance of the http client to be used.
209
+ * @returns The signed entity statement token.
210
+ * @throws {IoWalletError} If the http request fails.
211
+ */
212
+ export async function getSignedEntityStatement(
213
+ federationFetchEndpoint: string,
214
+ subordinatedEntityBaseUrl: string,
215
+ {
216
+ appFetch = fetch,
217
+ }: {
218
+ appFetch?: GlobalFetch["fetch"];
219
+ } = {}
220
+ ) {
221
+ const url = new URL(federationFetchEndpoint);
222
+ url.searchParams.set("sub", subordinatedEntityBaseUrl);
223
+
224
+ return await appFetch(url.toString(), {
225
+ method: "GET",
226
+ })
227
+ .then(hasStatusOrThrow(200))
228
+ .then((res) => res.text());
229
+ }
230
+
231
+ /**
232
+ * Fetch the federation list document from a given endpoint.
233
+ *
234
+ * @param federationListEndpoint The URL of the federation list endpoint.
235
+ * @param appFetch An optional instance of the http client to be used.
236
+ * @returns The federation list as an array of strings.
237
+ * @throws {IoWalletError} If the HTTP request fails.
238
+ * @throws {FederationError} If the result is not in the expected format.
239
+ */
240
+ export async function getFederationList(
241
+ federationListEndpoint: string,
242
+ {
243
+ appFetch = fetch,
244
+ }: {
245
+ appFetch?: GlobalFetch["fetch"];
246
+ } = {}
247
+ ): Promise<string[]> {
248
+ return await appFetch(federationListEndpoint, {
249
+ method: "GET",
250
+ })
251
+ .then(hasStatusOrThrow(200))
252
+ .then((res) => res.json())
253
+ .then((json) => {
254
+ const result = FederationListResponse.safeParse(json);
255
+ if (!result.success) {
256
+ throw new FederationListParseError(
257
+ `Invalid federation list format received from ${federationListEndpoint}. Error: ${result.error.message}`,
258
+ { url: federationListEndpoint, parseError: result.error.toString() }
259
+ );
260
+ }
261
+ return result.data;
262
+ });
263
+ }
264
+
265
+ /**
266
+ * Build a not-verified trust chain for a given Relying Party (RP) entity.
267
+ *
268
+ * @param relyingPartyEntityBaseUrl The base URL of the RP entity
269
+ * @param trustAnchorKey The public key of the Trust Anchor (TA) entity
270
+ * @param appFetch An optional instance of the http client to be used.
271
+ * @returns A list of signed tokens that represent the trust chain, in the order of the chain (from the RP to the Trust Anchor)
272
+ * @throws {FederationError} When an element of the chain fails to parse or other build steps fail.
273
+ */
274
+ export async function buildTrustChain(
275
+ relyingPartyEntityBaseUrl: string,
276
+ trustAnchorKey: JWK,
277
+ appFetch: GlobalFetch["fetch"] = fetch
278
+ ): Promise<string[]> {
279
+ // 1: Recursively gather the trust chain from the RP up to the Trust Anchor
280
+ const trustChain = await gatherTrustChain(
281
+ relyingPartyEntityBaseUrl,
282
+ appFetch
283
+ );
284
+
285
+ // 2: Trust Anchor signature verification
286
+ const trustAnchorJwt = trustChain[trustChain.length - 1];
287
+ if (!trustAnchorJwt) {
288
+ throw new BuildTrustChainError(
289
+ "Cannot verify trust anchor: missing entity configuration in gathered chain.",
290
+ { relyingPartyUrl: relyingPartyEntityBaseUrl }
291
+ );
292
+ }
293
+
294
+ if (!trustAnchorKey.kid) {
295
+ throw new TrustAnchorKidMissingError();
296
+ }
297
+
298
+ await verify(trustAnchorJwt, trustAnchorKey.kid, [trustAnchorKey]);
299
+
300
+ // 3: Check the federation list
301
+ const trustAnchorConfig = EntityConfiguration.parse(decode(trustAnchorJwt));
302
+ const federationListEndpoint =
303
+ trustAnchorConfig.payload.metadata.federation_entity
304
+ .federation_list_endpoint;
305
+
306
+ if (federationListEndpoint) {
307
+ const federationList = await getFederationList(federationListEndpoint, {
308
+ appFetch,
309
+ });
310
+
311
+ if (!federationList.includes(relyingPartyEntityBaseUrl)) {
312
+ throw new RelyingPartyNotAuthorizedError(
313
+ "Relying Party entity base URL is not authorized by the Trust Anchor's federation list.",
314
+ { relyingPartyUrl: relyingPartyEntityBaseUrl, federationListEndpoint }
315
+ );
316
+ }
317
+ }
318
+
319
+ return trustChain;
320
+ }
321
+
322
+ /**
323
+ * Recursively gather the trust chain for an entity and all its superiors.
324
+ * @param entityBaseUrl The base URL of the entity for which to gather the chain.
325
+ * @param appFetch An optional instance of the http client to be used.
326
+ * @param isLeaf Whether the current entity is the leaf of the chain.
327
+ * @returns A full ordered list of JWTs (ECs and ESs) forming the trust chain.
328
+ * @throws {FederationError} If any of the fetched documents fail to parse or other errors occur during the gathering process.
329
+ */
330
+ async function gatherTrustChain(
331
+ entityBaseUrl: string,
332
+ appFetch: GlobalFetch["fetch"],
333
+ isLeaf: boolean = true
334
+ ): Promise<string[]> {
335
+ const chain: string[] = [];
336
+
337
+ // Fetch self-signed EC (only needed for the leaf)
338
+ const entityECJwt = await getSignedEntityConfiguration(entityBaseUrl, {
339
+ appFetch,
340
+ });
341
+ const entityEC = EntityConfiguration.parse(decode(entityECJwt));
342
+
343
+ if (isLeaf) {
344
+ // Only push EC for the leaf
345
+ chain.push(entityECJwt);
346
+ }
347
+
348
+ // Find authority_hints (parent, if any)
349
+ const authorityHints = entityEC.payload.authority_hints ?? [];
350
+ if (authorityHints.length === 0) {
351
+ // This is the Trust Anchor (no parent)
352
+ if (!isLeaf) {
353
+ chain.push(entityECJwt);
354
+ }
355
+ return chain;
356
+ }
357
+
358
+ const parentEntityBaseUrl = authorityHints[0]!;
359
+
360
+ // Fetch parent EC
361
+ const parentECJwt = await getSignedEntityConfiguration(parentEntityBaseUrl, {
362
+ appFetch,
363
+ });
364
+ const parentEC = EntityConfiguration.parse(decode(parentECJwt));
365
+
366
+ // Fetch ES
367
+ const federationFetchEndpoint =
368
+ parentEC.payload.metadata.federation_entity.federation_fetch_endpoint;
369
+ if (!federationFetchEndpoint) {
370
+ throw new MissingFederationFetchEndpointError(
371
+ `Missing federation_fetch_endpoint in parent's (${parentEntityBaseUrl}) configuration when gathering chain for ${entityBaseUrl}.`,
372
+ { entityBaseUrl, missingInEntityUrl: parentEntityBaseUrl }
373
+ );
374
+ }
375
+
376
+ const entityStatementJwt = await getSignedEntityStatement(
377
+ federationFetchEndpoint,
378
+ entityBaseUrl,
379
+ { appFetch }
380
+ );
381
+ // Validate the ES
382
+ EntityStatement.parse(decode(entityStatementJwt));
383
+
384
+ // Push this ES into the chain
385
+ chain.push(entityStatementJwt);
386
+
387
+ // Recurse into the parent
388
+ const parentChain = await gatherTrustChain(
389
+ parentEntityBaseUrl,
390
+ appFetch,
391
+ false
392
+ );
393
+
394
+ return chain.concat(parentChain);
395
+ }
@@ -1,4 +1,5 @@
1
- import { IoWalletError, serializeAttrs } from "../utils/errors"; // Ensure this path is correct
1
+ import { IoWalletError, serializeAttrs } from "../utils/errors";
2
+ import type { CertificateValidationStatus } from "@pagopa/io-react-native-crypto"; // Ensure this path is correct
2
3
 
3
4
  /**
4
5
  * Base class for all federation-specific errors.
@@ -103,3 +104,33 @@ export class MissingFederationFetchEndpointError extends FederationError {
103
104
  super(message, details);
104
105
  }
105
106
  }
107
+
108
+ /**
109
+ * Error thrown when the X.509 certificate chain is missing in an entity's configuration.
110
+ */
111
+ export class MissingX509CertsError extends FederationError {
112
+ code = "ERR_FED_MISSING_X509_CERTS";
113
+ constructor(message: string) {
114
+ super(message, undefined);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Error thrown when an X.509 certificate validation fails.
120
+ * This is used to indicate issues with the certificate chain or signature verification.
121
+ */
122
+ export class X509ValidationError extends FederationError {
123
+ code = "ERR_FED_X509_VALIDATION_FAILED";
124
+ constructor(
125
+ message: string,
126
+ details?: {
127
+ tokenIndex?: number;
128
+ kid?: string;
129
+ x509ValidationStatus?: CertificateValidationStatus;
130
+ x509ErrorMessage?: string;
131
+ [key: string]: unknown;
132
+ }
133
+ ) {
134
+ super(message, details);
135
+ }
136
+ }