-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsaml.service.ee.ts
More file actions
544 lines (503 loc) · 18 KB
/
Copy pathsaml.service.ee.ts
File metadata and controls
544 lines (503 loc) · 18 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
import type { SamlPreferences, SamlPreferencesAttributeMapping } from '@n8n/api-types';
import { Logger } from '@n8n/backend-common';
import { GlobalConfig } from '@n8n/config';
import type { Settings, User } from '@n8n/db';
import { isValidEmail, SettingsRepository, UserRepository } from '@n8n/db';
import { OnPubSubEvent } from '@n8n/decorators';
import { Container, Service } from '@n8n/di';
import axios from 'axios';
import type express from 'express';
import { createHttpProxyAgent, createHttpsProxyAgent, InstanceSettings } from 'n8n-core';
import { jsonParse, UnexpectedError } from 'n8n-workflow';
import { type IdentityProviderInstance, type ServiceProviderInstance } from 'samlify';
import type { BindingContext, PostBindingContext } from 'samlify/types/src/entity';
import { AuthError } from '@/errors/response-errors/auth.error';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { ProvisioningService } from '@/modules/provisioning.ee/provisioning.service.ee';
import { UrlService } from '@/services/url.service';
import {
getSamlLoginLabel,
isSamlLicensedAndEnabled,
isSamlLoginEnabled,
isSsoJustInTimeProvisioningEnabled,
reloadAuthenticationMethod,
} from '@/sso.ee/sso-helpers';
import { SAML_PREFERENCES_DB_KEY } from './constants';
import { InvalidSamlMetadataUrlError } from './errors/invalid-saml-metadata-url.error';
import { InvalidSamlMetadataError } from './errors/invalid-saml-metadata.error';
import {
createUserFromSamlAttributes,
getMappedSamlAttributesFromFlowResult,
setSamlLoginEnabled,
setSamlLoginLabel,
updateUserFromSamlAttributes,
} from './saml-helpers';
import { SamlValidator } from './saml-validator';
import { getServiceProviderInstance } from './service-provider.ee';
import type { SamlLoginBinding, SamlUserAttributes } from './types';
@Service()
export class SamlService {
private identityProviderInstance: IdentityProviderInstance | undefined;
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
private samlify: typeof import('samlify') | undefined;
private _samlPreferences: SamlPreferences = {
mapping: {
email: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress',
firstName: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/firstname',
lastName: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/lastname',
userPrincipalName: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn',
},
metadata: '',
metadataUrl: '',
ignoreSSL: false,
loginBinding: 'redirect',
acsBinding: 'post',
authnRequestsSigned: false,
loginEnabled: false,
loginLabel: 'SAML',
wantAssertionsSigned: true,
wantMessageSigned: true,
relayState: this.urlService.getInstanceBaseUrl(),
signatureConfig: {
prefix: 'ds',
location: {
reference: '/samlp:Response/saml:Issuer',
action: 'after',
},
},
};
get samlPreferences(): SamlPreferences {
return {
...this._samlPreferences,
loginEnabled: isSamlLoginEnabled(),
loginLabel: getSamlLoginLabel(),
};
}
constructor(
private readonly logger: Logger,
private readonly urlService: UrlService,
private readonly validator: SamlValidator,
private readonly userRepository: UserRepository,
private readonly settingsRepository: SettingsRepository,
private readonly instanceSettings: InstanceSettings,
private readonly provisioningService: ProvisioningService,
) {}
async init(): Promise<void> {
try {
// load preferences first but do not apply so as to not load samlify unnecessarily
await this.loadFromDbAndApplySamlPreferences(false);
if (isSamlLicensedAndEnabled()) {
await this.validator.init();
await this.loadSamlify();
await this.loadFromDbAndApplySamlPreferences(true);
}
} catch (error) {
// If the SAML configuration has been corrupted in the database we'll
// delete the corrupted configuration and enable email logins again.
if (
error instanceof InvalidSamlMetadataUrlError ||
error instanceof InvalidSamlMetadataError ||
error instanceof SyntaxError
) {
this.logger.warn(
`SAML initialization failed because of invalid metadata in database: ${error.message}. IMPORTANT: Disabling SAML and switching to email-based login for all users. Please review your configuration and re-enable SAML.`,
);
await this.reset();
} else {
throw error;
}
}
}
async loadSamlify() {
if (this.samlify === undefined) {
this.logger.debug('Loading samlify library into memory');
await this.validator.init();
this.samlify = await import('samlify');
}
this.samlify.setSchemaValidator({
validate: async (response: string) => {
const valid = await this.validator.validateResponse(response);
if (!valid) {
throw new InvalidSamlMetadataError();
}
},
});
}
getIdentityProviderInstance(forceRecreate = false): IdentityProviderInstance {
if (this.samlify === undefined) {
throw new UnexpectedError('Samlify is not initialized');
}
if (!this._samlPreferences.metadata) {
throw new InvalidSamlMetadataError(
'No IdP metadata configured. Please provide valid identity provider metadata.',
);
}
if (this.identityProviderInstance === undefined || forceRecreate) {
this.identityProviderInstance = this.samlify.IdentityProvider({
metadata: this._samlPreferences.metadata,
});
}
this.validator.validateIdentityProvider(this.identityProviderInstance);
return this.identityProviderInstance;
}
getServiceProviderInstance(): ServiceProviderInstance {
if (this.samlify === undefined) {
throw new UnexpectedError('Samlify is not initialized');
}
return getServiceProviderInstance(this._samlPreferences, this.samlify);
}
/**
* Generate a login request URL.
* When `metadata` is provided, creates a temporary IdP from it (for testing without saving).
* Otherwise uses the cached IdP from persisted preferences.
*/
async getLoginRequestUrl(
relayState?: string,
binding?: SamlLoginBinding,
metadata?: string,
): Promise<{
binding: SamlLoginBinding;
context: BindingContext | PostBindingContext;
}> {
await this.loadSamlify();
if (this.samlify === undefined) {
throw new UnexpectedError('Samlify is not initialized');
}
let idp: IdentityProviderInstance;
if (metadata) {
const validationResult = await this.validator.validateMetadata(metadata);
if (!validationResult) {
throw new InvalidSamlMetadataError();
}
idp = this.samlify.IdentityProvider({ metadata });
this.validator.validateIdentityProvider(idp);
} else {
idp = this.getIdentityProviderInstance();
}
binding ??= this._samlPreferences.loginBinding ?? 'redirect';
const sp = this.getServiceProviderInstance();
sp.entitySetting.relayState = relayState ?? this.urlService.getInstanceBaseUrl();
const loginRequest = sp.createLoginRequest(idp, binding);
return {
binding,
context: binding === 'post' ? (loginRequest as PostBindingContext) : loginRequest,
};
}
async handleSamlLogin(
req: express.Request,
binding: SamlLoginBinding,
): Promise<{
authenticatedUser: User | undefined;
attributes: SamlUserAttributes;
onboardingRequired: boolean;
}> {
const attributes = await this.getAttributesFromLoginResponse(req, binding);
if (attributes.email) {
const lowerCasedEmail = attributes.email.toLowerCase();
if (!isValidEmail(lowerCasedEmail)) {
throw new BadRequestError('Invalid email format');
}
const user = await this.userRepository.findOne({
where: { email: lowerCasedEmail },
relations: ['authIdentities', 'role'],
});
if (user) {
// Login path for existing users that are fully set up and that have a SAML authIdentity set up
if (
user.authIdentities.find(
(e) => e.providerType === 'saml' && e.providerId === attributes.userPrincipalName,
)
) {
await this.applySsoProvisioning(user, attributes);
return {
authenticatedUser: user,
attributes,
onboardingRequired: false,
};
} else {
// Login path for existing users that are NOT fully set up for SAML
const updatedUser = await updateUserFromSamlAttributes(user, attributes);
const onboardingRequired = !updatedUser.firstName || !updatedUser.lastName;
await this.applySsoProvisioning(updatedUser, attributes);
return {
authenticatedUser: updatedUser,
attributes,
onboardingRequired,
};
}
} else {
// New users to be created JIT based on SAML attributes
if (isSsoJustInTimeProvisioningEnabled()) {
const newUser = await createUserFromSamlAttributes(attributes);
await this.applySsoProvisioning(newUser, attributes);
return {
authenticatedUser: newUser,
attributes,
onboardingRequired: true,
};
}
}
}
return {
authenticatedUser: undefined,
attributes,
onboardingRequired: false,
};
}
private async applySsoProvisioning(user: User, attributes: SamlPreferencesAttributeMapping) {
if (attributes?.n8nInstanceRole) {
await this.provisioningService.provisionInstanceRoleForUser(user, attributes.n8nInstanceRole);
}
if (attributes?.n8nProjectRoles) {
await this.provisioningService.provisionProjectRolesForUser(
user.id,
attributes.n8nProjectRoles,
);
}
}
private async broadcastReloadSAMLConfigurationCommand(): Promise<void> {
if (this.instanceSettings.isMultiMain) {
const { Publisher } = await import('@/scaling/pubsub/publisher.service');
await Container.get(Publisher).publishCommand({ command: 'reload-saml-config' });
}
}
private isReloading = false;
@OnPubSubEvent('reload-saml-config')
async reload(): Promise<void> {
if (this.isReloading) {
this.logger.warn('SAML configuration reload already in progress');
return;
}
this.isReloading = true;
try {
this.logger.debug('SAML configuration changed, starting to load it from the database');
await this.loadFromDbAndApplySamlPreferences(true, false);
await reloadAuthenticationMethod();
const samlLoginEnabled = isSamlLoginEnabled();
this.logger.debug(`SAML login is now ${samlLoginEnabled ? 'enabled' : 'disabled'}.`);
Container.get(GlobalConfig).sso.saml.loginEnabled = samlLoginEnabled;
} catch (error) {
this.logger.error('SAML configuration changed, failed to reload SAML configuration', {
error,
});
} finally {
this.isReloading = false;
}
}
async setSamlPreferences(
prefs: Partial<SamlPreferences>,
tryFallback: boolean = false,
broadcastReload: boolean = true,
): Promise<SamlPreferences | undefined> {
await this.loadSamlify();
const previousMetadataUrl = this._samlPreferences.metadataUrl;
await this.loadPreferencesWithoutValidation(prefs);
if (prefs.metadataUrl) {
try {
const fetchedMetadata = await this.fetchMetadataFromUrl();
if (fetchedMetadata) {
this._samlPreferences.metadata = fetchedMetadata;
} else {
// in this case the metadata url didn't produce a valid metadata for SAML
// therefore we are rejecting the change to it
throw new InvalidSamlMetadataUrlError(prefs.metadataUrl);
}
} catch (error) {
this._samlPreferences.metadataUrl = previousMetadataUrl;
if (!tryFallback) {
throw error;
}
// we were not able to produce correct metadata from the URL, but
// in this case we don't care and try to fallback on the saved metadata in the
// database.
this.logger.error(
'SAML initialization detected an invalid metadata URL in database. Trying to initialize from metadata in database if available.',
{ error },
);
}
} else if (prefs.metadata) {
const validationResult = await this.validator.validateMetadata(prefs.metadata);
if (!validationResult) {
throw new InvalidSamlMetadataError();
}
}
// If SAML login is enabled, we need to ensure that we have valid metadata available
// if the metadata url is provided and it was possible to fetch and validate that metadata
// it is now stored in this._samlPreferences.metadata.
// if no metadata url was provided but metadata directly as XML, it is also already stored
// in this._samlPreferences.metadata.
if (isSamlLoginEnabled()) {
if (this._samlPreferences.metadata) {
const validationResult = await this.validator.validateMetadata(
this._samlPreferences.metadata,
);
if (!validationResult) {
throw new InvalidSamlMetadataError();
}
} else {
// in this case SAML login is enabled but no valid metadata is available
throw new InvalidSamlMetadataError();
}
}
this.getIdentityProviderInstance(true);
const result = await this.saveSamlPreferencesToDb();
if (broadcastReload) {
await this.broadcastReloadSAMLConfigurationCommand();
}
return result;
}
async loadPreferencesWithoutValidation(prefs: Partial<SamlPreferences>) {
this._samlPreferences.loginBinding = prefs.loginBinding ?? this._samlPreferences.loginBinding;
this._samlPreferences.metadata = prefs.metadata ?? this._samlPreferences.metadata;
this._samlPreferences.mapping = prefs.mapping ?? this._samlPreferences.mapping;
this._samlPreferences.ignoreSSL = prefs.ignoreSSL ?? this._samlPreferences.ignoreSSL;
this._samlPreferences.acsBinding = prefs.acsBinding ?? this._samlPreferences.acsBinding;
this._samlPreferences.signatureConfig =
prefs.signatureConfig ?? this._samlPreferences.signatureConfig;
this._samlPreferences.authnRequestsSigned =
prefs.authnRequestsSigned ?? this._samlPreferences.authnRequestsSigned;
this._samlPreferences.wantAssertionsSigned =
prefs.wantAssertionsSigned ?? this._samlPreferences.wantAssertionsSigned;
this._samlPreferences.wantMessageSigned =
prefs.wantMessageSigned ?? this._samlPreferences.wantMessageSigned;
if (prefs.metadataUrl) {
this._samlPreferences.metadataUrl = prefs.metadataUrl;
} else if (prefs.metadata) {
// remove metadataUrl if metadata is set directly
this._samlPreferences.metadataUrl = undefined;
this._samlPreferences.metadata = prefs.metadata;
}
await setSamlLoginEnabled(prefs.loginEnabled ?? isSamlLoginEnabled());
setSamlLoginLabel(prefs.loginLabel ?? getSamlLoginLabel());
}
async loadFromDbAndApplySamlPreferences(
apply = true,
broadcastReload: boolean = true,
): Promise<SamlPreferences | undefined> {
const samlPreferences = await this.settingsRepository.findOne({
where: { key: SAML_PREFERENCES_DB_KEY },
});
if (samlPreferences) {
const prefs = jsonParse<SamlPreferences>(samlPreferences.value);
if (prefs) {
if (apply) {
await this.setSamlPreferences(prefs, true, broadcastReload);
} else {
await this.loadPreferencesWithoutValidation(prefs);
}
return prefs;
}
}
return;
}
async saveSamlPreferencesToDb(): Promise<SamlPreferences | undefined> {
const samlPreferences = await this.settingsRepository.findOne({
where: { key: SAML_PREFERENCES_DB_KEY },
});
const settingsValue = JSON.stringify(this.samlPreferences);
let result: Settings;
if (samlPreferences) {
samlPreferences.value = settingsValue;
result = await this.settingsRepository.save(samlPreferences, {
transaction: false,
});
} else {
result = await this.settingsRepository.save(
{
key: SAML_PREFERENCES_DB_KEY,
value: settingsValue,
loadOnStartup: true,
},
{ transaction: false },
);
}
if (result) return jsonParse<SamlPreferences>(result.value);
return;
}
async fetchMetadataFromUrl(
metadataUrl?: string,
ignoreSSL?: boolean,
): Promise<string | undefined> {
await this.loadSamlify();
const url = metadataUrl ?? this._samlPreferences.metadataUrl;
const shouldIgnoreSSL = ignoreSSL ?? this._samlPreferences.ignoreSSL;
if (!url) throw new BadRequestError('Error fetching SAML Metadata, no Metadata URL set');
try {
// Create a proxy-aware HTTPS agent that respects HTTP_PROXY, HTTPS_PROXY, and NO_PROXY
// environment variables while also supporting SSL certificate validation options
const httpsAgent = createHttpsProxyAgent(
null, // Uses proxy from environment variables
url,
{
rejectUnauthorized: !shouldIgnoreSSL,
},
);
const httpAgent = createHttpProxyAgent(null, url);
const response = await axios.get(url, {
httpsAgent,
httpAgent,
});
if (response.status === 200 && response.data) {
const xml = (await response.data) as string;
const validationResult = await this.validator.validateMetadata(xml);
if (!validationResult) {
throw new BadRequestError(`Data received from ${url} is not valid SAML metadata.`);
}
return xml;
}
} catch (error) {
if (error instanceof BadRequestError) throw error;
throw new BadRequestError(`Error fetching SAML Metadata from ${url}: ${error}`);
}
return;
}
async getAttributesFromLoginResponse(
req: express.Request,
binding: SamlLoginBinding,
): Promise<SamlUserAttributes> {
let parsedSamlResponse;
if (!this._samlPreferences.mapping)
throw new BadRequestError('Error fetching SAML Attributes, no Attribute mapping set');
try {
await this.loadSamlify();
parsedSamlResponse = await this.getServiceProviderInstance().parseLoginResponse(
this.getIdentityProviderInstance(),
binding,
req,
);
} catch (error) {
// throw error;
throw new AuthError(
// INFO: The error can be a string. Samlify rejects promises with strings.
`SAML Authentication failed. Could not parse SAML response. ${error instanceof Error ? error.message : error}`,
);
}
const { attributes, missingAttributes } = getMappedSamlAttributesFromFlowResult(
parsedSamlResponse,
this._samlPreferences.mapping,
{
instanceRole: await this.provisioningService.getInstanceRoleClaimName(),
projectRoles: await this.provisioningService.getProjectsRolesClaimName(),
},
);
if (!attributes) {
throw new AuthError('SAML Authentication failed. Invalid SAML response.');
}
if (missingAttributes.length > 0) {
throw new AuthError(
`SAML Authentication failed. Invalid SAML response (missing attributes: ${missingAttributes.join(
', ',
)}).`,
);
}
return attributes;
}
/**
* Disables SAML, switches to email based logins and deletes the SAML
* configuration from the database.
*/
async reset() {
await setSamlLoginEnabled(false);
await this.settingsRepository.delete({ key: SAML_PREFERENCES_DB_KEY });
}
}