-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathconfig.ts
416 lines (394 loc) · 14.8 KB
/
config.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import crypto from 'crypto';
import type { Duration } from 'moment';
import { schema, Type, TypeOf } from '@kbn/config-schema';
import { i18n } from '@kbn/i18n';
import { Logger, config as coreConfig } from '../../../../src/core/server';
import type { AuthenticationProvider } from '../common/model';
export type ConfigType = ReturnType<typeof createConfig>;
type RawConfigType = TypeOf<typeof ConfigSchema>;
interface ProvidersCommonConfigType {
enabled: Type<boolean>;
showInSelector: Type<boolean>;
order: Type<number>;
description?: Type<string>;
hint?: Type<string>;
icon?: Type<string>;
session?: Type<{ idleTimeout?: Duration | null; lifespan?: Duration | null }>;
}
const providerOptionsSchema = (providerType: string, optionsSchema: Type<any>) =>
schema.conditional(
schema.siblingRef('providers'),
schema.arrayOf(schema.string(), {
validate: (providers) => (!providers.includes(providerType) ? 'error' : undefined),
}),
optionsSchema,
schema.never()
);
function getCommonProviderSchemaProperties(overrides: Partial<ProvidersCommonConfigType> = {}) {
return {
enabled: schema.boolean({ defaultValue: true }),
showInSelector: schema.boolean({ defaultValue: true }),
order: schema.number({ min: 0 }),
description: schema.maybe(schema.string()),
hint: schema.maybe(schema.string()),
icon: schema.maybe(schema.string()),
accessAgreement: schema.maybe(schema.object({ message: schema.string() })),
session: schema.object({
idleTimeout: schema.maybe(schema.oneOf([schema.duration(), schema.literal(null)])),
lifespan: schema.maybe(schema.oneOf([schema.duration(), schema.literal(null)])),
}),
...overrides,
};
}
function getUniqueProviderSchema<TProperties extends Record<string, Type<any>>>(
providerType: string,
overrides?: Partial<ProvidersCommonConfigType>,
properties?: TProperties
) {
return schema.maybe(
schema.recordOf(
schema.string(),
schema.object(
properties
? { ...getCommonProviderSchemaProperties(overrides), ...properties }
: getCommonProviderSchemaProperties(overrides)
),
{
validate(config) {
if (Object.values(config).filter((provider) => provider.enabled).length > 1) {
return `Only one "${providerType}" provider can be configured.`;
}
},
}
)
);
}
type ProvidersConfigType = TypeOf<typeof providersConfigSchema>;
const providersConfigSchema = schema.object(
{
basic: getUniqueProviderSchema('basic', {
description: schema.string({
defaultValue: i18n.translate('xpack.security.loginWithElasticsearchLabel', {
defaultMessage: 'Log in with Elasticsearch',
}),
}),
icon: schema.string({ defaultValue: 'logoElasticsearch' }),
showInSelector: schema.boolean({
defaultValue: true,
validate: (value) => {
if (!value) {
return '`basic` provider only supports `true` in `showInSelector`.';
}
},
}),
}),
token: getUniqueProviderSchema('token', {
description: schema.string({
defaultValue: i18n.translate('xpack.security.loginWithElasticsearchLabel', {
defaultMessage: 'Log in with Elasticsearch',
}),
}),
icon: schema.string({ defaultValue: 'logoElasticsearch' }),
showInSelector: schema.boolean({
defaultValue: true,
validate: (value) => {
if (!value) {
return '`token` provider only supports `true` in `showInSelector`.';
}
},
}),
}),
kerberos: getUniqueProviderSchema('kerberos'),
pki: getUniqueProviderSchema('pki'),
saml: schema.maybe(
schema.recordOf(
schema.string(),
schema.object({
...getCommonProviderSchemaProperties(),
realm: schema.string(),
maxRedirectURLSize: schema.maybe(schema.byteSize()),
useRelayStateDeepLink: schema.boolean({ defaultValue: false }),
})
)
),
oidc: schema.maybe(
schema.recordOf(
schema.string(),
schema.object({ ...getCommonProviderSchemaProperties(), realm: schema.string() })
)
),
anonymous: getUniqueProviderSchema(
'anonymous',
{
description: schema.string({
defaultValue: i18n.translate('xpack.security.loginAsGuestLabel', {
defaultMessage: 'Continue as Guest',
}),
}),
hint: schema.string({
defaultValue: i18n.translate('xpack.security.loginAsGuestHintLabel', {
defaultMessage: 'For anonymous users',
}),
}),
icon: schema.string({ defaultValue: 'globe' }),
session: schema.object({
idleTimeout: schema.nullable(schema.duration()),
lifespan: schema.maybe(schema.oneOf([schema.duration(), schema.literal(null)])),
}),
},
{
credentials: schema.oneOf([
schema.object({
username: schema.string(),
password: schema.string(),
}),
schema.object({
apiKey: schema.oneOf([
schema.object({ id: schema.string(), key: schema.string() }),
schema.string(),
]),
}),
]),
}
),
},
{
validate(config) {
const checks = { sameOrder: new Map<number, string>(), sameName: new Map<string, string>() };
for (const [providerType, providerGroup] of Object.entries(config)) {
for (const [providerName, { enabled, order }] of Object.entries(providerGroup ?? {})) {
if (!enabled) {
continue;
}
const providerPath = `xpack.security.authc.providers.${providerType}.${providerName}`;
const providerWithSameOrderPath = checks.sameOrder.get(order);
if (providerWithSameOrderPath) {
return `Found multiple providers configured with the same order "${order}": [${providerWithSameOrderPath}, ${providerPath}]`;
}
checks.sameOrder.set(order, providerPath);
const providerWithSameName = checks.sameName.get(providerName);
if (providerWithSameName) {
return `Found multiple providers configured with the same name "${providerName}": [${providerWithSameName}, ${providerPath}]`;
}
checks.sameName.set(providerName, providerPath);
}
}
},
}
);
export const ConfigSchema = schema.object({
enabled: schema.boolean({ defaultValue: true }),
loginAssistanceMessage: schema.string({ defaultValue: '' }),
loginHelp: schema.maybe(schema.string()),
cookieName: schema.string({ defaultValue: 'sid' }),
encryptionKey: schema.conditional(
schema.contextRef('dist'),
true,
schema.maybe(schema.string({ minLength: 32 })),
schema.string({ minLength: 32, defaultValue: 'a'.repeat(32) })
),
session: schema.object({
idleTimeout: schema.maybe(schema.oneOf([schema.duration(), schema.literal(null)])),
lifespan: schema.maybe(schema.oneOf([schema.duration(), schema.literal(null)])),
cleanupInterval: schema.duration({
defaultValue: '1h',
validate(value) {
if (value.asSeconds() < 10) {
return 'the value must be greater or equal to 10 seconds.';
}
},
}),
}),
secureCookies: schema.boolean({ defaultValue: false }),
sameSiteCookies: schema.maybe(
schema.oneOf([schema.literal('Strict'), schema.literal('Lax'), schema.literal('None')])
),
authc: schema.object({
selector: schema.object({ enabled: schema.maybe(schema.boolean()) }),
providers: schema.oneOf([schema.arrayOf(schema.string()), providersConfigSchema], {
defaultValue: {
basic: {
basic: {
enabled: true,
showInSelector: true,
order: 0,
description: undefined,
hint: undefined,
icon: undefined,
accessAgreement: undefined,
session: { idleTimeout: undefined, lifespan: undefined },
},
},
token: undefined,
saml: undefined,
oidc: undefined,
pki: undefined,
kerberos: undefined,
anonymous: undefined,
},
}),
oidc: providerOptionsSchema('oidc', schema.object({ realm: schema.string() })),
saml: providerOptionsSchema(
'saml',
schema.object({
realm: schema.string(),
maxRedirectURLSize: schema.maybe(schema.byteSize()),
})
),
http: schema.object({
enabled: schema.boolean({ defaultValue: true }),
autoSchemesEnabled: schema.boolean({ defaultValue: true }),
schemes: schema.arrayOf(schema.string(), { defaultValue: ['apikey'] }),
}),
}),
audit: schema.object(
{
enabled: schema.boolean({ defaultValue: false }),
appender: schema.maybe(coreConfig.logging.appenders),
ignore_filters: schema.maybe(
schema.arrayOf(
schema.object({
actions: schema.maybe(schema.arrayOf(schema.string(), { minSize: 1 })),
categories: schema.maybe(schema.arrayOf(schema.string(), { minSize: 1 })),
types: schema.maybe(schema.arrayOf(schema.string(), { minSize: 1 })),
outcomes: schema.maybe(schema.arrayOf(schema.string(), { minSize: 1 })),
spaces: schema.maybe(schema.arrayOf(schema.string(), { minSize: 1 })),
})
)
),
},
{
validate: (auditConfig) => {
if (auditConfig.ignore_filters && !auditConfig.appender) {
return 'xpack.security.audit.ignore_filters can only be used with the ECS audit logger. To enable the ECS audit logger, specify where you want to write the audit events using xpack.security.audit.appender.';
}
},
}
),
});
export function createConfig(
config: RawConfigType,
logger: Logger,
{ isTLSEnabled }: { isTLSEnabled: boolean }
) {
let encryptionKey = config.encryptionKey;
if (encryptionKey === undefined) {
logger.warn(
'Generating a random key for xpack.security.encryptionKey. To prevent sessions from being invalidated on ' +
'restart, please set xpack.security.encryptionKey in the kibana.yml or use the bin/kibana-encryption-keys command.'
);
encryptionKey = crypto.randomBytes(16).toString('hex');
}
let secureCookies = config.secureCookies;
if (!isTLSEnabled) {
if (secureCookies) {
logger.warn(
'Using secure cookies, but SSL is not enabled inside Kibana. SSL must be configured outside of Kibana to ' +
'function properly.'
);
} else {
logger.warn(
'Session cookies will be transmitted over insecure connections. This is not recommended.'
);
}
} else if (!secureCookies) {
secureCookies = true;
}
const isUsingLegacyProvidersFormat = Array.isArray(config.authc.providers);
const providers = (isUsingLegacyProvidersFormat
? [...new Set(config.authc.providers as Array<keyof ProvidersConfigType>)].reduce(
(legacyProviders, providerType, order) => {
legacyProviders[providerType] = {
[providerType]:
providerType === 'saml' || providerType === 'oidc'
? { enabled: true, showInSelector: true, order, ...config.authc[providerType] }
: { enabled: true, showInSelector: true, order },
};
return legacyProviders;
},
{} as Record<string, unknown>
)
: config.authc.providers) as ProvidersConfigType;
// Remove disabled providers and sort the rest.
const sortedProviders: Array<{
type: keyof ProvidersConfigType;
name: string;
order: number;
hasAccessAgreement: boolean;
}> = [];
for (const [type, providerGroup] of Object.entries(providers)) {
for (const [name, { enabled, order, accessAgreement }] of Object.entries(providerGroup ?? {})) {
if (!enabled) {
delete providerGroup![name];
} else {
sortedProviders.push({
type: type as any,
name,
order,
hasAccessAgreement: !!accessAgreement?.message,
});
}
}
}
sortedProviders.sort(({ order: orderA }, { order: orderB }) =>
orderA < orderB ? -1 : orderA > orderB ? 1 : 0
);
// We enable Login Selector by default if a) it's not explicitly disabled, b) new config
// format of providers is used and c) we have more than one provider enabled.
const isLoginSelectorEnabled =
typeof config.authc.selector.enabled === 'boolean'
? config.authc.selector.enabled
: !isUsingLegacyProvidersFormat &&
sortedProviders.filter(({ type, name }) => providers[type]?.[name].showInSelector).length >
1;
return {
...config,
authc: {
selector: { ...config.authc.selector, enabled: isLoginSelectorEnabled },
providers,
sortedProviders: Object.freeze(sortedProviders),
http: config.authc.http,
},
session: getSessionConfig(config.session, providers),
encryptionKey,
secureCookies,
};
}
function getSessionConfig(session: RawConfigType['session'], providers: ProvidersConfigType) {
const defaultAnonymousSessionLifespan = schema.duration().validate('30d');
return {
cleanupInterval: session.cleanupInterval,
getExpirationTimeouts({ type, name }: AuthenticationProvider) {
// Both idle timeout and lifespan from the provider specific session config can have three
// possible types of values: `Duration`, `null` and `undefined`. The `undefined` type means that
// provider doesn't override session config and we should fall back to the global one instead.
const providerSessionConfig = providers[type as keyof ProvidersConfigType]?.[name]?.session;
// We treat anonymous sessions differently since users can create them without realizing it. This may lead to a
// non controllable amount of sessions stored in the session index. To reduce the impact we set a 30 days lifespan
// for the anonymous sessions in case neither global nor provider specific lifespan is configured explicitly.
// We can remove this code once https://github.com/elastic/kibana/issues/68885 is resolved.
const providerLifespan =
type === 'anonymous' &&
providerSessionConfig?.lifespan === undefined &&
session.lifespan === undefined
? defaultAnonymousSessionLifespan
: providerSessionConfig?.lifespan;
const [idleTimeout, lifespan] = [
[session.idleTimeout, providerSessionConfig?.idleTimeout],
[session.lifespan, providerLifespan],
].map(([globalTimeout, providerTimeout]) => {
const timeout = providerTimeout === undefined ? globalTimeout ?? null : providerTimeout;
return timeout && timeout.asMilliseconds() > 0 ? timeout : null;
});
return {
idleTimeout,
lifespan,
};
},
};
}