@owf/openid-federation 0.0.0-stage → 0.0.0
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/README.md +198 -2
- package/dist/index.d.mts +3127 -0
- package/dist/index.mjs +1490 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +44 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1490 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { base64url, base64urlDecodeJson, base64urlEncode, isMediaType, stringToBytes } from "@owf/identity-common";
|
|
3
|
+
//#region src/constraints.ts
|
|
4
|
+
const constraintSchema = z.object({
|
|
5
|
+
max_path_length: z.number().optional(),
|
|
6
|
+
naming_constraints: z.object({
|
|
7
|
+
permitted: z.array(z.string()).optional(),
|
|
8
|
+
excluded: z.array(z.string()).optional()
|
|
9
|
+
}).optional(),
|
|
10
|
+
allowed_entity_types: z.array(z.string().refine((s) => s !== "federation_entity", { message: `Value cannot be "federation_entity"` })).optional()
|
|
11
|
+
});
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/jsonWeb/createJsonWebToken.ts
|
|
14
|
+
/**
|
|
15
|
+
*
|
|
16
|
+
* Create a json web token according to {@link https://datatracker.ietf.org/doc/html/rfc7519 | RFC7519 }
|
|
17
|
+
*
|
|
18
|
+
*/
|
|
19
|
+
const createJsonWebToken = (header, payload, signature) => {
|
|
20
|
+
return `${base64urlEncode(JSON.stringify(header))}.${base64urlEncode(JSON.stringify(payload))}.${base64url.encode(signature)}`;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/jsonWeb/createJsonWebTokenSignableInput.ts
|
|
24
|
+
/**
|
|
25
|
+
*
|
|
26
|
+
* Converts a JSON header and payload into a byte array which can be used to verify and sign a JWT
|
|
27
|
+
*
|
|
28
|
+
*/
|
|
29
|
+
const createJwtSignableInput = (header, payload) => {
|
|
30
|
+
if (Object.keys(header).length === 0) throw new Error("Can not create JWT with an empty header");
|
|
31
|
+
if (Object.keys(payload).length === 0) throw new Error("Can not create JWT with an empty payload");
|
|
32
|
+
const toBeSignedString = `${base64urlEncode(JSON.stringify(header))}.${base64urlEncode(JSON.stringify(payload))}`;
|
|
33
|
+
return stringToBytes(toBeSignedString);
|
|
34
|
+
};
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/error/PolicyErrorStage.ts
|
|
37
|
+
let PolicyErrorStage = /* @__PURE__ */ function(PolicyErrorStage) {
|
|
38
|
+
PolicyErrorStage["Generic"] = "generic";
|
|
39
|
+
PolicyErrorStage["Validation"] = "validation";
|
|
40
|
+
PolicyErrorStage["MetadataPolicyCrit"] = "metadataPolicyCrit";
|
|
41
|
+
PolicyErrorStage["PolicyMerge"] = "policyMerge";
|
|
42
|
+
PolicyErrorStage["PolicyApply"] = "policyApply";
|
|
43
|
+
return PolicyErrorStage;
|
|
44
|
+
}({});
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/error/OpenIdFederationError.ts
|
|
47
|
+
var OpenIdFederationError = class OpenIdFederationError extends Error {
|
|
48
|
+
constructor(errorCode, message, cause) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.errorCode = errorCode;
|
|
51
|
+
this.cause = cause;
|
|
52
|
+
}
|
|
53
|
+
static fromZodError(zodError) {
|
|
54
|
+
return new OpenIdFederationError("validation", void 0, zodError);
|
|
55
|
+
}
|
|
56
|
+
static isMetadataPolicyCritError(error) {
|
|
57
|
+
return error instanceof OpenIdFederationError && error.errorCode === "metadataPolicyCrit";
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
//#region src/utils/validate.ts
|
|
62
|
+
const validate = ({ schema, data, errorMessage }) => {
|
|
63
|
+
try {
|
|
64
|
+
return schema.parse(data);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
const error = OpenIdFederationError.fromZodError(e);
|
|
67
|
+
error.message = errorMessage ?? error.message;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/jsonWeb/jsonWebKey.ts
|
|
73
|
+
const jsonWebKeySchema = z.object({
|
|
74
|
+
kty: z.string(),
|
|
75
|
+
kid: z.string(),
|
|
76
|
+
use: z.string().optional(),
|
|
77
|
+
key_ops: z.array(z.string()).optional(),
|
|
78
|
+
alg: z.string().optional(),
|
|
79
|
+
x5u: z.string().optional(),
|
|
80
|
+
x5c: z.array(z.string()).optional(),
|
|
81
|
+
x5t: z.string().optional(),
|
|
82
|
+
"x5t#S256": z.string().optional()
|
|
83
|
+
}).loose();
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/jsonWeb/jsonWebKeySet.ts
|
|
86
|
+
const jsonWebKeySetSchema = z.object({ keys: z.array(jsonWebKeySchema) });
|
|
87
|
+
//#endregion
|
|
88
|
+
//#region src/jsonWeb/getUsedJsonWebKey.ts
|
|
89
|
+
const getUsedJsonWebKey = (header, claims) => {
|
|
90
|
+
const validatedHeader = validate({
|
|
91
|
+
schema: z.object({ kid: z.string() }).loose(),
|
|
92
|
+
data: header,
|
|
93
|
+
errorMessage: "invalid header claims. Should contain a key id"
|
|
94
|
+
});
|
|
95
|
+
const key = validate({
|
|
96
|
+
schema: z.object({ jwks: jsonWebKeySetSchema }).loose(),
|
|
97
|
+
data: claims,
|
|
98
|
+
errorMessage: "Invalid payload claims. Should contain a json web key set"
|
|
99
|
+
}).jwks?.keys.find((key) => key.kid === validatedHeader.kid);
|
|
100
|
+
if (!key) throw new Error(`key with id: '${header.kid}' could not be found in the claims`);
|
|
101
|
+
return key;
|
|
102
|
+
};
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/jsonWeb/jsonWebToken.ts
|
|
105
|
+
const defaultSchema = z.record(z.string(), z.unknown());
|
|
106
|
+
/**
|
|
107
|
+
*
|
|
108
|
+
* @todo better jwt validation
|
|
109
|
+
*
|
|
110
|
+
*/
|
|
111
|
+
const jsonWebTokenSchema = ({ claimsSchema = defaultSchema, headerSchema = defaultSchema } = {
|
|
112
|
+
claimsSchema: defaultSchema,
|
|
113
|
+
headerSchema: defaultSchema
|
|
114
|
+
}) => z.string().transform((s, ctx) => {
|
|
115
|
+
const [header, claims, signature] = s.split(".");
|
|
116
|
+
if (!header) {
|
|
117
|
+
ctx.addIssue({
|
|
118
|
+
code: "custom",
|
|
119
|
+
message: "JWT does not contain a header parameter"
|
|
120
|
+
});
|
|
121
|
+
return z.NEVER;
|
|
122
|
+
}
|
|
123
|
+
if (!claims) {
|
|
124
|
+
ctx.addIssue({
|
|
125
|
+
code: "custom",
|
|
126
|
+
message: "JWT does not contain a payload"
|
|
127
|
+
});
|
|
128
|
+
return z.NEVER;
|
|
129
|
+
}
|
|
130
|
+
if (!signature) {
|
|
131
|
+
ctx.addIssue({
|
|
132
|
+
code: "custom",
|
|
133
|
+
message: "JWT does not contain a signature"
|
|
134
|
+
});
|
|
135
|
+
return z.NEVER;
|
|
136
|
+
}
|
|
137
|
+
let decodedHeader;
|
|
138
|
+
let decodedClaims;
|
|
139
|
+
let decodedSignature;
|
|
140
|
+
try {
|
|
141
|
+
decodedHeader = base64urlDecodeJson(header);
|
|
142
|
+
decodedClaims = base64urlDecodeJson(claims);
|
|
143
|
+
decodedSignature = base64url.decode(signature);
|
|
144
|
+
} catch {
|
|
145
|
+
ctx.addIssue({
|
|
146
|
+
code: "custom",
|
|
147
|
+
message: "JWT is not a valid compact JWS"
|
|
148
|
+
});
|
|
149
|
+
return z.NEVER;
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
jwt: s,
|
|
153
|
+
header: validate({
|
|
154
|
+
schema: headerSchema,
|
|
155
|
+
data: decodedHeader,
|
|
156
|
+
errorMessage: "invalid header claims provided"
|
|
157
|
+
}),
|
|
158
|
+
claims: validate({
|
|
159
|
+
schema: claimsSchema,
|
|
160
|
+
data: decodedClaims,
|
|
161
|
+
errorMessage: "invalid payload claims provided"
|
|
162
|
+
}),
|
|
163
|
+
signature: decodedSignature
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/metadata/common.ts
|
|
168
|
+
const commonMetadataSchema = z.object({
|
|
169
|
+
signed_jwks_uri: z.url().optional(),
|
|
170
|
+
jwks_uri: z.url().optional(),
|
|
171
|
+
jwks: jsonWebKeySetSchema.optional(),
|
|
172
|
+
organization_name: z.string().optional(),
|
|
173
|
+
contacts: z.array(z.string()).min(1).optional(),
|
|
174
|
+
logo_uri: z.url().optional(),
|
|
175
|
+
policy_uri: z.url().optional(),
|
|
176
|
+
homepage_uri: z.url().optional()
|
|
177
|
+
});
|
|
178
|
+
//#endregion
|
|
179
|
+
//#region src/metadata/operator/MetadataMergeStrategy.ts
|
|
180
|
+
let MetadataMergeStrategy = /* @__PURE__ */ function(MetadataMergeStrategy) {
|
|
181
|
+
/**
|
|
182
|
+
*
|
|
183
|
+
* Allowed only when the operator values are equal. If not, this MUST result in a policy error.
|
|
184
|
+
*
|
|
185
|
+
*/
|
|
186
|
+
MetadataMergeStrategy[MetadataMergeStrategy["OperatorValuesEqual"] = 0] = "OperatorValuesEqual";
|
|
187
|
+
/**
|
|
188
|
+
*
|
|
189
|
+
* The result of merging the values of two these operators is the union of the operator values.
|
|
190
|
+
*
|
|
191
|
+
*/
|
|
192
|
+
MetadataMergeStrategy[MetadataMergeStrategy["Union"] = 1] = "Union";
|
|
193
|
+
/**
|
|
194
|
+
*
|
|
195
|
+
* The result of merging the values of two these operators is the intersection of the operator values. If the intersection is empty, this MUST result in a policy error.
|
|
196
|
+
*
|
|
197
|
+
*/
|
|
198
|
+
MetadataMergeStrategy[MetadataMergeStrategy["Intersection"] = 2] = "Intersection";
|
|
199
|
+
/**
|
|
200
|
+
*
|
|
201
|
+
* The result of merging the values of two these operators is the logical disjunction (OR) of the operator values.
|
|
202
|
+
*
|
|
203
|
+
*/
|
|
204
|
+
MetadataMergeStrategy[MetadataMergeStrategy["LogicalOr"] = 3] = "LogicalOr";
|
|
205
|
+
/**
|
|
206
|
+
*
|
|
207
|
+
* The result of merging the values of two these operators is the intersection of the operator values. The intersection may be an empty array.
|
|
208
|
+
*
|
|
209
|
+
*/
|
|
210
|
+
MetadataMergeStrategy[MetadataMergeStrategy["IntersectionMayBeEmpty"] = 4] = "IntersectionMayBeEmpty";
|
|
211
|
+
return MetadataMergeStrategy;
|
|
212
|
+
}({});
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/metadata/operator/MetadataOrderOfApplication.ts
|
|
215
|
+
let MetadataOrderOfApplication = /* @__PURE__ */ function(MetadataOrderOfApplication) {
|
|
216
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["First"] = 0] = "First";
|
|
217
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["AfterValue"] = 1] = "AfterValue";
|
|
218
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["AfterAdd"] = 2] = "AfterAdd";
|
|
219
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["AfterDefault"] = 3] = "AfterDefault";
|
|
220
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["AfterOneOf"] = 4] = "AfterOneOf";
|
|
221
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["AfterSubsetOf"] = 5] = "AfterSubsetOf";
|
|
222
|
+
MetadataOrderOfApplication[MetadataOrderOfApplication["Last"] = 6] = "Last";
|
|
223
|
+
return MetadataOrderOfApplication;
|
|
224
|
+
}({});
|
|
225
|
+
//#endregion
|
|
226
|
+
//#region src/metadata/operator/utils/createPolicyOperatorSchema.ts
|
|
227
|
+
const createPolicyOperatorSchema = (operator) => ({
|
|
228
|
+
/**
|
|
229
|
+
* The key of the operator which is used to identify the operator
|
|
230
|
+
*/
|
|
231
|
+
key: operator.key,
|
|
232
|
+
/**
|
|
233
|
+
* The merge strategy of the operator
|
|
234
|
+
*/
|
|
235
|
+
mergeStrategy: operator.mergeStrategy,
|
|
236
|
+
/**
|
|
237
|
+
* The order of application of the operator
|
|
238
|
+
*/
|
|
239
|
+
orderOfApplication: operator.orderOfApplication,
|
|
240
|
+
/**
|
|
241
|
+
* The operator itself
|
|
242
|
+
*/
|
|
243
|
+
operator,
|
|
244
|
+
/**
|
|
245
|
+
* The schema for the operator itself so for essential it is only a boolean
|
|
246
|
+
*/
|
|
247
|
+
operatorSchema: operator.operatorJsonValues.reduce((acc, schema) => acc.or(schema)).optional(),
|
|
248
|
+
/**
|
|
249
|
+
* The schema for the parameter the operator can be applied to so when the policy is targeting federation_entity we can check if the policy can handle that property
|
|
250
|
+
*/
|
|
251
|
+
parameterSchema: operator.parameterJsonValues.reduce((acc, schema) => acc.or(schema)).optional()
|
|
252
|
+
});
|
|
253
|
+
//#endregion
|
|
254
|
+
//#region src/metadata/operator/utils/swapValidators.ts
|
|
255
|
+
const swapValidators = (schema, newValidator) => {
|
|
256
|
+
return z.object(Object.keys(schema.shape).reduce((acc, key) => {
|
|
257
|
+
acc[key] = newValidator;
|
|
258
|
+
return acc;
|
|
259
|
+
}, {}));
|
|
260
|
+
};
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/metadata/operator/standard/add.ts
|
|
263
|
+
const addOperator = createPolicyOperatorSchema({
|
|
264
|
+
key: "add",
|
|
265
|
+
parameterJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
266
|
+
operatorJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
267
|
+
canBeCombinedWith: [
|
|
268
|
+
"value",
|
|
269
|
+
"default",
|
|
270
|
+
"subset_of",
|
|
271
|
+
"superset_of",
|
|
272
|
+
"essential"
|
|
273
|
+
],
|
|
274
|
+
orderOfApplication: 1,
|
|
275
|
+
mergeStrategy: 1
|
|
276
|
+
});
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/metadata/operator/standard/default.ts
|
|
279
|
+
const defaultOperator = createPolicyOperatorSchema({
|
|
280
|
+
key: "default",
|
|
281
|
+
parameterJsonValues: [
|
|
282
|
+
z.string(),
|
|
283
|
+
z.number(),
|
|
284
|
+
z.boolean(),
|
|
285
|
+
z.record(z.string(), z.unknown()),
|
|
286
|
+
z.array(z.unknown())
|
|
287
|
+
],
|
|
288
|
+
operatorJsonValues: [
|
|
289
|
+
z.string(),
|
|
290
|
+
z.number(),
|
|
291
|
+
z.boolean(),
|
|
292
|
+
z.record(z.string(), z.unknown()),
|
|
293
|
+
z.array(z.unknown())
|
|
294
|
+
],
|
|
295
|
+
canBeCombinedWith: [
|
|
296
|
+
"value",
|
|
297
|
+
"add",
|
|
298
|
+
"one_of",
|
|
299
|
+
"subset_of",
|
|
300
|
+
"superset_of",
|
|
301
|
+
"essential"
|
|
302
|
+
],
|
|
303
|
+
orderOfApplication: 2,
|
|
304
|
+
mergeStrategy: 0
|
|
305
|
+
});
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/metadata/operator/standard/essential.ts
|
|
308
|
+
const essentialOperator = createPolicyOperatorSchema({
|
|
309
|
+
key: "essential",
|
|
310
|
+
parameterJsonValues: [
|
|
311
|
+
z.string(),
|
|
312
|
+
z.number(),
|
|
313
|
+
z.boolean(),
|
|
314
|
+
z.record(z.string(), z.string().or(z.number())),
|
|
315
|
+
z.unknown(),
|
|
316
|
+
z.array(z.unknown())
|
|
317
|
+
],
|
|
318
|
+
operatorJsonValues: [z.boolean()],
|
|
319
|
+
canBeCombinedWith: [
|
|
320
|
+
"add",
|
|
321
|
+
"default",
|
|
322
|
+
"one_of",
|
|
323
|
+
"subset_of",
|
|
324
|
+
"superset_of",
|
|
325
|
+
"value"
|
|
326
|
+
],
|
|
327
|
+
orderOfApplication: 6,
|
|
328
|
+
mergeStrategy: 3
|
|
329
|
+
});
|
|
330
|
+
//#endregion
|
|
331
|
+
//#region src/metadata/operator/standard/oneOf.ts
|
|
332
|
+
const oneOfOperator = createPolicyOperatorSchema({
|
|
333
|
+
key: "one_of",
|
|
334
|
+
parameterJsonValues: [z.string(), z.number()],
|
|
335
|
+
operatorJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
336
|
+
canBeCombinedWith: [
|
|
337
|
+
"value",
|
|
338
|
+
"default",
|
|
339
|
+
"essential"
|
|
340
|
+
],
|
|
341
|
+
orderOfApplication: 3,
|
|
342
|
+
mergeStrategy: 2
|
|
343
|
+
});
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region src/metadata/operator/standard/subsetOf.ts
|
|
346
|
+
const subsetOfOperator = createPolicyOperatorSchema({
|
|
347
|
+
key: "subset_of",
|
|
348
|
+
parameterJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
349
|
+
operatorJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
350
|
+
canBeCombinedWith: [
|
|
351
|
+
"value",
|
|
352
|
+
"add",
|
|
353
|
+
"default",
|
|
354
|
+
"superset_of",
|
|
355
|
+
"essential"
|
|
356
|
+
],
|
|
357
|
+
orderOfApplication: 4,
|
|
358
|
+
mergeStrategy: 4
|
|
359
|
+
});
|
|
360
|
+
//#endregion
|
|
361
|
+
//#region src/metadata/operator/standard/supersetOf.ts
|
|
362
|
+
const supersetOfOperator = createPolicyOperatorSchema({
|
|
363
|
+
key: "superset_of",
|
|
364
|
+
parameterJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
365
|
+
operatorJsonValues: [z.array(z.string()), z.array(z.number())],
|
|
366
|
+
canBeCombinedWith: [
|
|
367
|
+
"value",
|
|
368
|
+
"add",
|
|
369
|
+
"default",
|
|
370
|
+
"subset_of",
|
|
371
|
+
"essential"
|
|
372
|
+
],
|
|
373
|
+
orderOfApplication: 5,
|
|
374
|
+
mergeStrategy: 1
|
|
375
|
+
});
|
|
376
|
+
//#endregion
|
|
377
|
+
//#region src/metadata/operator/standard/value.ts
|
|
378
|
+
const valueOperator = createPolicyOperatorSchema({
|
|
379
|
+
key: "value",
|
|
380
|
+
parameterJsonValues: [
|
|
381
|
+
z.string(),
|
|
382
|
+
z.number(),
|
|
383
|
+
z.boolean(),
|
|
384
|
+
z.record(z.string(), z.unknown()),
|
|
385
|
+
z.array(z.unknown())
|
|
386
|
+
],
|
|
387
|
+
operatorJsonValues: [
|
|
388
|
+
z.string(),
|
|
389
|
+
z.number(),
|
|
390
|
+
z.boolean(),
|
|
391
|
+
z.record(z.string(), z.unknown()),
|
|
392
|
+
z.array(z.unknown()),
|
|
393
|
+
z.null()
|
|
394
|
+
],
|
|
395
|
+
canBeCombinedWith: [
|
|
396
|
+
"add",
|
|
397
|
+
"default",
|
|
398
|
+
"one_of",
|
|
399
|
+
"subset_of",
|
|
400
|
+
"superset_of",
|
|
401
|
+
"essential"
|
|
402
|
+
],
|
|
403
|
+
orderOfApplication: 0,
|
|
404
|
+
mergeStrategy: 0
|
|
405
|
+
});
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/metadata/policy.ts
|
|
408
|
+
const allSupportedPolicies = {
|
|
409
|
+
[addOperator.key]: addOperator,
|
|
410
|
+
[defaultOperator.key]: defaultOperator,
|
|
411
|
+
[essentialOperator.key]: essentialOperator,
|
|
412
|
+
[oneOfOperator.key]: oneOfOperator,
|
|
413
|
+
[subsetOfOperator.key]: subsetOfOperator,
|
|
414
|
+
[supersetOfOperator.key]: supersetOfOperator,
|
|
415
|
+
[valueOperator.key]: valueOperator
|
|
416
|
+
};
|
|
417
|
+
const isExistingPolicyKey = (key) => key in allSupportedPolicies;
|
|
418
|
+
const isSubset = (values, of) => Array.isArray(values) && Array.isArray(of) && values.every((value) => of.includes(value));
|
|
419
|
+
/**
|
|
420
|
+
* The conditions that Section 6.1.3.1 sets on combinations of the standard operators.
|
|
421
|
+
*/
|
|
422
|
+
const conditionalCombinationErrors = (policy) => {
|
|
423
|
+
const errors = [];
|
|
424
|
+
const has = (key) => policy[key] !== void 0;
|
|
425
|
+
const { value, add, one_of, subset_of, superset_of, essential } = policy;
|
|
426
|
+
if (has("value")) {
|
|
427
|
+
const values = value === null ? [] : value;
|
|
428
|
+
if (value === null && has("default")) errors.push("'value' null can not be combined with 'default'");
|
|
429
|
+
if (value === null && essential === true) errors.push("'value' null can not be combined with 'essential' true");
|
|
430
|
+
if (has("add") && !isSubset(add, values)) errors.push("the values of 'add' must be a subset of the values of 'value'");
|
|
431
|
+
if (has("one_of") && !(Array.isArray(one_of) && value !== null && one_of.includes(value))) errors.push("the value of 'value' must be among the 'one_of' values");
|
|
432
|
+
if (has("subset_of") && !isSubset(values, subset_of)) errors.push("the values of 'value' must be a subset of the values of 'subset_of'");
|
|
433
|
+
if (has("superset_of") && !isSubset(superset_of, values)) errors.push("the values of 'value' must be a superset of the values of 'superset_of'");
|
|
434
|
+
}
|
|
435
|
+
if (has("add") && has("subset_of") && !isSubset(add, subset_of)) errors.push("the values of 'add' must be a subset of the values of 'subset_of'");
|
|
436
|
+
if (has("subset_of") && has("superset_of") && !isSubset(superset_of, subset_of)) errors.push("the values of 'subset_of' must be a superset of the values of 'superset_of'");
|
|
437
|
+
return errors;
|
|
438
|
+
};
|
|
439
|
+
const metadataPolicySchema = z.object(Object.entries(allSupportedPolicies).reduce((acc, [key, policy]) => ({
|
|
440
|
+
...acc,
|
|
441
|
+
[key]: policy.operatorSchema
|
|
442
|
+
}), {})).and(z.record(z.string(), z.any())).superRefine((data, ctx) => {
|
|
443
|
+
const dataKeys = Object.keys(data);
|
|
444
|
+
for (const dataKey of dataKeys) {
|
|
445
|
+
if (!isExistingPolicyKey(dataKey)) continue;
|
|
446
|
+
const { operator } = allSupportedPolicies[dataKey];
|
|
447
|
+
if (dataKeys.some((key) => key !== operator.key && isExistingPolicyKey(key) && !operator.canBeCombinedWith.includes(key))) ctx.addIssue({
|
|
448
|
+
code: "custom",
|
|
449
|
+
message: `policy operator '${operator.key}' can only be combined with one of: [${operator.canBeCombinedWith.join(", ")}]. keys: [${Object.keys(data).join(",")}]`
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
for (const message of conditionalCombinationErrors(data)) ctx.addIssue({
|
|
453
|
+
code: "custom",
|
|
454
|
+
message
|
|
455
|
+
});
|
|
456
|
+
});
|
|
457
|
+
//#endregion
|
|
458
|
+
//#region src/metadata/entity/utils/createEntity.ts
|
|
459
|
+
const createEntity = ({ identifier, additionalValidation = {} }) => {
|
|
460
|
+
const schema = commonMetadataSchema.extend(additionalValidation);
|
|
461
|
+
return {
|
|
462
|
+
identifier,
|
|
463
|
+
schema: schema.loose(),
|
|
464
|
+
policySchema: swapValidators(schema, metadataPolicySchema.optional())
|
|
465
|
+
};
|
|
466
|
+
};
|
|
467
|
+
//#endregion
|
|
468
|
+
//#region src/metadata/entity/federationEntity.ts
|
|
469
|
+
/**
|
|
470
|
+
*
|
|
471
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.1-1 | Federation Entity}
|
|
472
|
+
*
|
|
473
|
+
*/
|
|
474
|
+
const federationEntityMetadata = createEntity({
|
|
475
|
+
identifier: "federation_entity",
|
|
476
|
+
additionalValidation: {
|
|
477
|
+
federation_fetch_endpoint: z.url().optional(),
|
|
478
|
+
federation_list_endpoint: z.url().optional(),
|
|
479
|
+
federation_resolve_endpoint: z.url().optional(),
|
|
480
|
+
federation_trust_mark_status_endpoint: z.url().optional(),
|
|
481
|
+
federation_trust_mark_list_endpoint: z.url().optional(),
|
|
482
|
+
federation_trust_mark_endpoint: z.url().optional(),
|
|
483
|
+
federation_historical_keys_endpoint: z.url().optional()
|
|
484
|
+
}
|
|
485
|
+
});
|
|
486
|
+
//#endregion
|
|
487
|
+
//#region src/metadata/entity/oauthAuthorizationServer.ts
|
|
488
|
+
/**
|
|
489
|
+
*
|
|
490
|
+
* https://openid.net/specs/openid-federation-1_0.html#section-5.1.4-1
|
|
491
|
+
*
|
|
492
|
+
*/
|
|
493
|
+
const oauthAuthorizationServerEntityMetadata = createEntity({ identifier: "oauth_authorization_server" });
|
|
494
|
+
//#endregion
|
|
495
|
+
//#region src/metadata/entity/oauthClient.ts
|
|
496
|
+
/**
|
|
497
|
+
*
|
|
498
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.5-1 | oauth Client}
|
|
499
|
+
*
|
|
500
|
+
*/
|
|
501
|
+
const oauthClientEntityMetadata = createEntity({ identifier: "oauth_client" });
|
|
502
|
+
//#endregion
|
|
503
|
+
//#region src/metadata/entity/oauthResource.ts
|
|
504
|
+
/**
|
|
505
|
+
*
|
|
506
|
+
* https://openid.net/specs/openid-federation-1_0.html#section-5.1.6
|
|
507
|
+
*
|
|
508
|
+
*/
|
|
509
|
+
const oauthResourceEntityMetadata = createEntity({ identifier: "oauth_resource" });
|
|
510
|
+
//#endregion
|
|
511
|
+
//#region src/metadata/entity/openIdCredentialIssuer.ts
|
|
512
|
+
/**
|
|
513
|
+
*
|
|
514
|
+
* {@link https://openid.github.io/federation-wallet/main.html#name-wallet-architecture-entity- | OpenID Credential Issuer}
|
|
515
|
+
*
|
|
516
|
+
*/
|
|
517
|
+
const openIdCredentialIssuerEntityMetadata = createEntity({
|
|
518
|
+
identifier: "openid_credential_issuer",
|
|
519
|
+
additionalValidation: {
|
|
520
|
+
client_registration_types_supported: z.array(z.string()).optional(),
|
|
521
|
+
federation_registration_endpoint: z.url().optional(),
|
|
522
|
+
request_authentication_methods_supported: z.object({
|
|
523
|
+
authorization_endpoint: z.array(z.string()).optional(),
|
|
524
|
+
pushed_authorization_request_endpoint: z.array(z.string()).optional()
|
|
525
|
+
}).optional(),
|
|
526
|
+
request_authentication_signing_alg_values_supported: z.array(z.string()).optional()
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/metadata/entity/openIdCredentialVerifier.ts
|
|
531
|
+
/**
|
|
532
|
+
*
|
|
533
|
+
* {@link https://openid.github.io/federation-wallet/main.html#name-wallet-architecture-entity- | OpenID Credential Verifier }
|
|
534
|
+
*
|
|
535
|
+
*/
|
|
536
|
+
const openidCredentialVerifierEntityMetadata = createEntity({
|
|
537
|
+
identifier: "openid_credential_verifier",
|
|
538
|
+
additionalValidation: { client_registration_types: z.array(z.string()).optional() }
|
|
539
|
+
});
|
|
540
|
+
//#endregion
|
|
541
|
+
//#region src/metadata/entity/openIdProvider.ts
|
|
542
|
+
/**
|
|
543
|
+
*
|
|
544
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.3-1 | openID Provider}
|
|
545
|
+
*
|
|
546
|
+
*/
|
|
547
|
+
const openIdProviderEntityMetadata = createEntity({
|
|
548
|
+
identifier: "openid_provider",
|
|
549
|
+
additionalValidation: {
|
|
550
|
+
client_registration_types_supported: z.array(z.string()).optional(),
|
|
551
|
+
federation_registration_endpoint: z.url().optional(),
|
|
552
|
+
request_authentication_methods_supported: z.object({
|
|
553
|
+
authorization_endpoint: z.array(z.string()).optional(),
|
|
554
|
+
pushed_authorization_request_endpoint: z.array(z.string()).optional()
|
|
555
|
+
}).optional(),
|
|
556
|
+
request_authentication_signing_alg_values_supported: z.array(z.string()).optional()
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
//#endregion
|
|
560
|
+
//#region src/metadata/entity/openIdRelyingParty.ts
|
|
561
|
+
/**
|
|
562
|
+
*
|
|
563
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-5.1.2-1 | openID Relying Party }
|
|
564
|
+
*
|
|
565
|
+
*/
|
|
566
|
+
const openidRelyingPartyEntityMetadata = createEntity({
|
|
567
|
+
identifier: "openid_relying_party",
|
|
568
|
+
additionalValidation: { client_registration_types: z.array(z.string()).optional() }
|
|
569
|
+
});
|
|
570
|
+
//#endregion
|
|
571
|
+
//#region src/metadata/metadata.ts
|
|
572
|
+
const metadataSchema = z.object({
|
|
573
|
+
[federationEntityMetadata.identifier]: federationEntityMetadata.schema.optional(),
|
|
574
|
+
[openidRelyingPartyEntityMetadata.identifier]: openidRelyingPartyEntityMetadata.schema.optional(),
|
|
575
|
+
[openidCredentialVerifierEntityMetadata.identifier]: openidCredentialVerifierEntityMetadata.schema.optional(),
|
|
576
|
+
[openIdCredentialIssuerEntityMetadata.identifier]: openIdCredentialIssuerEntityMetadata.schema.optional(),
|
|
577
|
+
[openIdProviderEntityMetadata.identifier]: openIdProviderEntityMetadata.schema.optional(),
|
|
578
|
+
[oauthAuthorizationServerEntityMetadata.identifier]: oauthAuthorizationServerEntityMetadata.schema.optional(),
|
|
579
|
+
[oauthClientEntityMetadata.identifier]: oauthClientEntityMetadata.schema.optional(),
|
|
580
|
+
[oauthResourceEntityMetadata.identifier]: oauthResourceEntityMetadata.schema.optional()
|
|
581
|
+
}).loose();
|
|
582
|
+
//#endregion
|
|
583
|
+
//#region src/utils/dateSchema.ts
|
|
584
|
+
/**
|
|
585
|
+
*
|
|
586
|
+
* NumericDate (RFC 7519 Section 2): seconds since the epoch, parsed to a js date object
|
|
587
|
+
*
|
|
588
|
+
*/
|
|
589
|
+
const dateSchema = z.number().transform((seconds) => /* @__PURE__ */ new Date(seconds * 1e3));
|
|
590
|
+
//#endregion
|
|
591
|
+
//#region src/utils/url.ts
|
|
592
|
+
/**
|
|
593
|
+
*
|
|
594
|
+
* Add paths to a url
|
|
595
|
+
*
|
|
596
|
+
* ## example
|
|
597
|
+
*
|
|
598
|
+
* ```typescript
|
|
599
|
+
* const url = addPaths('https://example.org','path', 'two')
|
|
600
|
+
* assert(url, "https://example.org/path/two")
|
|
601
|
+
*
|
|
602
|
+
* const url = addPaths('https://example.org/','path', 'two')
|
|
603
|
+
* assert(url, "https://example.org/path/two")
|
|
604
|
+
*
|
|
605
|
+
* const url = addPaths('https://example.org/','path/', '/two/')
|
|
606
|
+
* assert(url, "https://example.org/path/two")
|
|
607
|
+
* ```
|
|
608
|
+
*
|
|
609
|
+
*/
|
|
610
|
+
const addPaths = (baseUrl, ...paths) => {
|
|
611
|
+
const [scheme, rest] = baseUrl.split("://");
|
|
612
|
+
if (!rest) throw new OpenIdFederationError("validation", "not a valid URL");
|
|
613
|
+
return `${scheme}://${rest.split("/").concat(...paths.map((p) => p.split("/"))).filter((s) => s.length > 0).join("/")}`;
|
|
614
|
+
};
|
|
615
|
+
const addSearchParams = (baseUrl, searchParams) => baseUrl.endsWith("?") ? `${baseUrl}${searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams)}` : `${baseUrl}?${searchParams instanceof URLSearchParams ? searchParams : new URLSearchParams(searchParams)}`;
|
|
616
|
+
/**
|
|
617
|
+
*
|
|
618
|
+
* Compares two entity identifiers as Section 16 requires: code point by code point. A trailing slash is only removed
|
|
619
|
+
* when building the well-known URL.
|
|
620
|
+
*
|
|
621
|
+
*/
|
|
622
|
+
const isSameEntityId = (a, b) => a === b;
|
|
623
|
+
//#endregion
|
|
624
|
+
//#region src/utils/fetch.ts
|
|
625
|
+
const defaultFetch = (input, init) => globalThis.fetch(input, init);
|
|
626
|
+
async function get({ url, searchParams, responseValidationSchema, requiredContentType, fetchCallback = defaultFetch }) {
|
|
627
|
+
const urlSearchParams = new URLSearchParams(searchParams);
|
|
628
|
+
const urlWithSearchParams = urlSearchParams.toString() ? addSearchParams(url, urlSearchParams) : url;
|
|
629
|
+
const response = await fetchCallback(urlWithSearchParams, { method: "GET" });
|
|
630
|
+
if (!response.ok) throw new Error(`request to '${urlWithSearchParams}' failed with status ${response.status}`);
|
|
631
|
+
if (requiredContentType && !isMediaType(response.headers.get("content-type"), requiredContentType)) throw new Error(`received content-type '${response.headers.get("content-type")}' does not equal expected content-type '${requiredContentType}'`);
|
|
632
|
+
if (responseValidationSchema) {
|
|
633
|
+
const json = await response.json();
|
|
634
|
+
return validate({
|
|
635
|
+
data: json,
|
|
636
|
+
schema: responseValidationSchema,
|
|
637
|
+
errorMessage: "invalid response from the GET call"
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
return await response.text();
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
*
|
|
644
|
+
* @todo make get/post use the same method private internally as changes with apply to both
|
|
645
|
+
*
|
|
646
|
+
*/
|
|
647
|
+
const post = async ({ url, body, responseValidationSchema, fetchCallback = defaultFetch }) => {
|
|
648
|
+
const response = await fetchCallback(url, {
|
|
649
|
+
method: "POST",
|
|
650
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
651
|
+
headers: { "Content-Type": "application/json" }
|
|
652
|
+
});
|
|
653
|
+
if (responseValidationSchema) {
|
|
654
|
+
const json = await response.json();
|
|
655
|
+
return validate({
|
|
656
|
+
data: json,
|
|
657
|
+
schema: responseValidationSchema,
|
|
658
|
+
errorMessage: "invalid response from a POST call"
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
return await response.text();
|
|
662
|
+
};
|
|
663
|
+
const fetcher = {
|
|
664
|
+
get,
|
|
665
|
+
post
|
|
666
|
+
};
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region src/trustMark/trustMark.ts
|
|
669
|
+
/**
|
|
670
|
+
*
|
|
671
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-7.1 | Trust Mark Claims}
|
|
672
|
+
*
|
|
673
|
+
*/
|
|
674
|
+
const trustMarkClaimsSchema = z.object({
|
|
675
|
+
iss: z.string(),
|
|
676
|
+
sub: z.string(),
|
|
677
|
+
trust_mark_type: z.string(),
|
|
678
|
+
iat: dateSchema,
|
|
679
|
+
exp: dateSchema.optional(),
|
|
680
|
+
logo_uri: z.url().optional(),
|
|
681
|
+
ref: z.url().optional(),
|
|
682
|
+
delegation: z.string().optional()
|
|
683
|
+
}).loose();
|
|
684
|
+
/**
|
|
685
|
+
*
|
|
686
|
+
* An entry of the `trust_marks` claim of an entity configuration
|
|
687
|
+
*
|
|
688
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-3.1.1 | trust_marks}
|
|
689
|
+
*
|
|
690
|
+
*/
|
|
691
|
+
const trustMarkSchema = z.object({
|
|
692
|
+
trust_mark_type: z.string(),
|
|
693
|
+
trust_mark: jsonWebTokenSchema({ claimsSchema: trustMarkClaimsSchema })
|
|
694
|
+
}).refine((entry) => entry.trust_mark_type === entry.trust_mark.claims.trust_mark_type, {
|
|
695
|
+
message: "trust_mark_type must be the trust_mark_type of the trust mark JWT",
|
|
696
|
+
path: ["trust_mark_type"]
|
|
697
|
+
});
|
|
698
|
+
//#endregion
|
|
699
|
+
//#region src/trustMark/trustMarkIssuer.ts
|
|
700
|
+
const trustMarkIssuerSchema = z.record(z.string(), z.array(z.string()));
|
|
701
|
+
//#endregion
|
|
702
|
+
//#region src/trustMark/trustMarkOwner.ts
|
|
703
|
+
const trustMarkOwnerSchema = z.record(z.string(), z.object({
|
|
704
|
+
sub: z.string(),
|
|
705
|
+
jwks: jsonWebKeySetSchema
|
|
706
|
+
}));
|
|
707
|
+
//#endregion
|
|
708
|
+
//#region src/entityStatement/entityStatementClaims.ts
|
|
709
|
+
const entityStatementClaimsSchema = z.object({
|
|
710
|
+
iss: z.string(),
|
|
711
|
+
sub: z.string(),
|
|
712
|
+
iat: dateSchema,
|
|
713
|
+
exp: dateSchema,
|
|
714
|
+
jwks: jsonWebKeySetSchema,
|
|
715
|
+
authority_hints: z.array(z.url()).optional(),
|
|
716
|
+
metadata: metadataSchema.optional(),
|
|
717
|
+
metadata_policy: z.record(z.string(), z.record(z.string(), metadataPolicySchema.optional())).optional(),
|
|
718
|
+
constraints: constraintSchema.optional(),
|
|
719
|
+
crit: z.array(z.string()).optional(),
|
|
720
|
+
metadata_policy_crit: z.array(z.string()).optional(),
|
|
721
|
+
trust_marks: z.array(trustMarkSchema).optional(),
|
|
722
|
+
trust_mark_issuers: trustMarkIssuerSchema.optional(),
|
|
723
|
+
trust_mark_owners: trustMarkOwnerSchema.optional(),
|
|
724
|
+
source_endpoint: z.url().optional()
|
|
725
|
+
}).superRefine((data, ctx) => {
|
|
726
|
+
const keyIds = data.jwks.keys.map((key) => key.kid);
|
|
727
|
+
if (keyIds.some((key, i) => keyIds.indexOf(key) !== i)) ctx.addIssue({
|
|
728
|
+
code: "custom",
|
|
729
|
+
message: "keys include duplicate key ids",
|
|
730
|
+
path: ["jwks", "keys"]
|
|
731
|
+
});
|
|
732
|
+
});
|
|
733
|
+
//#endregion
|
|
734
|
+
//#region src/entityStatement/entityStatementHeader.ts
|
|
735
|
+
/**
|
|
736
|
+
*
|
|
737
|
+
* @todo define extact scheme
|
|
738
|
+
*
|
|
739
|
+
*/
|
|
740
|
+
const entityStatementHeaderSchema = z.object({
|
|
741
|
+
kid: z.string(),
|
|
742
|
+
typ: z.literal("entity-statement+jwt")
|
|
743
|
+
}).loose();
|
|
744
|
+
//#endregion
|
|
745
|
+
//#region src/entityStatement/createEntityStatement.ts
|
|
746
|
+
/**
|
|
747
|
+
*
|
|
748
|
+
* Create an entity statement
|
|
749
|
+
*
|
|
750
|
+
* The signing callback will be called with the `header.kid` value in the `claims.jwks.keys` and a signed JWT will be returned
|
|
751
|
+
*
|
|
752
|
+
*/
|
|
753
|
+
const createEntityStatement = async ({ signJwtCallback, claims, jwk, header = {
|
|
754
|
+
typ: "entity-statement+jwt",
|
|
755
|
+
kid: jwk.kid
|
|
756
|
+
} }) => {
|
|
757
|
+
if (header.kid !== jwk.kid) throw new Error(`key id in the header: '${header.kid}' does not match the key id in the JWK: '${jwk.kid}'`);
|
|
758
|
+
validate({
|
|
759
|
+
schema: entityStatementHeaderSchema,
|
|
760
|
+
data: header,
|
|
761
|
+
errorMessage: "invalid header claims provided"
|
|
762
|
+
});
|
|
763
|
+
validate({
|
|
764
|
+
schema: entityStatementClaimsSchema,
|
|
765
|
+
data: claims,
|
|
766
|
+
errorMessage: "invalid payload claims provided"
|
|
767
|
+
});
|
|
768
|
+
const signature = await signJwtCallback({
|
|
769
|
+
toBeSigned: createJwtSignableInput(header, claims),
|
|
770
|
+
jwk
|
|
771
|
+
});
|
|
772
|
+
return createJsonWebToken(header, claims, signature);
|
|
773
|
+
};
|
|
774
|
+
//#endregion
|
|
775
|
+
//#region src/jsonWeb/parseJsonWebToken.ts
|
|
776
|
+
const parseJsonWebToken = (jwt) => {
|
|
777
|
+
const [encodedHeader, encodedClaims, encodedSignature] = jwt.split(".");
|
|
778
|
+
if (!encodedHeader) throw new Error("could not find the header in the JWT");
|
|
779
|
+
if (!encodedClaims) throw new Error("could not find the claims in the JWT");
|
|
780
|
+
if (!encodedSignature) throw new Error("could not find the signature in the JWT");
|
|
781
|
+
return {
|
|
782
|
+
header: base64urlDecodeJson(encodedHeader),
|
|
783
|
+
claims: base64urlDecodeJson(encodedClaims),
|
|
784
|
+
signature: base64url.decode(encodedSignature),
|
|
785
|
+
signableInput: stringToBytes(`${encodedHeader}.${encodedClaims}`)
|
|
786
|
+
};
|
|
787
|
+
};
|
|
788
|
+
//#endregion
|
|
789
|
+
//#region src/jsonWeb/verifyJsonWebToken.ts
|
|
790
|
+
const verifyJwtSignature = async ({ jwt, jwks, verifyJwtCallback }) => {
|
|
791
|
+
const { header, signature, claims, signableInput } = parseJsonWebToken(jwt);
|
|
792
|
+
const jwk = getUsedJsonWebKey(header, jwks ? { jwks } : claims);
|
|
793
|
+
try {
|
|
794
|
+
if (!await verifyJwtCallback({
|
|
795
|
+
jwt,
|
|
796
|
+
header,
|
|
797
|
+
claims,
|
|
798
|
+
signature,
|
|
799
|
+
jwk,
|
|
800
|
+
data: signableInput
|
|
801
|
+
})) throw new Error("Signature in the JWT is invalid");
|
|
802
|
+
} catch (e) {
|
|
803
|
+
if (typeof e === "string") throw new Error(e);
|
|
804
|
+
throw e;
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
//#endregion
|
|
808
|
+
//#region src/entityStatement/entityStatementJwt.ts
|
|
809
|
+
const entityStatementJwtSchema = jsonWebTokenSchema({
|
|
810
|
+
headerSchema: entityStatementHeaderSchema,
|
|
811
|
+
claimsSchema: entityStatementClaimsSchema
|
|
812
|
+
});
|
|
813
|
+
//#endregion
|
|
814
|
+
//#region src/entityStatement/fetchEntityStatement.ts
|
|
815
|
+
const fetchEntityStatement = async ({ sub, verifyJwtCallback, iss, endpoint, issEntityConfiguration, fetchCallback }) => {
|
|
816
|
+
const issEntityConfigurationClaims = issEntityConfiguration ?? await fetchEntityConfiguration({
|
|
817
|
+
entityId: iss,
|
|
818
|
+
verifyJwtCallback,
|
|
819
|
+
fetchCallback
|
|
820
|
+
});
|
|
821
|
+
const fetchEndpoint = endpoint ?? issEntityConfigurationClaims.metadata?.federation_entity?.federation_fetch_endpoint;
|
|
822
|
+
if (!fetchEndpoint) throw new Error("No fetch endpoint provided or in the issuer configuration");
|
|
823
|
+
const entityStatementJwt = await fetcher.get({
|
|
824
|
+
url: fetchEndpoint,
|
|
825
|
+
searchParams: { sub },
|
|
826
|
+
requiredContentType: "application/entity-statement+jwt",
|
|
827
|
+
fetchCallback
|
|
828
|
+
});
|
|
829
|
+
const { claims } = validate({
|
|
830
|
+
schema: entityStatementJwtSchema,
|
|
831
|
+
data: entityStatementJwt,
|
|
832
|
+
errorMessage: "fetched entity statement JWT is invalid"
|
|
833
|
+
});
|
|
834
|
+
if (!isSameEntityId(claims.iss, iss) || !isSameEntityId(claims.sub, sub)) throw new OpenIdFederationError("validation", `entity statement fetched for issuer '${iss}' and subject '${sub}' has issuer '${claims.iss}' and subject '${claims.sub}'`);
|
|
835
|
+
await verifyJwtSignature({
|
|
836
|
+
verifyJwtCallback,
|
|
837
|
+
jwt: entityStatementJwt,
|
|
838
|
+
jwks: issEntityConfigurationClaims.jwks
|
|
839
|
+
});
|
|
840
|
+
return claims;
|
|
841
|
+
};
|
|
842
|
+
//#endregion
|
|
843
|
+
//#region src/entityConfiguration/entityConfigurationClaims.ts
|
|
844
|
+
const entityConfigurationClaimsSchema = entityStatementClaimsSchema.refine((data) => data.iss === data.sub, {
|
|
845
|
+
message: "iss and sub must be equal",
|
|
846
|
+
path: ["iss", "sub"]
|
|
847
|
+
});
|
|
848
|
+
//#endregion
|
|
849
|
+
//#region src/entityConfiguration/entityConfigurationHeader.ts
|
|
850
|
+
/**
|
|
851
|
+
*
|
|
852
|
+
* @todo define exact scheme
|
|
853
|
+
*
|
|
854
|
+
*/
|
|
855
|
+
const entityConfigurationHeaderSchema = z.object({
|
|
856
|
+
kid: z.string(),
|
|
857
|
+
typ: z.literal("entity-statement+jwt")
|
|
858
|
+
}).loose();
|
|
859
|
+
//#endregion
|
|
860
|
+
//#region src/entityConfiguration/createEntityConfiguration.ts
|
|
861
|
+
/**
|
|
862
|
+
*
|
|
863
|
+
* Create an entity configuration
|
|
864
|
+
*
|
|
865
|
+
* The signing callback will be called with the `header.kid` value in the `claims.jwks.keys` and a signed JWT will be returned
|
|
866
|
+
*
|
|
867
|
+
*/
|
|
868
|
+
const createEntityConfiguration = async ({ header, signJwtCallback, claims }) => {
|
|
869
|
+
const validatedHeader = validate({
|
|
870
|
+
schema: entityConfigurationHeaderSchema,
|
|
871
|
+
data: header,
|
|
872
|
+
errorMessage: "invalid header claims provided"
|
|
873
|
+
});
|
|
874
|
+
const validatedClaims = validate({
|
|
875
|
+
data: claims,
|
|
876
|
+
schema: entityConfigurationClaimsSchema,
|
|
877
|
+
errorMessage: "invalid payload claims provided"
|
|
878
|
+
});
|
|
879
|
+
const signature = await signJwtCallback({
|
|
880
|
+
toBeSigned: createJwtSignableInput(header, claims),
|
|
881
|
+
jwk: getUsedJsonWebKey(validatedHeader, validatedClaims)
|
|
882
|
+
});
|
|
883
|
+
return createJsonWebToken(header, claims, signature);
|
|
884
|
+
};
|
|
885
|
+
//#endregion
|
|
886
|
+
//#region src/entityConfiguration/entityConfigurationJwt.ts
|
|
887
|
+
const entityConfigurationJwtSchema = jsonWebTokenSchema({
|
|
888
|
+
headerSchema: entityConfigurationHeaderSchema,
|
|
889
|
+
claimsSchema: entityConfigurationClaimsSchema
|
|
890
|
+
});
|
|
891
|
+
//#endregion
|
|
892
|
+
//#region src/entityConfiguration/fetchEntityConfiguration.ts
|
|
893
|
+
/**
|
|
894
|
+
*
|
|
895
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-9.1 | Federation Entity Request}
|
|
896
|
+
*
|
|
897
|
+
*/
|
|
898
|
+
const fetchEntityConfiguration = async ({ entityId, verifyJwtCallback, fetchCallback }) => {
|
|
899
|
+
const federationUrl = addPaths(entityId, ".well-known", "openid-federation");
|
|
900
|
+
const entityConfigurationJwt = await fetcher.get({
|
|
901
|
+
url: federationUrl,
|
|
902
|
+
requiredContentType: "application/entity-statement+jwt",
|
|
903
|
+
fetchCallback
|
|
904
|
+
});
|
|
905
|
+
const { claims } = validate({
|
|
906
|
+
schema: entityConfigurationJwtSchema,
|
|
907
|
+
data: entityConfigurationJwt,
|
|
908
|
+
errorMessage: "fetched entity configuration JWT is invalid"
|
|
909
|
+
});
|
|
910
|
+
if (!isSameEntityId(claims.sub, entityId)) throw new OpenIdFederationError("validation", `entity configuration fetched for '${entityId}' has subject '${claims.sub}'`);
|
|
911
|
+
await verifyJwtSignature({
|
|
912
|
+
jwt: entityConfigurationJwt,
|
|
913
|
+
verifyJwtCallback
|
|
914
|
+
});
|
|
915
|
+
return claims;
|
|
916
|
+
};
|
|
917
|
+
//#endregion
|
|
918
|
+
//#region src/utils/data.ts
|
|
919
|
+
/**
|
|
920
|
+
* Converts an object to an array of entries with better typing for the key
|
|
921
|
+
*/
|
|
922
|
+
function objectToEntries(obj) {
|
|
923
|
+
return Object.entries(obj);
|
|
924
|
+
}
|
|
925
|
+
const isNullOrUndefined = (value) => value === null || value === void 0;
|
|
926
|
+
const immutable = (obj) => new Proxy(obj, {
|
|
927
|
+
get(target, prop) {
|
|
928
|
+
const value = target[prop];
|
|
929
|
+
return typeof value === "object" && value !== null ? Array.isArray(value) ? Object.freeze([...value].map((item) => typeof item === "object" && item !== null ? immutable(item) : item)) : immutable(value) : value;
|
|
930
|
+
},
|
|
931
|
+
set() {
|
|
932
|
+
throw new Error("This object is immutable.");
|
|
933
|
+
},
|
|
934
|
+
deleteProperty() {
|
|
935
|
+
throw new Error("This object is immutable.");
|
|
936
|
+
}
|
|
937
|
+
});
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region src/resolveTrustChains/policies/errors/PolicyValidationError.ts
|
|
940
|
+
var PolicyValidationError = class extends Error {
|
|
941
|
+
constructor(message, details) {
|
|
942
|
+
super(message);
|
|
943
|
+
this.name = "PolicyValidationError";
|
|
944
|
+
this.details = details;
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
//#endregion
|
|
948
|
+
//#region src/resolveTrustChains/policies/MetadataHelper.ts
|
|
949
|
+
var MetadataHelper = class {
|
|
950
|
+
constructor(leafMetadata) {
|
|
951
|
+
this.leafMetadata = leafMetadata;
|
|
952
|
+
}
|
|
953
|
+
hasEntityType(service) {
|
|
954
|
+
return this.leafMetadata[service] !== void 0;
|
|
955
|
+
}
|
|
956
|
+
hasProperty(service, property) {
|
|
957
|
+
return this.leafMetadata[service]?.[property] !== void 0;
|
|
958
|
+
}
|
|
959
|
+
getPropertyValue(service, property) {
|
|
960
|
+
const serviceBlock = this.leafMetadata[service];
|
|
961
|
+
if (serviceBlock === void 0) return void 0;
|
|
962
|
+
const propertyValue = serviceBlock[property];
|
|
963
|
+
if (propertyValue === void 0) return void 0;
|
|
964
|
+
return propertyValue;
|
|
965
|
+
}
|
|
966
|
+
setPropertyValue(service, property, value) {
|
|
967
|
+
this.leafMetadata = {
|
|
968
|
+
...this.leafMetadata,
|
|
969
|
+
[service]: {
|
|
970
|
+
...this.leafMetadata[service],
|
|
971
|
+
[property]: value
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
deleteProperty(service, property) {
|
|
976
|
+
if (this.leafMetadata[service] === void 0) return;
|
|
977
|
+
this.leafMetadata = {
|
|
978
|
+
...this.leafMetadata,
|
|
979
|
+
[service]: { ...this.leafMetadata[service] }
|
|
980
|
+
};
|
|
981
|
+
delete this.leafMetadata[service][property];
|
|
982
|
+
}
|
|
983
|
+
asMetadata() {
|
|
984
|
+
return this.leafMetadata;
|
|
985
|
+
}
|
|
986
|
+
asMetadataPolicy() {
|
|
987
|
+
return this.leafMetadata;
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
//#endregion
|
|
991
|
+
//#region src/resolveTrustChains/policies/utils.ts
|
|
992
|
+
function intersect(operator1, operator2) {
|
|
993
|
+
const set1 = new Set(operator1);
|
|
994
|
+
const set2 = new Set(operator2);
|
|
995
|
+
return [...set1].filter((value) => set2.has(value));
|
|
996
|
+
}
|
|
997
|
+
function union(operator1, operator2) {
|
|
998
|
+
return [.../* @__PURE__ */ new Set([...operator1, ...operator2])];
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Merges the metadata of the leaf entity with the metadata of the superior entity statement
|
|
1002
|
+
* The superior always has the highest priority
|
|
1003
|
+
*/
|
|
1004
|
+
function mergeMetadata(leafConfigMetadata, superiorEntityStatement) {
|
|
1005
|
+
const mergedLeafMetadata = new MetadataHelper(immutable(leafConfigMetadata));
|
|
1006
|
+
for (const [entityType, entityConfigMetadata] of objectToEntries(superiorEntityStatement)) {
|
|
1007
|
+
if (!mergedLeafMetadata.hasEntityType(String(entityType))) continue;
|
|
1008
|
+
for (const [key, value] of objectToEntries(entityConfigMetadata ?? {})) mergedLeafMetadata.setPropertyValue(String(entityType), String(key), value);
|
|
1009
|
+
}
|
|
1010
|
+
return mergedLeafMetadata.asMetadata();
|
|
1011
|
+
}
|
|
1012
|
+
//#endregion
|
|
1013
|
+
//#region src/resolveTrustChains/policies/applyMetadataPolicyToMetadata.ts
|
|
1014
|
+
function applyMetadataPolicyToMetadata({ leafMetadata, policyMetadata }) {
|
|
1015
|
+
const resolvedLeafMetadata = new MetadataHelper(immutable(leafMetadata));
|
|
1016
|
+
for (const [serviceKey, service] of objectToEntries(policyMetadata)) {
|
|
1017
|
+
if (!service || !resolvedLeafMetadata.hasEntityType(serviceKey)) continue;
|
|
1018
|
+
for (const [servicePropertyKey, policyValue] of objectToEntries(service)) {
|
|
1019
|
+
if (!policyValue) continue;
|
|
1020
|
+
const policies = objectToEntries(policyValue).filter(([key]) => isExistingPolicyKey(key)).sort(([policyKeyA], [policyKeyB]) => allSupportedPolicies[policyKeyA].orderOfApplication - allSupportedPolicies[policyKeyB].orderOfApplication);
|
|
1021
|
+
const path = `${serviceKey}.${servicePropertyKey}`;
|
|
1022
|
+
const isScope = servicePropertyKey === "scope";
|
|
1023
|
+
const scope = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1024
|
+
if (isScope && typeof scope === "string") resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, splitScope(scope));
|
|
1025
|
+
for (const [policyPropertyKey, rawValueFromPolicy] of policies) {
|
|
1026
|
+
const valueFromPolicy = isScope && typeof rawValueFromPolicy === "string" ? splitScope(rawValueFromPolicy) : rawValueFromPolicy;
|
|
1027
|
+
switch (policyPropertyKey) {
|
|
1028
|
+
case "value":
|
|
1029
|
+
if (valueFromPolicy === null) {
|
|
1030
|
+
resolvedLeafMetadata.deleteProperty(serviceKey, servicePropertyKey);
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, valueFromPolicy);
|
|
1034
|
+
break;
|
|
1035
|
+
case "add": {
|
|
1036
|
+
const targetValue = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey) ?? [];
|
|
1037
|
+
if (!Array.isArray(targetValue)) throw new PolicyValidationError("Cannot apply add policy because the target is not an array", {
|
|
1038
|
+
path,
|
|
1039
|
+
policyValue: valueFromPolicy,
|
|
1040
|
+
targetValue
|
|
1041
|
+
});
|
|
1042
|
+
const newValue = union(targetValue, valueFromPolicy);
|
|
1043
|
+
resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, newValue);
|
|
1044
|
+
break;
|
|
1045
|
+
}
|
|
1046
|
+
case "one_of": {
|
|
1047
|
+
const targetValue = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1048
|
+
if (isNullOrUndefined(targetValue)) break;
|
|
1049
|
+
if (!Array.isArray(valueFromPolicy)) throw new PolicyValidationError("Cannot apply one_of policy because the value is not an array", {
|
|
1050
|
+
path,
|
|
1051
|
+
policyValue: valueFromPolicy,
|
|
1052
|
+
targetValue
|
|
1053
|
+
});
|
|
1054
|
+
if (!valueFromPolicy.some((value) => value === targetValue)) throw new PolicyValidationError("Cannot apply one_of policy because the intersection is empty", {
|
|
1055
|
+
path,
|
|
1056
|
+
policyValue: valueFromPolicy,
|
|
1057
|
+
targetValue
|
|
1058
|
+
});
|
|
1059
|
+
break;
|
|
1060
|
+
}
|
|
1061
|
+
case "default":
|
|
1062
|
+
if (resolvedLeafMetadata.hasProperty(serviceKey, servicePropertyKey)) continue;
|
|
1063
|
+
resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, valueFromPolicy);
|
|
1064
|
+
break;
|
|
1065
|
+
case "subset_of": {
|
|
1066
|
+
const targetValue = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1067
|
+
if (isNullOrUndefined(targetValue)) break;
|
|
1068
|
+
if (!Array.isArray(targetValue)) throw new PolicyValidationError("Cannot apply subset_of policy because the target is not an array", {
|
|
1069
|
+
path,
|
|
1070
|
+
policyValue: valueFromPolicy,
|
|
1071
|
+
targetValue
|
|
1072
|
+
});
|
|
1073
|
+
if (!Array.isArray(valueFromPolicy)) throw new PolicyValidationError("Cannot apply subset_of policy because the value is not an array", {
|
|
1074
|
+
path,
|
|
1075
|
+
policyValue: valueFromPolicy,
|
|
1076
|
+
targetValue
|
|
1077
|
+
});
|
|
1078
|
+
const newValue = targetValue.filter((value) => valueFromPolicy.includes(value));
|
|
1079
|
+
resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, newValue);
|
|
1080
|
+
break;
|
|
1081
|
+
}
|
|
1082
|
+
case "superset_of": {
|
|
1083
|
+
const targetValue = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1084
|
+
if (isNullOrUndefined(targetValue)) break;
|
|
1085
|
+
if (!Array.isArray(targetValue)) throw new PolicyValidationError("Cannot apply superset_of policy because the target is not an array", {
|
|
1086
|
+
path,
|
|
1087
|
+
policyValue: valueFromPolicy,
|
|
1088
|
+
targetValue
|
|
1089
|
+
});
|
|
1090
|
+
if (!Array.isArray(valueFromPolicy)) throw new PolicyValidationError("Cannot apply superset_of policy because the value is not an array", {
|
|
1091
|
+
path,
|
|
1092
|
+
policyValue: valueFromPolicy,
|
|
1093
|
+
targetValue
|
|
1094
|
+
});
|
|
1095
|
+
if (!valueFromPolicy.every((value) => targetValue.includes(value))) throw new PolicyValidationError("The target does not contain all the values from the policy superset", {
|
|
1096
|
+
path,
|
|
1097
|
+
policyValue: valueFromPolicy,
|
|
1098
|
+
targetValue
|
|
1099
|
+
});
|
|
1100
|
+
break;
|
|
1101
|
+
}
|
|
1102
|
+
case "essential": {
|
|
1103
|
+
if (!valueFromPolicy) break;
|
|
1104
|
+
const targetValue = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1105
|
+
if (isNullOrUndefined(targetValue)) throw new PolicyValidationError("The policy is required to have a value", {
|
|
1106
|
+
path,
|
|
1107
|
+
policyValue: valueFromPolicy,
|
|
1108
|
+
targetValue
|
|
1109
|
+
});
|
|
1110
|
+
break;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
const resolvedScope = resolvedLeafMetadata.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1115
|
+
if (isScope && Array.isArray(resolvedScope)) resolvedLeafMetadata.setPropertyValue(serviceKey, servicePropertyKey, resolvedScope.join(" "));
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
return { resolvedLeafMetadata: resolvedLeafMetadata.asMetadata() };
|
|
1119
|
+
}
|
|
1120
|
+
const splitScope = (scope) => scope.split(" ").filter((value) => value !== "");
|
|
1121
|
+
//#endregion
|
|
1122
|
+
//#region src/resolveTrustChains/policies/errors/PolicyMergeError.ts
|
|
1123
|
+
var PolicyOperatorMergeError = class extends Error {
|
|
1124
|
+
constructor(message, details) {
|
|
1125
|
+
super(message);
|
|
1126
|
+
this.name = "PolicyOperatorMergeError";
|
|
1127
|
+
this.details = details;
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
//#endregion
|
|
1131
|
+
//#region src/resolveTrustChains/policies/combineExistingMetadataPolicyOperators.ts
|
|
1132
|
+
function combineExistingMetadataPolicyOperators({ contextPath, existingPolicyRules, newPolicyRules }) {
|
|
1133
|
+
const combinedPolicyRules = { ...existingPolicyRules };
|
|
1134
|
+
for (const [policyPropertyKey, policyRuleValue] of objectToEntries(newPolicyRules)) {
|
|
1135
|
+
if (!isExistingPolicyKey(policyPropertyKey)) continue;
|
|
1136
|
+
if (combinedPolicyRules[policyPropertyKey] === void 0) {
|
|
1137
|
+
combinedPolicyRules[policyPropertyKey] = policyRuleValue;
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
1140
|
+
const existingPolicyRuleValue = combinedPolicyRules[policyPropertyKey];
|
|
1141
|
+
const operator = allSupportedPolicies[policyPropertyKey];
|
|
1142
|
+
const operatorInputResult = operator.operatorSchema.safeParse(policyRuleValue);
|
|
1143
|
+
if (!operatorInputResult.success) throw operatorInputResult.error;
|
|
1144
|
+
const newPolicyRuleValue = operatorInputResult.data;
|
|
1145
|
+
switch (operator.mergeStrategy) {
|
|
1146
|
+
case 0:
|
|
1147
|
+
if (Array.isArray(existingPolicyRuleValue) && Array.isArray(newPolicyRuleValue)) {
|
|
1148
|
+
if (existingPolicyRuleValue.length !== newPolicyRuleValue.length) throw new PolicyOperatorMergeError("Policy rule values are not equal", {
|
|
1149
|
+
path: contextPath,
|
|
1150
|
+
operatorA: existingPolicyRules,
|
|
1151
|
+
operatorB: newPolicyRules
|
|
1152
|
+
});
|
|
1153
|
+
if (existingPolicyRuleValue.some((value, i) => value !== newPolicyRuleValue[i])) throw new PolicyOperatorMergeError("Policy rule values are not equal", {
|
|
1154
|
+
path: contextPath,
|
|
1155
|
+
operatorA: existingPolicyRules,
|
|
1156
|
+
operatorB: newPolicyRules
|
|
1157
|
+
});
|
|
1158
|
+
} else if (existingPolicyRuleValue !== newPolicyRuleValue) throw new PolicyOperatorMergeError("Policy rule values are not equal", {
|
|
1159
|
+
path: contextPath,
|
|
1160
|
+
operatorA: existingPolicyRules,
|
|
1161
|
+
operatorB: newPolicyRules
|
|
1162
|
+
});
|
|
1163
|
+
break;
|
|
1164
|
+
case 1:
|
|
1165
|
+
if (!Array.isArray(existingPolicyRuleValue) || !Array.isArray(newPolicyRuleValue)) throw new PolicyOperatorMergeError("Operator values are not an array", {
|
|
1166
|
+
path: contextPath,
|
|
1167
|
+
operatorA: existingPolicyRules,
|
|
1168
|
+
operatorB: newPolicyRules
|
|
1169
|
+
});
|
|
1170
|
+
combinedPolicyRules[policyPropertyKey] = union(existingPolicyRuleValue, newPolicyRuleValue);
|
|
1171
|
+
break;
|
|
1172
|
+
case 2:
|
|
1173
|
+
case 4: {
|
|
1174
|
+
if (!Array.isArray(existingPolicyRuleValue) || !Array.isArray(newPolicyRuleValue)) throw new PolicyOperatorMergeError("Existing policy rule value is not an array", {
|
|
1175
|
+
path: contextPath,
|
|
1176
|
+
operatorA: existingPolicyRules,
|
|
1177
|
+
operatorB: newPolicyRules
|
|
1178
|
+
});
|
|
1179
|
+
const intersection = intersect(existingPolicyRuleValue, newPolicyRuleValue);
|
|
1180
|
+
if (intersection.length === 0 && operator.mergeStrategy === 2) throw new PolicyOperatorMergeError("Intersection is empty", {
|
|
1181
|
+
path: contextPath,
|
|
1182
|
+
operatorA: existingPolicyRules,
|
|
1183
|
+
operatorB: newPolicyRules
|
|
1184
|
+
});
|
|
1185
|
+
combinedPolicyRules[policyPropertyKey] = intersection;
|
|
1186
|
+
break;
|
|
1187
|
+
}
|
|
1188
|
+
case 3:
|
|
1189
|
+
if (typeof existingPolicyRuleValue !== "boolean" || typeof newPolicyRuleValue !== "boolean") throw new PolicyOperatorMergeError("Existing policy rule value is not a boolean", {
|
|
1190
|
+
path: contextPath,
|
|
1191
|
+
operatorA: existingPolicyRules,
|
|
1192
|
+
operatorB: newPolicyRules
|
|
1193
|
+
});
|
|
1194
|
+
combinedPolicyRules[policyPropertyKey] = existingPolicyRuleValue || newPolicyRuleValue;
|
|
1195
|
+
break;
|
|
1196
|
+
default: throw new PolicyOperatorMergeError(`Unknown merge strategy: ${operator.mergeStrategy}`, {
|
|
1197
|
+
path: contextPath,
|
|
1198
|
+
operatorA: existingPolicyRules,
|
|
1199
|
+
operatorB: newPolicyRules
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
return combinedPolicyRules;
|
|
1204
|
+
}
|
|
1205
|
+
//#endregion
|
|
1206
|
+
//#region src/resolveTrustChains/policies/combineMetadataPolicies.ts
|
|
1207
|
+
function combineMetadataPolicies({ statements }) {
|
|
1208
|
+
if (statements.length === 0) throw new OpenIdFederationError("generic", "Chain is empty");
|
|
1209
|
+
const mergedPolicyMap = new MetadataHelper({});
|
|
1210
|
+
for (let i = statements.length - 1; i >= 0; i--) {
|
|
1211
|
+
const entityStatement = statements[i];
|
|
1212
|
+
if (!entityStatement) continue;
|
|
1213
|
+
if (!entityStatement.metadata_policy) continue;
|
|
1214
|
+
const metadataPolicyCrit = entityStatement.metadata_policy_crit;
|
|
1215
|
+
for (const [serviceKey, serviceProperties] of objectToEntries(entityStatement.metadata_policy)) for (const [servicePropertyKey, newPolicyRules] of objectToEntries(serviceProperties)) {
|
|
1216
|
+
if (newPolicyRules === void 0) continue;
|
|
1217
|
+
const contextPath = `${serviceKey}.${servicePropertyKey}`;
|
|
1218
|
+
if (metadataPolicyCrit) {
|
|
1219
|
+
const unsupportedMethodsAndRequired = Object.keys(newPolicyRules).filter((method) => !isExistingPolicyKey(method) && metadataPolicyCrit.includes(method));
|
|
1220
|
+
if (unsupportedMethodsAndRequired.length > 0) throw new OpenIdFederationError("metadataPolicyCrit", `Unsupported policy method and is required by the metadata_policy_crit: ${unsupportedMethodsAndRequired.join(", ")}`);
|
|
1221
|
+
}
|
|
1222
|
+
const existingPolicyRule = mergedPolicyMap.getPropertyValue(serviceKey, servicePropertyKey);
|
|
1223
|
+
if (!existingPolicyRule) {
|
|
1224
|
+
mergedPolicyMap.setPropertyValue(serviceKey, servicePropertyKey, newPolicyRules);
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
const combinedPolicyRulesRaw = combineExistingMetadataPolicyOperators({
|
|
1228
|
+
contextPath,
|
|
1229
|
+
existingPolicyRules: existingPolicyRule,
|
|
1230
|
+
newPolicyRules
|
|
1231
|
+
});
|
|
1232
|
+
const combinedPolicyRules = metadataPolicySchema.safeParse(combinedPolicyRulesRaw);
|
|
1233
|
+
if (!combinedPolicyRules.success) throw combinedPolicyRules.error;
|
|
1234
|
+
mergedPolicyMap.setPropertyValue(serviceKey, servicePropertyKey, combinedPolicyRules.data);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
return { mergedPolicy: mergedPolicyMap.asMetadataPolicy() };
|
|
1238
|
+
}
|
|
1239
|
+
//#endregion
|
|
1240
|
+
//#region src/resolveTrustChains/resolveTrustChains.ts
|
|
1241
|
+
const ENTITY_STATEMENT_CONTENT_TYPE = "application/entity-statement+jwt";
|
|
1242
|
+
const fail = (message) => new OpenIdFederationError("validation", message);
|
|
1243
|
+
const reasonOf = (error) => error instanceof Error && error.message ? error.message : String(error);
|
|
1244
|
+
/**
|
|
1245
|
+
* Resolves the trust chains from the given entity to the given trust anchors and validates them as described in
|
|
1246
|
+
* {@link https://openid.net/specs/openid-federation-1_0.html#section-10 | Section 10}.
|
|
1247
|
+
*
|
|
1248
|
+
* Every entity configuration and subordinate statement is checked for its signature, `iat`, `exp` and `crit`. An
|
|
1249
|
+
* entity configuration must be about the requested entity and signed with a key its superior's subordinate statement
|
|
1250
|
+
* lists. A subordinate statement must be issued by the superior about the subject. Each statement may only contain the
|
|
1251
|
+
* claims Section 3.2 allows for its kind. `max_path_length` and
|
|
1252
|
+
* `allowed_entity_types` constraints are applied, then the metadata policies. Chains with `naming_constraints` are
|
|
1253
|
+
* rejected, as they are not evaluated. Trust marks are not verified.
|
|
1254
|
+
*
|
|
1255
|
+
* Paths that fail are returned in `failures` with the reason.
|
|
1256
|
+
*/
|
|
1257
|
+
const resolveTrustChainsWithFailures = async (options) => {
|
|
1258
|
+
const { entityId, verifyJwtCallback, fetchCallback, clockSkewSeconds = 0, maxDepth = 8, maxRequests = 64, maxAuthorityHints = 10, understoodCriticalClaims = [] } = options;
|
|
1259
|
+
const now = options.currentDate ?? /* @__PURE__ */ new Date();
|
|
1260
|
+
const { trustAnchors } = options;
|
|
1261
|
+
if (trustAnchors.length === 0) throw fail("Cannot resolve a trust chain for zero trust anchors");
|
|
1262
|
+
const findTrustAnchor = (id) => trustAnchors.find((anchor) => isSameEntityId(anchor.entityId, id));
|
|
1263
|
+
const failures = [];
|
|
1264
|
+
let requests = 0;
|
|
1265
|
+
let visits = 0;
|
|
1266
|
+
const get = async (url, searchParams) => {
|
|
1267
|
+
requests++;
|
|
1268
|
+
if (requests > maxRequests) throw fail(`trust chain resolution exceeded ${maxRequests} requests`);
|
|
1269
|
+
return fetcher.get({
|
|
1270
|
+
url,
|
|
1271
|
+
searchParams,
|
|
1272
|
+
requiredContentType: ENTITY_STATEMENT_CONTENT_TYPE,
|
|
1273
|
+
fetchCallback
|
|
1274
|
+
});
|
|
1275
|
+
};
|
|
1276
|
+
const assertCurrent = (statement) => {
|
|
1277
|
+
const skewMs = clockSkewSeconds * 1e3;
|
|
1278
|
+
if (!Number.isFinite(statement.iat.getTime()) || !Number.isFinite(statement.exp.getTime())) throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has an invalid iat or exp`);
|
|
1279
|
+
if (statement.iat.getTime() > now.getTime() + skewMs) throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has an iat in the future`);
|
|
1280
|
+
if (statement.exp.getTime() <= now.getTime() - skewMs) throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has expired`);
|
|
1281
|
+
const notUnderstood = (statement.crit ?? []).filter((claim) => !understoodCriticalClaims.includes(claim));
|
|
1282
|
+
if (notUnderstood.length > 0) throw fail(`statement about '${statement.sub}' issued by '${statement.iss}' has critical claims that are not understood: ${notUnderstood.join(", ")}`);
|
|
1283
|
+
};
|
|
1284
|
+
const entityConfigurations = /* @__PURE__ */ new Map();
|
|
1285
|
+
const fetchEntityConfiguration = (id) => {
|
|
1286
|
+
let pending = entityConfigurations.get(id);
|
|
1287
|
+
if (!pending) {
|
|
1288
|
+
pending = (async () => {
|
|
1289
|
+
const jwt = await get(addPaths(id, ".well-known", "openid-federation"));
|
|
1290
|
+
const { claims } = validate({
|
|
1291
|
+
schema: entityConfigurationJwtSchema,
|
|
1292
|
+
data: jwt,
|
|
1293
|
+
errorMessage: `entity configuration of '${id}' is invalid`
|
|
1294
|
+
});
|
|
1295
|
+
if (!isSameEntityId(claims.sub, id)) throw fail(`entity configuration fetched for '${id}' has subject '${claims.sub}'`);
|
|
1296
|
+
await verifyJwtSignature({
|
|
1297
|
+
jwt,
|
|
1298
|
+
verifyJwtCallback
|
|
1299
|
+
});
|
|
1300
|
+
assertCurrent(claims);
|
|
1301
|
+
assertEntityConfigurationClaims(claims);
|
|
1302
|
+
return {
|
|
1303
|
+
jwt,
|
|
1304
|
+
claims
|
|
1305
|
+
};
|
|
1306
|
+
})();
|
|
1307
|
+
entityConfigurations.set(id, pending);
|
|
1308
|
+
}
|
|
1309
|
+
return pending;
|
|
1310
|
+
};
|
|
1311
|
+
/**
|
|
1312
|
+
* Follows the authority hints up to the trust anchors and returns every path of entity configurations,
|
|
1313
|
+
* leaf first, that ends at a trust anchor.
|
|
1314
|
+
*/
|
|
1315
|
+
const discover = async (id, path) => {
|
|
1316
|
+
visits++;
|
|
1317
|
+
if (visits > maxRequests) throw fail(`trust chain resolution exceeded ${maxRequests} entity visits`);
|
|
1318
|
+
const configuration = await fetchEntityConfiguration(id);
|
|
1319
|
+
const localPath = [...path, configuration];
|
|
1320
|
+
const paths = [];
|
|
1321
|
+
if (findTrustAnchor(configuration.claims.sub)) paths.push(localPath);
|
|
1322
|
+
if (localPath.length > maxDepth) return paths;
|
|
1323
|
+
const superiors = [];
|
|
1324
|
+
for (const superior of configuration.claims.authority_hints ?? []) {
|
|
1325
|
+
if (superiors.length === maxAuthorityHints) break;
|
|
1326
|
+
if (localPath.some((entry) => isSameEntityId(entry.claims.sub, superior))) continue;
|
|
1327
|
+
if (superiors.some((entry) => isSameEntityId(entry, superior))) continue;
|
|
1328
|
+
superiors.push(superior);
|
|
1329
|
+
}
|
|
1330
|
+
(await Promise.allSettled(superiors.map((superior) => discover(superior, localPath)))).forEach((result, index) => {
|
|
1331
|
+
if (result.status === "fulfilled") paths.push(...result.value);
|
|
1332
|
+
else failures.push({
|
|
1333
|
+
entityIds: [...localPath.map((entry) => entry.claims.sub), superiors[index]],
|
|
1334
|
+
reason: reasonOf(result.reason),
|
|
1335
|
+
cause: result.reason
|
|
1336
|
+
});
|
|
1337
|
+
});
|
|
1338
|
+
return paths;
|
|
1339
|
+
};
|
|
1340
|
+
const validatePath = async (path) => {
|
|
1341
|
+
const leaf = path[0];
|
|
1342
|
+
const trustAnchorConfiguration = path[path.length - 1];
|
|
1343
|
+
const trustAnchor = findTrustAnchor(trustAnchorConfiguration.claims.sub);
|
|
1344
|
+
if (trustAnchor.jwks) await verifyJwtSignature({
|
|
1345
|
+
jwt: trustAnchorConfiguration.jwt,
|
|
1346
|
+
jwks: trustAnchor.jwks,
|
|
1347
|
+
verifyJwtCallback
|
|
1348
|
+
}).catch((error) => {
|
|
1349
|
+
throw fail(`entity configuration of trust anchor '${trustAnchor.entityId}' is not signed with a configured key: ${reasonOf(error)}`);
|
|
1350
|
+
});
|
|
1351
|
+
const statements = [];
|
|
1352
|
+
for (let index = 0; index < path.length - 1; index++) {
|
|
1353
|
+
const subject = path[index];
|
|
1354
|
+
const superior = path[index + 1];
|
|
1355
|
+
const fetchEndpoint = superior.claims.metadata?.federation_entity?.federation_fetch_endpoint;
|
|
1356
|
+
if (!fetchEndpoint) throw fail(`'${superior.claims.sub}' has no federation_fetch_endpoint`);
|
|
1357
|
+
const jwt = await get(fetchEndpoint, { sub: subject.claims.sub });
|
|
1358
|
+
const { claims } = validate({
|
|
1359
|
+
schema: entityStatementJwtSchema,
|
|
1360
|
+
data: jwt,
|
|
1361
|
+
errorMessage: `subordinate statement about '${subject.claims.sub}' issued by '${superior.claims.sub}' is invalid`
|
|
1362
|
+
});
|
|
1363
|
+
if (!isSameEntityId(claims.iss, superior.claims.sub) || !isSameEntityId(claims.sub, subject.claims.sub)) throw fail(`subordinate statement requested from '${superior.claims.sub}' about '${subject.claims.sub}' has issuer '${claims.iss}' and subject '${claims.sub}'`);
|
|
1364
|
+
assertCurrent(claims);
|
|
1365
|
+
assertSubordinateStatementClaims(claims);
|
|
1366
|
+
if (claims.constraints?.naming_constraints) throw fail(`'${superior.claims.sub}' sets naming_constraints, which are not supported`);
|
|
1367
|
+
const maxPathLength = claims.constraints?.max_path_length;
|
|
1368
|
+
if (maxPathLength !== void 0 && index > maxPathLength) throw fail(`'${superior.claims.sub}' allows ${maxPathLength} intermediates, the chain has ${index}`);
|
|
1369
|
+
statements.push({
|
|
1370
|
+
jwt,
|
|
1371
|
+
claims
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
const signers = statements.length > 0 ? [leaf, ...statements] : [];
|
|
1375
|
+
for (let index = 0; index < signers.length; index++) {
|
|
1376
|
+
const signed = signers[index];
|
|
1377
|
+
const next = statements[index];
|
|
1378
|
+
const jwks = next ? next.claims.jwks : trustAnchorConfiguration.claims.jwks;
|
|
1379
|
+
await verifyJwtSignature({
|
|
1380
|
+
jwt: signed.jwt,
|
|
1381
|
+
jwks,
|
|
1382
|
+
verifyJwtCallback
|
|
1383
|
+
}).catch((error) => {
|
|
1384
|
+
throw fail(`statement about '${signed.claims.sub}' issued by '${signed.claims.iss}' is not signed with a key listed by '${next ? next.claims.iss : trustAnchorConfiguration.claims.sub}': ${reasonOf(error)}`);
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
const expiresAt = new Date(Math.min(...[...path, ...statements].map((statement) => statement.claims.exp.getTime())));
|
|
1388
|
+
if (statements.length === 0) return {
|
|
1389
|
+
valid: true,
|
|
1390
|
+
chain: [leaf.claims],
|
|
1391
|
+
jwtChain: [leaf.jwt],
|
|
1392
|
+
rawLeafEntityConfiguration: leaf.claims,
|
|
1393
|
+
resolvedLeafMetadata: leaf.claims.metadata,
|
|
1394
|
+
trustAnchorEntityConfiguration: leaf.claims,
|
|
1395
|
+
expiresAt
|
|
1396
|
+
};
|
|
1397
|
+
const statementClaims = statements.map((statement) => statement.claims);
|
|
1398
|
+
const { mergedPolicy } = combineMetadataPolicies({ statements: statementClaims });
|
|
1399
|
+
const { resolvedLeafMetadata } = applyMetadataPolicyToMetadata({
|
|
1400
|
+
leafMetadata: restrictEntityTypes(mergeMetadata(leaf.claims.metadata ?? {}, statementClaims[0]?.metadata ?? {}), statementClaims),
|
|
1401
|
+
policyMetadata: mergedPolicy
|
|
1402
|
+
});
|
|
1403
|
+
return {
|
|
1404
|
+
valid: true,
|
|
1405
|
+
chain: [...statementClaims, trustAnchorConfiguration.claims],
|
|
1406
|
+
jwtChain: [
|
|
1407
|
+
leaf.jwt,
|
|
1408
|
+
...statements.map((statement) => statement.jwt),
|
|
1409
|
+
trustAnchorConfiguration.jwt
|
|
1410
|
+
],
|
|
1411
|
+
rawLeafEntityConfiguration: leaf.claims,
|
|
1412
|
+
resolvedLeafMetadata,
|
|
1413
|
+
trustAnchorEntityConfiguration: trustAnchorConfiguration.claims,
|
|
1414
|
+
expiresAt
|
|
1415
|
+
};
|
|
1416
|
+
};
|
|
1417
|
+
let paths;
|
|
1418
|
+
try {
|
|
1419
|
+
paths = await discover(entityId, []);
|
|
1420
|
+
} catch (error) {
|
|
1421
|
+
return {
|
|
1422
|
+
trustChains: [],
|
|
1423
|
+
failures: [{
|
|
1424
|
+
entityIds: [entityId],
|
|
1425
|
+
reason: reasonOf(error),
|
|
1426
|
+
cause: error
|
|
1427
|
+
}]
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
const trustChains = [];
|
|
1431
|
+
for (const path of paths) try {
|
|
1432
|
+
trustChains.push(await validatePath(path));
|
|
1433
|
+
} catch (error) {
|
|
1434
|
+
failures.push({
|
|
1435
|
+
entityIds: path.map((entry) => entry.claims.sub),
|
|
1436
|
+
reason: reasonOf(error),
|
|
1437
|
+
cause: error
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
return {
|
|
1441
|
+
trustChains,
|
|
1442
|
+
failures
|
|
1443
|
+
};
|
|
1444
|
+
};
|
|
1445
|
+
/**
|
|
1446
|
+
* Section 3.2: claims that only a subordinate statement may contain are rejected in an entity configuration.
|
|
1447
|
+
*/
|
|
1448
|
+
const assertEntityConfigurationClaims = (claims) => {
|
|
1449
|
+
const present = [
|
|
1450
|
+
"metadata_policy",
|
|
1451
|
+
"metadata_policy_crit",
|
|
1452
|
+
"constraints",
|
|
1453
|
+
"source_endpoint"
|
|
1454
|
+
].filter((claim) => claims[claim] !== void 0);
|
|
1455
|
+
if (present.length > 0) throw fail(`entity configuration of '${claims.sub}' contains ${present.join(", ")}, which only subordinate statements may contain`);
|
|
1456
|
+
if (claims.authority_hints?.length === 0) throw fail(`entity configuration of '${claims.sub}' has an empty authority_hints array`);
|
|
1457
|
+
};
|
|
1458
|
+
/**
|
|
1459
|
+
* Section 3.2: claims that only an entity configuration may contain are rejected in a subordinate statement.
|
|
1460
|
+
*/
|
|
1461
|
+
const assertSubordinateStatementClaims = (claims) => {
|
|
1462
|
+
const present = [
|
|
1463
|
+
"authority_hints",
|
|
1464
|
+
"trust_marks",
|
|
1465
|
+
"trust_mark_issuers",
|
|
1466
|
+
"trust_mark_owners"
|
|
1467
|
+
].filter((claim) => claims[claim] !== void 0);
|
|
1468
|
+
if (present.length > 0) throw fail(`subordinate statement about '${claims.sub}' issued by '${claims.iss}' contains ${present.join(", ")}, which only entity configurations may contain`);
|
|
1469
|
+
if (claims.metadata_policy_crit?.length === 0) throw fail(`subordinate statement about '${claims.sub}' issued by '${claims.iss}' has an empty metadata_policy_crit array`);
|
|
1470
|
+
if (claims.metadata_policy_crit !== void 0) throw fail(`subordinate statement about '${claims.sub}' issued by '${claims.iss}' requires policy operators that are not supported: ${claims.metadata_policy_crit.join(", ")}`);
|
|
1471
|
+
};
|
|
1472
|
+
/**
|
|
1473
|
+
* Removes the entity types that `allowed_entity_types` constraints of the chain do not allow. `federation_entity` is always allowed.
|
|
1474
|
+
*/
|
|
1475
|
+
const restrictEntityTypes = (metadata, statements) => {
|
|
1476
|
+
const allowed = statements.map((statement) => statement.constraints?.allowed_entity_types).filter((types) => types !== void 0);
|
|
1477
|
+
if (allowed.length === 0) return metadata;
|
|
1478
|
+
return Object.fromEntries(Object.entries(metadata).filter(([entityType]) => entityType === "federation_entity" || allowed.every((types) => types.includes(entityType))));
|
|
1479
|
+
};
|
|
1480
|
+
/**
|
|
1481
|
+
* Resolves the trust chains for the given entityId and trust anchors. See {@link resolveTrustChainsWithFailures},
|
|
1482
|
+
* which also returns why paths failed.
|
|
1483
|
+
*
|
|
1484
|
+
* @returns the valid trust chains
|
|
1485
|
+
*/
|
|
1486
|
+
const resolveTrustChains = async (options) => (await resolveTrustChainsWithFailures(options)).trustChains;
|
|
1487
|
+
//#endregion
|
|
1488
|
+
export { MetadataMergeStrategy, MetadataOrderOfApplication, OpenIdFederationError, PolicyErrorStage, PolicyOperatorMergeError, PolicyValidationError, addOperator, addPaths, addSearchParams, allSupportedPolicies, applyMetadataPolicyToMetadata, combineMetadataPolicies, constraintSchema, createEntityConfiguration, createEntityStatement, createJsonWebToken, createJwtSignableInput, createPolicyOperatorSchema, dateSchema, defaultOperator, entityConfigurationClaimsSchema, entityConfigurationHeaderSchema, entityStatementClaimsSchema, entityStatementHeaderSchema, essentialOperator, federationEntityMetadata, fetchEntityConfiguration, fetchEntityStatement, fetcher, getUsedJsonWebKey, isExistingPolicyKey, isSameEntityId, jsonWebKeySchema, jsonWebKeySetSchema, jsonWebTokenSchema, metadataPolicySchema, metadataSchema, oauthAuthorizationServerEntityMetadata, oauthClientEntityMetadata, oauthResourceEntityMetadata, oneOfOperator, openIdCredentialIssuerEntityMetadata, openIdProviderEntityMetadata, openidCredentialVerifierEntityMetadata, openidRelyingPartyEntityMetadata, resolveTrustChains, resolveTrustChainsWithFailures, subsetOfOperator, supersetOfOperator, swapValidators, trustMarkClaimsSchema, trustMarkIssuerSchema, trustMarkOwnerSchema, trustMarkSchema, valueOperator };
|
|
1489
|
+
|
|
1490
|
+
//# sourceMappingURL=index.mjs.map
|