-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttp.ts
More file actions
410 lines (393 loc) · 10.4 KB
/
http.ts
File metadata and controls
410 lines (393 loc) · 10.4 KB
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
import { IncomingMessage, OutgoingMessage } from 'node:http';
import { CAT, CommonAccessToken } from '..';
import {
InvalidAudienceError,
InvalidIssuerError,
InvalidReuseDetected,
KeyNotFoundError,
MethodNotAllowedError,
ReplayNotAllowedError,
TokenExpiredError,
UriNotAllowedError
} from '../errors';
import {
CloudFrontHeaders,
CloudFrontRequest,
CloudFrontResponse
} from 'aws-lambda';
import { CommonAccessTokenDict } from '../cat';
import { ICTIStore } from '../stores/interface';
import { ITokenLogger } from '../loggers/interface';
interface HttpValidatorKey {
kid: string;
key: Buffer;
}
/**
* Options for the HttpValidator
*/
export interface HttpValidatorOptions {
/**
* If token is mandatory to be present in the request
*/
tokenMandatory?: boolean;
/**
* If token should be automatically renewed according to CATR
*/
autoRenewEnabled?: boolean;
/**
* Name of the query parameter to look for token
*/
tokenUriParam?: string;
/**
* Algorithm to use for token validation
*/
alg?: string;
/**
* Keys to use for token validation
*/
keys: HttpValidatorKey[];
/**
* Expected issuer of token
*/
issuer: string;
/**
* Allowed audiences for token
*/
audience?: string[];
/**
* Store for tracking token usage
*/
store?: ICTIStore;
/**
* Logger for logging token usage
*/
logger?: ITokenLogger;
/**
* Callback for reuse detection
*/
reuseDetection?: (
cat: CommonAccessToken,
store?: ICTIStore,
logger?: ITokenLogger
) => Promise<boolean>;
}
/**
* Response from the HttpValidator
*/
export interface HttpResponse {
/**
* HTTP status code
*/
status: number;
/**
* Optional message
*/
message?: string;
/**
* Claims from the token
*/
claims?: CommonAccessTokenDict;
/**
* Number of times token has been used
*/
count?: number;
}
export class NoTokenFoundError extends Error {
constructor() {
super('No CTA token could be found');
}
}
/**
* Handle request and validate CTA Common Access Token
*
* @example
* const httpValidator = new HttpValidator({
* keys: [
* {
* kid: 'Symmetric256',
* key: Buffer.from(
* '403697de87af64611c1d32a05dab0fe1fcb715a86ab435f1ec99192d79569388',
* 'hex'
* )
* }
* ],
* issuer: 'eyevinn',
* audience: ['one', 'two'], // Optional
* store: new MemoryCTIStore() // Optional store for tracking token usage
* });
* const result = await httpValidator.validateHttpRequest(
* request,
* 'Symmetric256'
* );
* // { status: 200, message: 'info', claims: { iss: 'eyevinn' } }
*/
export class HttpValidator {
private keys: { [key: string]: Buffer } = {};
private opts: HttpValidatorOptions;
private tokenUriParam: string;
private store?: ICTIStore;
private logger?: ITokenLogger;
constructor(opts: HttpValidatorOptions) {
opts.keys.forEach((k: HttpValidatorKey) => {
this.keys[k.kid] = k.key;
});
this.opts = opts;
this.opts.tokenMandatory = opts.tokenMandatory ?? true;
this.opts.autoRenewEnabled = opts.autoRenewEnabled ?? true;
this.tokenUriParam = opts.tokenUriParam ?? 'cat';
this.store = opts.store;
this.logger = opts.logger;
}
/**
* Validate a CloudFront request
*/
public async validateCloudFrontRequest(
/**
* CloudFront request
*/
cfRequest: CloudFrontRequest
): Promise<HttpResponse & { cfResponse: CloudFrontResponse }> {
const requestLike: Pick<IncomingMessage, 'headers'> &
Pick<IncomingMessage, 'url'> &
Pick<IncomingMessage, 'method'> = {
headers: {},
url: '',
method: cfRequest.method
};
const response = new OutgoingMessage();
if (cfRequest.headers) {
Object.entries(cfRequest.headers).forEach(([name, header]) => {
if (header && header.length > 0) {
requestLike.headers[name.toLowerCase()] = header
.map((h) => h.value)
.join(',');
}
});
}
requestLike.url = cfRequest.uri;
const result = await this.validateHttpRequest(
requestLike as IncomingMessage,
response
);
const cfHeaders: CloudFrontHeaders = {};
Object.entries(response.getHeaders()).forEach(([name, value]) => {
cfHeaders[name] = [{ key: name, value: value as string }];
});
const cfResponse: CloudFrontResponse = {
status: result.status.toString(),
statusDescription: result.message || 'ok',
headers: cfHeaders
};
return { ...result, cfResponse: cfResponse };
}
/**
* Validate a HTTP request
*/
public async validateHttpRequest(
/**
* HTTP request
*/
request: IncomingMessage,
/**
* HTTP response to set headers on
*/
response?: OutgoingMessage
): Promise<HttpResponse> {
const validator = new CAT({
keys: this.keys
});
let url: URL | undefined = undefined;
const host = request.headers.host;
if (host) {
url = new URL(`https://${host}${request.url}`);
}
let cat;
const headerName = 'cta-common-access-token';
const { token, catrType } = this.findToken(request, headerName, url);
if (this.opts.tokenMandatory && !token) {
throw new NoTokenFoundError();
} else {
if (!token) {
return { status: 200 };
}
try {
const result = await validator.validate(token, 'mac', {
issuer: this.opts.issuer,
audience: this.opts.audience,
url
});
cat = result.cat;
if (!result.error) {
let count;
let code = 200;
// CAT is acceptable
if (cat) {
if (this.store) {
count = await this.store.storeToken(cat);
}
if (this.logger) {
await this.logger.logToken(cat);
}
if (cat.claims.catreplay !== undefined) {
await this.handleReplay({ cat, count });
}
await this.checkAllowedMethods(cat, request);
const { status } = await this.handleAutoRenew({
validator,
cat,
catrType,
headerName,
response,
url
});
code = status;
}
return { status: code, claims: cat?.claims, count };
} else {
return {
status: 401,
message: result.error.message,
claims: cat?.claims
};
}
} catch (err) {
if (
err instanceof InvalidIssuerError ||
err instanceof InvalidAudienceError ||
err instanceof KeyNotFoundError ||
err instanceof TokenExpiredError ||
err instanceof UriNotAllowedError ||
err instanceof ReplayNotAllowedError ||
err instanceof InvalidReuseDetected ||
err instanceof MethodNotAllowedError
) {
return {
status: 401,
message: (err as Error).message,
claims: cat?.claims
};
} else {
console.log(`Internal error`, err);
return { status: 500, message: (err as Error).message };
}
}
}
}
private findToken(
request: IncomingMessage,
headerName: string,
url?: URL
): { token?: string; catrType: string } {
let catrType = 'header';
let token = undefined;
// Check for token in headers first
if (request.headers[headerName]) {
token = Array.isArray(request.headers[headerName])
? request.headers[headerName]![0]
: (request.headers[headerName] as string);
catrType = 'header';
} else if (url && url.searchParams.has(this.tokenUriParam)) {
token = url.searchParams.get(this.tokenUriParam) || undefined;
catrType = 'query';
}
return { token, catrType };
}
private checkAllowedMethods(
cat: CommonAccessToken,
request: IncomingMessage
) {
if (cat.claims.catm && !request.method) {
throw new Error('Missing method in request');
}
if (cat.claims.catm && request.method) {
const methods = cat.claims.catm as string[];
if (methods.indexOf(request.method) === -1) {
throw new MethodNotAllowedError(request.method);
}
}
}
private async handleReplay({
cat,
count
}: {
cat: CommonAccessToken;
count?: number;
}) {
if (cat.claims.catreplay === 1 && count) {
if (count > 1) {
throw new ReplayNotAllowedError(count);
}
} else if (cat.claims.catreplay === 2 && this.opts.reuseDetection) {
if (await this.opts.reuseDetection(cat, this.store, this.logger)) {
throw new InvalidReuseDetected();
}
}
}
private async handleAutoRenew({
validator,
cat,
catrType,
headerName,
response,
url
}: {
validator: CAT;
cat: CommonAccessToken;
catrType?: string;
headerName: string;
response?: OutgoingMessage;
url?: URL;
}) {
if (!cat.keyId) {
throw new Error('Key ID not found');
}
if (
cat &&
cat?.shouldRenew &&
this.opts.autoRenewEnabled &&
response &&
cat.keyId
) {
// Renew token
const renewedToken = await validator.renewToken(cat, {
type: 'mac',
issuer: this.opts.issuer,
kid: cat.keyId,
alg: this.opts.alg || 'HS256'
});
const catr = cat.claims.catr as any;
if (
catr.type === 'header' ||
(catr.type === 'automatic' && catrType === 'header')
) {
response.setHeader(
catr['header-name'] || headerName,
renewedToken +
(catr['header-params'] ? `;${catr['header-params']}` : '')
);
} else if (
catr.type === 'cookie' ||
(catr.type === 'automatic' && catrType === 'cookie')
) {
const cookieName = catr['cookie-name'] || 'cta-common-access-token';
response.setHeader(
'Set-Cookie',
`${cookieName}=${renewedToken}${
catr['cookie-params'] ? '; ' + catr['cookie-params'] : ''
}`
);
} else if (
catr.type === 'redirect' ||
(catr.type === 'automatic' && catrType === 'query')
) {
if (url) {
const redirectUrl = url;
redirectUrl.searchParams.delete(this.tokenUriParam);
redirectUrl.searchParams.set(this.tokenUriParam, renewedToken);
response.setHeader('Location', redirectUrl.toString());
}
}
}
return { status: 200 };
}
}