-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
Copy pathindex.ts
181 lines (164 loc) · 6.07 KB
/
index.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
/*
* 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 type { PublicMethodsOf, UnwrapPromise } from '@kbn/utility-types';
import {
ILegacyClusterClient,
KibanaRequest,
LoggerFactory,
HttpServiceSetup,
} from '../../../../../src/core/server';
import { SecurityLicense } from '../../common/licensing';
import { AuthenticatedUser } from '../../common/model';
import { SecurityAuditLogger, AuditServiceSetup } from '../audit';
import { ConfigType } from '../config';
import { getErrorStatusCode } from '../errors';
import { SecurityFeatureUsageServiceStart } from '../feature_usage';
import { Session } from '../session_management';
import { Authenticator } from './authenticator';
import { APIKeys, CreateAPIKeyParams, InvalidateAPIKeyParams } from './api_keys';
export { canRedirectRequest } from './can_redirect_request';
export { Authenticator, ProviderLoginAttempt } from './authenticator';
export { AuthenticationResult } from './authentication_result';
export { DeauthenticationResult } from './deauthentication_result';
export {
OIDCLogin,
SAMLLogin,
BasicAuthenticationProvider,
TokenAuthenticationProvider,
SAMLAuthenticationProvider,
OIDCAuthenticationProvider,
} from './providers';
export {
CreateAPIKeyResult,
InvalidateAPIKeyResult,
CreateAPIKeyParams,
InvalidateAPIKeyParams,
GrantAPIKeyResult,
} from './api_keys';
export {
BasicHTTPAuthorizationHeaderCredentials,
HTTPAuthorizationHeader,
} from './http_authentication';
interface SetupAuthenticationParams {
legacyAuditLogger: SecurityAuditLogger;
audit: AuditServiceSetup;
getFeatureUsageService: () => SecurityFeatureUsageServiceStart;
http: HttpServiceSetup;
clusterClient: ILegacyClusterClient;
config: ConfigType;
license: SecurityLicense;
loggers: LoggerFactory;
session: PublicMethodsOf<Session>;
}
export type Authentication = UnwrapPromise<ReturnType<typeof setupAuthentication>>;
export async function setupAuthentication({
legacyAuditLogger: auditLogger,
audit,
getFeatureUsageService,
http,
clusterClient,
config,
license,
loggers,
session,
}: SetupAuthenticationParams) {
const authLogger = loggers.get('authentication');
/**
* Retrieves currently authenticated user associated with the specified request.
* @param request
*/
const getCurrentUser = (request: KibanaRequest) => {
if (!license.isEnabled()) {
return null;
}
return (http.auth.get(request).state ?? null) as AuthenticatedUser | null;
};
const authenticator = new Authenticator({
legacyAuditLogger: auditLogger,
audit,
loggers,
clusterClient,
basePath: http.basePath,
config: { authc: config.authc },
getCurrentUser,
getFeatureUsageService,
license,
session,
});
authLogger.debug('Successfully initialized authenticator.');
http.registerAuth(async (request, response, t) => {
// If security is disabled continue with no user credentials and delete the client cookie as well.
if (!license.isEnabled()) {
return t.authenticated();
}
let authenticationResult;
try {
authenticationResult = await authenticator.authenticate(request);
} catch (err) {
authLogger.error(err);
return response.internalError();
}
if (authenticationResult.succeeded()) {
return t.authenticated({
state: authenticationResult.user,
requestHeaders: authenticationResult.authHeaders,
responseHeaders: authenticationResult.authResponseHeaders,
});
}
if (authenticationResult.redirected()) {
// Some authentication mechanisms may require user to be redirected to another location to
// initiate or complete authentication flow. It can be Kibana own login page for basic
// authentication (username and password) or arbitrary external page managed by 3rd party
// Identity Provider for SSO authentication mechanisms. Authentication provider is the one who
// decides what location user should be redirected to.
return t.redirected({
location: authenticationResult.redirectURL!,
...(authenticationResult.authResponseHeaders || {}),
});
}
if (authenticationResult.failed()) {
authLogger.info(`Authentication attempt failed: ${authenticationResult.error!.message}`);
const error = authenticationResult.error!;
// proxy Elasticsearch "native" errors
const statusCode = getErrorStatusCode(error);
if (typeof statusCode === 'number') {
return response.customError({
body: error,
statusCode,
headers: authenticationResult.authResponseHeaders,
});
}
return response.unauthorized({
headers: authenticationResult.authResponseHeaders,
});
}
authLogger.debug('Could not handle authentication attempt');
return t.notHandled();
});
authLogger.debug('Successfully registered core authentication handler.');
const apiKeys = new APIKeys({
clusterClient,
logger: loggers.get('api-key'),
license,
});
return {
login: authenticator.login.bind(authenticator),
logout: authenticator.logout.bind(authenticator),
isProviderTypeEnabled: authenticator.isProviderTypeEnabled.bind(authenticator),
acknowledgeAccessAgreement: authenticator.acknowledgeAccessAgreement.bind(authenticator),
getCurrentUser,
areAPIKeysEnabled: () => apiKeys.areAPIKeysEnabled(),
createAPIKey: (request: KibanaRequest, params: CreateAPIKeyParams) =>
apiKeys.create(request, params),
grantAPIKeyAsInternalUser: (request: KibanaRequest, params: CreateAPIKeyParams) =>
apiKeys.grantAsInternalUser(request, params),
invalidateAPIKey: (request: KibanaRequest, params: InvalidateAPIKeyParams) =>
apiKeys.invalidate(request, params),
invalidateAPIKeyAsInternalUser: (params: InvalidateAPIKeyParams) =>
apiKeys.invalidateAsInternalUser(params),
isAuthenticated: (request: KibanaRequest) => http.auth.isAuthenticated(request),
};
}