-
Notifications
You must be signed in to change notification settings - Fork 166
/
oauth.ts
1115 lines (999 loc) · 35.3 KB
/
oauth.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import crypto from 'crypto';
import * as jose from 'jose';
import { promisify } from 'util';
import { deflateRaw } from 'zlib';
import saml from '@boxyhq/saml20';
import { TokenSet, errors, generators } from 'openid-client';
import { SAMLProfile } from '@boxyhq/saml20/dist/typings';
import type {
IOAuthController,
JacksonOption,
OAuthReq,
OAuthTokenReq,
OAuthTokenRes,
Profile,
SAMLResponsePayload,
Storable,
SAMLSSORecord,
OIDCSSORecord,
SSOTracerInstance,
OAuthErrorHandlerParams,
OIDCAuthzResponsePayload,
} from '../typings';
import {
relayStatePrefix,
IndexNames,
OAuthErrorResponse,
getErrorMessage,
loadJWSPrivateKey,
isJWSKeyPairLoaded,
extractOIDCUserProfile,
getScopeValues,
getEncodedTenantProduct,
isConnectionActive,
} from './utils';
import * as metrics from '../opentelemetry/metrics';
import { JacksonError } from './error';
import * as allowed from './oauth/allowed';
import * as codeVerifier from './oauth/code-verifier';
import * as redirect from './oauth/redirect';
import { getDefaultCertificate } from '../saml/x509';
import { SSOHandler } from './sso-handler';
import { ValidateOption, extractSAMLResponseAttributes } from '../saml/lib';
import { oidcIssuerInstance } from './oauth/oidc-issuer';
const deflateRawAsync = promisify(deflateRaw);
export class OAuthController implements IOAuthController {
private connectionStore: Storable;
private sessionStore: Storable;
private codeStore: Storable;
private tokenStore: Storable;
private ssoTracer: SSOTracerInstance;
private opts: JacksonOption;
private ssoHandler: SSOHandler;
constructor({ connectionStore, sessionStore, codeStore, tokenStore, ssoTracer, opts }) {
this.connectionStore = connectionStore;
this.sessionStore = sessionStore;
this.codeStore = codeStore;
this.tokenStore = tokenStore;
this.ssoTracer = ssoTracer;
this.opts = opts;
this.ssoHandler = new SSOHandler({
connection: connectionStore,
session: sessionStore,
opts,
});
}
public async authorize(body: OAuthReq): Promise<{ redirect_url?: string; authorize_form?: string }> {
const {
response_type = 'code',
client_id,
redirect_uri,
state,
scope,
nonce,
code_challenge,
code_challenge_method = '',
idp_hint,
forceAuthn = 'false',
login_hint,
} = body;
let requestedTenant;
let requestedProduct;
let requestedScopes: string[] | undefined;
let requestedOIDCFlow: boolean | undefined;
let connection: SAMLSSORecord | OIDCSSORecord | undefined;
try {
const tenant = 'tenant' in body ? body.tenant : undefined;
const product = 'product' in body ? body.product : undefined;
const access_type = 'access_type' in body ? body.access_type : undefined;
const resource = 'resource' in body ? body.resource : undefined;
requestedTenant = tenant;
requestedProduct = product;
metrics.increment('oauthAuthorize');
if (!redirect_uri) {
throw new JacksonError('Please specify a redirect URL.', 400);
}
requestedScopes = getScopeValues(scope);
requestedOIDCFlow = requestedScopes.includes('openid');
if (tenant && product) {
const response = await this.ssoHandler.resolveConnection({
tenant,
product,
idp_hint,
authFlow: 'oauth',
originalParams: { ...body },
});
if ('redirectUrl' in response) {
return {
redirect_url: response.redirectUrl,
};
}
if ('connection' in response) {
connection = response.connection;
}
} else if (client_id && client_id !== '' && client_id !== 'undefined' && client_id !== 'null') {
// if tenant and product are encoded in the client_id then we parse it and check for the relevant connection(s)
let sp = getEncodedTenantProduct(client_id);
if (!sp && access_type) {
sp = getEncodedTenantProduct(access_type);
}
if (!sp && resource) {
sp = getEncodedTenantProduct(resource);
}
if (!sp && requestedScopes) {
const encodedParams = requestedScopes.find((scope) => scope.includes('=') && scope.includes('&')); // for now assume only one encoded param i.e. for tenant/product
if (encodedParams) {
sp = getEncodedTenantProduct(encodedParams);
}
}
if (sp && sp.tenant && sp.product) {
const { tenant, product } = sp;
requestedTenant = tenant;
requestedProduct = product;
const response = await this.ssoHandler.resolveConnection({
tenant,
product,
idp_hint,
authFlow: 'oauth',
originalParams: { ...body },
});
if ('redirectUrl' in response) {
return {
redirect_url: response.redirectUrl,
};
}
if ('connection' in response) {
connection = response.connection;
}
} else {
connection = await this.connectionStore.get(client_id);
if (connection) {
requestedTenant = connection.tenant;
requestedProduct = connection.product;
}
}
} else {
throw new JacksonError('You need to specify client_id or tenant & product', 403);
}
if (!connection) {
throw new JacksonError('IdP connection not found.', 403);
}
if (!allowed.redirect(redirect_uri, connection.redirectUrl as string[])) {
throw new JacksonError('Redirect URL is not allowed.', 403);
}
} catch (err: unknown) {
const error_description = getErrorMessage(err);
// Save the error trace
await this.ssoTracer.saveTrace({
error: error_description,
context: {
tenant: requestedTenant || '',
product: requestedProduct || '',
clientID: connection?.clientID || '',
requestedOIDCFlow,
redirectUri: redirect_uri,
},
});
throw err;
}
if (!isConnectionActive(connection)) {
throw new JacksonError('SSO connection is deactivated. Please contact your administrator.', 403);
}
const isMissingJWTKeysForOIDCFlow =
requestedOIDCFlow &&
(!this.opts.openid?.jwtSigningKeys || !isJWSKeyPairLoaded(this.opts.openid.jwtSigningKeys));
const oAuthClientReqError = !state || response_type !== 'code';
const connectionIsSAML = 'idpMetadata' in connection && connection.idpMetadata !== undefined;
const connectionIsOIDC = 'oidcProvider' in connection && connection.oidcProvider !== undefined;
if (isMissingJWTKeysForOIDCFlow || oAuthClientReqError || (!connectionIsSAML && !connectionIsOIDC)) {
let error, error_description;
if (isMissingJWTKeysForOIDCFlow) {
error = 'server_error';
error_description =
'OAuth server not configured correctly for openid flow, check if JWT signing keys are loaded';
}
if (!state) {
error = 'invalid_request';
error_description = 'Please specify a state to safeguard against XSRF attacks';
}
if (response_type !== 'code') {
error = 'unsupported_response_type';
error_description = 'Only Authorization Code grant is supported';
}
if (!connectionIsSAML && !connectionIsOIDC) {
error = 'server_error';
error_description = 'Connection appears to be misconfigured';
}
// Save the error trace
const traceId = await this.ssoTracer.saveTrace({
error: error_description,
context: {
tenant: requestedTenant,
product: requestedProduct,
clientID: connection.clientID,
requestedOIDCFlow,
redirectUri: redirect_uri,
},
});
return {
redirect_url: OAuthErrorResponse({
error,
error_description: traceId ? `${traceId}: ${error_description}` : error_description,
redirect_uri,
state,
}),
};
}
// Connection retrieved: Handover to IdP starts here
let ssoUrl;
let post = false;
// Init sessionId
const sessionId = crypto.randomBytes(16).toString('hex');
const relayState = relayStatePrefix + sessionId;
// SAML connection: SAML request will be constructed here
let samlReq;
if (connectionIsSAML) {
try {
const { sso } = (connection as SAMLSSORecord).idpMetadata;
if ('redirectUrl' in sso) {
// HTTP Redirect binding
ssoUrl = sso.redirectUrl;
} else if ('postUrl' in sso) {
// HTTP-POST binding
ssoUrl = sso.postUrl;
post = true;
} else {
// This code here is kept for backward compatibility. We now have validation while adding the SSO connection to ensure binding is present.
const error_description = 'SAML binding could not be retrieved';
// Save the error trace
const traceId = await this.ssoTracer.saveTrace({
error: error_description,
context: {
tenant: requestedTenant as string,
product: requestedProduct as string,
clientID: connection.clientID,
requestedOIDCFlow,
redirectUri: redirect_uri,
},
});
return {
redirect_url: OAuthErrorResponse({
error: 'invalid_request',
error_description: traceId ? `${traceId}: ${error_description}` : error_description,
redirect_uri,
state,
}),
};
}
const cert = await getDefaultCertificate();
samlReq = saml.request({
ssoUrl,
entityID: this.opts.samlAudience!,
callbackUrl: this.opts.externalUrl + this.opts.samlPath,
signingKey: cert.privateKey,
publicKey: cert.publicKey,
forceAuthn: forceAuthn === 'true' ? true : !!(connection as SAMLSSORecord).forceAuthn,
identifierFormat: (connection as SAMLSSORecord).identifierFormat
? (connection as SAMLSSORecord).identifierFormat
: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
});
} catch (err: unknown) {
const error_description = getErrorMessage(err);
// Save the error trace
const traceId = await this.ssoTracer.saveTrace({
error: error_description,
context: {
tenant: requestedTenant,
product: requestedProduct,
clientID: connection.clientID,
requestedOIDCFlow,
redirectUri: redirect_uri,
},
});
return {
redirect_url: OAuthErrorResponse({
error: 'server_error',
error_description: traceId ? `${traceId}: ${error_description}` : error_description,
redirect_uri,
state,
}),
};
}
}
// OIDC Connection: Issuer discovery, openid-client init and extraction of authorization endpoint happens here
let oidcCodeVerifier: string | undefined;
let oidcNonce: string | undefined;
if (connectionIsOIDC) {
if (!this.opts.oidcPath) {
return {
redirect_url: OAuthErrorResponse({
error: 'server_error',
error_description: 'OpenID response handler path (oidcPath) is not set',
redirect_uri,
state,
}),
};
}
const { discoveryUrl, metadata, clientId, clientSecret } = (connection as OIDCSSORecord).oidcProvider;
try {
const oidcIssuer = await oidcIssuerInstance(discoveryUrl, metadata);
const oidcClient = new oidcIssuer.Client({
client_id: clientId as string,
client_secret: clientSecret,
redirect_uris: [this.opts.externalUrl + this.opts.oidcPath],
response_types: ['code'],
});
oidcCodeVerifier = generators.codeVerifier();
const code_challenge = generators.codeChallenge(oidcCodeVerifier);
oidcNonce = generators.nonce();
ssoUrl = oidcClient.authorizationUrl({
scope: [...requestedScopes, 'openid', 'email', 'profile']
.filter((value, index, self) => self.indexOf(value) === index) // filter out duplicates
.join(' '),
code_challenge,
code_challenge_method: 'S256',
state: relayState,
nonce: oidcNonce,
login_hint,
});
} catch (err: unknown) {
if (err) {
return {
redirect_url: OAuthErrorResponse({
error: 'server_error',
error_description: (err as errors.OPError)?.error || getErrorMessage(err),
redirect_uri,
state,
}),
};
}
}
}
// Session persistence happens here
try {
const requested = { client_id, state, redirect_uri } as Record<string, string | boolean | string[]>;
if (requestedTenant) {
requested.tenant = requestedTenant;
}
if (requestedProduct) {
requested.product = requestedProduct;
}
if (idp_hint) {
requested.idp_hint = idp_hint;
}
if (requestedOIDCFlow) {
requested.oidc = true;
if (nonce) {
requested.nonce = nonce;
}
}
if (requestedScopes) {
requested.scope = requestedScopes;
}
const sessionObj = {
redirect_uri,
response_type,
state,
code_challenge,
code_challenge_method,
requested,
};
await this.sessionStore.put(
sessionId,
connectionIsSAML
? {
...sessionObj,
id: samlReq?.id,
}
: { ...sessionObj, id: connection.clientID, oidcCodeVerifier, oidcNonce }
);
// Redirect to IdP
if (connectionIsSAML) {
let redirectUrl;
let authorizeForm;
if (!post) {
// HTTP Redirect binding
redirectUrl = redirect.success(ssoUrl, {
RelayState: relayState,
SAMLRequest: Buffer.from(await deflateRawAsync(samlReq.request)).toString('base64'),
});
} else {
// HTTP POST binding
authorizeForm = saml.createPostForm(ssoUrl, [
{
name: 'RelayState',
value: relayState,
},
{
name: 'SAMLRequest',
value: Buffer.from(samlReq.request).toString('base64'),
},
]);
}
return {
redirect_url: redirectUrl,
authorize_form: authorizeForm,
};
}
if (connectionIsOIDC) {
return { redirect_url: ssoUrl };
}
throw 'Connection appears to be misconfigured';
} catch (err: unknown) {
const error_description = getErrorMessage(err);
// Save the error trace
const traceId = await this.ssoTracer.saveTrace({
error: error_description,
context: {
tenant: requestedTenant as string,
product: requestedProduct as string,
clientID: connection.clientID,
requestedOIDCFlow,
redirectUri: redirect_uri,
samlRequest: samlReq?.request || '',
},
});
return {
redirect_url: OAuthErrorResponse({
error: 'server_error',
error_description: traceId ? `${traceId}: ${error_description}` : error_description,
redirect_uri,
state,
}),
};
}
}
public async samlResponse(
body: SAMLResponsePayload
): Promise<{ redirect_url?: string; app_select_form?: string; response_form?: string }> {
let connection: SAMLSSORecord | undefined;
let rawResponse: string | undefined;
let sessionId: string | undefined;
let session: any;
let issuer: string | undefined;
let isIdPFlow: boolean | undefined;
let isSAMLFederated: boolean | undefined;
let validateOpts: ValidateOption;
let redirect_uri: string | undefined;
const { SAMLResponse, idp_hint, RelayState = '' } = body;
try {
isIdPFlow = !RelayState.startsWith(relayStatePrefix);
rawResponse = Buffer.from(SAMLResponse, 'base64').toString();
issuer = saml.parseIssuer(rawResponse);
if (!this.opts.idpEnabled && isIdPFlow) {
// IdP login is disabled so block the request
throw new JacksonError(
'IdP (Identity Provider) flow has been disabled. Please head to your Service Provider to login.',
403
);
}
sessionId = RelayState.replace(relayStatePrefix, '');
if (!issuer) {
throw new JacksonError('Issuer not found.', 403);
}
const connections: SAMLSSORecord[] = (
await this.connectionStore.getByIndex({
name: IndexNames.EntityID,
value: issuer,
})
).data;
if (!connections || connections.length === 0) {
throw new JacksonError('SAML connection not found.', 403);
}
session = sessionId ? await this.sessionStore.get(sessionId) : null;
if (!isIdPFlow && !session) {
throw new JacksonError('Unable to validate state from the origin request.', 403);
}
isSAMLFederated = session && 'samlFederated' in session;
const isSPFlow = !isIdPFlow && !isSAMLFederated;
// IdP initiated SSO flow
if (isIdPFlow) {
const response = await this.ssoHandler.resolveConnection({
idp_hint,
authFlow: 'idp-initiated',
entityId: issuer,
originalParams: {
SAMLResponse,
},
});
// Redirect to the product selection page
if ('postForm' in response) {
return {
app_select_form: response.postForm,
};
}
// Found a connection
if ('connection' in response) {
connection = response.connection as SAMLSSORecord;
}
}
// SP initiated SSO flow
// Resolve if there are multiple matches for SP login
if (isSPFlow || isSAMLFederated) {
connection = connections.filter((c) => {
return (
c.clientID === session.requested.client_id ||
(c.tenant === session.requested.tenant && c.product === session.requested.product)
);
})[0];
}
if (!connection) {
throw new JacksonError('SAML connection not found.', 403);
}
if (
session &&
session.redirect_uri &&
!allowed.redirect(session.redirect_uri, connection.redirectUrl as string[])
) {
throw new JacksonError('Redirect URL is not allowed.', 403);
}
const { privateKey } = await getDefaultCertificate();
validateOpts = {
audience: `${this.opts.samlAudience}`,
privateKey,
};
if (connection.idpMetadata.publicKey) {
validateOpts.publicKey = connection.idpMetadata.publicKey;
} else if (connection.idpMetadata.thumbprint) {
validateOpts.thumbprint = connection.idpMetadata.thumbprint;
}
if (session && session.id) {
validateOpts['inResponseTo'] = session.id;
}
redirect_uri = ((session && session.redirect_uri) as string) || connection.defaultRedirectUrl;
} catch (err: unknown) {
// Save the error trace
await this.ssoTracer.saveTrace({
error: getErrorMessage(err),
context: {
samlResponse: rawResponse,
tenant: session?.requested?.tenant || connection?.tenant,
product: session?.requested?.product || connection?.product,
clientID: session?.requested?.client_id || connection?.clientID,
providerName: connection?.idpMetadata?.provider,
redirectUri: isIdPFlow ? connection?.defaultRedirectUrl : session?.redirect_uri,
issuer,
isSAMLFederated: !!isSAMLFederated,
isIdPFlow: !!isIdPFlow,
requestedOIDCFlow: !!session?.requested?.oidc,
acsUrl: session?.requested?.acsUrl,
entityId: session?.requested?.entityId,
relayState: RelayState,
},
});
throw err; // Rethrow the error
}
let profile: SAMLProfile | undefined;
try {
profile = await extractSAMLResponseAttributes(rawResponse, validateOpts);
// This is a federated SAML flow, let's create a new SAMLResponse and POST it to the SP
if (isSAMLFederated) {
const { responseForm } = await this.ssoHandler.createSAMLResponse({ profile, session });
await this.sessionStore.delete(sessionId);
return { response_form: responseForm };
}
const code = await this._buildAuthorizationCode(connection, profile, session, isIdPFlow);
const params = {
code,
};
if (session && session.state) {
params['state'] = session.state;
}
await this.sessionStore.delete(sessionId);
return { redirect_url: redirect.success(redirect_uri, params) };
} catch (err: unknown) {
const error_description = getErrorMessage(err);
// Trace the error
const traceId = await this.ssoTracer.saveTrace({
error: error_description,
context: {
samlResponse: rawResponse,
tenant: connection.tenant,
product: connection.product,
clientID: connection.clientID,
providerName: connection?.idpMetadata?.provider,
redirectUri: isIdPFlow ? connection?.defaultRedirectUrl : session?.redirect_uri,
isSAMLFederated,
isIdPFlow,
acsUrl: session.requested.acsUrl,
entityId: session.requested.entityId,
requestedOIDCFlow: !!session.requested.oidc,
relayState: RelayState,
issuer,
profile,
},
});
if (isSAMLFederated) {
throw err;
}
return {
redirect_url: OAuthErrorResponse({
error: 'access_denied',
error_description: traceId ? `${traceId}: ${error_description}` : error_description,
redirect_uri,
state: session.requested?.state,
}),
};
}
}
public async oidcAuthzResponse(
body: OIDCAuthzResponsePayload
): Promise<{ redirect_url?: string; response_form?: string }> {
let oidcConnection: OIDCSSORecord | undefined;
let session: any;
let isSAMLFederated: boolean | undefined;
let redirect_uri: string | undefined;
let profile;
const callbackParams = body;
let RelayState = callbackParams.state || '';
try {
if (!RelayState) {
throw new JacksonError('State from original request is missing.', 403);
}
RelayState = RelayState.replace(relayStatePrefix, '');
session = await this.sessionStore.get(RelayState);
if (!session) {
throw new JacksonError('Unable to validate state from the original request.', 403);
}
isSAMLFederated = session && 'samlFederated' in session;
oidcConnection = await this.connectionStore.get(session.id);
if (!oidcConnection) {
throw new JacksonError('OIDC connection not found.', 403);
}
if (!isSAMLFederated) {
redirect_uri = session && session.redirect_uri;
if (!redirect_uri) {
throw new JacksonError('Redirect URL from the authorization request could not be retrieved', 403);
}
if (redirect_uri && !allowed.redirect(redirect_uri, oidcConnection.redirectUrl as string[])) {
throw new JacksonError('Redirect URL is not allowed.', 403);
}
}
} catch (err) {
await this.ssoTracer.saveTrace({
error: getErrorMessage(err),
context: {
tenant: session?.requested?.tenant || oidcConnection?.tenant,
product: session?.requested?.product || oidcConnection?.product,
clientID: session?.requested?.client_id || oidcConnection?.clientID,
providerName: oidcConnection?.oidcProvider?.provider,
acsUrl: session?.requested?.acsUrl,
entityId: session?.requested?.entityId,
redirectUri: redirect_uri,
relayState: RelayState,
isSAMLFederated: !!isSAMLFederated,
requestedOIDCFlow: !!session?.requested?.oidc,
},
});
// Rethrow err and redirect to Jackson error page
throw err;
}
// Reconstruct the oidcClient, code exchange for token and user profile happens here
const { discoveryUrl, metadata, clientId, clientSecret } = oidcConnection.oidcProvider;
let tokenSet: TokenSet | undefined;
try {
const oidcIssuer = await oidcIssuerInstance(discoveryUrl, metadata);
const oidcClient = new oidcIssuer.Client({
client_id: clientId,
client_secret: clientSecret,
redirect_uris: [this.opts.externalUrl + this.opts.oidcPath],
response_types: ['code'],
});
tokenSet = await oidcClient.callback(this.opts.externalUrl + this.opts.oidcPath, callbackParams, {
code_verifier: session.oidcCodeVerifier,
nonce: session.oidcNonce,
state: callbackParams.state,
});
profile = await extractOIDCUserProfile(tokenSet, oidcClient);
if (isSAMLFederated) {
const { responseForm } = await this.ssoHandler.createSAMLResponse({ profile, session });
await this.sessionStore.delete(RelayState);
return { response_form: responseForm };
}
const code = await this._buildAuthorizationCode(oidcConnection, profile, session, false);
const params = {
code,
};
if (session && session.state) {
params['state'] = session.state;
}
await this.sessionStore.delete(RelayState);
return { redirect_url: redirect.success(redirect_uri!, params) };
} catch (err: unknown) {
const { error, error_description, error_uri, session_state, scope, stack } = err as errors.OPError;
const error_message = getErrorMessage(err);
const traceId = await this.ssoTracer.saveTrace({
error: error_message,
context: {
tenant: oidcConnection.tenant,
product: oidcConnection.product,
clientID: oidcConnection.clientID,
providerName: oidcConnection.oidcProvider.provider,
redirectUri: redirect_uri,
relayState: RelayState,
isSAMLFederated: !!isSAMLFederated,
acsUrl: session.requested.acsUrl,
entityId: session.requested.entityId,
requestedOIDCFlow: !!session.requested.oidc,
profile,
error,
error_description,
error_uri,
session_state_from_op_error: session_state,
scope_from_op_error: scope,
stack,
oidcTokenSet: { id_token: tokenSet?.id_token, access_token: tokenSet?.access_token },
},
});
if (isSAMLFederated) {
throw err;
}
return {
redirect_url: OAuthErrorResponse({
error: (error as OAuthErrorHandlerParams['error']) || 'server_error',
error_description: traceId ? `${traceId}: ${error_message}` : error_message,
redirect_uri: redirect_uri!,
state: session.state,
}),
};
}
}
// Build the authorization code for the session
private async _buildAuthorizationCode(
connection: SAMLSSORecord | OIDCSSORecord,
profile: any,
session: any,
isIdPFlow: boolean
) {
// Store details against a code
const code = crypto.randomBytes(20).toString('hex');
const requested = isIdPFlow
? { isIdPFlow: true, tenant: connection.tenant, product: connection.product }
: session
? session.requested
: null;
const codeVal = {
profile,
clientID: connection.clientID,
clientSecret: connection.clientSecret,
requested,
isIdPFlow,
};
if (session) {
codeVal['session'] = session;
}
await this.codeStore.put(code, codeVal);
return code;
}
/**
* @swagger
*
* /oauth/token:
* post:
* summary: Code exchange
* operationId: oauth-code-exchange
* tags:
* - OAuth
* consumes:
* - application/x-www-form-urlencoded
* parameters:
* - name: grant_type
* in: formData
* type: string
* description: Grant type should be 'authorization_code'
* default: authorization_code
* required: true
* - name: client_id
* in: formData
* type: string
* description: Use the client_id returned by the SAML connection API
* required: true
* - name: client_secret
* in: formData
* type: string
* description: Use the client_secret returned by the SAML connection API
* required: true
* - name: code_verifier
* in: formData
* type: string
* description: code_verifier against the code_challenge in the authz request (relevant to PKCE flow)
* - name: redirect_uri
* in: formData
* type: string
* description: Redirect URI
* required: true
* - name: code
* in: formData
* type: string
* description: Code
* required: true
* responses:
* '200':
* description: Success
* schema:
* type: object
* properties:
* access_token:
* type: string
* token_type:
* type: string
* expires_in:
* type: string
* example:
* access_token: 8958e13053832b5af58fdf2ee83f35f5d013dc74
* token_type: bearer
* expires_in: 300
*/
public async token(body: OAuthTokenReq): Promise<OAuthTokenRes> {
const { code, grant_type = 'authorization_code', redirect_uri } = body;
const client_id = 'client_id' in body ? body.client_id : undefined;
const client_secret = 'client_secret' in body ? body.client_secret : undefined;
const code_verifier = 'code_verifier' in body ? body.code_verifier : undefined;
metrics.increment('oauthToken');
if (grant_type !== 'authorization_code') {
throw new JacksonError('Unsupported grant_type', 400);
}
if (!code) {
throw new JacksonError('Please specify code', 400);
}
const codeVal = await this.codeStore.get(code);
if (!codeVal || !codeVal.profile) {
throw new JacksonError('Invalid code', 403);
}
if (codeVal.requested?.redirect_uri) {
if (redirect_uri !== codeVal.requested.redirect_uri) {
throw new JacksonError(
`Invalid request: ${!redirect_uri ? 'redirect_uri missing' : 'redirect_uri mismatch'}`,
400
);
}
}
if (code_verifier) {
// PKCE flow
let cv = code_verifier;
if (codeVal.session.code_challenge_method?.toLowerCase() === 's256') {
cv = codeVerifier.encode(code_verifier);
}
if (codeVal.session.code_challenge !== cv) {
throw new JacksonError('Invalid code_verifier', 401);
}
} else if (client_id && client_secret) {
// check if we have an encoded client_id
if (client_id !== 'dummy') {
const sp = getEncodedTenantProduct(client_id);
if (!sp) {
// OAuth flow
if (client_id !== codeVal.clientID || client_secret !== codeVal.clientSecret) {
throw new JacksonError('Invalid client_id or client_secret', 401);
}
} else {
if (
!codeVal.isIdPFlow &&
(sp.tenant !== codeVal.requested?.tenant || sp.product !== codeVal.requested?.product)
) {
throw new JacksonError('Invalid tenant or product', 401);
}
// encoded client_id, verify client_secret
if (client_secret !== this.opts.clientSecretVerifier) {
throw new JacksonError('Invalid client_secret', 401);
}
}
} else {
if (client_secret !== this.opts.clientSecretVerifier && client_secret !== codeVal.clientSecret) {
throw new JacksonError('Invalid client_secret', 401);
}
}
} else if (codeVal && codeVal.session) {
throw new JacksonError('Please specify client_secret or code_verifier', 401);
}
// store details against a token
const token = crypto.randomBytes(20).toString('hex');
const tokenVal = {
...codeVal.profile,
requested: codeVal.requested,