-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontroller.ts
More file actions
583 lines (512 loc) · 17.7 KB
/
controller.ts
File metadata and controls
583 lines (512 loc) · 17.7 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
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
import express from 'express';
import { v4 as uuid } from 'uuid';
import { ObjectId } from 'mongodb';
import SamlService from './service';
import { SamlStateStoreInterface } from './store/SamlStateStoreInterface';
import { ContextFactories } from '../../types/graphql';
import { SamlResponseData } from '../types';
import WorkspaceModel from '../../models/workspace';
import UserModel from '../../models/user';
import { sgr, Effect } from '../../utils/ansi';
/**
* Controller for SAML SSO endpoints
*/
export default class SamlController {
/**
* SAML service instance
*/
private samlService: SamlService;
/**
* Context factories for database access
*/
private factories: ContextFactories;
/**
* SAML state store instance
*/
private store: SamlStateStoreInterface;
/**
* SAML controller constructor used for DI
*
* @param factories - for working with models
* @param store - SAML state store instance
*/
constructor(factories: ContextFactories, store: SamlStateStoreInterface) {
this.samlService = new SamlService();
this.factories = factories;
this.store = store;
}
/**
* Initiate SSO login (GET /auth/sso/saml/:workspaceId)
* @param req - Express request
* @param res - Express response
*/
public async initiateLogin(req: express.Request, res: express.Response): Promise<void> {
const { workspaceId } = req.params;
try {
const returnUrl = (req.query.returnUrl as string) || `/workspace/${workspaceId}`;
/**
* Validate workspace ID format
*/
if (!this.isValidWorkspaceId(workspaceId)) {
this.log('warn', 'Invalid workspace ID format:', sgr(workspaceId, Effect.ForegroundRed));
res.status(400).json({ error: `Invalid workspace ID format: ${workspaceId}` });
return;
}
/**
* 1. Check if workspace has SSO enabled
*/
const workspace = await this.factories.workspacesFactory.findById(workspaceId);
if (!workspace || !workspace.sso?.enabled) {
this.log('warn', 'SSO not enabled for workspace:', sgr(workspaceId, Effect.ForegroundCyan));
res.status(400).json({ error: `SSO is not enabled for workspace: ${workspaceId}` });
return;
}
/**
* 2. Compose Assertion Consumer Service URL
*/
const acsUrl = this.getAcsUrl(workspaceId);
const relayStateId = uuid();
/**
* 3. Save RelayState to temporary storage
*/
this.log(
'info',
'[Store] Saving RelayState:',
sgr(relayStateId.slice(0, 8), Effect.ForegroundGray),
'| Store:',
sgr(this.store.type, Effect.ForegroundBlue),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
await this.store.saveRelayState(relayStateId, {
returnUrl,
workspaceId,
});
this.log('log', '[Store] RelayState saved:', sgr(relayStateId.slice(0, 8), Effect.ForegroundGray));
/**
* 4. Generate AuthnRequest
*/
const spEntityId = process.env.SSO_SP_ENTITY_ID || 'NOT_SET';
this.log(
'info',
'Generating SAML AuthnRequest:',
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'| SP Entity ID:',
sgr(spEntityId, [Effect.ForegroundMagenta, Effect.Bold]),
'| ACS URL:',
sgr(acsUrl, Effect.ForegroundGray)
);
const { requestId, encodedRequest } = await this.samlService.generateAuthnRequest(
workspaceId,
acsUrl,
relayStateId,
workspace.sso.saml
);
/**
* 5. Save AuthnRequest ID for InResponseTo validation
*/
this.log(
'info',
'[Store] Saving AuthnRequest:',
sgr(requestId.slice(0, 8), Effect.ForegroundGray),
'| Store:',
sgr(this.store.type, Effect.ForegroundBlue),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
await this.store.saveAuthnRequest(requestId, workspaceId);
this.log('log', '[Store] AuthnRequest saved:', sgr(requestId.slice(0, 8), Effect.ForegroundGray));
/**
* 6. Redirect to IdP
*/
const redirectUrl = new URL(workspace.sso.saml.ssoUrl);
redirectUrl.searchParams.set('SAMLRequest', encodedRequest);
redirectUrl.searchParams.set('RelayState', relayStateId);
this.log(
'log',
'Initiating SSO login for workspace:',
sgr(workspaceId, [Effect.ForegroundCyan, Effect.Bold]),
'| Request ID:',
sgr(requestId.slice(0, 8), Effect.ForegroundGray)
);
res.redirect(redirectUrl.toString());
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
this.log(
'error',
'SSO initiation error for workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'|',
sgr(errorMessage, Effect.ForegroundRed)
);
res.status(500).json({ error: `Failed to initiate SSO login for workspace ${workspaceId}: ${errorMessage}` });
}
}
/**
* Handle ACS callback (POST /auth/sso/saml/:workspaceId/acs)
* @param req - Express request object
* @param res - Express response object
* @returns void
*/
public async handleAcs(req: express.Request, res: express.Response): Promise<void> {
const { workspaceId } = req.params;
try {
const samlResponse = req.body.SAMLResponse as string;
const relayStateId = req.body.RelayState as string;
/**
* Validate workspace ID format
*/
if (!this.isValidWorkspaceId(workspaceId)) {
this.log('warn', '[ACS] Invalid workspace ID format:', sgr(workspaceId, Effect.ForegroundRed));
res.status(400).json({ error: `Invalid workspace ID format: ${workspaceId}` });
return;
}
/**
* Validate required SAML response
*/
if (!samlResponse) {
this.log('warn', '[ACS] Missing SAML response for workspace:', sgr(workspaceId, Effect.ForegroundCyan));
res.status(400).json({ error: `SAML response is required for workspace: ${workspaceId}` });
return;
}
/**
* 1. Get workspace SSO configuration and check if SSO is enabled
*/
const workspace = await this.factories.workspacesFactory.findById(workspaceId);
if (!workspace || !workspace.sso?.enabled) {
this.log('warn', '[ACS] SSO not enabled for workspace:', sgr(workspaceId, Effect.ForegroundCyan));
res.status(400).json({ error: `SSO is not enabled for workspace: ${workspaceId}` });
return;
}
/**
* 2. Validate and parse SAML Response
*/
const acsUrl = this.getAcsUrl(workspaceId);
let samlData: SamlResponseData;
try {
/**
* Validate and parse SAML Response
* Note: InResponseTo validation is done separately after parsing
*/
samlData = await this.samlService.validateAndParseResponse(
samlResponse,
workspaceId,
acsUrl,
workspace.sso.saml
);
this.log(
'log',
'[ACS] SAML response validated for workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'| User:',
sgr(samlData.email, [Effect.ForegroundMagenta, Effect.Bold])
);
/**
* Validate InResponseTo against stored AuthnRequest
*/
if (samlData.inResponseTo) {
this.log(
'info',
'[Store] Validating AuthnRequest:',
sgr(samlData.inResponseTo.slice(0, 8), Effect.ForegroundGray),
'| Store:',
sgr(this.store.type, Effect.ForegroundBlue),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
const isValidRequest = await this.store.validateAndConsumeAuthnRequest(
samlData.inResponseTo,
workspaceId
);
if (isValidRequest) {
this.log(
'log',
'[Store] AuthnRequest validated and consumed:',
sgr(samlData.inResponseTo.slice(0, 8), Effect.ForegroundGray)
);
} else {
this.log(
'warn',
'[Store] AuthnRequest validation failed:',
sgr(samlData.inResponseTo.slice(0, 8), Effect.ForegroundRed)
);
}
if (!isValidRequest) {
const requestIdShort = samlData.inResponseTo.slice(0, 8);
this.log(
'error',
'[ACS] InResponseTo validation failed for workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'| Request ID:',
sgr(requestIdShort, Effect.ForegroundGray)
);
res.status(400).json({ error: `Invalid SAML response: InResponseTo validation failed for workspace ${workspaceId}, request ID: ${requestIdShort}` });
return;
}
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
this.log(
'error',
'[ACS] SAML validation error for workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'|',
sgr(errorMessage, Effect.ForegroundRed)
);
res.status(400).json({ error: `Invalid SAML response for workspace ${workspaceId}: ${errorMessage}` });
return;
}
/**
* 3. Find or create user
*/
let user = await this.factories.usersFactory.findBySamlIdentity(workspaceId, samlData.nameId);
if (!user) {
/**
* JIT provisioning or invite-only policy
*/
this.log(
'info',
'[ACS] User not found, starting provisioning:',
sgr(samlData.email, Effect.ForegroundMagenta),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
user = await this.handleUserProvisioning(workspaceId, samlData, workspace);
} else {
this.log(
'log',
'[ACS] Existing user found:',
sgr(samlData.email, Effect.ForegroundMagenta),
'| User ID:',
sgr(user._id.toString().slice(0, 8), Effect.ForegroundGray)
);
}
/**
* 4. Get RelayState for return URL (before consuming)
* Note: RelayState is consumed after first use, so we need to get it before validation
*/
this.log(
'info',
'[Store] Getting RelayState:',
sgr(relayStateId.slice(0, 8), Effect.ForegroundGray),
'| Store:',
sgr(this.store.type, Effect.ForegroundBlue)
);
const relayState = await this.store.getRelayState(relayStateId);
if (relayState) {
this.log(
'log',
'[Store] RelayState retrieved and consumed:',
sgr(relayStateId.slice(0, 8), Effect.ForegroundGray),
'| Return URL:',
sgr(relayState.returnUrl, Effect.ForegroundGray)
);
} else {
this.log('warn', '[Store] RelayState not found or expired:', sgr(relayStateId.slice(0, 8), Effect.ForegroundRed));
}
const finalReturnUrl = relayState?.returnUrl || `/workspace/${workspaceId}`;
/**
* 5. Create Hawk session
* Use shorter token lifetime for enforced SSO workspaces
*/
const tokens = await user.generateTokensPair(workspace.sso?.enforced || false);
/**
* 6. Redirect to Garage SSO callback page with tokens
* The SSO callback page will save tokens to store and redirect to finalReturnUrl
*/
const callbackPath = `/login/sso/${workspaceId}`;
const frontendUrl = new URL(callbackPath, process.env.GARAGE_URL || 'http://localhost:3000');
frontendUrl.searchParams.set('access_token', tokens.accessToken);
frontendUrl.searchParams.set('refresh_token', tokens.refreshToken);
frontendUrl.searchParams.set('returnUrl', finalReturnUrl);
this.log(
'success',
'[ACS] ✓ SSO login successful:',
sgr(samlData.email, [Effect.ForegroundMagenta, Effect.Bold]),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'| Redirecting to:',
sgr(callbackPath, Effect.ForegroundGray),
'→',
sgr(finalReturnUrl, Effect.ForegroundGray)
);
res.redirect(frontendUrl.toString());
} catch (error) {
/**
* Handle specific error types
*/
if (error instanceof Error && error.message.includes('SAML')) {
const errorMessage = error.message;
this.log(
'error',
'[ACS] SAML processing error for workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'|',
sgr(errorMessage, Effect.ForegroundRed)
);
res.status(400).json({ error: `Invalid SAML response for workspace ${workspaceId}: ${errorMessage}` });
return;
}
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
this.log(
'error',
'[ACS] ACS callback error for workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'|',
sgr(errorMessage, Effect.ForegroundRed)
);
res.status(500).json({ error: `Failed to process SSO callback for workspace ${workspaceId}: ${errorMessage}` });
}
}
/**
* Log message with SSO prefix
*
* @param level - log level ('log', 'warn', 'error', 'info', 'success')
* @param args - arguments to log
*/
private log(level: 'log' | 'warn' | 'error' | 'info' | 'success', ...args: unknown[]): void {
/**
* Disable logging in test environment
*/
if (process.env.NODE_ENV === 'test') {
return;
}
const colors = {
log: Effect.ForegroundGreen,
warn: Effect.ForegroundYellow,
error: Effect.ForegroundRed,
info: Effect.ForegroundBlue,
success: [Effect.ForegroundGreen, Effect.Bold],
};
let logger: typeof console.log;
if (level === 'error') {
logger = console.error;
} else if (level === 'warn') {
logger = console.warn;
} else {
logger = console.log;
}
logger(sgr('[SSO]', colors[level]), ...args);
}
/**
* Validate workspace ID format
*
* @param workspaceId - workspace ID to validate
* @returns true if valid, false otherwise
*/
private isValidWorkspaceId(workspaceId: string): boolean {
return ObjectId.isValid(workspaceId);
}
/**
* Compose Assertion Consumer Service URL for workspace
*
* @param workspaceId - workspace ID
* @returns ACS URL
*/
private getAcsUrl(workspaceId: string): string {
const apiUrl = process.env.API_URL || 'https://api.hawk.so';
return `${apiUrl}/auth/sso/saml/${workspaceId}/acs`;
}
/**
* Handle user provisioning (JIT or invite-only)
*
* @param workspaceId - workspace ID
* @param samlData - parsed SAML response data
* @param workspace - workspace model
* @returns UserModel instance
*/
private async handleUserProvisioning(
workspaceId: string,
samlData: SamlResponseData,
workspace: WorkspaceModel
): Promise<UserModel> {
try {
/**
* Find user by email
*/
let user = await this.factories.usersFactory.findByEmail(samlData.email);
if (!user) {
/**
* Create new user (JIT provisioning)
* Password is not set - only SSO login is allowed
*/
this.log(
'info',
'[Provisioning] Creating new user:',
sgr(samlData.email, [Effect.ForegroundMagenta, Effect.Bold]),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
user = await this.factories.usersFactory.create(samlData.email, undefined, undefined);
}
/**
* Link SAML identity to user
*/
this.log(
'info',
'[Provisioning] Linking SAML identity for user:',
sgr(samlData.email, Effect.ForegroundMagenta),
'| NameID:',
sgr(samlData.nameId.slice(0, 16) + '...', Effect.ForegroundGray)
);
await user.linkSamlIdentity(workspaceId, samlData.nameId, samlData.email);
/**
* Check if user is a member of the workspace
*/
const member = await workspace.getMemberInfo(user._id.toString());
if (!member) {
/**
* Add user to workspace (JIT provisioning)
*/
this.log(
'log',
'[Provisioning] Adding user to workspace:',
sgr(samlData.email, Effect.ForegroundMagenta),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
await workspace.addMember(user._id.toString());
await user.addWorkspace(workspaceId);
} else if (WorkspaceModel.isPendingMember(member)) {
/**
* Confirm pending membership
*/
this.log(
'log',
'[Provisioning] Confirming pending membership:',
sgr(samlData.email, Effect.ForegroundMagenta),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan)
);
await workspace.confirmMembership(user);
await user.confirmMembership(workspaceId);
} else {
this.log(
'log',
'[Provisioning] User already member of workspace:',
sgr(samlData.email, Effect.ForegroundMagenta)
);
}
this.log(
'success',
'[Provisioning] ✓ User provisioning completed:',
sgr(samlData.email, [Effect.ForegroundMagenta, Effect.Bold]),
'| User ID:',
sgr(user._id.toString(), Effect.ForegroundGray)
);
return user;
} catch (error) {
this.log(
'error',
'[Provisioning] Provisioning error for user:',
sgr(samlData.email, Effect.ForegroundMagenta),
'| Workspace:',
sgr(workspaceId, Effect.ForegroundCyan),
'|',
sgr(error instanceof Error ? error.message : 'Unknown error', Effect.ForegroundRed)
);
throw error;
}
}
}