@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.
- package/lib/commonjs/credential/issuance/02-evaluate-issuer-trust.js +2 -2
- package/lib/commonjs/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
- package/lib/commonjs/credential/presentation/02-evaluate-rp-trust.js +2 -2
- package/lib/commonjs/credential/presentation/02-evaluate-rp-trust.js.map +1 -1
- package/lib/commonjs/credential/presentation/05-verify-request-object.js.map +1 -1
- package/lib/commonjs/credential/presentation/08-send-authorization-response.js.map +1 -1
- package/lib/commonjs/trust/README.md +147 -0
- package/lib/commonjs/trust/build-chain.js +252 -0
- package/lib/commonjs/trust/build-chain.js.map +1 -0
- package/lib/commonjs/trust/errors.js +24 -1
- package/lib/commonjs/trust/errors.js.map +1 -1
- package/lib/commonjs/trust/index.js +11 -276
- package/lib/commonjs/trust/index.js.map +1 -1
- package/lib/commonjs/trust/utils.js +30 -1
- package/lib/commonjs/trust/utils.js.map +1 -1
- package/lib/commonjs/trust/{chain.js → verify-chain.js} +87 -15
- package/lib/commonjs/trust/verify-chain.js.map +1 -0
- package/lib/commonjs/utils/errors.js.map +1 -1
- package/lib/module/credential/issuance/02-evaluate-issuer-trust.js +1 -1
- package/lib/module/credential/issuance/02-evaluate-issuer-trust.js.map +1 -1
- package/lib/module/credential/presentation/02-evaluate-rp-trust.js +1 -1
- package/lib/module/credential/presentation/02-evaluate-rp-trust.js.map +1 -1
- package/lib/module/credential/presentation/05-verify-request-object.js.map +1 -1
- package/lib/module/credential/presentation/08-send-authorization-response.js +1 -1
- package/lib/module/credential/presentation/08-send-authorization-response.js.map +1 -1
- package/lib/module/trust/README.md +147 -0
- package/lib/module/trust/build-chain.js +235 -0
- package/lib/module/trust/build-chain.js.map +1 -0
- package/lib/module/trust/errors.js +23 -2
- package/lib/module/trust/errors.js.map +1 -1
- package/lib/module/trust/index.js +5 -262
- package/lib/module/trust/index.js.map +1 -1
- package/lib/module/trust/utils.js +27 -0
- package/lib/module/trust/utils.js.map +1 -1
- package/lib/module/trust/{chain.js → verify-chain.js} +85 -14
- package/lib/module/trust/verify-chain.js.map +1 -0
- package/lib/module/utils/errors.js +1 -1
- package/lib/module/utils/errors.js.map +1 -1
- package/lib/typescript/credential/issuance/02-evaluate-issuer-trust.d.ts.map +1 -1
- package/lib/typescript/credential/presentation/02-evaluate-rp-trust.d.ts.map +1 -1
- package/lib/typescript/credential/presentation/05-verify-request-object.d.ts +1 -1
- package/lib/typescript/credential/presentation/05-verify-request-object.d.ts.map +1 -1
- package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts +2 -2
- package/lib/typescript/credential/presentation/08-send-authorization-response.d.ts.map +1 -1
- package/lib/typescript/credential/status/types.d.ts +6 -6
- package/lib/typescript/sd-jwt/index.d.ts +12 -12
- package/lib/typescript/sd-jwt/types.d.ts +6 -6
- package/lib/typescript/trust/build-chain.d.ts +1284 -0
- package/lib/typescript/trust/build-chain.d.ts.map +1 -0
- package/lib/typescript/trust/errors.d.ts +22 -0
- package/lib/typescript/trust/errors.d.ts.map +1 -1
- package/lib/typescript/trust/index.d.ts +5 -1299
- package/lib/typescript/trust/index.d.ts.map +1 -1
- package/lib/typescript/trust/types.d.ts +54 -54
- package/lib/typescript/trust/utils.d.ts +10 -0
- package/lib/typescript/trust/utils.d.ts.map +1 -1
- package/lib/typescript/trust/verify-chain.d.ts +39 -0
- package/lib/typescript/trust/verify-chain.d.ts.map +1 -0
- package/lib/typescript/utils/errors.d.ts +2 -2
- package/lib/typescript/utils/errors.d.ts.map +1 -1
- package/lib/typescript/wallet-instance-attestation/types.d.ts +21 -21
- package/package.json +2 -2
- package/src/credential/issuance/02-evaluate-issuer-trust.ts +1 -1
- package/src/credential/presentation/02-evaluate-rp-trust.ts +1 -1
- package/src/credential/presentation/05-verify-request-object.ts +1 -1
- package/src/credential/presentation/08-send-authorization-response.ts +4 -4
- package/src/trust/README.md +147 -0
- package/src/trust/build-chain.ts +395 -0
- package/src/trust/errors.ts +32 -1
- package/src/trust/index.ts +5 -435
- package/src/trust/utils.ts +35 -0
- package/src/trust/{chain.ts → verify-chain.ts} +132 -16
- package/src/utils/errors.ts +4 -4
- package/lib/commonjs/trust/chain.js.map +0 -1
- package/lib/module/trust/chain.js.map +0 -1
- package/lib/typescript/trust/chain.d.ts +0 -21
- package/lib/typescript/trust/chain.d.ts.map +0 -1
package/src/trust/index.ts
CHANGED
@@ -1,436 +1,6 @@
|
|
1
|
-
import
|
2
|
-
import
|
3
|
-
import
|
4
|
-
|
5
|
-
EntityConfiguration,
|
6
|
-
EntityStatement,
|
7
|
-
FederationListResponse,
|
8
|
-
RelyingPartyEntityConfiguration,
|
9
|
-
TrustAnchorEntityConfiguration,
|
10
|
-
WalletProviderEntityConfiguration,
|
11
|
-
} from "./types";
|
12
|
-
import { renewTrustChain, validateTrustChain } from "./chain";
|
13
|
-
import { hasStatusOrThrow } from "../utils/misc";
|
14
|
-
import type { JWK } from "../utils/jwk";
|
15
|
-
import {
|
16
|
-
BuildTrustChainError,
|
17
|
-
FederationListParseError,
|
18
|
-
MissingFederationFetchEndpointError,
|
19
|
-
RelyingPartyNotAuthorizedError,
|
20
|
-
TrustAnchorKidMissingError,
|
21
|
-
} from "./errors";
|
1
|
+
import * as Build from "./build-chain";
|
2
|
+
import * as Verify from "./verify-chain";
|
3
|
+
import * as Errors from "./errors";
|
4
|
+
import * as Types from "./types";
|
22
5
|
|
23
|
-
export
|
24
|
-
WalletProviderEntityConfiguration,
|
25
|
-
TrustAnchorEntityConfiguration,
|
26
|
-
CredentialIssuerEntityConfiguration,
|
27
|
-
RelyingPartyEntityConfiguration,
|
28
|
-
EntityConfiguration,
|
29
|
-
EntityStatement,
|
30
|
-
};
|
31
|
-
|
32
|
-
/**
|
33
|
-
* Verify a given trust chain is actually valid.
|
34
|
-
* It can handle fast chain renewal, which means we try to fetch a fresh version of each statement.
|
35
|
-
*
|
36
|
-
* @param trustAnchorEntity The entity configuration of the known trust anchor
|
37
|
-
* @param chain The chain of statements to be validated
|
38
|
-
* @param renewOnFail Whether to renew the provided chain if the validation fails at first. Default: true
|
39
|
-
* @param appFetch Fetch api implementation. Default: the built-in implementation
|
40
|
-
* @returns The result of the chain validation
|
41
|
-
* @throws {FederationError} If the chain is not valid
|
42
|
-
*/
|
43
|
-
export async function verifyTrustChain(
|
44
|
-
trustAnchorEntity: TrustAnchorEntityConfiguration,
|
45
|
-
chain: string[],
|
46
|
-
{
|
47
|
-
appFetch = fetch,
|
48
|
-
renewOnFail = true,
|
49
|
-
}: { appFetch?: GlobalFetch["fetch"]; renewOnFail?: boolean } = {}
|
50
|
-
): Promise<ReturnType<typeof validateTrustChain>> {
|
51
|
-
try {
|
52
|
-
return validateTrustChain(trustAnchorEntity, chain);
|
53
|
-
} catch (error) {
|
54
|
-
if (renewOnFail) {
|
55
|
-
const renewedChain = await renewTrustChain(chain, appFetch);
|
56
|
-
return validateTrustChain(trustAnchorEntity, renewedChain);
|
57
|
-
} else {
|
58
|
-
throw error;
|
59
|
-
}
|
60
|
-
}
|
61
|
-
}
|
62
|
-
|
63
|
-
/**
|
64
|
-
* Fetch the signed entity configuration token for an entity
|
65
|
-
*
|
66
|
-
* @param entityBaseUrl The url of the entity to fetch
|
67
|
-
* @param appFetch (optional) fetch api implementation
|
68
|
-
* @returns The signed Entity Configuration token
|
69
|
-
*/
|
70
|
-
export async function getSignedEntityConfiguration(
|
71
|
-
entityBaseUrl: string,
|
72
|
-
{
|
73
|
-
appFetch = fetch,
|
74
|
-
}: {
|
75
|
-
appFetch?: GlobalFetch["fetch"];
|
76
|
-
} = {}
|
77
|
-
): Promise<string> {
|
78
|
-
const wellKnownUrl = `${entityBaseUrl}/.well-known/openid-federation`;
|
79
|
-
|
80
|
-
return await appFetch(wellKnownUrl, {
|
81
|
-
method: "GET",
|
82
|
-
})
|
83
|
-
.then(hasStatusOrThrow(200))
|
84
|
-
.then((res) => res.text());
|
85
|
-
}
|
86
|
-
|
87
|
-
/**
|
88
|
-
* Fetch and parse the entity configuration document for a given federation entity.
|
89
|
-
* This is an inner method to serve public interfaces.
|
90
|
-
*
|
91
|
-
* To add another entity configuration type (example: Foo entity type):
|
92
|
-
* - create its zod schema and type by inherit from the base type (example: FooEntityConfiguration = BaseEntityConfiguration.and(...))
|
93
|
-
* - add such type to EntityConfiguration union
|
94
|
-
* - add an overload to this function
|
95
|
-
* - create a public function which use such type (example: getFooEntityConfiguration = (url, options) => Promise<FooEntityConfiguration>)
|
96
|
-
*
|
97
|
-
* @param entityBaseUrl The base url of the entity.
|
98
|
-
* @param schema The expected schema of the entity configuration, according to the kind of entity we are fetching from.
|
99
|
-
* @param options An optional object with additional options.
|
100
|
-
* @param options.appFetch An optional instance of the http client to be used.
|
101
|
-
* @returns The parsed entity configuration object
|
102
|
-
* @throws {IoWalletError} If the http request fails
|
103
|
-
* @throws Parse error if the document is not in the expected shape.
|
104
|
-
*/
|
105
|
-
async function fetchAndParseEntityConfiguration(
|
106
|
-
entityBaseUrl: string,
|
107
|
-
schema: typeof WalletProviderEntityConfiguration,
|
108
|
-
options?: {
|
109
|
-
appFetch?: GlobalFetch["fetch"];
|
110
|
-
}
|
111
|
-
): Promise<WalletProviderEntityConfiguration>;
|
112
|
-
async function fetchAndParseEntityConfiguration(
|
113
|
-
entityBaseUrl: string,
|
114
|
-
schema: typeof RelyingPartyEntityConfiguration,
|
115
|
-
options?: {
|
116
|
-
appFetch?: GlobalFetch["fetch"];
|
117
|
-
}
|
118
|
-
): Promise<RelyingPartyEntityConfiguration>;
|
119
|
-
async function fetchAndParseEntityConfiguration(
|
120
|
-
entityBaseUrl: string,
|
121
|
-
schema: typeof TrustAnchorEntityConfiguration,
|
122
|
-
options?: {
|
123
|
-
appFetch?: GlobalFetch["fetch"];
|
124
|
-
}
|
125
|
-
): Promise<TrustAnchorEntityConfiguration>;
|
126
|
-
async function fetchAndParseEntityConfiguration(
|
127
|
-
entityBaseUrl: string,
|
128
|
-
schema: typeof CredentialIssuerEntityConfiguration,
|
129
|
-
options?: {
|
130
|
-
appFetch?: GlobalFetch["fetch"];
|
131
|
-
}
|
132
|
-
): Promise<CredentialIssuerEntityConfiguration>;
|
133
|
-
async function fetchAndParseEntityConfiguration(
|
134
|
-
entityBaseUrl: string,
|
135
|
-
schema: typeof EntityConfiguration,
|
136
|
-
options?: {
|
137
|
-
appFetch?: GlobalFetch["fetch"];
|
138
|
-
}
|
139
|
-
): Promise<EntityConfiguration>;
|
140
|
-
async function fetchAndParseEntityConfiguration(
|
141
|
-
entityBaseUrl: string,
|
142
|
-
schema: /* FIXME: why is it different from "typeof EntityConfiguration"? */
|
143
|
-
| typeof CredentialIssuerEntityConfiguration
|
144
|
-
| typeof WalletProviderEntityConfiguration
|
145
|
-
| typeof RelyingPartyEntityConfiguration
|
146
|
-
| typeof TrustAnchorEntityConfiguration
|
147
|
-
| typeof EntityConfiguration,
|
148
|
-
{
|
149
|
-
appFetch = fetch,
|
150
|
-
}: {
|
151
|
-
appFetch?: GlobalFetch["fetch"];
|
152
|
-
} = {}
|
153
|
-
) {
|
154
|
-
const responseText = await getSignedEntityConfiguration(entityBaseUrl, {
|
155
|
-
appFetch,
|
156
|
-
});
|
157
|
-
|
158
|
-
const responseJwt = decodeJwt(responseText);
|
159
|
-
return schema.parse({
|
160
|
-
header: responseJwt.protectedHeader,
|
161
|
-
payload: responseJwt.payload,
|
162
|
-
});
|
163
|
-
}
|
164
|
-
|
165
|
-
export const getWalletProviderEntityConfiguration = (
|
166
|
-
entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
|
167
|
-
options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
|
168
|
-
) =>
|
169
|
-
fetchAndParseEntityConfiguration(
|
170
|
-
entityBaseUrl,
|
171
|
-
WalletProviderEntityConfiguration,
|
172
|
-
options
|
173
|
-
);
|
174
|
-
|
175
|
-
export const getCredentialIssuerEntityConfiguration = (
|
176
|
-
entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
|
177
|
-
options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
|
178
|
-
) =>
|
179
|
-
fetchAndParseEntityConfiguration(
|
180
|
-
entityBaseUrl,
|
181
|
-
CredentialIssuerEntityConfiguration,
|
182
|
-
options
|
183
|
-
);
|
184
|
-
|
185
|
-
export const getTrustAnchorEntityConfiguration = (
|
186
|
-
entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
|
187
|
-
options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
|
188
|
-
) =>
|
189
|
-
fetchAndParseEntityConfiguration(
|
190
|
-
entityBaseUrl,
|
191
|
-
TrustAnchorEntityConfiguration,
|
192
|
-
options
|
193
|
-
);
|
194
|
-
|
195
|
-
export const getRelyingPartyEntityConfiguration = (
|
196
|
-
entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
|
197
|
-
options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
|
198
|
-
) =>
|
199
|
-
fetchAndParseEntityConfiguration(
|
200
|
-
entityBaseUrl,
|
201
|
-
RelyingPartyEntityConfiguration,
|
202
|
-
options
|
203
|
-
);
|
204
|
-
|
205
|
-
export const getEntityConfiguration = (
|
206
|
-
entityBaseUrl: Parameters<typeof fetchAndParseEntityConfiguration>[0],
|
207
|
-
options?: Parameters<typeof fetchAndParseEntityConfiguration>[2]
|
208
|
-
) =>
|
209
|
-
fetchAndParseEntityConfiguration(entityBaseUrl, EntityConfiguration, options);
|
210
|
-
|
211
|
-
/**
|
212
|
-
* Fetch and parse the entity statement document for a given federation entity.
|
213
|
-
*
|
214
|
-
* @param accreditationBodyBaseUrl The base url of the accreditation body which holds and signs the required entity statement
|
215
|
-
* @param subordinatedEntityBaseUrl The url that identifies the subordinate entity
|
216
|
-
* @param appFetch An optional instance of the http client to be used.
|
217
|
-
* @returns The parsed entity configuration object
|
218
|
-
* @throws {IoWalletError} If the http request fails
|
219
|
-
*/
|
220
|
-
export async function getEntityStatement(
|
221
|
-
accreditationBodyBaseUrl: string,
|
222
|
-
subordinatedEntityBaseUrl: string,
|
223
|
-
{
|
224
|
-
appFetch = fetch,
|
225
|
-
}: {
|
226
|
-
appFetch?: GlobalFetch["fetch"];
|
227
|
-
} = {}
|
228
|
-
) {
|
229
|
-
const responseText = await getSignedEntityStatement(
|
230
|
-
accreditationBodyBaseUrl,
|
231
|
-
subordinatedEntityBaseUrl,
|
232
|
-
{
|
233
|
-
appFetch,
|
234
|
-
}
|
235
|
-
);
|
236
|
-
|
237
|
-
const responseJwt = decodeJwt(responseText);
|
238
|
-
return EntityStatement.parse({
|
239
|
-
header: responseJwt.protectedHeader,
|
240
|
-
payload: responseJwt.payload,
|
241
|
-
});
|
242
|
-
}
|
243
|
-
|
244
|
-
/**
|
245
|
-
* Fetch the entity statement document for a given federation entity.
|
246
|
-
*
|
247
|
-
* @param federationFetchEndpoint The exact endpoint provided by the parent EC's metadata.
|
248
|
-
* @param subordinatedEntityBaseUrl The url that identifies the subordinate entity.
|
249
|
-
* @param appFetch An optional instance of the http client to be used.
|
250
|
-
* @returns The signed entity statement token.
|
251
|
-
* @throws {IoWalletError} If the http request fails.
|
252
|
-
*/
|
253
|
-
export async function getSignedEntityStatement(
|
254
|
-
federationFetchEndpoint: string,
|
255
|
-
subordinatedEntityBaseUrl: string,
|
256
|
-
{
|
257
|
-
appFetch = fetch,
|
258
|
-
}: {
|
259
|
-
appFetch?: GlobalFetch["fetch"];
|
260
|
-
} = {}
|
261
|
-
) {
|
262
|
-
const url = new URL(federationFetchEndpoint);
|
263
|
-
url.searchParams.set("sub", subordinatedEntityBaseUrl);
|
264
|
-
|
265
|
-
return await appFetch(url.toString(), {
|
266
|
-
method: "GET",
|
267
|
-
})
|
268
|
-
.then(hasStatusOrThrow(200))
|
269
|
-
.then((res) => res.text());
|
270
|
-
}
|
271
|
-
|
272
|
-
/**
|
273
|
-
* Fetch the federation list document from a given endpoint.
|
274
|
-
*
|
275
|
-
* @param federationListEndpoint The URL of the federation list endpoint.
|
276
|
-
* @param appFetch An optional instance of the http client to be used.
|
277
|
-
* @returns The federation list as an array of strings.
|
278
|
-
* @throws {IoWalletError} If the HTTP request fails.
|
279
|
-
* @throws {FederationError} If the result is not in the expected format.
|
280
|
-
*/
|
281
|
-
export async function getFederationList(
|
282
|
-
federationListEndpoint: string,
|
283
|
-
{
|
284
|
-
appFetch = fetch,
|
285
|
-
}: {
|
286
|
-
appFetch?: GlobalFetch["fetch"];
|
287
|
-
} = {}
|
288
|
-
): Promise<string[]> {
|
289
|
-
return await appFetch(federationListEndpoint, {
|
290
|
-
method: "GET",
|
291
|
-
})
|
292
|
-
.then(hasStatusOrThrow(200))
|
293
|
-
.then((res) => res.json())
|
294
|
-
.then((json) => {
|
295
|
-
const result = FederationListResponse.safeParse(json);
|
296
|
-
if (!result.success) {
|
297
|
-
throw new FederationListParseError(
|
298
|
-
`Invalid federation list format received from ${federationListEndpoint}. Error: ${result.error.message}`,
|
299
|
-
{ url: federationListEndpoint, parseError: result.error.toString() }
|
300
|
-
);
|
301
|
-
}
|
302
|
-
return result.data;
|
303
|
-
});
|
304
|
-
}
|
305
|
-
|
306
|
-
/**
|
307
|
-
* Build a not-verified trust chain for a given Relying Party (RP) entity.
|
308
|
-
*
|
309
|
-
* @param relyingPartyEntityBaseUrl The base URL of the RP entity
|
310
|
-
* @param trustAnchorKey The public key of the Trust Anchor (TA) entity
|
311
|
-
* @param appFetch An optional instance of the http client to be used.
|
312
|
-
* @returns A list of signed tokens that represent the trust chain, in the order of the chain (from the RP to the Trust Anchor)
|
313
|
-
* @throws {FederationError} When an element of the chain fails to parse or other build steps fail.
|
314
|
-
*/
|
315
|
-
export async function buildTrustChain(
|
316
|
-
relyingPartyEntityBaseUrl: string,
|
317
|
-
trustAnchorKey: JWK,
|
318
|
-
appFetch: GlobalFetch["fetch"] = fetch
|
319
|
-
): Promise<string[]> {
|
320
|
-
// 1: Recursively gather the trust chain from the RP up to the Trust Anchor
|
321
|
-
const trustChain = await gatherTrustChain(
|
322
|
-
relyingPartyEntityBaseUrl,
|
323
|
-
appFetch
|
324
|
-
);
|
325
|
-
|
326
|
-
// 2: Trust Anchor signature verification
|
327
|
-
const trustAnchorJwt = trustChain[trustChain.length - 1];
|
328
|
-
if (!trustAnchorJwt) {
|
329
|
-
throw new BuildTrustChainError(
|
330
|
-
"Cannot verify trust anchor: missing entity configuration in gathered chain.",
|
331
|
-
{ relyingPartyUrl: relyingPartyEntityBaseUrl }
|
332
|
-
);
|
333
|
-
}
|
334
|
-
|
335
|
-
if (!trustAnchorKey.kid) {
|
336
|
-
throw new TrustAnchorKidMissingError();
|
337
|
-
}
|
338
|
-
|
339
|
-
await verify(trustAnchorJwt, trustAnchorKey.kid, [trustAnchorKey]);
|
340
|
-
|
341
|
-
// 3: Check the federation list
|
342
|
-
const trustAnchorConfig = EntityConfiguration.parse(decode(trustAnchorJwt));
|
343
|
-
const federationListEndpoint =
|
344
|
-
trustAnchorConfig.payload.metadata.federation_entity
|
345
|
-
.federation_list_endpoint;
|
346
|
-
|
347
|
-
if (federationListEndpoint) {
|
348
|
-
const federationList = await getFederationList(federationListEndpoint, {
|
349
|
-
appFetch,
|
350
|
-
});
|
351
|
-
|
352
|
-
if (!federationList.includes(relyingPartyEntityBaseUrl)) {
|
353
|
-
throw new RelyingPartyNotAuthorizedError(
|
354
|
-
"Relying Party entity base URL is not authorized by the Trust Anchor's federation list.",
|
355
|
-
{ relyingPartyUrl: relyingPartyEntityBaseUrl, federationListEndpoint }
|
356
|
-
);
|
357
|
-
}
|
358
|
-
}
|
359
|
-
|
360
|
-
return trustChain;
|
361
|
-
}
|
362
|
-
|
363
|
-
/**
|
364
|
-
* Recursively gather the trust chain for an entity and all its superiors.
|
365
|
-
* @param entityBaseUrl The base URL of the entity for which to gather the chain.
|
366
|
-
* @param appFetch An optional instance of the http client to be used.
|
367
|
-
* @param isLeaf Whether the current entity is the leaf of the chain.
|
368
|
-
* @returns A full ordered list of JWTs (ECs and ESs) forming the trust chain.
|
369
|
-
* @throws {FederationError} If any of the fetched documents fail to parse or other errors occur during the gathering process.
|
370
|
-
*/
|
371
|
-
async function gatherTrustChain(
|
372
|
-
entityBaseUrl: string,
|
373
|
-
appFetch: GlobalFetch["fetch"],
|
374
|
-
isLeaf: boolean = true
|
375
|
-
): Promise<string[]> {
|
376
|
-
const chain: string[] = [];
|
377
|
-
|
378
|
-
// Fetch self-signed EC (only needed for the leaf)
|
379
|
-
const entityECJwt = await getSignedEntityConfiguration(entityBaseUrl, {
|
380
|
-
appFetch,
|
381
|
-
});
|
382
|
-
const entityEC = EntityConfiguration.parse(decode(entityECJwt));
|
383
|
-
|
384
|
-
if (isLeaf) {
|
385
|
-
// Only push EC for the leaf
|
386
|
-
chain.push(entityECJwt);
|
387
|
-
}
|
388
|
-
|
389
|
-
// Find authority_hints (parent, if any)
|
390
|
-
const authorityHints = entityEC.payload.authority_hints ?? [];
|
391
|
-
if (authorityHints.length === 0) {
|
392
|
-
// This is the Trust Anchor (no parent)
|
393
|
-
if (!isLeaf) {
|
394
|
-
chain.push(entityECJwt);
|
395
|
-
}
|
396
|
-
return chain;
|
397
|
-
}
|
398
|
-
|
399
|
-
const parentEntityBaseUrl = authorityHints[0]!;
|
400
|
-
|
401
|
-
// Fetch parent EC
|
402
|
-
const parentECJwt = await getSignedEntityConfiguration(parentEntityBaseUrl, {
|
403
|
-
appFetch,
|
404
|
-
});
|
405
|
-
const parentEC = EntityConfiguration.parse(decode(parentECJwt));
|
406
|
-
|
407
|
-
// Fetch ES
|
408
|
-
const federationFetchEndpoint =
|
409
|
-
parentEC.payload.metadata.federation_entity.federation_fetch_endpoint;
|
410
|
-
if (!federationFetchEndpoint) {
|
411
|
-
throw new MissingFederationFetchEndpointError(
|
412
|
-
`Missing federation_fetch_endpoint in parent's (${parentEntityBaseUrl}) configuration when gathering chain for ${entityBaseUrl}.`,
|
413
|
-
{ entityBaseUrl, missingInEntityUrl: parentEntityBaseUrl }
|
414
|
-
);
|
415
|
-
}
|
416
|
-
|
417
|
-
const entityStatementJwt = await getSignedEntityStatement(
|
418
|
-
federationFetchEndpoint,
|
419
|
-
entityBaseUrl,
|
420
|
-
{ appFetch }
|
421
|
-
);
|
422
|
-
// Validate the ES
|
423
|
-
EntityStatement.parse(decode(entityStatementJwt));
|
424
|
-
|
425
|
-
// Push this ES into the chain
|
426
|
-
chain.push(entityStatementJwt);
|
427
|
-
|
428
|
-
// Recurse into the parent
|
429
|
-
const parentChain = await gatherTrustChain(
|
430
|
-
parentEntityBaseUrl,
|
431
|
-
appFetch,
|
432
|
-
false
|
433
|
-
);
|
434
|
-
|
435
|
-
return chain.concat(parentChain);
|
436
|
-
}
|
6
|
+
export { Build, Verify, Errors, Types };
|
package/src/trust/utils.ts
CHANGED
@@ -4,6 +4,8 @@ import {
|
|
4
4
|
} from "@pagopa/io-react-native-jwt";
|
5
5
|
|
6
6
|
import type { JWK, JWTDecodeResult } from "../utils/jwk";
|
7
|
+
import { FederationError } from "./errors";
|
8
|
+
import type { TrustAnchorEntityConfiguration } from "./types";
|
7
9
|
|
8
10
|
export type ParsedToken = {
|
9
11
|
header: JWTDecodeResult["protectedHeader"];
|
@@ -33,3 +35,36 @@ export const decode = (token: string): ParsedToken => {
|
|
33
35
|
const { protectedHeader: header, payload } = decodeJwt(token);
|
34
36
|
return { header, payload };
|
35
37
|
};
|
38
|
+
|
39
|
+
/**
|
40
|
+
* Extracts the X.509 Trust Anchor certificate (Base64 encoded) from the
|
41
|
+
* Trust Anchor's Entity Configuration.
|
42
|
+
*
|
43
|
+
* @param trustAnchorEntity The entity configuration of the known trust anchor.
|
44
|
+
* @returns The Base64 encoded X.509 certificate string.
|
45
|
+
* @throws {FederationError} If the certificate cannot be derived.
|
46
|
+
*/
|
47
|
+
export function getTrustAnchorX509Certificate(
|
48
|
+
trustAnchorEntity: TrustAnchorEntityConfiguration
|
49
|
+
): string {
|
50
|
+
const taHeaderKid = trustAnchorEntity.header.kid;
|
51
|
+
const taSigningJwk = trustAnchorEntity.payload.jwks.keys.find(
|
52
|
+
(key) => key.kid === taHeaderKid
|
53
|
+
);
|
54
|
+
|
55
|
+
if (!taSigningJwk) {
|
56
|
+
throw new FederationError(
|
57
|
+
`Cannot derive X.509 Trust Anchor certificate: JWK with kid '${taHeaderKid}' not found in Trust Anchor's JWKS.`,
|
58
|
+
{ trustAnchorKid: taHeaderKid, reason: "JWK not found for header kid" }
|
59
|
+
);
|
60
|
+
}
|
61
|
+
|
62
|
+
if (taSigningJwk.x5c && taSigningJwk.x5c.length > 0 && taSigningJwk.x5c[0]) {
|
63
|
+
return taSigningJwk.x5c[0];
|
64
|
+
}
|
65
|
+
|
66
|
+
throw new FederationError(
|
67
|
+
`Cannot derive X.509 Trust Anchor certificate: JWK with kid '${taHeaderKid}' does not contain a valid 'x5c' certificate array.`,
|
68
|
+
{ trustAnchorKid: taHeaderKid, reason: "Missing or empty x5c in JWK" }
|
69
|
+
);
|
70
|
+
}
|
@@ -5,14 +5,30 @@ import {
|
|
5
5
|
} from "./types";
|
6
6
|
import { JWK } from "../utils/jwk";
|
7
7
|
import * as z from "zod";
|
8
|
-
import { getSignedEntityConfiguration, getSignedEntityStatement } from ".";
|
9
|
-
import { decode, type ParsedToken, verify } from "./utils";
|
10
8
|
import {
|
9
|
+
decode,
|
10
|
+
getTrustAnchorX509Certificate,
|
11
|
+
type ParsedToken,
|
12
|
+
verify,
|
13
|
+
} from "./utils";
|
14
|
+
import {
|
15
|
+
FederationError,
|
11
16
|
MissingFederationFetchEndpointError,
|
17
|
+
MissingX509CertsError,
|
12
18
|
TrustChainEmptyError,
|
13
19
|
TrustChainRenewalError,
|
14
20
|
TrustChainTokenMissingError,
|
21
|
+
X509ValidationError,
|
15
22
|
} from "./errors";
|
23
|
+
import {
|
24
|
+
type CertificateValidationResult,
|
25
|
+
verifyCertificateChain,
|
26
|
+
type X509CertificateOptions,
|
27
|
+
} from "@pagopa/io-react-native-crypto";
|
28
|
+
import {
|
29
|
+
getSignedEntityConfiguration,
|
30
|
+
getSignedEntityStatement,
|
31
|
+
} from "./build-chain";
|
16
32
|
|
17
33
|
// The first element of the chain is supposed to be the Entity Configuration for the document issuer
|
18
34
|
const FirstElementShape = EntityConfiguration;
|
@@ -26,16 +42,18 @@ const LastElementShape = z.union([
|
|
26
42
|
]);
|
27
43
|
|
28
44
|
/**
|
29
|
-
* Validates a provided trust chain against a known trust
|
45
|
+
* Validates a provided trust chain against a known trust anchor, including X.509 certificate checks.
|
30
46
|
*
|
31
|
-
* @param trustAnchorEntity The entity configuration of the known trust anchor
|
32
|
-
* @param chain The chain of statements to be validated
|
33
|
-
* @
|
34
|
-
* @
|
47
|
+
* @param trustAnchorEntity The entity configuration of the known trust anchor (for JWT validation).
|
48
|
+
* @param chain The chain of statements to be validated.
|
49
|
+
* @param x509Options Options for X.509 certificate validation.
|
50
|
+
* @returns The list of parsed tokens representing the chain.
|
51
|
+
* @throws {FederationError} If the chain is not valid (JWT or X.509). Specific errors like TrustChainEmptyError, X509ValidationError may be thrown.
|
35
52
|
*/
|
36
53
|
export async function validateTrustChain(
|
37
54
|
trustAnchorEntity: TrustAnchorEntityConfiguration,
|
38
|
-
chain: string[]
|
55
|
+
chain: string[],
|
56
|
+
x509Options: X509CertificateOptions
|
39
57
|
): Promise<ParsedToken[]> {
|
40
58
|
// If the chain is empty, fail
|
41
59
|
if (chain.length === 0) {
|
@@ -50,7 +68,7 @@ export async function validateTrustChain(
|
|
50
68
|
? LastElementShape
|
51
69
|
: MiddleElementShape;
|
52
70
|
|
53
|
-
//
|
71
|
+
// Select the kid from the current index
|
54
72
|
const selectKid = (currentIndex: number): string => {
|
55
73
|
const token = chain[currentIndex];
|
56
74
|
if (!token) {
|
@@ -63,8 +81,8 @@ export async function validateTrustChain(
|
|
63
81
|
return shape.parse(decode(token)).header.kid;
|
64
82
|
};
|
65
83
|
|
66
|
-
//
|
67
|
-
//
|
84
|
+
// Select keys from the next token
|
85
|
+
// If the current token is the last, keys from trust anchor will be used
|
68
86
|
const selectKeys = (currentIndex: number): JWK[] => {
|
69
87
|
if (currentIndex === chain.length - 1) {
|
70
88
|
return trustAnchorEntity.payload.jwks.keys;
|
@@ -82,13 +100,74 @@ export async function validateTrustChain(
|
|
82
100
|
return shape.parse(decode(nextToken)).payload.jwks.keys;
|
83
101
|
};
|
84
102
|
|
103
|
+
const x509TrustAnchorCertBase64 =
|
104
|
+
getTrustAnchorX509Certificate(trustAnchorEntity);
|
105
|
+
|
85
106
|
// Iterate the chain and validate each element's signature against the public keys of its next
|
86
107
|
// If there is no next, hence it's the end of the chain, and it must be verified by the Trust Anchor
|
87
|
-
|
88
|
-
|
89
|
-
|
90
|
-
|
91
|
-
|
108
|
+
const validationPromises = chain.map(async (tokenString, i) => {
|
109
|
+
const kidFromTokenHeader = selectKid(i);
|
110
|
+
const signerJwks = selectKeys(i);
|
111
|
+
|
112
|
+
// Step 1: Verify JWT signature
|
113
|
+
const parsedToken = await verify(
|
114
|
+
tokenString,
|
115
|
+
kidFromTokenHeader,
|
116
|
+
signerJwks
|
117
|
+
);
|
118
|
+
|
119
|
+
// Step 2: X.509 Certificate Chain Validation
|
120
|
+
const jwkUsedForVerification = signerJwks.find(
|
121
|
+
(k) => k.kid === kidFromTokenHeader
|
122
|
+
);
|
123
|
+
|
124
|
+
if (!jwkUsedForVerification) {
|
125
|
+
throw new FederationError(
|
126
|
+
`JWK with kid '${kidFromTokenHeader}' was not found in signer's JWKS for token at index ${i}, though JWT verification passed.`,
|
127
|
+
{ tokenIndex: i, kid: kidFromTokenHeader }
|
128
|
+
);
|
129
|
+
}
|
130
|
+
|
131
|
+
if (
|
132
|
+
!jwkUsedForVerification.x5c ||
|
133
|
+
jwkUsedForVerification.x5c.length === 0
|
134
|
+
) {
|
135
|
+
throw new MissingX509CertsError(
|
136
|
+
`JWK with kid '${kidFromTokenHeader}' does not contain an X.509 certificate chain (x5c) for token at index ${i}.`
|
137
|
+
);
|
138
|
+
}
|
139
|
+
|
140
|
+
// If the chain has more than one certificate AND
|
141
|
+
// the last certificate in the x5c chain is the same as the trust anchor,
|
142
|
+
// remove the anchor from the chain being passed, as it's supplied separately.
|
143
|
+
const certChainBase64 =
|
144
|
+
jwkUsedForVerification.x5c.length > 1 &&
|
145
|
+
jwkUsedForVerification.x5c.at(-1) === x509TrustAnchorCertBase64
|
146
|
+
? jwkUsedForVerification.x5c.slice(0, -1)
|
147
|
+
: jwkUsedForVerification.x5c;
|
148
|
+
|
149
|
+
const x509ValidationResult: CertificateValidationResult =
|
150
|
+
await verifyCertificateChain(
|
151
|
+
certChainBase64,
|
152
|
+
x509TrustAnchorCertBase64,
|
153
|
+
x509Options
|
154
|
+
);
|
155
|
+
|
156
|
+
if (!x509ValidationResult.isValid) {
|
157
|
+
throw new X509ValidationError(
|
158
|
+
`X.509 certificate chain validation failed for token at index ${i} (kid: ${kidFromTokenHeader}). Status: ${x509ValidationResult.validationStatus}. Error: ${x509ValidationResult.errorMessage}`,
|
159
|
+
{
|
160
|
+
tokenIndex: i,
|
161
|
+
kid: kidFromTokenHeader,
|
162
|
+
x509ValidationStatus: x509ValidationResult.validationStatus,
|
163
|
+
x509ErrorMessage: x509ValidationResult.errorMessage,
|
164
|
+
}
|
165
|
+
);
|
166
|
+
}
|
167
|
+
return parsedToken;
|
168
|
+
});
|
169
|
+
|
170
|
+
return Promise.all(validationPromises);
|
92
171
|
}
|
93
172
|
|
94
173
|
/**
|
@@ -149,3 +228,40 @@ export async function renewTrustChain(
|
|
149
228
|
})
|
150
229
|
);
|
151
230
|
}
|
231
|
+
|
232
|
+
/**
|
233
|
+
* Verify a given trust chain is actually valid.
|
234
|
+
* It can handle fast chain renewal, which means we try to fetch a fresh version of each statement.
|
235
|
+
*
|
236
|
+
* @param trustAnchorEntity The entity configuration of the known trust anchor
|
237
|
+
* @param chain The chain of statements to be validated
|
238
|
+
* @param x509Options Options for the verification process
|
239
|
+
* @param appFetch (optional) fetch api implementation
|
240
|
+
* @param renewOnFail Whether to attempt to renew the trust chain if the initial validation fails
|
241
|
+
* @returns The result of the chain validation
|
242
|
+
* @throws {FederationError} If the chain is not valid
|
243
|
+
*/
|
244
|
+
export async function verifyTrustChain(
|
245
|
+
trustAnchorEntity: TrustAnchorEntityConfiguration,
|
246
|
+
chain: string[],
|
247
|
+
x509Options: X509CertificateOptions = {
|
248
|
+
connectTimeout: 10000,
|
249
|
+
readTimeout: 10000,
|
250
|
+
requireCrl: true,
|
251
|
+
},
|
252
|
+
{
|
253
|
+
appFetch = fetch,
|
254
|
+
renewOnFail = true,
|
255
|
+
}: { appFetch?: GlobalFetch["fetch"]; renewOnFail?: boolean } = {}
|
256
|
+
): Promise<ReturnType<typeof validateTrustChain>> {
|
257
|
+
try {
|
258
|
+
return validateTrustChain(trustAnchorEntity, chain, x509Options);
|
259
|
+
} catch (error) {
|
260
|
+
if (renewOnFail) {
|
261
|
+
const renewedChain = await renewTrustChain(chain, appFetch);
|
262
|
+
return validateTrustChain(trustAnchorEntity, renewedChain, x509Options);
|
263
|
+
} else {
|
264
|
+
throw error;
|
265
|
+
}
|
266
|
+
}
|
267
|
+
}
|
package/src/utils/errors.ts
CHANGED
@@ -1,13 +1,13 @@
|
|
1
1
|
import type { ProblemDetail } from "../client/generated/wallet-provider";
|
2
|
-
import type { CredentialIssuerEntityConfiguration } from "../trust";
|
3
2
|
import {
|
3
|
+
type IssuerResponseErrorCode,
|
4
4
|
IssuerResponseErrorCodes,
|
5
|
-
|
5
|
+
type RelyingPartyResponseErrorCode,
|
6
6
|
RelyingPartyResponseErrorCodes,
|
7
|
-
type IssuerResponseErrorCode,
|
8
7
|
type WalletProviderResponseErrorCode,
|
9
|
-
|
8
|
+
WalletProviderResponseErrorCodes,
|
10
9
|
} from "./error-codes";
|
10
|
+
import type { CredentialIssuerEntityConfiguration } from "../trust/types";
|
11
11
|
|
12
12
|
export {
|
13
13
|
IssuerResponseErrorCodes,
|