-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathauth.ts
526 lines (476 loc) · 16.5 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import { MediaType } from '../constants';
import { IProofService } from '../../proof/proof-service';
import { PROTOCOL_MESSAGE_TYPE } from '../constants';
import {
StateVerificationOpts,
AuthorizationRequestMessage,
AuthorizationResponseMessage,
BasicMessage,
IPackageManager,
JWSPackerParams,
ZeroKnowledgeProofRequest,
JSONObject
} from '../types';
import { DID, getUnixTimestamp } from '@iden3/js-iden3-core';
import { proving } from '@iden3/js-jwz';
import * as uuid from 'uuid';
import { ProofQuery } from '../../verifiable';
import { byteDecoder, byteEncoder } from '../../utils';
import { processZeroKnowledgeProofRequests, verifyExpiresTime } from './common';
import { CircuitId } from '../../circuits';
import {
AbstractMessageHandler,
BasicHandlerOptions,
IProtocolMessageHandler
} from './message-handler';
import { parseAcceptProfile } from '../utils';
import {
getIden3CommSingleRecipient,
Iden3DIDcommCompatibilityOptions
} from '../types/protocol/common';
/**
* Options to pass to createAuthorizationRequest function
* @public
*/
export type AuthorizationRequestCreateOptions = {
accept?: string[];
scope?: ZeroKnowledgeProofRequest[];
expires_time?: Date;
};
/**
* createAuthorizationRequest is a function to create protocol authorization request
* @param {string} reason - reason to request proof
* @param {string} sender - sender did
* @param {string} callbackUrl - callback that user should use to send response
* @param {AuthorizationRequestCreateOptions} opts - authorization request options
* @returns `Promise<AuthorizationRequestMessage>`
*/
export function createAuthorizationRequest(
reason: string,
sender: string,
callbackUrl: string,
opts?: AuthorizationRequestCreateOptions
): AuthorizationRequestMessage {
return createAuthorizationRequestWithMessage(reason, '', sender, callbackUrl, opts);
}
/**
* createAuthorizationRequestWithMessage is a function to create protocol authorization request with explicit message to sign
* @param {string} reason - reason to request proof
* @param {string} message - message to sign in the response
* @param {string} sender - sender did
* @param {string} callbackUrl - callback that user should use to send response
* @param {AuthorizationRequestCreateOptions} opts - authorization request options
* @returns `Promise<AuthorizationRequestMessage>`
*/
export function createAuthorizationRequestWithMessage(
reason: string,
message: string,
sender: string,
callbackUrl: string,
opts?: AuthorizationRequestCreateOptions
): AuthorizationRequestMessage {
const uuidv4 = uuid.v4();
const request: AuthorizationRequestMessage = {
id: uuidv4,
thid: uuidv4,
from: sender,
typ: MediaType.PlainMessage,
type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE,
body: {
accept: opts?.accept,
reason: reason,
message: message,
callbackUrl: callbackUrl,
scope: opts?.scope ?? []
},
created_time: getUnixTimestamp(new Date()),
expires_time: opts?.expires_time ? getUnixTimestamp(opts.expires_time) : undefined
};
return request;
}
/**
*
* Options to pass to auth response handler
*
* @public
*/
export type AuthResponseHandlerOptions = StateVerificationOpts &
BasicHandlerOptions & {
// acceptedProofGenerationDelay is the period of time in milliseconds that a generated proof remains valid.
acceptedProofGenerationDelay?: number;
} & Iden3DIDcommCompatibilityOptions;
/**
* Interface that allows the processing of the authorization request in the raw format for given identifier
*
* @public
* @interface IAuthHandler
*/
export interface IAuthHandler {
/**
* unpacks authorization request
* @public
* @param {Uint8Array} request - raw byte message
* @returns `Promise<AuthorizationRequestMessage>`
*/
parseAuthorizationRequest(request: Uint8Array): Promise<AuthorizationRequestMessage>;
/**
* unpacks authorization request
* @public
* @param {did} did - sender DID
* @param {Uint8Array} request - raw byte message
* @returns `Promise<{
token: string;
authRequest: AuthorizationRequestMessage;
authResponse: AuthorizationResponseMessage;
}>`
*/
handleAuthorizationRequest(
did: DID,
request: Uint8Array,
opts?: AuthHandlerOptions
): Promise<{
token: string;
authRequest: AuthorizationRequestMessage;
authResponse: AuthorizationResponseMessage;
}>;
/**
* handle authorization response
* @public
* @param {AuthorizationResponseMessage} response - auth response
* @param {AuthorizationRequestMessage} request - auth request
* @param {AuthResponseHandlerOptions} opts - options
* @returns `Promise<{
request: AuthorizationRequestMessage;
response: AuthorizationResponseMessage;
}>`
*/
handleAuthorizationResponse(
response: AuthorizationResponseMessage,
request: AuthorizationRequestMessage,
opts?: AuthResponseHandlerOptions
): Promise<{
request: AuthorizationRequestMessage;
response: AuthorizationResponseMessage;
}>;
}
type AuthReqOptions = {
senderDid: DID;
mediaType?: MediaType;
} & Iden3DIDcommCompatibilityOptions;
type AuthRespOptions = {
request: AuthorizationRequestMessage;
acceptedStateTransitionDelay?: number;
acceptedProofGenerationDelay?: number;
} & Iden3DIDcommCompatibilityOptions;
export type AuthMessageHandlerOptions = AuthReqOptions | AuthRespOptions;
/**
*
* Options to pass to auth handler
*
* @public
* @interface AuthHandlerOptions
*/
export type AuthHandlerOptions = BasicHandlerOptions & {
mediaType: MediaType;
packerOptions?: JWSPackerParams;
} & Iden3DIDcommCompatibilityOptions;
/**
*
* Allows to process AuthorizationRequest protocol message and produce JWZ response.
*
* @public
* @class AuthHandler
* @implements implements IAuthHandler interface
*/
export class AuthHandler
extends AbstractMessageHandler
implements IAuthHandler, IProtocolMessageHandler
{
private readonly _supportedCircuits = [
CircuitId.AtomicQueryV3,
CircuitId.AtomicQuerySigV2,
CircuitId.AtomicQueryMTPV2,
CircuitId.LinkedMultiQuery10
];
/**
* Creates an instance of AuthHandler.
* @param {IPackageManager} _packerMgr - package manager to unpack message envelope
* @param {IProofService} _proofService - proof service to verify zk proofs
*
*/
constructor(
private readonly _packerMgr: IPackageManager,
private readonly _proofService: IProofService
) {
super();
}
handle(message: BasicMessage, ctx: AuthMessageHandlerOptions): Promise<BasicMessage | null> {
switch (message.type) {
case PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE:
return this.handleAuthRequest(
message as AuthorizationRequestMessage,
ctx as AuthReqOptions
);
case PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:
return this.handleAuthResponse(
message as AuthorizationResponseMessage,
ctx as AuthRespOptions
);
default:
return super.handle(message, ctx);
}
}
/**
* @inheritdoc IAuthHandler#parseAuthorizationRequest
*/
async parseAuthorizationRequest(request: Uint8Array): Promise<AuthorizationRequestMessage> {
const { unpackedMessage: message } = await this._packerMgr.unpack(request);
const authRequest = message as unknown as AuthorizationRequestMessage;
if (message.type !== PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE) {
throw new Error('Invalid media type');
}
authRequest.body.scope = authRequest.body.scope || [];
return authRequest;
}
private async handleAuthRequest(
authRequest: AuthorizationRequestMessage,
ctx: AuthReqOptions
): Promise<AuthorizationResponseMessage> {
if (authRequest.type !== PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE) {
throw new Error('Invalid message type for authorization request');
}
// override sender did if it's explicitly specified in the auth request
const to = getIden3CommSingleRecipient(authRequest) ?? ctx.senderDid;
const guid = uuid.v4();
if (!authRequest.from) {
throw new Error('auth request should contain from field');
}
const responseType = PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE;
const mediaType = this.getSupportedMediaTypeByProfile(
ctx,
responseType,
authRequest.body.accept
);
const from = DID.parse(authRequest.from);
const responseScope = await processZeroKnowledgeProofRequests(
to,
authRequest?.body.scope,
from,
this._proofService,
{ mediaType, supportedCircuits: this._supportedCircuits }
);
return {
id: guid,
typ: mediaType,
type: responseType,
thid: authRequest.thid ?? guid,
body: {
message: authRequest?.body?.message,
scope: responseScope
},
from: to.string(),
to: ctx.multipleRecipientsFormat ? [authRequest.from] : authRequest.from
};
}
/**
* @inheritdoc IAuthHandler#handleAuthorizationRequest
*/
async handleAuthorizationRequest(
did: DID,
request: Uint8Array,
opts?: AuthHandlerOptions
): Promise<{
token: string;
authRequest: AuthorizationRequestMessage;
authResponse: AuthorizationResponseMessage;
}> {
const authRequest = await this.parseAuthorizationRequest(request);
if (!opts?.allowExpiredMessages) {
verifyExpiresTime(authRequest);
}
if (!opts) {
opts = {
mediaType: MediaType.ZKPMessage
};
}
if (opts.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
}
const authResponse = await this.handleAuthRequest(authRequest, {
senderDid: did,
mediaType: opts.mediaType,
multipleRecipientsFormat: opts.multipleRecipientsFormat
});
const msgBytes = byteEncoder.encode(JSON.stringify(authResponse));
const packerOpts =
opts.mediaType === MediaType.SignedMessage
? opts.packerOptions
: {
provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
};
const token = byteDecoder.decode(
await this._packerMgr.pack(opts.mediaType, msgBytes, {
senderDID: did,
...packerOpts
})
);
return { authRequest, authResponse, token };
}
private async handleAuthResponse(
response: AuthorizationResponseMessage,
ctx: AuthRespOptions
): Promise<BasicMessage | null> {
const request = ctx.request;
if (response.type !== PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE) {
throw new Error('Invalid message type for authorization response');
}
if ((request.body.message ?? '') !== (response.body.message ?? '')) {
throw new Error('message for signing from request is not presented in response');
}
const to = getIden3CommSingleRecipient(response);
if (!to) {
throw new Error('auth response must have valid recipient');
}
if (request.from !== to.string()) {
throw new Error(
`sender of the request is not a target of response - expected ${request.from}, given ${response.to}`
);
}
this.verifyAuthRequest(request);
const requestScope = request.body.scope || [];
const responseScope = response.body.scope || [];
if (!response.from) {
throw new Error(`proof response doesn't contain from field`);
}
const groupIdToLinkIdMap = new Map<number, { linkID: number; requestId: number }[]>();
// group requests by query group id
for (const proofRequest of requestScope) {
const groupId = proofRequest.query.groupId as number;
const proofResp = responseScope.find((resp) => resp.id === proofRequest.id);
if (!proofResp) {
throw new Error(`proof is not given for requestId ${proofRequest.id}`);
}
const circuitId = proofResp.circuitId;
if (circuitId !== proofRequest.circuitId) {
throw new Error(
`proof is not given for requested circuit expected: ${proofRequest.circuitId}, given ${circuitId}`
);
}
const params: JSONObject = proofRequest.params ?? {};
params.verifierDid = DID.parse(request.from);
const opts = [ctx.acceptedProofGenerationDelay, ctx.acceptedStateTransitionDelay].some(
(delay) => delay !== undefined
)
? {
acceptedProofGenerationDelay: ctx.acceptedProofGenerationDelay,
acceptedStateTransitionDelay: ctx.acceptedStateTransitionDelay
}
: undefined;
const { linkID } = await this._proofService.verifyZKPResponse(proofResp, {
query: proofRequest.query as unknown as ProofQuery,
sender: response.from,
params,
opts
});
// write linkId to the proof response
// const pubSig = pubSignals as unknown as { linkID?: number };
if (linkID && groupId) {
groupIdToLinkIdMap.set(groupId, [
...(groupIdToLinkIdMap.get(groupId) ?? []),
{ linkID: linkID, requestId: proofResp.id }
]);
}
}
// verify grouping links
for (const [groupId, metas] of groupIdToLinkIdMap.entries()) {
// check that all linkIds are the same
if (metas.some((meta) => meta.linkID !== metas[0].linkID)) {
throw new Error(
`Link id validation failed for group ${groupId}, request linkID to requestIds info: ${JSON.stringify(
metas
)}`
);
}
}
return response;
}
/**
* @inheritdoc IAuthHandler#handleAuthorizationResponse
*/
async handleAuthorizationResponse(
response: AuthorizationResponseMessage,
request: AuthorizationRequestMessage,
opts?: AuthResponseHandlerOptions | undefined
): Promise<{
request: AuthorizationRequestMessage;
response: AuthorizationResponseMessage;
}> {
if (!opts?.allowExpiredMessages) {
verifyExpiresTime(response);
}
const authResp = (await this.handleAuthResponse(response, {
request,
acceptedStateTransitionDelay: opts?.acceptedStateTransitionDelay,
acceptedProofGenerationDelay: opts?.acceptedProofGenerationDelay,
multipleRecipientsFormat: opts?.multipleRecipientsFormat
})) as AuthorizationResponseMessage;
return { request, response: authResp };
}
private verifyAuthRequest(request: AuthorizationRequestMessage) {
const groupIdValidationMap: { [k: string]: ZeroKnowledgeProofRequest[] } = {};
const requestScope = request.body.scope || [];
for (const proofRequest of requestScope) {
const groupId = proofRequest.query.groupId as number;
if (groupId) {
const existingRequests = groupIdValidationMap[groupId] ?? [];
//validate that all requests in the group have the same schema, issuer and circuit
for (const existingRequest of existingRequests) {
if (existingRequest.query.type !== proofRequest.query.type) {
throw new Error(`all requests in the group should have the same type`);
}
if (existingRequest.query.context !== proofRequest.query.context) {
throw new Error(`all requests in the group should have the same context`);
}
const allowedIssuers = proofRequest.query.allowedIssuers as string[];
const existingRequestAllowedIssuers = existingRequest.query.allowedIssuers as string[];
if (
!(
allowedIssuers.includes('*') ||
allowedIssuers.every((issuer) => existingRequestAllowedIssuers.includes(issuer))
)
) {
throw new Error(`all requests in the group should have the same issuer`);
}
}
groupIdValidationMap[groupId] = [...(groupIdValidationMap[groupId] ?? []), proofRequest];
}
}
}
private getSupportedMediaTypeByProfile(
ctx: AuthReqOptions,
responseType: string,
profile?: string[] | undefined
): MediaType {
let mediaType: MediaType;
if (!profile?.length) {
return ctx.mediaType || MediaType.ZKPMessage;
}
const supportedMediaTypes: MediaType[] = [];
for (const acceptProfile of profile) {
const { env } = parseAcceptProfile(acceptProfile);
if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
supportedMediaTypes.push(env);
}
}
if (!supportedMediaTypes.length) {
throw new Error('no packer with profile which meets `accept` header requirements');
}
mediaType = supportedMediaTypes.includes(MediaType.ZKPMessage)
? MediaType.ZKPMessage
: supportedMediaTypes[0];
if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
mediaType = ctx.mediaType;
}
return mediaType;
}
}