mirror of
https://github.com/elastic/kibana.git
synced 2025-04-23 17:28:26 -04:00
Implement Server-Side sessions (#68117)
This commit is contained in:
parent
28e6dd3521
commit
e46e66210f
124 changed files with 7271 additions and 2683 deletions
11
.github/CODEOWNERS
vendored
11
.github/CODEOWNERS
vendored
|
@ -174,6 +174,17 @@
|
|||
/x-pack/plugins/security/ @elastic/kibana-security
|
||||
/x-pack/plugins/security/**/*.scss @elastic/kibana-core-ui-designers
|
||||
/x-pack/test/api_integration/apis/security/ @elastic/kibana-security
|
||||
/x-pack/test/encrypted_saved_objects_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/functional/apps/security/ @elastic/kibana-security
|
||||
/x-pack/test/kerberos_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/login_selector_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/oidc_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/pki_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/saml_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/security_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/security_functional/ @elastic/kibana-security
|
||||
/x-pack/test/spaces_api_integration/ @elastic/kibana-security
|
||||
/x-pack/test/token_api_integration/ @elastic/kibana-security
|
||||
|
||||
# Kibana Localization
|
||||
/src/dev/i18n/ @elastic/kibana-localization
|
||||
|
|
|
@ -96,16 +96,13 @@ The valid settings in the `xpack.security.authc.providers` namespace vary depend
|
|||
`<provider-type>.<provider-name>.showInSelector`
|
||||
| Flag that indicates if the provider should have an entry on the Login Selector UI. Setting this to `false` doesn't remove the provider from the authentication chain.
|
||||
|
||||
|===
|
||||
|
||||
2+a|
|
||||
[TIP]
|
||||
[NOTE]
|
||||
============
|
||||
You are unable to set this setting to `false` for `basic` and `token` authentication providers.
|
||||
============
|
||||
|
||||
[cols="2*<"]
|
||||
|===
|
||||
|
||||
| `xpack.security.authc.providers.`
|
||||
`<provider-type>.<provider-name>.accessAgreement.message`
|
||||
| Access agreement text in Markdown format. For more information, refer to <<xpack-security-access-agreement>>.
|
||||
|
@ -125,8 +122,8 @@ In addition to <<authentication-provider-settings,the settings that are valid fo
|
|||
| SAML realm in {es} that provider should use.
|
||||
|
||||
| `xpack.security.authc.providers.`
|
||||
`saml.<provider-name>.maxRedirectURLSize`
|
||||
| The maximum size of the URL that {kib} is allowed to store during the authentication SAML handshake. For more information, refer to <<security-saml-and-long-urls>>.
|
||||
`saml.<provider-name>.useRelayStateDeepLink`
|
||||
| Determines if the provider should treat the `RelayState` parameter as a deep link in {kib} during Identity Provider initiated log in. By default, this setting is set to `false`. The link specified in `RelayState` should be a relative, URL-encoded {kib} URL. For example, the `/app/dashboards#/list` link in `RelayState` parameter would look like this: `RelayState=%2Fapp%2Fdashboards%23%2Flist`.
|
||||
|
||||
|===
|
||||
|
||||
|
@ -164,19 +161,27 @@ There is a very limited set of cases when you'd want to change these settings. F
|
|||
|===
|
||||
|
||||
[float]
|
||||
[[login-selector-settings]]
|
||||
===== Login Selector UI settings
|
||||
[[login-ui-settings]]
|
||||
===== Login user interface settings
|
||||
|
||||
You can configure the following settings in the `kibana.yml` file.
|
||||
|
||||
[cols="2*<"]
|
||||
|===
|
||||
| `xpack.security.loginAssistanceMessage`
|
||||
| Adds a message to the login UI. Useful for displaying information about maintenance windows, links to corporate sign up pages, and so on.
|
||||
|
||||
| `xpack.security.loginHelp`
|
||||
| Adds a message accessible at the login UI with additional help information for the login process.
|
||||
|
||||
| `xpack.security.authc.selector.enabled`
|
||||
| Determines if the Login Selector UI should be enabled. By default, this setting is set to `true` if more than one authentication provider is configured.
|
||||
| Determines if the login selector UI should be enabled. By default, this setting is set to `true` if more than one authentication provider is configured.
|
||||
|
||||
|===
|
||||
|
||||
[float]
|
||||
[[security-ui-settings]]
|
||||
==== User interface security settings
|
||||
[[security-session-and-cookie-settings]]
|
||||
==== Session and cookie security settings
|
||||
|
||||
You can configure the following settings in the `kibana.yml` file.
|
||||
|
||||
|
@ -186,8 +191,7 @@ You can configure the following settings in the `kibana.yml` file.
|
|||
| Sets the name of the cookie used for the session. The default value is `"sid"`.
|
||||
|
||||
| `xpack.security.encryptionKey`
|
||||
| An arbitrary string of 32 characters or more that is used to encrypt credentials
|
||||
in a cookie. It is crucial that this key is not exposed to users of {kib}. By
|
||||
| An arbitrary string of 32 characters or more that is used to encrypt session information. Do **not** expose this key to users of {kib}. By
|
||||
default, a value is automatically generated in memory. If you use that default
|
||||
behavior, all sessions are invalidated when {kib} restarts.
|
||||
In addition, high-availability deployments of {kib} will behave unexpectedly
|
||||
|
@ -205,42 +209,33 @@ You can configure the following settings in the `kibana.yml` file.
|
|||
This is *not set* by default, which modern browsers will treat as `Lax`. If you use Kibana embedded in an iframe in modern browsers, you might need to set it to `None`. Setting this value to `None` requires cookies to be sent over a secure connection by setting `xpack.security.secureCookies: true`.
|
||||
|
||||
| `xpack.security.session.idleTimeout`
|
||||
| Sets the session duration. By default, sessions stay active until the
|
||||
browser is closed. When this is set to an explicit idle timeout, closing the
|
||||
browser still requires the user to log back in to {kib}.
|
||||
|
||||
|===
|
||||
| Ensures that user sessions will expire after a period of inactivity. This and `xpack.security.session.lifespan` are both
|
||||
highly recommended. By default, this setting is not set.
|
||||
|
||||
2+a|
|
||||
[TIP]
|
||||
============
|
||||
The format is a string of `<count>[ms|s|m|h|d|w|M|Y]`
|
||||
(e.g. '70ms', '5s', '3d', '1Y').
|
||||
The format is a string of `<count>[ms\|s\|m\|h\|d\|w\|M\|Y]` (e.g. '20m', '24h', '7d', '1w').
|
||||
============
|
||||
|
||||
[cols="2*<"]
|
||||
|===
|
||||
|
||||
| `xpack.security.session.lifespan`
|
||||
| Sets the maximum duration, also known as "absolute timeout". By default,
|
||||
a session can be renewed indefinitely. When this value is set, a session will end
|
||||
once its lifespan is exceeded, even if the user is not idle. NOTE: if `idleTimeout`
|
||||
is not set, this setting will still cause sessions to expire.
|
||||
|
||||
|===
|
||||
| Ensures that user sessions will expire after the defined time period. This behavior also known as an "absolute timeout". If
|
||||
this is _not_ set, user sessions could stay active indefinitely. This and `xpack.security.session.idleTimeout` are both highly
|
||||
recommended. By default, this setting is not set.
|
||||
|
||||
2+a|
|
||||
[TIP]
|
||||
============
|
||||
The format is a
|
||||
string of `<count>[ms|s|m|h|d|w|M|Y]` (e.g. '70ms', '5s', '3d', '1Y').
|
||||
The format is a string of `<count>[ms\|s\|m\|h\|d\|w\|M\|Y]` (e.g. '20m', '24h', '7d', '1w').
|
||||
============
|
||||
|
||||
[cols="2*<"]
|
||||
|===
|
||||
| `xpack.security.session.cleanupInterval`
|
||||
| Sets the interval at which {kib} tries to remove expired and invalid sessions from the session index. By default, this value is 1 hour. The minimum value is 10 seconds.
|
||||
|
||||
| `xpack.security.loginAssistanceMessage`
|
||||
| Adds a message to the login screen. Useful for displaying information about maintenance windows, links to corporate sign up pages etc.
|
||||
|
||||
| `xpack.security.loginHelp`
|
||||
| Adds a message accessible at the Login Selector UI with additional help information for the login process.
|
||||
2+a|
|
||||
[TIP]
|
||||
============
|
||||
The format is a string of `<count>[ms\|s\|m\|h\|d\|w\|M\|Y]` (e.g. '20m', '24h', '7d', '1w').
|
||||
============
|
||||
|
||||
|===
|
||||
|
|
|
@ -132,7 +132,7 @@ server.port
|
|||
|
||||
Settings that must be the same:
|
||||
--------
|
||||
xpack.security.encryptionKey //decrypting session cookies
|
||||
xpack.security.encryptionKey //decrypting session information
|
||||
xpack.reporting.encryptionKey //decrypting reports
|
||||
xpack.encryptedSavedObjects.encryptionKey // decrypting saved objects
|
||||
--------
|
||||
|
|
|
@ -59,8 +59,6 @@ For more information, refer to <<authentication-security-settings, authenticatio
|
|||
|
||||
To successfully log in to {kib}, basic authentication requires a username and password. Basic authentication is enabled by default, and is based on the Native, LDAP, or Active Directory security realm that is provided by {es}. The basic authentication provider uses a {kib} provided login form, and supports authentication using the `Authorization` request header `Basic` scheme.
|
||||
|
||||
The session cookies that are issued by the basic authentication provider are stateless. Therefore, logging out of {kib} when using the basic authentication provider clears the session cookies from the browser, but does not invalidate the session cookie for reuse.
|
||||
|
||||
NOTE: You can configure only one Basic provider per {kib} instance.
|
||||
|
||||
For more information about basic authentication and built-in users, see
|
||||
|
@ -71,8 +69,6 @@ For more information about basic authentication and built-in users, see
|
|||
|
||||
Token authentication allows users to log in using the same {kib} provided login form as basic authentication, and is based on the Native security realm or LDAP security realm that is provided by {es}. The token authentication provider is built on {es} token APIs.
|
||||
|
||||
The session cookies that are issued by the token authentication provider are stateful, and logging out of {kib} invalidates the session cookies for reuse.
|
||||
|
||||
Prior to configuring {kib}, ensure token support is enabled in {es}. See the {ref}/security-api-get-token.html[{es} token API] documentation for more information.
|
||||
|
||||
To enable the token authentication provider in {kib}, set the following value in your `kibana.yml`:
|
||||
|
@ -181,26 +177,6 @@ Basic authentication is supported _only_ if the `basic` authentication provider
|
|||
|
||||
To support basic authentication for the applications like `curl` or when the `Authorization: Basic base64(username:password)` HTTP header is included in the request (for example, by reverse proxy), add `Basic` scheme to the list of supported schemes for the <<http-authentication,HTTP authentication>>.
|
||||
|
||||
[float]
|
||||
[[security-saml-and-long-urls]]
|
||||
===== SAML and long URLs
|
||||
|
||||
At the beginning of the SAML handshake, {kib} stores the initial URL in the session cookie, so it can redirect the user back to that URL after successful SAML authentication.
|
||||
If the URL is long, the session cookie might exceed the maximum size supported by the browser--typically 4KB for all cookies per domain. When this happens, the session cookie is truncated,
|
||||
or dropped completely, and you might experience sporadic failures during SAML authentication.
|
||||
|
||||
To remedy this issue, you can decrease the maximum
|
||||
size of the URL that {kib} is allowed to store during the SAML handshake. The default value is 2KB.
|
||||
|
||||
[source,yaml]
|
||||
--------------------------------------------------------------------------------
|
||||
xpack.security.authc.providers:
|
||||
saml.saml1:
|
||||
order: 0
|
||||
realm: saml1
|
||||
maxRedirectURLSize: 1kb
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
[[oidc]]
|
||||
==== OpenID Connect single sign-on
|
||||
|
||||
|
@ -263,11 +239,11 @@ The following sections apply both to <<saml>> and <<oidc>>
|
|||
===== Access and refresh tokens
|
||||
|
||||
Once the user logs in to {kib} Single Sign-On, either using SAML or OpenID Connect, {es} issues access and refresh tokens
|
||||
that {kib} encrypts and stores them in its own session cookie. This way, the user isn't redirected to the Identity Provider
|
||||
for every request that requires authentication. It also means that the {kib} session depends on the <<security-ui-settings,
|
||||
that {kib} encrypts and stores as a part of its own session. This way, the user isn't redirected to the Identity Provider
|
||||
for every request that requires authentication. It also means that the {kib} session depends on the <<security-session-and-cookie-settings,
|
||||
`xpack.security.session.idleTimeout` and `xpack.security.session.lifespan`>> settings, and the user is automatically logged
|
||||
out if the session expires. An access token that is stored in the session cookie can expire, in which case {kib} will
|
||||
automatically renew it with a one-time-use refresh token and store it in the same cookie.
|
||||
out if the session expires. An access token that is stored in the session can expire, in which case {kib} will
|
||||
automatically renew it with a one-time-use refresh token and store it in the same session.
|
||||
|
||||
{kib} can only determine if an access token has expired if it receives a request that requires authentication. If both access
|
||||
and refresh tokens have already expired (for example, after 24 hours of inactivity), {kib} initiates a new "handshake" and
|
||||
|
@ -280,8 +256,7 @@ indicates that both access and refresh tokens are expired. Reloading the current
|
|||
[float]
|
||||
===== Local and global logout
|
||||
|
||||
During logout, both the {kib} session cookie and access/refresh token pair are invalidated. Even if the cookie has been
|
||||
leaked, it can't be re-used after logout. This is known as "local" logout.
|
||||
During logout, both the {kib} session and {es} access/refresh token pair are invalidated. This is known as "local" logout.
|
||||
|
||||
{kib} can also initiate a "global" logout or _Single Logout_ if it's supported by the external authentication provider and not
|
||||
explicitly disabled by {es}. In this case, the user is redirected to the external authentication provider for log out of
|
||||
|
|
|
@ -56,34 +56,16 @@ xpack.security.encryptionKey: "something_at_least_32_characters"
|
|||
For more information, see <<security-settings-kb,Security settings in {kib}>>.
|
||||
--
|
||||
|
||||
. Optional: Set a timeout to expire idle sessions. By default, a session stays
|
||||
active until the browser is closed. To define a sliding session expiration, set
|
||||
the `xpack.security.session.idleTimeout` property in the `kibana.yml`
|
||||
configuration file. The idle timeout is formatted as a duration of
|
||||
`<count>[ms|s|m|h|d|w|M|Y]` (e.g. '70ms', '5s', '3d', '1Y'). For example, set
|
||||
the idle timeout to expire idle sessions after 10 minutes:
|
||||
. Configure {kib}'s session expiration settings. Set both the idle timeout and lifespan settings:
|
||||
+
|
||||
--
|
||||
[source,yaml]
|
||||
--------------------------------------------------------------------------------
|
||||
xpack.security.session.idleTimeout: "10m"
|
||||
xpack.security.session.idleTimeout: "1h"
|
||||
xpack.security.session.lifespan: "30d"
|
||||
--------------------------------------------------------------------------------
|
||||
--
|
||||
|
||||
. Optional: Change the maximum session duration or "lifespan" -- also known as
|
||||
the "absolute timeout". By default, a session stays active until the browser is
|
||||
closed. If an idle timeout is defined, a session can still be extended
|
||||
indefinitely. To define a maximum session lifespan, set the
|
||||
`xpack.security.session.lifespan` property in the `kibana.yml` configuration
|
||||
file. The lifespan is formatted as a duration of `<count>[ms|s|m|h|d|w|M|Y]`
|
||||
(e.g. '70ms', '5s', '3d', '1Y'). For example, set the lifespan to expire
|
||||
sessions after 8 hours:
|
||||
+
|
||||
--
|
||||
[source,yaml]
|
||||
--------------------------------------------------------------------------------
|
||||
xpack.security.session.lifespan: "8h"
|
||||
--------------------------------------------------------------------------------
|
||||
For more information, see <<xpack-security-session-management, Session management in {kib}>>.
|
||||
--
|
||||
|
||||
. Optional: <<configuring-tls,Configure {kib} to encrypt communications>>.
|
||||
|
@ -146,3 +128,4 @@ include::securing-communications/index.asciidoc[]
|
|||
include::securing-communications/elasticsearch-mutual-tls.asciidoc[]
|
||||
include::audit-logging.asciidoc[]
|
||||
include::access-agreement.asciidoc[]
|
||||
include::session-management.asciidoc[]
|
||||
|
|
49
docs/user/security/session-management.asciidoc
Normal file
49
docs/user/security/session-management.asciidoc
Normal file
|
@ -0,0 +1,49 @@
|
|||
[role="xpack"]
|
||||
[[xpack-security-session-management]]
|
||||
=== Session management
|
||||
|
||||
When you log in, {kib} creates a session that is used to authenticate subsequent requests to {kib}. A session consists of two components: an encrypted cookie that is stored in your browser, and an encrypted document in a dedicated {es} hidden index. By default, the name of that index is `.kibana_security_session_1`, where the prefix is derived from the primary `.kibana` index. If either of these components are missing, the session is no longer valid.
|
||||
|
||||
When your session expires, or you log out, {kib} will invalidate your cookie and remove session information from the index. {kib} also periodically invalidates and removes any expired sessions that weren't explicitly invalidated.
|
||||
|
||||
[[session-idle-timeout]]
|
||||
==== Session idle timeout
|
||||
|
||||
You can use `xpack.security.session.idleTimeout` to expire sessions after a period of inactivity. This and `xpack.security.session.lifespan` are both highly recommended.
|
||||
By default, sessions don't expire because of inactivity. To define a sliding session expiration, set the property in the `kibana.yml` configuration file. The idle timeout is formatted as a duration of `<count>[ms|s|m|h|d|w|M|Y]` (e.g. '20m', '24h', '7d', '1w'). For example, set the idle timeout to expire sessions after 1 hour of inactivity:
|
||||
|
||||
--
|
||||
[source,yaml]
|
||||
--------------------------------------------------------------------------------
|
||||
xpack.security.session.idleTimeout: "1h"
|
||||
--------------------------------------------------------------------------------
|
||||
--
|
||||
|
||||
[[session-lifespan]]
|
||||
==== Session lifespan
|
||||
|
||||
You can use `xpack.security.session.lifespan` to configure the maximum session duration or "lifespan" -- also known as the "absolute timeout". This and `xpack.security.session.idleTimeout` are both highly recommended. By default, sessions don't have a fixed lifespan, and if an idle timeout is defined, a session can still be extended indefinitely. To define a maximum session lifespan, set the property in the `kibana.yml` configuration file. The lifespan is formatted as a duration of `<count>[ms|s|m|h|d|w|M|Y]` (e.g. '20m', '24h', '7d', '1w'). For example, set the lifespan to expire sessions after 30 days:
|
||||
|
||||
--
|
||||
[source,yaml]
|
||||
--------------------------------------------------------------------------------
|
||||
xpack.security.session.lifespan: "30d"
|
||||
--------------------------------------------------------------------------------
|
||||
--
|
||||
|
||||
[[session-cleanup-interval]]
|
||||
==== Session cleanup interval
|
||||
|
||||
[IMPORTANT]
|
||||
============================================================================
|
||||
If you specify neither session idle timeout nor lifespan, then {kib} will not automatically remove session information from the index unless you explicitly log out. This might lead to an infinitely growing session index. Configure the idle timeout and lifespan settings for the {kib} sessions so that they can be cleaned up even if you don't explicitly log out.
|
||||
============================================================================
|
||||
|
||||
You can configure the interval at which {kib} tries to remove expired and invalid sessions from the session index. By default, this value is 1 hour and cannot be less than 10 seconds. To define another interval, set the `xpack.security.session.cleanupInterval` property in the `kibana.yml` configuration file. The interval is formatted as a duration of `<count>[ms|s|m|h|d|w|M|Y]` (e.g. '20m', '24h', '7d', '1w'). For example, schedule the session index cleanup to perform once a day:
|
||||
|
||||
--
|
||||
[source,yaml]
|
||||
--------------------------------------------------------------------------------
|
||||
xpack.security.session.cleanupInterval: "1d"
|
||||
--------------------------------------------------------------------------------
|
||||
--
|
|
@ -237,6 +237,7 @@ kibana_vars=(
|
|||
xpack.security.sessionTimeout
|
||||
xpack.security.session.idleTimeout
|
||||
xpack.security.session.lifespan
|
||||
xpack.security.session.cleanupInterval
|
||||
xpack.security.loginAssistanceMessage
|
||||
xpack.security.loginHelp
|
||||
xpack.spaces.enabled
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
"version": "8.0.0",
|
||||
"kibanaVersion": "kibana",
|
||||
"configPath": ["xpack", "security"],
|
||||
"requiredPlugins": ["data", "features", "licensing"],
|
||||
"requiredPlugins": ["data", "features", "licensing", "taskManager"],
|
||||
"optionalPlugins": ["home", "management"],
|
||||
"server": true,
|
||||
"ui": true,
|
||||
|
|
|
@ -4,7 +4,12 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { ApplicationSetup, StartServicesAccessor, HttpSetup } from 'src/core/public';
|
||||
import {
|
||||
ApplicationSetup,
|
||||
StartServicesAccessor,
|
||||
HttpSetup,
|
||||
FatalErrorsSetup,
|
||||
} from 'src/core/public';
|
||||
import { AuthenticatedUser } from '../../common/model';
|
||||
import { ConfigType } from '../config';
|
||||
import { PluginStartDependencies } from '../plugin';
|
||||
|
@ -13,9 +18,11 @@ import { loginApp } from './login';
|
|||
import { logoutApp } from './logout';
|
||||
import { loggedOutApp } from './logged_out';
|
||||
import { overwrittenSessionApp } from './overwritten_session';
|
||||
import { captureURLApp } from './capture_url';
|
||||
|
||||
interface SetupParams {
|
||||
application: ApplicationSetup;
|
||||
fatalErrors: FatalErrorsSetup;
|
||||
config: ConfigType;
|
||||
http: HttpSetup;
|
||||
getStartServices: StartServicesAccessor<PluginStartDependencies>;
|
||||
|
@ -36,6 +43,7 @@ export interface AuthenticationServiceSetup {
|
|||
export class AuthenticationService {
|
||||
public setup({
|
||||
application,
|
||||
fatalErrors,
|
||||
config,
|
||||
getStartServices,
|
||||
http,
|
||||
|
@ -48,6 +56,7 @@ export class AuthenticationService {
|
|||
.apiKeysEnabled;
|
||||
|
||||
accessAgreementApp.create({ application, getStartServices });
|
||||
captureURLApp.create({ application, fatalErrors, http });
|
||||
loginApp.create({ application, config, getStartServices, http });
|
||||
logoutApp.create({ application, http });
|
||||
loggedOutApp.create({ application, getStartServices, http });
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
* 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 { AppMount, ScopedHistory } from 'src/core/public';
|
||||
import { captureURLApp } from './capture_url_app';
|
||||
|
||||
import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks';
|
||||
|
||||
describe('captureURLApp', () => {
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: { href: 'https://some-host' },
|
||||
writable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('properly registers application', () => {
|
||||
const coreSetupMock = coreMock.createSetup();
|
||||
|
||||
captureURLApp.create(coreSetupMock);
|
||||
|
||||
expect(coreSetupMock.http.anonymousPaths.register).toHaveBeenCalledTimes(1);
|
||||
expect(coreSetupMock.http.anonymousPaths.register).toHaveBeenCalledWith(
|
||||
'/internal/security/capture-url'
|
||||
);
|
||||
|
||||
expect(coreSetupMock.application.register).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [[appRegistration]] = coreSetupMock.application.register.mock.calls;
|
||||
expect(appRegistration).toEqual({
|
||||
id: 'security_capture_url',
|
||||
chromeless: true,
|
||||
appRoute: '/internal/security/capture-url',
|
||||
title: 'Capture URL',
|
||||
mount: expect.any(Function),
|
||||
});
|
||||
});
|
||||
|
||||
it('properly handles captured URL', async () => {
|
||||
window.location.href = `https://host.com/mock-base-path/internal/security/capture-url?next=${encodeURIComponent(
|
||||
'/mock-base-path/app/home'
|
||||
)}&providerType=saml&providerName=saml1#/?_g=()`;
|
||||
|
||||
const coreSetupMock = coreMock.createSetup();
|
||||
coreSetupMock.http.post.mockResolvedValue({ location: '/mock-base-path/app/home#/?_g=()' });
|
||||
|
||||
captureURLApp.create(coreSetupMock);
|
||||
|
||||
const [[{ mount }]] = coreSetupMock.application.register.mock.calls;
|
||||
await (mount as AppMount)({
|
||||
element: document.createElement('div'),
|
||||
appBasePath: '',
|
||||
onAppLeave: jest.fn(),
|
||||
history: (scopedHistoryMock.create() as unknown) as ScopedHistory,
|
||||
});
|
||||
|
||||
expect(coreSetupMock.http.post).toHaveBeenCalledTimes(1);
|
||||
expect(coreSetupMock.http.post).toHaveBeenCalledWith('/internal/security/login', {
|
||||
body: JSON.stringify({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml1',
|
||||
currentURL: `https://host.com/mock-base-path/internal/security/capture-url?next=${encodeURIComponent(
|
||||
'/mock-base-path/app/home'
|
||||
)}&providerType=saml&providerName=saml1#/?_g=()`,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(window.location.href).toBe('/mock-base-path/app/home#/?_g=()');
|
||||
});
|
||||
});
|
|
@ -0,0 +1,68 @@
|
|||
/*
|
||||
* 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 { parse } from 'url';
|
||||
import { ApplicationSetup, FatalErrorsSetup, HttpSetup } from 'src/core/public';
|
||||
|
||||
interface CreateDeps {
|
||||
application: ApplicationSetup;
|
||||
http: HttpSetup;
|
||||
fatalErrors: FatalErrorsSetup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Some authentication providers need to know current user URL to, for example, restore it after a
|
||||
* complex authentication handshake. But most of the Kibana URLs include hash fragment that is never
|
||||
* sent to the server. To capture that authentication provider can redirect user to this app putting
|
||||
* path segment into the `next` query string parameter (so that it's not lost during redirect). And
|
||||
* since browsers preserve hash fragments during redirects (assuming redirect location doesn't
|
||||
* specify its own hash fragment, which is true in our case) this app can capture both path and
|
||||
* hash URL segments and send them back to the authentication provider via login endpoint.
|
||||
*
|
||||
* The flow can look like this:
|
||||
* 1. User visits `/app/kibana#/management/elasticsearch` that initiates authentication.
|
||||
* 2. Provider redirect user to `/internal/security/capture-url?next=%2Fapp%2Fkibana&providerType=saml&providerName=saml1`.
|
||||
* 3. Browser preserves hash segment and users ends up at `/internal/security/capture-url?next=%2Fapp%2Fkibana&providerType=saml&providerName=saml1#/management/elasticsearch`.
|
||||
* 4. The app captures full URL and sends it back as is via login endpoint:
|
||||
* {
|
||||
* providerType: 'saml',
|
||||
* providerName: 'saml1',
|
||||
* currentURL: 'https://kibana.com/internal/security/capture-url?next=%2Fapp%2Fkibana&providerType=saml&providerName=saml1#/management/elasticsearch'
|
||||
* }
|
||||
* 5. Login endpoint handler parses and validates `next` parameter, joins it with the hash segment
|
||||
* and finally passes it to the provider that initiated capturing.
|
||||
*/
|
||||
export const captureURLApp = Object.freeze({
|
||||
id: 'security_capture_url',
|
||||
create({ application, fatalErrors, http }: CreateDeps) {
|
||||
http.anonymousPaths.register('/internal/security/capture-url');
|
||||
application.register({
|
||||
id: this.id,
|
||||
title: 'Capture URL',
|
||||
chromeless: true,
|
||||
appRoute: '/internal/security/capture-url',
|
||||
async mount() {
|
||||
try {
|
||||
const { providerName, providerType } = parse(window.location.href, true).query ?? {};
|
||||
if (!providerName || !providerType) {
|
||||
fatalErrors.add(new Error('Provider to capture URL for is not specified.'));
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const { location } = await http.post<{ location: string }>('/internal/security/login', {
|
||||
body: JSON.stringify({ providerType, providerName, currentURL: window.location.href }),
|
||||
});
|
||||
|
||||
window.location.href = location;
|
||||
} catch (err) {
|
||||
fatalErrors.add(new Error('Cannot login with captured URL.'));
|
||||
}
|
||||
|
||||
return () => {};
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
|
@ -0,0 +1,7 @@
|
|||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export { captureURLApp } from './capture_url_app';
|
|
@ -171,7 +171,7 @@ describe('LoginForm', () => {
|
|||
'/some-base-path/app/home#/?_g=()'
|
||||
)}`;
|
||||
const coreStartMock = coreMock.createStart({ basePath: '/some-base-path' });
|
||||
coreStartMock.http.post.mockResolvedValue({});
|
||||
coreStartMock.http.post.mockResolvedValue({ location: '/some-base-path/app/home#/?_g=()' });
|
||||
|
||||
const wrapper = mountWithIntl(
|
||||
<LoginForm
|
||||
|
@ -180,7 +180,7 @@ describe('LoginForm', () => {
|
|||
loginAssistanceMessage=""
|
||||
selector={{
|
||||
enabled: false,
|
||||
providers: [{ type: 'basic', name: 'basic', usesLoginForm: true }],
|
||||
providers: [{ type: 'basic', name: 'basic1', usesLoginForm: true }],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
@ -198,7 +198,14 @@ describe('LoginForm', () => {
|
|||
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledTimes(1);
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledWith('/internal/security/login', {
|
||||
body: JSON.stringify({ username: 'username1', password: 'password1' }),
|
||||
body: JSON.stringify({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: `https://some-host/login?next=${encodeURIComponent(
|
||||
'/some-base-path/app/home#/?_g=()'
|
||||
)}`,
|
||||
params: { username: 'username1', password: 'password1' },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(window.location.href).toBe('/some-base-path/app/home#/?_g=()');
|
||||
|
@ -363,7 +370,7 @@ describe('LoginForm', () => {
|
|||
});
|
||||
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledTimes(1);
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledWith('/internal/security/login_with', {
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledWith('/internal/security/login', {
|
||||
body: JSON.stringify({ providerType: 'saml', providerName: 'saml1', currentURL }),
|
||||
});
|
||||
|
||||
|
@ -407,7 +414,7 @@ describe('LoginForm', () => {
|
|||
});
|
||||
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledTimes(1);
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledWith('/internal/security/login_with', {
|
||||
expect(coreStartMock.http.post).toHaveBeenCalledWith('/internal/security/login', {
|
||||
body: JSON.stringify({ providerType: 'saml', providerName: 'saml1', currentURL }),
|
||||
});
|
||||
|
||||
|
|
|
@ -29,7 +29,6 @@ import {
|
|||
import { i18n } from '@kbn/i18n';
|
||||
import { FormattedMessage } from '@kbn/i18n/react';
|
||||
import { HttpStart, IHttpFetchError, NotificationsStart } from 'src/core/public';
|
||||
import { parseNext } from '../../../../../common/parse_next';
|
||||
import { LoginSelector } from '../../../../../common/login_state';
|
||||
import { LoginValidator } from './validate_login';
|
||||
|
||||
|
@ -401,11 +400,25 @@ export class LoginForm extends Component<Props, State> {
|
|||
message: { type: MessageType.None },
|
||||
});
|
||||
|
||||
const { http } = this.props;
|
||||
// We try to log in with the provider that uses login form and has the lowest order.
|
||||
const providerToLoginWith = this.props.selector.providers.find(
|
||||
(provider) => provider.usesLoginForm
|
||||
)!;
|
||||
|
||||
try {
|
||||
await http.post('/internal/security/login', { body: JSON.stringify({ username, password }) });
|
||||
window.location.href = parseNext(window.location.href, http.basePath.serverBasePath);
|
||||
const { location } = await this.props.http.post<{ location: string }>(
|
||||
'/internal/security/login',
|
||||
{
|
||||
body: JSON.stringify({
|
||||
providerType: providerToLoginWith.type,
|
||||
providerName: providerToLoginWith.name,
|
||||
currentURL: window.location.href,
|
||||
params: { username, password },
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
window.location.href = location;
|
||||
} catch (error) {
|
||||
const message =
|
||||
(error as IHttpFetchError).response?.status === 401
|
||||
|
@ -432,7 +445,7 @@ export class LoginForm extends Component<Props, State> {
|
|||
|
||||
try {
|
||||
const { location } = await this.props.http.post<{ location: string }>(
|
||||
'/internal/security/login_with',
|
||||
'/internal/security/login',
|
||||
{ body: JSON.stringify({ providerType, providerName, currentURL: window.location.href }) }
|
||||
);
|
||||
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { EuiButton } from '@elastic/eui';
|
||||
import { act } from '@testing-library/react';
|
||||
import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers';
|
||||
import { OverwrittenSessionPage } from './overwritten_session_page';
|
||||
|
@ -15,6 +16,13 @@ import { mockAuthenticatedUser } from '../../../common/model/authenticated_user.
|
|||
import { AuthenticationStatePage } from '../components/authentication_state_page';
|
||||
|
||||
describe('OverwrittenSessionPage', () => {
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: { href: 'https://some-host' },
|
||||
writable: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('renders as expected', async () => {
|
||||
const basePathMock = coreMock.createStart({ basePath: '/mock-base-path' }).http.basePath;
|
||||
const authenticationSetupMock = authenticationMock.createSetup();
|
||||
|
@ -36,4 +44,30 @@ describe('OverwrittenSessionPage', () => {
|
|||
|
||||
expect(wrapper.find(AuthenticationStatePage)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('properly parses `next` parameter', async () => {
|
||||
window.location.href = `https://host.com/mock-base-path/security/overwritten_session?next=${encodeURIComponent(
|
||||
'/mock-base-path/app/home#/?_g=()'
|
||||
)}`;
|
||||
|
||||
const basePathMock = coreMock.createStart({ basePath: '/mock-base-path' }).http.basePath;
|
||||
const authenticationSetupMock = authenticationMock.createSetup();
|
||||
authenticationSetupMock.getCurrentUser.mockResolvedValue(
|
||||
mockAuthenticatedUser({ username: 'mock-user' })
|
||||
);
|
||||
|
||||
const wrapper = mountWithIntl(
|
||||
<OverwrittenSessionPage basePath={basePathMock} authc={authenticationSetupMock} />
|
||||
);
|
||||
|
||||
// Shouldn't render anything if username isn't yet available.
|
||||
expect(wrapper.isEmptyRender()).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
await nextTick();
|
||||
wrapper.update();
|
||||
});
|
||||
|
||||
expect(wrapper.find(EuiButton).prop('href')).toBe('/mock-base-path/app/home#/?_g=()');
|
||||
});
|
||||
});
|
||||
|
|
|
@ -9,6 +9,7 @@ import ReactDOM from 'react-dom';
|
|||
import { EuiButton } from '@elastic/eui';
|
||||
import { FormattedMessage } from '@kbn/i18n/react';
|
||||
import { CoreStart, IBasePath } from 'src/core/public';
|
||||
import { parseNext } from '../../../common/parse_next';
|
||||
import { AuthenticationServiceSetup } from '../authentication_service';
|
||||
import { AuthenticationStatePage } from '../components';
|
||||
|
||||
|
@ -36,7 +37,7 @@ export function OverwrittenSessionPage({ authc, basePath }: Props) {
|
|||
/>
|
||||
}
|
||||
>
|
||||
<EuiButton href={basePath.prepend('/')}>
|
||||
<EuiButton href={parseNext(window.location.href, basePath.serverBasePath)}>
|
||||
<FormattedMessage
|
||||
id="xpack.security.overwrittenSession.continueAsUserText"
|
||||
defaultMessage="Continue as {username}"
|
||||
|
|
|
@ -84,6 +84,7 @@ export class SecurityPlugin
|
|||
|
||||
this.authc = this.authenticationService.setup({
|
||||
application: core.application,
|
||||
fatalErrors: core.fatalErrors,
|
||||
config: this.config,
|
||||
getStartServices: core.getStartServices,
|
||||
http: core.http,
|
||||
|
|
|
@ -167,7 +167,7 @@ describe('AuthenticationResult', () => {
|
|||
);
|
||||
});
|
||||
|
||||
it('correctly produces `redirected` authentication result without state.', () => {
|
||||
it('correctly produces `redirected` authentication result without state, user and response headers.', () => {
|
||||
const redirectURL = '/redirect/url';
|
||||
const authenticationResult = AuthenticationResult.redirectTo(redirectURL);
|
||||
|
||||
|
@ -201,6 +201,49 @@ describe('AuthenticationResult', () => {
|
|||
expect(authenticationResult.user).toBeUndefined();
|
||||
expect(authenticationResult.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('correctly produces `redirected` authentication result with state and user.', () => {
|
||||
const redirectURL = '/redirect/url';
|
||||
const state = { some: 'state' };
|
||||
const user = mockAuthenticatedUser();
|
||||
const authenticationResult = AuthenticationResult.redirectTo(redirectURL, { user, state });
|
||||
|
||||
expect(authenticationResult.redirected()).toBe(true);
|
||||
expect(authenticationResult.succeeded()).toBe(false);
|
||||
expect(authenticationResult.failed()).toBe(false);
|
||||
expect(authenticationResult.notHandled()).toBe(false);
|
||||
|
||||
expect(authenticationResult.redirectURL).toBe(redirectURL);
|
||||
expect(authenticationResult.state).toBe(state);
|
||||
expect(authenticationResult.authHeaders).toBeUndefined();
|
||||
expect(authenticationResult.authResponseHeaders).toBeUndefined();
|
||||
expect(authenticationResult.user).toBe(user);
|
||||
expect(authenticationResult.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('correctly produces `redirected` authentication result with state, user and response headers.', () => {
|
||||
const redirectURL = '/redirect/url';
|
||||
const state = { some: 'state' };
|
||||
const user = mockAuthenticatedUser();
|
||||
const authResponseHeaders = { 'WWW-Authenticate': 'Negotiate' };
|
||||
const authenticationResult = AuthenticationResult.redirectTo(redirectURL, {
|
||||
user,
|
||||
state,
|
||||
authResponseHeaders,
|
||||
});
|
||||
|
||||
expect(authenticationResult.redirected()).toBe(true);
|
||||
expect(authenticationResult.succeeded()).toBe(false);
|
||||
expect(authenticationResult.failed()).toBe(false);
|
||||
expect(authenticationResult.notHandled()).toBe(false);
|
||||
|
||||
expect(authenticationResult.redirectURL).toBe(redirectURL);
|
||||
expect(authenticationResult.state).toBe(state);
|
||||
expect(authenticationResult.authHeaders).toBeUndefined();
|
||||
expect(authenticationResult.authResponseHeaders).toBe(authResponseHeaders);
|
||||
expect(authenticationResult.user).toBe(user);
|
||||
expect(authenticationResult.error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('shouldUpdateState', () => {
|
||||
|
|
|
@ -113,17 +113,29 @@ export class AuthenticationResult {
|
|||
/**
|
||||
* Produces `AuthenticationResult` for the case when authentication needs user to be redirected.
|
||||
* @param redirectURL URL that should be used to redirect user to complete authentication.
|
||||
* @param [user] Optional user information retrieved as a result of successful authentication attempt.
|
||||
* @param [authResponseHeaders] Optional dictionary of the HTTP headers with authentication
|
||||
* information that should be specified in the response we send to the client request.
|
||||
* @param [state] Optional state to be stored and reused for the next request.
|
||||
*/
|
||||
public static redirectTo(
|
||||
redirectURL: string,
|
||||
{ state }: Pick<AuthenticationOptions, 'state'> = {}
|
||||
{
|
||||
user,
|
||||
authResponseHeaders,
|
||||
state,
|
||||
}: Pick<AuthenticationOptions, 'user' | 'authResponseHeaders' | 'state'> = {}
|
||||
) {
|
||||
if (!redirectURL) {
|
||||
throw new Error('Redirect URL must be specified.');
|
||||
}
|
||||
|
||||
return new AuthenticationResult(AuthenticationResultStatus.Redirected, { redirectURL, state });
|
||||
return new AuthenticationResult(AuthenticationResultStatus.Redirected, {
|
||||
redirectURL,
|
||||
user,
|
||||
authResponseHeaders,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -4,22 +4,20 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { Duration } from 'moment';
|
||||
import {
|
||||
SessionStorageFactory,
|
||||
SessionStorage,
|
||||
KibanaRequest,
|
||||
LoggerFactory,
|
||||
Logger,
|
||||
HttpServiceSetup,
|
||||
ILegacyClusterClient,
|
||||
IBasePath,
|
||||
} from '../../../../../src/core/server';
|
||||
import { SecurityLicense } from '../../common/licensing';
|
||||
import { AuthenticatedUser } from '../../common/model';
|
||||
import { AuthenticationProvider, SessionInfo } from '../../common/types';
|
||||
import { AuthenticationProvider } from '../../common/types';
|
||||
import { SecurityAuditLogger } from '../audit';
|
||||
import { ConfigType } from '../config';
|
||||
import { getErrorStatusCode } from '../errors';
|
||||
import { SecurityFeatureUsageServiceStart } from '../feature_usage';
|
||||
import { SessionValue, Session } from '../session_management';
|
||||
|
||||
import {
|
||||
AuthenticationProviderOptions,
|
||||
|
@ -38,45 +36,6 @@ import { DeauthenticationResult } from './deauthentication_result';
|
|||
import { Tokens } from './tokens';
|
||||
import { canRedirectRequest } from './can_redirect_request';
|
||||
import { HTTPAuthorizationHeader } from './http_authentication';
|
||||
import { SecurityFeatureUsageServiceStart } from '../feature_usage';
|
||||
|
||||
/**
|
||||
* The shape of the session that is actually stored in the cookie.
|
||||
*/
|
||||
export interface ProviderSession {
|
||||
/**
|
||||
* Name and type of the provider this session belongs to.
|
||||
*/
|
||||
provider: AuthenticationProvider;
|
||||
|
||||
/**
|
||||
* The Unix time in ms when the session should be considered expired. If `null`, session will stay
|
||||
* active until the browser is closed.
|
||||
*/
|
||||
idleTimeoutExpiration: number | null;
|
||||
|
||||
/**
|
||||
* The Unix time in ms which is the max total lifespan of the session. If `null`, session expire
|
||||
* time can be extended indefinitely.
|
||||
*/
|
||||
lifespanExpiration: number | null;
|
||||
|
||||
/**
|
||||
* Session value that is fed to the authentication provider. The shape is unknown upfront and
|
||||
* entirely determined by the authentication provider that owns the current session.
|
||||
*/
|
||||
state: unknown;
|
||||
|
||||
/**
|
||||
* Cookie "Path" attribute that is validated against the current Kibana server configuration.
|
||||
*/
|
||||
path: string;
|
||||
|
||||
/**
|
||||
* Indicates whether user acknowledged access agreement or not.
|
||||
*/
|
||||
accessAgreementAcknowledged?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape of the login attempt.
|
||||
|
@ -87,6 +46,12 @@ export interface ProviderLoginAttempt {
|
|||
*/
|
||||
provider: Pick<AuthenticationProvider, 'name'> | Pick<AuthenticationProvider, 'type'>;
|
||||
|
||||
/**
|
||||
* Optional URL to redirect user to after successful login. This URL is ignored if provider
|
||||
* decides to redirect user to another URL after login.
|
||||
*/
|
||||
redirectURL?: string;
|
||||
|
||||
/**
|
||||
* Login attempt can have any form and defined by the specific provider.
|
||||
*/
|
||||
|
@ -97,12 +62,12 @@ export interface AuthenticatorOptions {
|
|||
auditLogger: SecurityAuditLogger;
|
||||
getFeatureUsageService: () => SecurityFeatureUsageServiceStart;
|
||||
getCurrentUser: (request: KibanaRequest) => AuthenticatedUser | null;
|
||||
config: Pick<ConfigType, 'session' | 'authc'>;
|
||||
basePath: HttpServiceSetup['basePath'];
|
||||
config: Pick<ConfigType, 'authc'>;
|
||||
basePath: IBasePath;
|
||||
license: SecurityLicense;
|
||||
loggers: LoggerFactory;
|
||||
clusterClient: ILegacyClusterClient;
|
||||
sessionStorageFactory: SessionStorageFactory<ProviderSession>;
|
||||
session: PublicMethodsOf<Session>;
|
||||
}
|
||||
|
||||
// Mapping between provider key defined in the config and authentication
|
||||
|
@ -127,6 +92,11 @@ const providerMap = new Map<
|
|||
*/
|
||||
const ACCESS_AGREEMENT_ROUTE = '/security/access_agreement';
|
||||
|
||||
/**
|
||||
* The route to the overwritten session UI.
|
||||
*/
|
||||
const OVERWRITTEN_SESSION_ROUTE = '/security/overwritten_session';
|
||||
|
||||
function assertRequest(request: KibanaRequest) {
|
||||
if (!(request instanceof KibanaRequest)) {
|
||||
throw new Error(`Request should be a valid "KibanaRequest" instance, was [${typeof request}].`);
|
||||
|
@ -161,15 +131,6 @@ function isLoginAttemptWithProviderType(
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if session value was created by the previous Kibana versions which had a different
|
||||
* session value format.
|
||||
* @param sessionValue The session value to check.
|
||||
*/
|
||||
function isLegacyProviderSession(sessionValue: any) {
|
||||
return typeof sessionValue?.provider === 'string';
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates authentication provider based on the provider key from config.
|
||||
* @param providerType Provider type key.
|
||||
|
@ -209,32 +170,20 @@ export class Authenticator {
|
|||
private readonly providers: Map<string, BaseAuthenticationProvider>;
|
||||
|
||||
/**
|
||||
* Which base path the HTTP server is hosted on.
|
||||
* Session instance.
|
||||
*/
|
||||
private readonly serverBasePath: string;
|
||||
|
||||
/**
|
||||
* Session timeout in ms. If `null` session will stay active until the browser is closed.
|
||||
*/
|
||||
private readonly idleTimeout: Duration | null = null;
|
||||
|
||||
/**
|
||||
* Session max lifespan in ms. If `null` session may live indefinitely.
|
||||
*/
|
||||
private readonly lifespan: Duration | null = null;
|
||||
private readonly session = this.options.session;
|
||||
|
||||
/**
|
||||
* Internal authenticator logger.
|
||||
*/
|
||||
private readonly logger: Logger;
|
||||
private readonly logger = this.options.loggers.get('authenticator');
|
||||
|
||||
/**
|
||||
* Instantiates Authenticator and bootstrap configured providers.
|
||||
* @param options Authenticator options.
|
||||
*/
|
||||
constructor(private readonly options: Readonly<AuthenticatorOptions>) {
|
||||
this.logger = options.loggers.get('authenticator');
|
||||
|
||||
const providerCommonOptions = {
|
||||
client: this.options.clusterClient,
|
||||
basePath: this.options.basePath,
|
||||
|
@ -284,11 +233,6 @@ export class Authenticator {
|
|||
'No authentication provider is configured. Verify `xpack.security.authc.*` config value.'
|
||||
);
|
||||
}
|
||||
|
||||
this.serverBasePath = this.options.basePath.serverBasePath || '/';
|
||||
|
||||
this.idleTimeout = this.options.config.session.idleTimeout;
|
||||
this.lifespan = this.options.config.session.lifespan;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -300,8 +244,7 @@ export class Authenticator {
|
|||
assertRequest(request);
|
||||
assertLoginAttempt(attempt);
|
||||
|
||||
const sessionStorage = this.options.sessionStorageFactory.asScoped(request);
|
||||
const existingSession = await this.getSessionValue(sessionStorage);
|
||||
const existingSessionValue = await this.getSessionValue(request);
|
||||
|
||||
// Login attempt can target specific provider by its name (e.g. chosen at the Login Selector UI)
|
||||
// or a group of providers with the specified type (e.g. in case of 3rd-party initiated login
|
||||
|
@ -311,7 +254,7 @@ export class Authenticator {
|
|||
isLoginAttemptWithProviderName(attempt) && this.providers.has(attempt.provider.name)
|
||||
? [[attempt.provider.name, this.providers.get(attempt.provider.name)!]]
|
||||
: isLoginAttemptWithProviderType(attempt)
|
||||
? [...this.providerIterator(existingSession)].filter(
|
||||
? [...this.providerIterator(existingSessionValue)].filter(
|
||||
([, { type }]) => type === attempt.provider.type
|
||||
)
|
||||
: [];
|
||||
|
@ -330,24 +273,28 @@ export class Authenticator {
|
|||
for (const [providerName, provider] of providers) {
|
||||
// Check if current session has been set by this provider.
|
||||
const ownsSession =
|
||||
existingSession?.provider.name === providerName &&
|
||||
existingSession?.provider.type === provider.type;
|
||||
existingSessionValue?.provider.name === providerName &&
|
||||
existingSessionValue?.provider.type === provider.type;
|
||||
|
||||
const authenticationResult = await provider.login(
|
||||
request,
|
||||
attempt.value,
|
||||
ownsSession ? existingSession!.state : null
|
||||
ownsSession ? existingSessionValue!.state : null
|
||||
);
|
||||
|
||||
this.updateSessionValue(sessionStorage, {
|
||||
provider: { type: provider.type, name: providerName },
|
||||
isSystemRequest: request.isSystemRequest,
|
||||
authenticationResult,
|
||||
existingSession: ownsSession ? existingSession : null,
|
||||
});
|
||||
|
||||
if (!authenticationResult.notHandled()) {
|
||||
return authenticationResult;
|
||||
const sessionUpdateResult = await this.updateSessionValue(request, {
|
||||
provider: { type: provider.type, name: providerName },
|
||||
authenticationResult,
|
||||
existingSessionValue,
|
||||
});
|
||||
|
||||
return this.handlePreAccessRedirects(
|
||||
request,
|
||||
authenticationResult,
|
||||
sessionUpdateResult,
|
||||
attempt.redirectURL
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -361,10 +308,9 @@ export class Authenticator {
|
|||
async authenticate(request: KibanaRequest) {
|
||||
assertRequest(request);
|
||||
|
||||
const sessionStorage = this.options.sessionStorageFactory.asScoped(request);
|
||||
const existingSession = await this.getSessionValue(sessionStorage);
|
||||
const existingSessionValue = await this.getSessionValue(request);
|
||||
|
||||
if (this.shouldRedirectToLoginSelector(request, existingSession)) {
|
||||
if (this.shouldRedirectToLoginSelector(request, existingSessionValue)) {
|
||||
this.logger.debug('Redirecting request to Login Selector.');
|
||||
return AuthenticationResult.redirectTo(
|
||||
`${this.options.basePath.serverBasePath}/login?next=${encodeURIComponent(
|
||||
|
@ -373,40 +319,27 @@ export class Authenticator {
|
|||
);
|
||||
}
|
||||
|
||||
for (const [providerName, provider] of this.providerIterator(existingSession)) {
|
||||
for (const [providerName, provider] of this.providerIterator(existingSessionValue)) {
|
||||
// Check if current session has been set by this provider.
|
||||
const ownsSession =
|
||||
existingSession?.provider.name === providerName &&
|
||||
existingSession?.provider.type === provider.type;
|
||||
existingSessionValue?.provider.name === providerName &&
|
||||
existingSessionValue?.provider.type === provider.type;
|
||||
|
||||
const authenticationResult = await provider.authenticate(
|
||||
request,
|
||||
ownsSession ? existingSession!.state : null
|
||||
ownsSession ? existingSessionValue!.state : null
|
||||
);
|
||||
|
||||
const updatedSession = this.updateSessionValue(sessionStorage, {
|
||||
provider: { type: provider.type, name: providerName },
|
||||
isSystemRequest: request.isSystemRequest,
|
||||
authenticationResult,
|
||||
existingSession: ownsSession ? existingSession : null,
|
||||
});
|
||||
|
||||
if (!authenticationResult.notHandled()) {
|
||||
if (
|
||||
authenticationResult.succeeded() &&
|
||||
this.shouldRedirectToAccessAgreement(request, updatedSession)
|
||||
) {
|
||||
this.logger.debug('Redirecting user to the access agreement screen.');
|
||||
return AuthenticationResult.redirectTo(
|
||||
`${
|
||||
this.options.basePath.serverBasePath
|
||||
}${ACCESS_AGREEMENT_ROUTE}?next=${encodeURIComponent(
|
||||
`${this.options.basePath.get(request)}${request.url.path}`
|
||||
)}`
|
||||
);
|
||||
}
|
||||
const sessionUpdateResult = await this.updateSessionValue(request, {
|
||||
provider: { type: provider.type, name: providerName },
|
||||
authenticationResult,
|
||||
existingSessionValue,
|
||||
});
|
||||
|
||||
return authenticationResult;
|
||||
return canRedirectRequest(request)
|
||||
? this.handlePreAccessRedirects(request, authenticationResult, sessionUpdateResult)
|
||||
: authenticationResult;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -420,19 +353,19 @@ export class Authenticator {
|
|||
async logout(request: KibanaRequest) {
|
||||
assertRequest(request);
|
||||
|
||||
const sessionStorage = this.options.sessionStorageFactory.asScoped(request);
|
||||
const sessionValue = await this.getSessionValue(sessionStorage);
|
||||
const sessionValue = await this.getSessionValue(request);
|
||||
if (sessionValue) {
|
||||
sessionStorage.clear();
|
||||
|
||||
return this.providers.get(sessionValue.provider.name)!.logout(request, sessionValue.state);
|
||||
await this.session.clear(request);
|
||||
return this.providers
|
||||
.get(sessionValue.provider.name)!
|
||||
.logout(request, sessionValue.state ?? null);
|
||||
}
|
||||
|
||||
const providerName = this.getProviderName(request.query);
|
||||
if (providerName) {
|
||||
const queryStringProviderName = (request.query as Record<string, string>)?.provider;
|
||||
if (queryStringProviderName) {
|
||||
// provider name is passed in a query param and sourced from the browser's local storage;
|
||||
// hence, we can't assume that this provider exists, so we have to check it
|
||||
const provider = this.providers.get(providerName);
|
||||
const provider = this.providers.get(queryStringProviderName);
|
||||
if (provider) {
|
||||
return provider.logout(request, null);
|
||||
}
|
||||
|
@ -454,29 +387,6 @@ export class Authenticator {
|
|||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns session information for the current request.
|
||||
* @param request Request instance.
|
||||
*/
|
||||
async getSessionInfo(request: KibanaRequest): Promise<SessionInfo | null> {
|
||||
assertRequest(request);
|
||||
|
||||
const sessionStorage = this.options.sessionStorageFactory.asScoped(request);
|
||||
const sessionValue = await this.getSessionValue(sessionStorage);
|
||||
|
||||
if (sessionValue) {
|
||||
// We can't rely on the client's system clock, so in addition to returning expiration timestamps, we also return
|
||||
// the current server time -- that way the client can calculate the relative time to expiration.
|
||||
return {
|
||||
now: Date.now(),
|
||||
idleTimeoutExpiration: sessionValue.idleTimeoutExpiration,
|
||||
lifespanExpiration: sessionValue.lifespanExpiration,
|
||||
provider: sessionValue.provider,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether specified provider type is currently enabled.
|
||||
* @param providerType Type of the provider (`basic`, `saml`, `pki` etc.).
|
||||
|
@ -492,10 +402,9 @@ export class Authenticator {
|
|||
async acknowledgeAccessAgreement(request: KibanaRequest) {
|
||||
assertRequest(request);
|
||||
|
||||
const sessionStorage = this.options.sessionStorageFactory.asScoped(request);
|
||||
const existingSession = await this.getSessionValue(sessionStorage);
|
||||
const existingSessionValue = await this.getSessionValue(request);
|
||||
const currentUser = this.options.getCurrentUser(request);
|
||||
if (!existingSession || !currentUser) {
|
||||
if (!existingSessionValue || !currentUser) {
|
||||
throw new Error('Cannot acknowledge access agreement for unauthenticated user.');
|
||||
}
|
||||
|
||||
|
@ -503,11 +412,14 @@ export class Authenticator {
|
|||
throw new Error('Current license does not allow access agreement acknowledgement.');
|
||||
}
|
||||
|
||||
sessionStorage.set({ ...existingSession, accessAgreementAcknowledged: true });
|
||||
await this.session.update(request, {
|
||||
...existingSessionValue,
|
||||
accessAgreementAcknowledged: true,
|
||||
});
|
||||
|
||||
this.options.auditLogger.accessAgreementAcknowledged(
|
||||
currentUser.username,
|
||||
existingSession.provider
|
||||
existingSessionValue.provider
|
||||
);
|
||||
|
||||
this.options.getFeatureUsageService().recordPreAccessAgreementUsage();
|
||||
|
@ -546,7 +458,7 @@ export class Authenticator {
|
|||
* @param sessionValue Current session value.
|
||||
*/
|
||||
private *providerIterator(
|
||||
sessionValue: ProviderSession | null
|
||||
sessionValue: SessionValue | null
|
||||
): IterableIterator<[string, BaseAuthenticationProvider]> {
|
||||
// If there is no session to predict which provider to use first, let's use the order
|
||||
// providers are configured in. Otherwise return provider that owns session first, and only then the rest
|
||||
|
@ -565,114 +477,159 @@ export class Authenticator {
|
|||
}
|
||||
|
||||
/**
|
||||
* Extracts session value for the specified request. Under the hood it can
|
||||
* clear session if it belongs to the provider that is not available.
|
||||
* @param sessionStorage Session storage instance.
|
||||
* Extracts session value for the specified request. Under the hood it can clear session if it
|
||||
* belongs to the provider that is not available.
|
||||
* @param request Request instance.
|
||||
*/
|
||||
private async getSessionValue(sessionStorage: SessionStorage<ProviderSession>) {
|
||||
const sessionValue = await sessionStorage.get();
|
||||
private async getSessionValue(request: KibanaRequest) {
|
||||
const existingSessionValue = await this.session.get(request);
|
||||
|
||||
// If we detect that session is in incompatible format or for some reason we have a session
|
||||
// stored for the provider that is not available anymore (e.g. when user was logged in with one
|
||||
// provider, but then configuration has changed and that provider is no longer available), then
|
||||
// we should clear session entirely.
|
||||
// If we detect that for some reason we have a session stored for the provider that is not
|
||||
// available anymore (e.g. when user was logged in with one provider, but then configuration has
|
||||
// changed and that provider is no longer available), then we should clear session entirely.
|
||||
if (
|
||||
sessionValue &&
|
||||
(isLegacyProviderSession(sessionValue) ||
|
||||
this.providers.get(sessionValue.provider.name)?.type !== sessionValue.provider.type)
|
||||
existingSessionValue &&
|
||||
this.providers.get(existingSessionValue.provider.name)?.type !==
|
||||
existingSessionValue.provider.type
|
||||
) {
|
||||
sessionStorage.clear();
|
||||
this.logger.warn(
|
||||
`Attempted to retrieve session for the "${existingSessionValue.provider.type}/${existingSessionValue.provider.name}" provider, but it is not configured.`
|
||||
);
|
||||
await this.session.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
return sessionValue;
|
||||
return existingSessionValue;
|
||||
}
|
||||
|
||||
private updateSessionValue(
|
||||
sessionStorage: SessionStorage<ProviderSession>,
|
||||
/**
|
||||
* Updates, creates, extends or clears session value based on the received authentication result.
|
||||
* @param request Request instance.
|
||||
* @param provider Provider that produced provided authentication result.
|
||||
* @param authenticationResult Result of the authentication or login attempt.
|
||||
* @param existingSessionValue Value of the existing session if any.
|
||||
*/
|
||||
private async updateSessionValue(
|
||||
request: KibanaRequest,
|
||||
{
|
||||
provider,
|
||||
authenticationResult,
|
||||
existingSession,
|
||||
isSystemRequest,
|
||||
existingSessionValue,
|
||||
}: {
|
||||
provider: AuthenticationProvider;
|
||||
authenticationResult: AuthenticationResult;
|
||||
existingSession: ProviderSession | null;
|
||||
isSystemRequest: boolean;
|
||||
existingSessionValue: Readonly<SessionValue> | null;
|
||||
}
|
||||
) {
|
||||
if (!existingSession && !authenticationResult.shouldUpdateState()) {
|
||||
if (!existingSessionValue && !authenticationResult.shouldUpdateState()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Provider can specifically ask to clear session by setting it to `null` even if authentication
|
||||
// attempt didn't fail.
|
||||
if (authenticationResult.shouldClearState()) {
|
||||
this.logger.debug('Authentication provider requested to invalidate existing session.');
|
||||
await this.session.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
const ownsSession =
|
||||
existingSessionValue?.provider.name === provider.name &&
|
||||
existingSessionValue?.provider.type === provider.type;
|
||||
|
||||
// If provider owned the session, but failed to authenticate anyway, that likely means that
|
||||
// session is not valid and we should clear it. Unexpected errors should not cause session
|
||||
// invalidation (e.g. when Elasticsearch is temporarily unavailable).
|
||||
if (authenticationResult.failed()) {
|
||||
if (ownsSession && getErrorStatusCode(authenticationResult.error) === 401) {
|
||||
this.logger.debug('Authentication attempt failed, existing session will be invalidated.');
|
||||
await this.session.clear(request);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// If authentication succeeds or requires redirect we should automatically extend existing user session,
|
||||
// unless authentication has been triggered by a system API request. In case provider explicitly returns new
|
||||
// state we should store it in the session regardless of whether it's a system API request or not.
|
||||
const sessionCanBeUpdated =
|
||||
const sessionShouldBeUpdatedOrExtended =
|
||||
(authenticationResult.succeeded() || authenticationResult.redirected()) &&
|
||||
(authenticationResult.shouldUpdateState() || !isSystemRequest);
|
||||
|
||||
// If provider owned the session, but failed to authenticate anyway, that likely means that
|
||||
// session is not valid and we should clear it. Also provider can specifically ask to clear
|
||||
// session by setting it to `null` even if authentication attempt didn't fail.
|
||||
if (
|
||||
authenticationResult.shouldClearState() ||
|
||||
(authenticationResult.failed() && getErrorStatusCode(authenticationResult.error) === 401)
|
||||
) {
|
||||
sessionStorage.clear();
|
||||
return null;
|
||||
(authenticationResult.shouldUpdateState() || (!request.isSystemRequest && ownsSession));
|
||||
if (!sessionShouldBeUpdatedOrExtended) {
|
||||
return ownsSession ? { value: existingSessionValue, overwritten: false } : null;
|
||||
}
|
||||
|
||||
if (sessionCanBeUpdated) {
|
||||
const { idleTimeoutExpiration, lifespanExpiration } = this.calculateExpiry(existingSession);
|
||||
const updatedSession = {
|
||||
const isExistingSessionAuthenticated = !!existingSessionValue?.username;
|
||||
const isNewSessionAuthenticated = !!authenticationResult.user;
|
||||
|
||||
const providerHasChanged = !!existingSessionValue && !ownsSession;
|
||||
const sessionHasBeenAuthenticated =
|
||||
!!existingSessionValue && !isExistingSessionAuthenticated && isNewSessionAuthenticated;
|
||||
const usernameHasChanged =
|
||||
isExistingSessionAuthenticated &&
|
||||
isNewSessionAuthenticated &&
|
||||
authenticationResult.user!.username !== existingSessionValue!.username;
|
||||
|
||||
// There are 3 cases when we SHOULD invalidate existing session and create a new one with
|
||||
// regenerated SID/AAD:
|
||||
// 1. If a new session must be created while existing is still valid (e.g. IdP initiated login
|
||||
// for the user with active session created by another provider).
|
||||
// 2. If the existing session was unauthenticated (e.g. intermediate session used during SSO
|
||||
// handshake) and can now be turned into an authenticated one.
|
||||
// 3. If we re-authenticated user with another username (e.g. during IdP initiated SSO login or
|
||||
// when client certificate changes and PKI provider needs to re-authenticate user).
|
||||
if (providerHasChanged) {
|
||||
this.logger.debug(
|
||||
'Authentication provider has changed, existing session will be invalidated.'
|
||||
);
|
||||
await this.session.clear(request);
|
||||
existingSessionValue = null;
|
||||
} else if (sessionHasBeenAuthenticated) {
|
||||
this.logger.debug(
|
||||
'Session is authenticated, existing unauthenticated session will be invalidated.'
|
||||
);
|
||||
await this.session.clear(request);
|
||||
existingSessionValue = null;
|
||||
} else if (usernameHasChanged) {
|
||||
this.logger.debug('Username has changed, existing session will be invalidated.');
|
||||
await this.session.clear(request);
|
||||
existingSessionValue = null;
|
||||
}
|
||||
|
||||
let newSessionValue;
|
||||
if (!existingSessionValue) {
|
||||
newSessionValue = await this.session.create(request, {
|
||||
username: authenticationResult.user?.username,
|
||||
provider,
|
||||
state: authenticationResult.shouldUpdateState() ? authenticationResult.state : null,
|
||||
});
|
||||
} else if (authenticationResult.shouldUpdateState()) {
|
||||
newSessionValue = await this.session.update(request, {
|
||||
...existingSessionValue,
|
||||
state: authenticationResult.shouldUpdateState()
|
||||
? authenticationResult.state
|
||||
: existingSession!.state,
|
||||
provider,
|
||||
idleTimeoutExpiration,
|
||||
lifespanExpiration,
|
||||
path: this.serverBasePath,
|
||||
accessAgreementAcknowledged: existingSession?.accessAgreementAcknowledged,
|
||||
};
|
||||
sessionStorage.set(updatedSession);
|
||||
return updatedSession;
|
||||
: existingSessionValue.state,
|
||||
});
|
||||
} else {
|
||||
newSessionValue = await this.session.extend(request, existingSessionValue);
|
||||
}
|
||||
|
||||
return existingSession;
|
||||
}
|
||||
|
||||
private getProviderName(query: any): string | null {
|
||||
if (query && query.provider && typeof query.provider === 'string') {
|
||||
return query.provider;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private calculateExpiry(
|
||||
existingSession: ProviderSession | null
|
||||
): { idleTimeoutExpiration: number | null; lifespanExpiration: number | null } {
|
||||
const now = Date.now();
|
||||
// if we are renewing an existing session, use its `lifespanExpiration` -- otherwise, set this value
|
||||
// based on the configured server `lifespan`.
|
||||
// note, if the server had a `lifespan` set and then removes it, remove `lifespanExpiration` on renewed sessions
|
||||
// also, if the server did not have a `lifespan` set and then adds it, add `lifespanExpiration` on renewed sessions
|
||||
const lifespanExpiration =
|
||||
existingSession?.lifespanExpiration && this.lifespan
|
||||
? existingSession.lifespanExpiration
|
||||
: this.lifespan && now + this.lifespan.asMilliseconds();
|
||||
const idleTimeoutExpiration = this.idleTimeout && now + this.idleTimeout.asMilliseconds();
|
||||
|
||||
return { idleTimeoutExpiration, lifespanExpiration };
|
||||
return {
|
||||
value: newSessionValue,
|
||||
// We care only about cases when one authenticated session has been overwritten by another
|
||||
// authenticated session that belongs to a different user (different name or provider/realm).
|
||||
overwritten:
|
||||
isExistingSessionAuthenticated &&
|
||||
isNewSessionAuthenticated &&
|
||||
(providerHasChanged || usernameHasChanged),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether request should be redirected to the Login Selector UI.
|
||||
* @param request Request instance.
|
||||
* @param session Current session value if any.
|
||||
* @param sessionValue Current session value if any.
|
||||
*/
|
||||
private shouldRedirectToLoginSelector(request: KibanaRequest, session: ProviderSession | null) {
|
||||
private shouldRedirectToLoginSelector(request: KibanaRequest, sessionValue: SessionValue | null) {
|
||||
// Request should be redirected to Login Selector UI only if all following conditions are met:
|
||||
// 1. Request can be redirected (not API call)
|
||||
// 2. Request is not authenticated yet
|
||||
|
@ -680,7 +637,7 @@ export class Authenticator {
|
|||
// 4. Request isn't attributed with HTTP Authorization header
|
||||
return (
|
||||
canRedirectRequest(request) &&
|
||||
!session &&
|
||||
!sessionValue &&
|
||||
this.options.config.authc.selector.enabled &&
|
||||
HTTPAuthorizationHeader.parseFromRequest(request) == null
|
||||
);
|
||||
|
@ -688,10 +645,9 @@ export class Authenticator {
|
|||
|
||||
/**
|
||||
* Checks whether request should be redirected to the Access Agreement UI.
|
||||
* @param request Request instance.
|
||||
* @param session Current session value if any.
|
||||
* @param sessionValue Current session value if any.
|
||||
*/
|
||||
private shouldRedirectToAccessAgreement(request: KibanaRequest, session: ProviderSession | null) {
|
||||
private shouldRedirectToAccessAgreement(sessionValue: SessionValue | null) {
|
||||
// Request should be redirected to Access Agreement UI only if all following conditions are met:
|
||||
// 1. Request can be redirected (not API call)
|
||||
// 2. Request is authenticated, but user hasn't acknowledged access agreement in the current
|
||||
|
@ -700,14 +656,71 @@ export class Authenticator {
|
|||
// 4. Current license allows access agreement
|
||||
// 5. And it's not a request to the Access Agreement UI itself
|
||||
return (
|
||||
canRedirectRequest(request) &&
|
||||
session != null &&
|
||||
!session.accessAgreementAcknowledged &&
|
||||
(this.options.config.authc.providers as Record<string, any>)[session.provider.type]?.[
|
||||
session.provider.name
|
||||
sessionValue != null &&
|
||||
!sessionValue.accessAgreementAcknowledged &&
|
||||
(this.options.config.authc.providers as Record<string, any>)[sessionValue.provider.type]?.[
|
||||
sessionValue.provider.name
|
||||
]?.accessAgreement &&
|
||||
this.options.license.getFeatures().allowAccessAgreement &&
|
||||
request.url.pathname !== ACCESS_AGREEMENT_ROUTE
|
||||
this.options.license.getFeatures().allowAccessAgreement
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* In some cases we'd like to redirect user to another page right after successful authentication
|
||||
* before they can access anything else in Kibana. This method makes sure we do a proper redirect
|
||||
* that would eventually lead user to a initially requested Kibana URL.
|
||||
* @param request Request instance.
|
||||
* @param authenticationResult Result of the authentication.
|
||||
* @param sessionUpdateResult Result of the session update.
|
||||
* @param redirectURL
|
||||
*/
|
||||
private handlePreAccessRedirects(
|
||||
request: KibanaRequest,
|
||||
authenticationResult: AuthenticationResult,
|
||||
sessionUpdateResult: { value: Readonly<SessionValue> | null; overwritten: boolean } | null,
|
||||
redirectURL?: string
|
||||
) {
|
||||
if (
|
||||
authenticationResult.failed() ||
|
||||
request.url.pathname === ACCESS_AGREEMENT_ROUTE ||
|
||||
request.url.pathname === OVERWRITTEN_SESSION_ROUTE
|
||||
) {
|
||||
return authenticationResult;
|
||||
}
|
||||
|
||||
const isSessionAuthenticated = !!sessionUpdateResult?.value?.username;
|
||||
|
||||
let preAccessRedirectURL;
|
||||
if (isSessionAuthenticated && sessionUpdateResult?.overwritten) {
|
||||
this.logger.debug('Redirecting user to the overwritten session UI.');
|
||||
preAccessRedirectURL = `${this.options.basePath.serverBasePath}${OVERWRITTEN_SESSION_ROUTE}`;
|
||||
} else if (
|
||||
isSessionAuthenticated &&
|
||||
this.shouldRedirectToAccessAgreement(sessionUpdateResult?.value ?? null)
|
||||
) {
|
||||
this.logger.debug('Redirecting user to the access agreement UI.');
|
||||
preAccessRedirectURL = `${this.options.basePath.serverBasePath}${ACCESS_AGREEMENT_ROUTE}`;
|
||||
}
|
||||
|
||||
// If we need to redirect user to anywhere else before they can access Kibana we should remember
|
||||
// redirect URL in the `next` parameter. Redirect URL provided in authentication result, if any,
|
||||
// always takes precedence over what is specified in `redirectURL` parameter.
|
||||
if (preAccessRedirectURL) {
|
||||
preAccessRedirectURL = `${preAccessRedirectURL}?next=${encodeURIComponent(
|
||||
authenticationResult.redirectURL ||
|
||||
redirectURL ||
|
||||
`${this.options.basePath.get(request)}${request.url.path}`
|
||||
)}`;
|
||||
} else if (redirectURL && !authenticationResult.redirectURL) {
|
||||
preAccessRedirectURL = redirectURL;
|
||||
}
|
||||
|
||||
return preAccessRedirectURL
|
||||
? AuthenticationResult.redirectTo(preAccessRedirectURL, {
|
||||
state: authenticationResult.state,
|
||||
user: authenticationResult.user,
|
||||
authResponseHeaders: authenticationResult.authResponseHeaders,
|
||||
})
|
||||
: authenticationResult;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -18,7 +18,6 @@ export const authenticationMock = {
|
|||
invalidateAPIKey: jest.fn(),
|
||||
invalidateAPIKeyAsInternalUser: jest.fn(),
|
||||
isAuthenticated: jest.fn(),
|
||||
getSessionInfo: jest.fn(),
|
||||
acknowledgeAccessAgreement: jest.fn(),
|
||||
}),
|
||||
};
|
||||
|
|
|
@ -4,8 +4,6 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { licenseMock } from '../../common/licensing/index.mock';
|
||||
|
||||
jest.mock('./api_keys');
|
||||
jest.mock('./authenticator');
|
||||
|
||||
|
@ -18,17 +16,20 @@ import {
|
|||
httpServiceMock,
|
||||
elasticsearchServiceMock,
|
||||
} from '../../../../../src/core/server/mocks';
|
||||
import { licenseMock } from '../../common/licensing/index.mock';
|
||||
import { mockAuthenticatedUser } from '../../common/model/authenticated_user.mock';
|
||||
import { securityAuditLoggerMock } from '../audit/index.mock';
|
||||
import { securityFeatureUsageServiceMock } from '../feature_usage/index.mock';
|
||||
import { sessionMock } from '../session_management/session.mock';
|
||||
|
||||
import {
|
||||
AuthenticationHandler,
|
||||
AuthToolkit,
|
||||
ILegacyClusterClient,
|
||||
CoreSetup,
|
||||
KibanaRequest,
|
||||
LoggerFactory,
|
||||
LegacyScopedClusterClient,
|
||||
HttpServiceSetup,
|
||||
} from '../../../../../src/core/server';
|
||||
import { AuthenticatedUser } from '../../common/model';
|
||||
import { ConfigSchema, ConfigType, createConfig } from '../config';
|
||||
|
@ -43,17 +44,18 @@ import {
|
|||
import { SecurityLicense } from '../../common/licensing';
|
||||
import { SecurityAuditLogger } from '../audit';
|
||||
import { SecurityFeatureUsageServiceStart } from '../feature_usage';
|
||||
import { securityFeatureUsageServiceMock } from '../feature_usage/index.mock';
|
||||
import { Session } from '../session_management';
|
||||
|
||||
describe('setupAuthentication()', () => {
|
||||
let mockSetupAuthenticationParams: {
|
||||
auditLogger: jest.Mocked<SecurityAuditLogger>;
|
||||
config: ConfigType;
|
||||
loggers: LoggerFactory;
|
||||
http: jest.Mocked<CoreSetup['http']>;
|
||||
http: jest.Mocked<HttpServiceSetup>;
|
||||
clusterClient: jest.Mocked<ILegacyClusterClient>;
|
||||
license: jest.Mocked<SecurityLicense>;
|
||||
getFeatureUsageService: () => jest.Mocked<SecurityFeatureUsageServiceStart>;
|
||||
session: jest.Mocked<PublicMethodsOf<Session>>;
|
||||
};
|
||||
let mockScopedClusterClient: jest.Mocked<PublicMethodsOf<LegacyScopedClusterClient>>;
|
||||
beforeEach(() => {
|
||||
|
@ -75,6 +77,7 @@ describe('setupAuthentication()', () => {
|
|||
getFeatureUsageService: jest
|
||||
.fn()
|
||||
.mockReturnValue(securityFeatureUsageServiceMock.createStartContract()),
|
||||
session: sessionMock.create(),
|
||||
};
|
||||
|
||||
mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
|
@ -85,31 +88,13 @@ describe('setupAuthentication()', () => {
|
|||
|
||||
afterEach(() => jest.clearAllMocks());
|
||||
|
||||
it('properly initializes session storage and registers auth handler', async () => {
|
||||
const config = {
|
||||
encryptionKey: 'ab'.repeat(16),
|
||||
secureCookies: true,
|
||||
cookieName: 'my-sid-cookie',
|
||||
};
|
||||
|
||||
it('properly registers auth handler', async () => {
|
||||
await setupAuthentication(mockSetupAuthenticationParams);
|
||||
|
||||
expect(mockSetupAuthenticationParams.http.registerAuth).toHaveBeenCalledTimes(1);
|
||||
expect(mockSetupAuthenticationParams.http.registerAuth).toHaveBeenCalledWith(
|
||||
expect.any(Function)
|
||||
);
|
||||
|
||||
expect(
|
||||
mockSetupAuthenticationParams.http.createCookieSessionStorageFactory
|
||||
).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
mockSetupAuthenticationParams.http.createCookieSessionStorageFactory
|
||||
).toHaveBeenCalledWith({
|
||||
encryptionKey: config.encryptionKey,
|
||||
isSecure: config.secureCookies,
|
||||
name: config.cookieName,
|
||||
validate: expect.any(Function),
|
||||
});
|
||||
});
|
||||
|
||||
describe('authentication handler', () => {
|
||||
|
@ -121,6 +106,11 @@ describe('setupAuthentication()', () => {
|
|||
|
||||
await setupAuthentication(mockSetupAuthenticationParams);
|
||||
|
||||
expect(mockSetupAuthenticationParams.http.registerAuth).toHaveBeenCalledTimes(1);
|
||||
expect(mockSetupAuthenticationParams.http.registerAuth).toHaveBeenCalledWith(
|
||||
expect.any(Function)
|
||||
);
|
||||
|
||||
authHandler = mockSetupAuthenticationParams.http.registerAuth.mock.calls[0][0];
|
||||
authenticate = jest.requireMock('./authenticator').Authenticator.mock.instances[0]
|
||||
.authenticate;
|
||||
|
@ -195,15 +185,20 @@ describe('setupAuthentication()', () => {
|
|||
expect(authenticate).toHaveBeenCalledWith(mockRequest);
|
||||
});
|
||||
|
||||
it('redirects user if redirection is requested by the authenticator', async () => {
|
||||
it('redirects user if redirection is requested by the authenticator preserving authentication response headers if any', async () => {
|
||||
const mockResponse = httpServerMock.createLifecycleResponseFactory();
|
||||
authenticate.mockResolvedValue(AuthenticationResult.redirectTo('/some/url'));
|
||||
authenticate.mockResolvedValue(
|
||||
AuthenticationResult.redirectTo('/some/url', {
|
||||
authResponseHeaders: { 'WWW-Authenticate': 'Negotiate' },
|
||||
})
|
||||
);
|
||||
|
||||
await authHandler(httpServerMock.createKibanaRequest(), mockResponse, mockAuthToolkit);
|
||||
|
||||
expect(mockAuthToolkit.redirected).toHaveBeenCalledTimes(1);
|
||||
expect(mockAuthToolkit.redirected).toHaveBeenCalledWith({
|
||||
location: '/some/url',
|
||||
'WWW-Authenticate': 'Negotiate',
|
||||
});
|
||||
expect(mockAuthToolkit.authenticated).not.toHaveBeenCalled();
|
||||
expect(mockResponse.internalError).not.toHaveBeenCalled();
|
||||
|
|
|
@ -6,24 +6,32 @@
|
|||
import { UnwrapPromise } from '@kbn/utility-types';
|
||||
import {
|
||||
ILegacyClusterClient,
|
||||
CoreSetup,
|
||||
KibanaRequest,
|
||||
LoggerFactory,
|
||||
HttpServiceSetup,
|
||||
} from '../../../../../src/core/server';
|
||||
import { SecurityLicense } from '../../common/licensing';
|
||||
import { AuthenticatedUser } from '../../common/model';
|
||||
import { SecurityAuditLogger } from '../audit';
|
||||
import { ConfigType } from '../config';
|
||||
import { getErrorStatusCode } from '../errors';
|
||||
import { Authenticator, ProviderSession } from './authenticator';
|
||||
import { APIKeys, CreateAPIKeyParams, InvalidateAPIKeyParams } from './api_keys';
|
||||
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 } from './providers';
|
||||
export {
|
||||
OIDCLogin,
|
||||
SAMLLogin,
|
||||
BasicAuthenticationProvider,
|
||||
TokenAuthenticationProvider,
|
||||
SAMLAuthenticationProvider,
|
||||
OIDCAuthenticationProvider,
|
||||
} from './providers';
|
||||
export {
|
||||
CreateAPIKeyResult,
|
||||
InvalidateAPIKeyResult,
|
||||
|
@ -39,11 +47,12 @@ export {
|
|||
interface SetupAuthenticationParams {
|
||||
auditLogger: SecurityAuditLogger;
|
||||
getFeatureUsageService: () => SecurityFeatureUsageServiceStart;
|
||||
http: CoreSetup['http'];
|
||||
http: HttpServiceSetup;
|
||||
clusterClient: ILegacyClusterClient;
|
||||
config: ConfigType;
|
||||
license: SecurityLicense;
|
||||
loggers: LoggerFactory;
|
||||
session: PublicMethodsOf<Session>;
|
||||
}
|
||||
|
||||
export type Authentication = UnwrapPromise<ReturnType<typeof setupAuthentication>>;
|
||||
|
@ -56,6 +65,7 @@ export async function setupAuthentication({
|
|||
config,
|
||||
license,
|
||||
loggers,
|
||||
session,
|
||||
}: SetupAuthenticationParams) {
|
||||
const authLogger = loggers.get('authentication');
|
||||
|
||||
|
@ -71,46 +81,16 @@ export async function setupAuthentication({
|
|||
return (http.auth.get(request).state ?? null) as AuthenticatedUser | null;
|
||||
};
|
||||
|
||||
const isValid = (sessionValue: ProviderSession) => {
|
||||
// ensure that this cookie was created with the current Kibana configuration
|
||||
const { path, idleTimeoutExpiration, lifespanExpiration } = sessionValue;
|
||||
if (path !== undefined && path !== (http.basePath.serverBasePath || '/')) {
|
||||
authLogger.debug(`Outdated session value with path "${sessionValue.path}"`);
|
||||
return false;
|
||||
}
|
||||
// ensure that this cookie is not expired
|
||||
if (idleTimeoutExpiration && idleTimeoutExpiration < Date.now()) {
|
||||
return false;
|
||||
} else if (lifespanExpiration && lifespanExpiration < Date.now()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const authenticator = new Authenticator({
|
||||
auditLogger,
|
||||
getFeatureUsageService,
|
||||
getCurrentUser,
|
||||
loggers,
|
||||
clusterClient,
|
||||
basePath: http.basePath,
|
||||
config: { session: config.session, authc: config.authc },
|
||||
config: { authc: config.authc },
|
||||
getCurrentUser,
|
||||
getFeatureUsageService,
|
||||
license,
|
||||
loggers,
|
||||
sessionStorageFactory: await http.createCookieSessionStorageFactory({
|
||||
encryptionKey: config.encryptionKey,
|
||||
isSecure: config.secureCookies,
|
||||
name: config.cookieName,
|
||||
sameSite: config.sameSiteCookies,
|
||||
validate: (session: ProviderSession | ProviderSession[]) => {
|
||||
const array: ProviderSession[] = Array.isArray(session) ? session : [session];
|
||||
for (const sess of array) {
|
||||
if (!isValid(sess)) {
|
||||
return { isValid: false, path: sess.path };
|
||||
}
|
||||
}
|
||||
return { isValid: true };
|
||||
},
|
||||
}),
|
||||
session,
|
||||
});
|
||||
|
||||
authLogger.debug('Successfully initialized authenticator.');
|
||||
|
@ -145,6 +125,7 @@ export async function setupAuthentication({
|
|||
// decides what location user should be redirected to.
|
||||
return t.redirected({
|
||||
location: authenticationResult.redirectURL!,
|
||||
...(authenticationResult.authResponseHeaders || {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -180,7 +161,6 @@ export async function setupAuthentication({
|
|||
return {
|
||||
login: authenticator.login.bind(authenticator),
|
||||
logout: authenticator.logout.bind(authenticator),
|
||||
getSessionInfo: authenticator.getSessionInfo.bind(authenticator),
|
||||
isProviderTypeEnabled: authenticator.isProviderTypeEnabled.bind(authenticator),
|
||||
acknowledgeAccessAgreement: authenticator.acknowledgeAccessAgreement.bind(authenticator),
|
||||
getCurrentUser,
|
||||
|
|
|
@ -184,6 +184,12 @@ describe('BasicAuthenticationProvider', () => {
|
|||
);
|
||||
});
|
||||
|
||||
it('redirects to login view if state is `null`.', async () => {
|
||||
await expect(provider.logout(httpServerMock.createKibanaRequest(), null)).resolves.toEqual(
|
||||
DeauthenticationResult.redirectTo('/mock-server-basepath/login?msg=LOGGED_OUT')
|
||||
);
|
||||
});
|
||||
|
||||
it('always redirects to the login page.', async () => {
|
||||
await expect(provider.logout(httpServerMock.createKibanaRequest(), {})).resolves.toEqual(
|
||||
DeauthenticationResult.redirectTo('/mock-server-basepath/login?msg=LOGGED_OUT')
|
||||
|
|
|
@ -121,7 +121,9 @@ export class BasicAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
public async logout(request: KibanaRequest, state?: ProviderState | null) {
|
||||
this.logger.debug(`Trying to log user out via ${request.url.path}.`);
|
||||
|
||||
if (!state) {
|
||||
// Having a `null` state means that provider was specifically called to do a logout, but when
|
||||
// session isn't defined then provider is just being probed whether or not it can perform logout.
|
||||
if (state === undefined) {
|
||||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
|
|
|
@ -496,8 +496,14 @@ describe('KerberosAuthenticationProvider', () => {
|
|||
|
||||
await expect(provider.logout(request)).resolves.toEqual(DeauthenticationResult.notHandled());
|
||||
|
||||
expect(mockOptions.tokens.invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to logged out view if state is `null`.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
await expect(provider.logout(request, null)).resolves.toEqual(
|
||||
DeauthenticationResult.notHandled()
|
||||
DeauthenticationResult.redirectTo(mockOptions.urls.loggedOut)
|
||||
);
|
||||
|
||||
expect(mockOptions.tokens.invalidate).not.toHaveBeenCalled();
|
||||
|
|
|
@ -102,16 +102,20 @@ export class KerberosAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
public async logout(request: KibanaRequest, state?: ProviderState | null) {
|
||||
this.logger.debug(`Trying to log user out via ${request.url.path}.`);
|
||||
|
||||
if (!state) {
|
||||
// Having a `null` state means that provider was specifically called to do a logout, but when
|
||||
// session isn't defined then provider is just being probed whether or not it can perform logout.
|
||||
if (state === undefined) {
|
||||
this.logger.debug('There is no access token invalidate.');
|
||||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
try {
|
||||
await this.options.tokens.invalidate(state);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed invalidating access and/or refresh tokens: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
if (state) {
|
||||
try {
|
||||
await this.options.tokens.invalidate(state);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed invalidating access and/or refresh tokens: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
}
|
||||
|
||||
return DeauthenticationResult.redirectTo(this.options.urls.loggedOut);
|
||||
|
|
|
@ -12,31 +12,33 @@ import { MockAuthenticationProviderOptions, mockAuthenticationProviderOptions }
|
|||
|
||||
import {
|
||||
LegacyElasticsearchErrorHelpers,
|
||||
ILegacyClusterClient,
|
||||
KibanaRequest,
|
||||
ScopeableRequest,
|
||||
ILegacyScopedClusterClient,
|
||||
} from '../../../../../../src/core/server';
|
||||
import { AuthenticationResult } from '../authentication_result';
|
||||
import { DeauthenticationResult } from '../deauthentication_result';
|
||||
import { OIDCAuthenticationProvider, OIDCLogin, ProviderLoginAttempt } from './oidc';
|
||||
|
||||
function expectAuthenticateCall(
|
||||
mockClusterClient: jest.Mocked<ILegacyClusterClient>,
|
||||
scopeableRequest: ScopeableRequest
|
||||
) {
|
||||
expect(mockClusterClient.asScoped).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.asScoped).toHaveBeenCalledWith(scopeableRequest);
|
||||
|
||||
const mockScopedClusterClient = mockClusterClient.asScoped.mock.results[0].value;
|
||||
expect(mockScopedClusterClient.callAsCurrentUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockScopedClusterClient.callAsCurrentUser).toHaveBeenCalledWith('shield.authenticate');
|
||||
}
|
||||
import { AuthenticatedUser } from '../../../common/model';
|
||||
|
||||
describe('OIDCAuthenticationProvider', () => {
|
||||
let provider: OIDCAuthenticationProvider;
|
||||
let mockOptions: MockAuthenticationProviderOptions;
|
||||
let mockUser: AuthenticatedUser;
|
||||
let mockScopedClusterClient: jest.Mocked<ILegacyScopedClusterClient>;
|
||||
beforeEach(() => {
|
||||
mockOptions = mockAuthenticationProviderOptions({ name: 'oidc' });
|
||||
|
||||
mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockUser = mockAuthenticatedUser({ authentication_provider: 'oidc' });
|
||||
mockScopedClusterClient.callAsCurrentUser.mockImplementation(async (method) => {
|
||||
if (method === 'shield.authenticate') {
|
||||
return mockUser;
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected call to ${method}!`);
|
||||
});
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
provider = new OIDCAuthenticationProvider(mockOptions, { realm: 'oidc1' });
|
||||
});
|
||||
|
||||
|
@ -88,7 +90,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
state: {
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
nextURL: '/mock-server-basepath/',
|
||||
redirectURL: '/mock-server-basepath/',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
}
|
||||
|
@ -118,7 +120,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
await expect(
|
||||
provider.login(request, {
|
||||
type: OIDCLogin.LoginInitiatedByUser,
|
||||
redirectURLPath: '/mock-server-basepath/app/super-kibana',
|
||||
redirectURL: '/mock-server-basepath/app/super-kibana#some-hash',
|
||||
})
|
||||
).resolves.toEqual(
|
||||
AuthenticationResult.redirectTo(
|
||||
|
@ -132,7 +134,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
state: {
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
nextURL: '/mock-server-basepath/app/super-kibana',
|
||||
redirectURL: '/mock-server-basepath/app/super-kibana#some-hash',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
}
|
||||
|
@ -144,6 +146,24 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('fails if OpenID Connect authentication request preparation fails.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
const failureReason = new Error('Realm is misconfigured!');
|
||||
mockOptions.client.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(
|
||||
provider.login(request, {
|
||||
type: OIDCLogin.LoginInitiatedByUser,
|
||||
redirectURL: '/mock-server-basepath/app/super-kibana#some-hash',
|
||||
})
|
||||
).resolves.toEqual(AuthenticationResult.failed(failureReason));
|
||||
|
||||
expect(mockOptions.client.callAsInternalUser).toHaveBeenCalledWith('shield.oidcPrepare', {
|
||||
body: { realm: `oidc1` },
|
||||
});
|
||||
});
|
||||
|
||||
function defineAuthenticationFlowTests(
|
||||
getMocks: () => {
|
||||
request: KibanaRequest;
|
||||
|
@ -163,7 +183,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
provider.login(request, attempt, {
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
nextURL: '/base-path/some-path',
|
||||
redirectURL: '/base-path/some-path',
|
||||
realm: 'oidc1',
|
||||
})
|
||||
).resolves.toEqual(
|
||||
|
@ -173,6 +193,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
refreshToken: 'some-refresh-token',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
user: mockUser,
|
||||
})
|
||||
);
|
||||
|
||||
|
@ -193,7 +214,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
const { request, attempt } = getMocks();
|
||||
|
||||
await expect(
|
||||
provider.login(request, attempt, { nextURL: '/base-path/some-path', realm: 'oidc1' })
|
||||
provider.login(request, attempt, { redirectURL: '/base-path/some-path', realm: 'oidc1' })
|
||||
).resolves.toEqual(
|
||||
AuthenticationResult.failed(
|
||||
Boom.badRequest(
|
||||
|
@ -251,7 +272,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
provider.login(request, attempt, {
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
nextURL: '/base-path/some-path',
|
||||
redirectURL: '/base-path/some-path',
|
||||
realm: 'oidc1',
|
||||
})
|
||||
).resolves.toEqual(AuthenticationResult.failed(failureReason));
|
||||
|
@ -328,60 +349,25 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
);
|
||||
});
|
||||
|
||||
it('redirects non-AJAX request that can not be authenticated to the OpenId Connect Provider.', async () => {
|
||||
it('redirects non-AJAX request that can not be authenticated to the "capture URL" page.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest({ path: '/s/foo/some-path' });
|
||||
|
||||
mockOptions.client.callAsInternalUser.mockResolvedValue({
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
redirect:
|
||||
'https://op-host/path/login?response_type=code' +
|
||||
'&scope=openid%20profile%20email' +
|
||||
'&client_id=s6BhdRkqt3' +
|
||||
'&state=statevalue' +
|
||||
'&redirect_uri=https%3A%2F%2Ftest-hostname:1234%2Ftest-base-path%2Fapi%2Fsecurity%2Fv1%2F/oidc',
|
||||
id: 'some-request-id',
|
||||
redirect: 'https://idp-host/path/login?SAMLRequest=some%20request%20',
|
||||
});
|
||||
|
||||
await expect(provider.authenticate(request, null)).resolves.toEqual(
|
||||
AuthenticationResult.redirectTo(
|
||||
'https://op-host/path/login?response_type=code' +
|
||||
'&scope=openid%20profile%20email' +
|
||||
'&client_id=s6BhdRkqt3' +
|
||||
'&state=statevalue' +
|
||||
'&redirect_uri=https%3A%2F%2Ftest-hostname:1234%2Ftest-base-path%2Fapi%2Fsecurity%2Fv1%2F/oidc',
|
||||
{
|
||||
state: {
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
nextURL: '/mock-server-basepath/s/foo/some-path',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
}
|
||||
'/mock-server-basepath/internal/security/capture-url?next=%2Fmock-server-basepath%2Fs%2Ffoo%2Fsome-path&providerType=oidc&providerName=oidc',
|
||||
{ state: null }
|
||||
)
|
||||
);
|
||||
|
||||
expect(mockOptions.client.callAsInternalUser).toHaveBeenCalledWith('shield.oidcPrepare', {
|
||||
body: { realm: `oidc1` },
|
||||
});
|
||||
});
|
||||
|
||||
it('fails if OpenID Connect authentication request preparation fails.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest({ path: '/some-path' });
|
||||
|
||||
const failureReason = new Error('Realm is misconfigured!');
|
||||
mockOptions.client.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(provider.authenticate(request, null)).resolves.toEqual(
|
||||
AuthenticationResult.failed(failureReason)
|
||||
);
|
||||
|
||||
expect(mockOptions.client.callAsInternalUser).toHaveBeenCalledWith('shield.oidcPrepare', {
|
||||
body: { realm: `oidc1` },
|
||||
});
|
||||
expect(mockOptions.client.callAsInternalUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('succeeds if state contains a valid token.', async () => {
|
||||
const user = mockAuthenticatedUser();
|
||||
const request = httpServerMock.createKibanaRequest({ headers: {} });
|
||||
const tokenPair = {
|
||||
accessToken: 'some-valid-token',
|
||||
|
@ -389,20 +375,13 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
};
|
||||
const authorization = `Bearer ${tokenPair.accessToken}`;
|
||||
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user);
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
await expect(
|
||||
provider.authenticate(request, { ...tokenPair, realm: 'oidc1' })
|
||||
).resolves.toEqual(
|
||||
AuthenticationResult.succeeded(
|
||||
{ ...user, authentication_provider: 'oidc' },
|
||||
{ authHeaders: { authorization } }
|
||||
)
|
||||
AuthenticationResult.succeeded(mockUser, { authHeaders: { authorization } })
|
||||
);
|
||||
|
||||
expectAuthenticateCall(mockOptions.client, { headers: { authorization } });
|
||||
expect(mockOptions.client.asScoped).toHaveBeenCalledWith({ headers: { authorization } });
|
||||
|
||||
expect(request.headers).not.toHaveProperty('authorization');
|
||||
});
|
||||
|
@ -446,36 +425,31 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
const authorization = `Bearer ${tokenPair.accessToken}`;
|
||||
|
||||
const failureReason = new Error('Token is not valid!');
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason);
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
await expect(
|
||||
provider.authenticate(request, { ...tokenPair, realm: 'oidc1' })
|
||||
).resolves.toEqual(AuthenticationResult.failed(failureReason));
|
||||
|
||||
expectAuthenticateCall(mockOptions.client, { headers: { authorization } });
|
||||
expect(mockOptions.client.asScoped).toHaveBeenCalledWith({ headers: { authorization } });
|
||||
|
||||
expect(request.headers).not.toHaveProperty('authorization');
|
||||
});
|
||||
|
||||
it('succeeds if token from the state is expired, but has been successfully refreshed.', async () => {
|
||||
const user = mockAuthenticatedUser();
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
const tokenPair = { accessToken: 'expired-token', refreshToken: 'valid-refresh-token' };
|
||||
|
||||
mockOptions.client.asScoped.mockImplementation((scopeableRequest) => {
|
||||
if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) {
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(
|
||||
const mockScopedClusterClientToFail = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClientToFail.callAsCurrentUser.mockRejectedValue(
|
||||
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error())
|
||||
);
|
||||
return mockScopedClusterClient;
|
||||
return mockScopedClusterClientToFail;
|
||||
}
|
||||
|
||||
if (scopeableRequest?.headers.authorization === 'Bearer new-access-token') {
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user);
|
||||
return mockScopedClusterClient;
|
||||
}
|
||||
|
||||
|
@ -490,17 +464,14 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
await expect(
|
||||
provider.authenticate(request, { ...tokenPair, realm: 'oidc1' })
|
||||
).resolves.toEqual(
|
||||
AuthenticationResult.succeeded(
|
||||
{ ...user, authentication_provider: 'oidc' },
|
||||
{
|
||||
authHeaders: { authorization: 'Bearer new-access-token' },
|
||||
state: {
|
||||
accessToken: 'new-access-token',
|
||||
refreshToken: 'new-refresh-token',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
}
|
||||
)
|
||||
AuthenticationResult.succeeded(mockUser, {
|
||||
authHeaders: { authorization: 'Bearer new-access-token' },
|
||||
state: {
|
||||
accessToken: 'new-access-token',
|
||||
refreshToken: 'new-refresh-token',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(mockOptions.tokens.refresh).toHaveBeenCalledTimes(1);
|
||||
|
@ -514,11 +485,9 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
const tokenPair = { accessToken: 'expired-token', refreshToken: 'invalid-refresh-token' };
|
||||
const authorization = `Bearer ${tokenPair.accessToken}`;
|
||||
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(
|
||||
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error())
|
||||
);
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
const refreshFailureReason = {
|
||||
statusCode: 500,
|
||||
|
@ -533,32 +502,19 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
expect(mockOptions.tokens.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(mockOptions.tokens.refresh).toHaveBeenCalledWith(tokenPair.refreshToken);
|
||||
|
||||
expectAuthenticateCall(mockOptions.client, { headers: { authorization } });
|
||||
expect(mockOptions.client.asScoped).toHaveBeenCalledWith({ headers: { authorization } });
|
||||
|
||||
expect(request.headers).not.toHaveProperty('authorization');
|
||||
});
|
||||
|
||||
it('redirects to OpenID Connect Provider for non-AJAX requests if refresh token is expired or already refreshed.', async () => {
|
||||
it('redirects non-AJAX requests to the "capture URL" page if refresh token is expired or already refreshed.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest({ path: '/s/foo/some-path', headers: {} });
|
||||
const tokenPair = { accessToken: 'expired-token', refreshToken: 'expired-refresh-token' };
|
||||
const authorization = `Bearer ${tokenPair.accessToken}`;
|
||||
|
||||
mockOptions.client.callAsInternalUser.mockResolvedValue({
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
redirect:
|
||||
'https://op-host/path/login?response_type=code' +
|
||||
'&scope=openid%20profile%20email' +
|
||||
'&client_id=s6BhdRkqt3' +
|
||||
'&state=statevalue' +
|
||||
'&redirect_uri=https%3A%2F%2Ftest-hostname:1234%2Ftest-base-path%2Fapi%2Fsecurity%2Fv1%2F/oidc',
|
||||
});
|
||||
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(
|
||||
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error())
|
||||
);
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
mockOptions.tokens.refresh.mockResolvedValue(null);
|
||||
|
||||
|
@ -566,19 +522,8 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
provider.authenticate(request, { ...tokenPair, realm: 'oidc1' })
|
||||
).resolves.toEqual(
|
||||
AuthenticationResult.redirectTo(
|
||||
'https://op-host/path/login?response_type=code' +
|
||||
'&scope=openid%20profile%20email' +
|
||||
'&client_id=s6BhdRkqt3' +
|
||||
'&state=statevalue' +
|
||||
'&redirect_uri=https%3A%2F%2Ftest-hostname:1234%2Ftest-base-path%2Fapi%2Fsecurity%2Fv1%2F/oidc',
|
||||
{
|
||||
state: {
|
||||
state: 'statevalue',
|
||||
nonce: 'noncevalue',
|
||||
nextURL: '/mock-server-basepath/s/foo/some-path',
|
||||
realm: 'oidc1',
|
||||
},
|
||||
}
|
||||
'/mock-server-basepath/internal/security/capture-url?next=%2Fmock-server-basepath%2Fs%2Ffoo%2Fsome-path&providerType=oidc&providerName=oidc',
|
||||
{ state: null }
|
||||
)
|
||||
);
|
||||
|
||||
|
@ -592,9 +537,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
expect(mockScopedClusterClient.callAsCurrentUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockScopedClusterClient.callAsCurrentUser).toHaveBeenCalledWith('shield.authenticate');
|
||||
|
||||
expect(mockOptions.client.callAsInternalUser).toHaveBeenCalledWith('shield.oidcPrepare', {
|
||||
body: { realm: `oidc1` },
|
||||
});
|
||||
expect(mockOptions.client.callAsInternalUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails for AJAX requests with user friendly message if refresh token is expired.', async () => {
|
||||
|
@ -602,11 +545,9 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
const tokenPair = { accessToken: 'expired-token', refreshToken: 'expired-refresh-token' };
|
||||
const authorization = `Bearer ${tokenPair.accessToken}`;
|
||||
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(
|
||||
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error())
|
||||
);
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
mockOptions.tokens.refresh.mockResolvedValue(null);
|
||||
|
||||
|
@ -619,7 +560,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
expect(mockOptions.tokens.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(mockOptions.tokens.refresh).toHaveBeenCalledWith(tokenPair.refreshToken);
|
||||
|
||||
expectAuthenticateCall(mockOptions.client, {
|
||||
expect(mockOptions.client.asScoped).toHaveBeenCalledWith({
|
||||
headers: { 'kbn-xsrf': 'xsrf', authorization },
|
||||
});
|
||||
|
||||
|
@ -631,11 +572,9 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
const tokenPair = { accessToken: 'expired-token', refreshToken: 'expired-refresh-token' };
|
||||
const authorization = `Bearer ${tokenPair.accessToken}`;
|
||||
|
||||
const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(
|
||||
LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error())
|
||||
);
|
||||
mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient);
|
||||
|
||||
mockOptions.tokens.refresh.mockResolvedValue(null);
|
||||
|
||||
|
@ -648,7 +587,7 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
expect(mockOptions.tokens.refresh).toHaveBeenCalledTimes(1);
|
||||
expect(mockOptions.tokens.refresh).toHaveBeenCalledWith(tokenPair.refreshToken);
|
||||
|
||||
expectAuthenticateCall(mockOptions.client, { headers: { authorization } });
|
||||
expect(mockOptions.client.asScoped).toHaveBeenCalledWith({ headers: { authorization } });
|
||||
|
||||
expect(request.headers).not.toHaveProperty('authorization');
|
||||
});
|
||||
|
@ -666,19 +605,26 @@ describe('OIDCAuthenticationProvider', () => {
|
|||
});
|
||||
|
||||
describe('`logout` method', () => {
|
||||
it('returns `notHandled` if state is not presented or does not include access token.', async () => {
|
||||
it('returns `notHandled` if state is not presented.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
await expect(provider.logout(request, undefined as any)).resolves.toEqual(
|
||||
DeauthenticationResult.notHandled()
|
||||
);
|
||||
|
||||
await expect(provider.logout(request, {} as any)).resolves.toEqual(
|
||||
DeauthenticationResult.notHandled()
|
||||
);
|
||||
await expect(provider.logout(request)).resolves.toEqual(DeauthenticationResult.notHandled());
|
||||
|
||||
expect(mockOptions.client.callAsInternalUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to logged out view if state is `null` or does not include access token.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
await expect(provider.logout(request, null)).resolves.toEqual(
|
||||
DeauthenticationResult.redirectTo(mockOptions.urls.loggedOut)
|
||||
);
|
||||
await expect(provider.logout(request, { nonce: 'x', realm: 'oidc1' })).resolves.toEqual(
|
||||
DeauthenticationResult.notHandled()
|
||||
DeauthenticationResult.redirectTo(mockOptions.urls.loggedOut)
|
||||
);
|
||||
|
||||
expect(mockOptions.client.callAsInternalUser).not.toHaveBeenCalled();
|
||||
|
|
|
@ -7,6 +7,7 @@
|
|||
import Boom from 'boom';
|
||||
import type from 'type-detect';
|
||||
import { KibanaRequest } from '../../../../../../src/core/server';
|
||||
import { AuthenticatedUser } from '../../../common/model';
|
||||
import { AuthenticationResult } from '../authentication_result';
|
||||
import { canRedirectRequest } from '../can_redirect_request';
|
||||
import { DeauthenticationResult } from '../deauthentication_result';
|
||||
|
@ -32,7 +33,7 @@ export enum OIDCLogin {
|
|||
* Describes the parameters that are required by the provider to process the initial login request.
|
||||
*/
|
||||
export type ProviderLoginAttempt =
|
||||
| { type: OIDCLogin.LoginInitiatedByUser; redirectURLPath: string }
|
||||
| { type: OIDCLogin.LoginInitiatedByUser; redirectURL: string }
|
||||
| {
|
||||
type: OIDCLogin.LoginWithImplicitFlow | OIDCLogin.LoginWithAuthorizationCodeFlow;
|
||||
authenticationResponseURI: string;
|
||||
|
@ -58,7 +59,7 @@ interface ProviderState extends Partial<TokenPair> {
|
|||
/**
|
||||
* URL to redirect user to after successful OpenID Connect handshake.
|
||||
*/
|
||||
nextURL?: string;
|
||||
redirectURL?: string;
|
||||
|
||||
/**
|
||||
* The name of the OpenID Connect realm that was used to establish session.
|
||||
|
@ -143,11 +144,7 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
|
||||
if (attempt.type === OIDCLogin.LoginInitiatedByUser) {
|
||||
this.logger.debug(`Login has been initiated by a user.`);
|
||||
return this.initiateOIDCAuthentication(
|
||||
request,
|
||||
{ realm: this.realm },
|
||||
attempt.redirectURLPath
|
||||
);
|
||||
return this.initiateOIDCAuthentication(request, { realm: this.realm }, attempt.redirectURL);
|
||||
}
|
||||
|
||||
if (attempt.type === OIDCLogin.LoginWithImplicitFlow) {
|
||||
|
@ -200,7 +197,7 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
// We might already have a state and nonce generated by Elasticsearch (from an unfinished authentication in
|
||||
// another tab)
|
||||
return authenticationResult.notHandled() && canStartNewSession(request)
|
||||
? await this.initiateOIDCAuthentication(request, { realm: this.realm })
|
||||
? await this.captureRedirectURL(request)
|
||||
: authenticationResult;
|
||||
}
|
||||
|
||||
|
@ -231,8 +228,11 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
// If it is an authentication response and the users' session state doesn't contain all the necessary information,
|
||||
// then something unexpected happened and we should fail because Elasticsearch won't be able to validate the
|
||||
// response.
|
||||
const { nonce: stateNonce = '', state: stateOIDCState = '', nextURL: stateRedirectURL = '' } =
|
||||
sessionState || {};
|
||||
const {
|
||||
nonce: stateNonce = '',
|
||||
state: stateOIDCState = '',
|
||||
redirectURL: stateRedirectURL = '',
|
||||
} = sessionState || {};
|
||||
if (!stateNonce || !stateOIDCState || !stateRedirectURL) {
|
||||
const message =
|
||||
'Response session state does not have corresponding state or nonce parameters or redirect URL.';
|
||||
|
@ -241,30 +241,47 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
}
|
||||
|
||||
// We have all the necessary parameters, so attempt to complete the OpenID Connect Authentication
|
||||
let accessToken;
|
||||
let refreshToken;
|
||||
try {
|
||||
// This operation should be performed on behalf of the user with a privilege that normal
|
||||
// user usually doesn't have `cluster:admin/xpack/security/oidc/authenticate`.
|
||||
const {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
} = await this.options.client.callAsInternalUser('shield.oidcAuthenticate', {
|
||||
body: {
|
||||
state: stateOIDCState,
|
||||
nonce: stateNonce,
|
||||
redirect_uri: authenticationResponseURI,
|
||||
realm: this.realm,
|
||||
},
|
||||
});
|
||||
const authenticateResponse = await this.options.client.callAsInternalUser(
|
||||
'shield.oidcAuthenticate',
|
||||
{
|
||||
body: {
|
||||
state: stateOIDCState,
|
||||
nonce: stateNonce,
|
||||
redirect_uri: authenticationResponseURI,
|
||||
realm: this.realm,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
this.logger.debug('Request has been authenticated via OpenID Connect.');
|
||||
|
||||
return AuthenticationResult.redirectTo(stateRedirectURL, {
|
||||
state: { accessToken, refreshToken, realm: this.realm },
|
||||
});
|
||||
accessToken = authenticateResponse.access_token;
|
||||
refreshToken = authenticateResponse.refresh_token;
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to authenticate request via OpenID Connect: ${err.message}`);
|
||||
return AuthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
// Now we need to retrieve full user information.
|
||||
let user: Readonly<AuthenticatedUser>;
|
||||
try {
|
||||
user = await this.getUser(request, {
|
||||
authorization: new HTTPAuthorizationHeader('Bearer', accessToken).toString(),
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to retrieve user using access token: ${err.message}`);
|
||||
return AuthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
this.logger.debug('Login has been performed with OpenID Connect response.');
|
||||
|
||||
return AuthenticationResult.redirectTo(stateRedirectURL, {
|
||||
state: { accessToken, refreshToken, realm: this.realm },
|
||||
user,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -272,13 +289,12 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
*
|
||||
* @param request Request instance.
|
||||
* @param params OIDC authentication parameters.
|
||||
* @param [redirectURLPath] Optional URL user is supposed to be redirected to after successful
|
||||
* login. If not provided the URL of the specified request is used.
|
||||
* @param redirectURL URL user is supposed to be redirected to after successful login.
|
||||
*/
|
||||
private async initiateOIDCAuthentication(
|
||||
request: KibanaRequest,
|
||||
params: { realm: string } | { iss: string; login_hint?: string },
|
||||
redirectURLPath = `${this.options.basePath.get(request)}${request.url.path}`
|
||||
redirectURL: string
|
||||
) {
|
||||
this.logger.debug('Trying to initiate OpenID Connect authentication.');
|
||||
|
||||
|
@ -295,7 +311,7 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
return AuthenticationResult.redirectTo(
|
||||
redirect,
|
||||
// Store the state and nonce parameters in the session state of the user
|
||||
{ state: { state, nonce, nextURL: redirectURLPath, realm: this.realm } }
|
||||
{ state: { state, nonce, redirectURL, realm: this.realm } }
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to initiate OpenID Connect authentication: ${err.message}`);
|
||||
|
@ -367,7 +383,7 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
this.logger.debug(
|
||||
'Both elasticsearch access and refresh tokens are expired. Re-initiating OpenID Connect authentication.'
|
||||
);
|
||||
return this.initiateOIDCAuthentication(request, { realm: this.realm });
|
||||
return this.captureRedirectURL(request);
|
||||
}
|
||||
|
||||
return AuthenticationResult.failed(
|
||||
|
@ -401,43 +417,47 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
* @param request Request instance.
|
||||
* @param state State value previously stored by the provider.
|
||||
*/
|
||||
public async logout(request: KibanaRequest, state: ProviderState) {
|
||||
public async logout(request: KibanaRequest, state?: ProviderState | null) {
|
||||
this.logger.debug(`Trying to log user out via ${request.url.path}.`);
|
||||
|
||||
if (!state || !state.accessToken) {
|
||||
// Having a `null` state means that provider was specifically called to do a logout, but when
|
||||
// session isn't defined then provider is just being probed whether or not it can perform logout.
|
||||
if (state === undefined) {
|
||||
this.logger.debug('There is no elasticsearch access token to invalidate.');
|
||||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
try {
|
||||
const logoutBody = {
|
||||
body: {
|
||||
token: state.accessToken,
|
||||
refresh_token: state.refreshToken,
|
||||
},
|
||||
};
|
||||
// This operation should be performed on behalf of the user with a privilege that normal
|
||||
// user usually doesn't have `cluster:admin/xpack/security/oidc/logout`.
|
||||
const { redirect } = await this.options.client.callAsInternalUser(
|
||||
'shield.oidcLogout',
|
||||
logoutBody
|
||||
);
|
||||
if (state?.accessToken) {
|
||||
try {
|
||||
const logoutBody = {
|
||||
body: {
|
||||
token: state.accessToken,
|
||||
refresh_token: state.refreshToken,
|
||||
},
|
||||
};
|
||||
// This operation should be performed on behalf of the user with a privilege that normal
|
||||
// user usually doesn't have `cluster:admin/xpack/security/oidc/logout`.
|
||||
const { redirect } = await this.options.client.callAsInternalUser(
|
||||
'shield.oidcLogout',
|
||||
logoutBody
|
||||
);
|
||||
|
||||
this.logger.debug('User session has been successfully invalidated.');
|
||||
this.logger.debug('User session has been successfully invalidated.');
|
||||
|
||||
// Having non-null `redirect` field within logout response means that the OpenID Connect realm configuration
|
||||
// supports RP initiated Single Logout and we should redirect user to the specified location in the OpenID Connect
|
||||
// Provider to properly complete logout.
|
||||
if (redirect != null) {
|
||||
this.logger.debug('Redirecting user to the OpenID Connect Provider to complete logout.');
|
||||
return DeauthenticationResult.redirectTo(redirect);
|
||||
// Having non-null `redirect` field within logout response means that the OpenID Connect realm configuration
|
||||
// supports RP initiated Single Logout and we should redirect user to the specified location in the OpenID Connect
|
||||
// Provider to properly complete logout.
|
||||
if (redirect != null) {
|
||||
this.logger.debug('Redirecting user to the OpenID Connect Provider to complete logout.');
|
||||
return DeauthenticationResult.redirectTo(redirect);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to deauthenticate user: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
return DeauthenticationResult.redirectTo(this.options.urls.loggedOut);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to deauthenticate user: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
return DeauthenticationResult.redirectTo(this.options.urls.loggedOut);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -447,4 +467,23 @@ export class OIDCAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
public getHTTPAuthenticationScheme() {
|
||||
return 'bearer';
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to capture full redirect URL (both path and fragment) and initiate OIDC handshake.
|
||||
* @param request Request instance.
|
||||
*/
|
||||
private captureRedirectURL(request: KibanaRequest) {
|
||||
return AuthenticationResult.redirectTo(
|
||||
`${
|
||||
this.options.basePath.serverBasePath
|
||||
}/internal/security/capture-url?next=${encodeURIComponent(
|
||||
`${this.options.basePath.get(request)}${request.url.path}`
|
||||
)}&providerType=${encodeURIComponent(this.type)}&providerName=${encodeURIComponent(
|
||||
this.options.name
|
||||
)}`,
|
||||
// Here we indicate that current session, if any, should be invalidated. It is a no-op for the
|
||||
// initial handshake, but is essential when both access and refresh tokens are expired.
|
||||
{ state: null }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -527,8 +527,14 @@ describe('PKIAuthenticationProvider', () => {
|
|||
|
||||
await expect(provider.logout(request)).resolves.toEqual(DeauthenticationResult.notHandled());
|
||||
|
||||
expect(mockOptions.tokens.invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to logged out view if state is `null`.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
await expect(provider.logout(request, null)).resolves.toEqual(
|
||||
DeauthenticationResult.notHandled()
|
||||
DeauthenticationResult.redirectTo(mockOptions.urls.loggedOut)
|
||||
);
|
||||
|
||||
expect(mockOptions.tokens.invalidate).not.toHaveBeenCalled();
|
||||
|
|
|
@ -107,16 +107,20 @@ export class PKIAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
public async logout(request: KibanaRequest, state?: ProviderState | null) {
|
||||
this.logger.debug(`Trying to log user out via ${request.url.path}.`);
|
||||
|
||||
if (!state) {
|
||||
// Having a `null` state means that provider was specifically called to do a logout, but when
|
||||
// session isn't defined then provider is just being probed whether or not it can perform logout.
|
||||
if (state === undefined) {
|
||||
this.logger.debug('There is no access token to invalidate.');
|
||||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
try {
|
||||
await this.options.tokens.invalidate({ accessToken: state.accessToken });
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed invalidating access token: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
if (state) {
|
||||
try {
|
||||
await this.options.tokens.invalidate({ accessToken: state.accessToken });
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed invalidating access token: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
}
|
||||
|
||||
return DeauthenticationResult.redirectTo(this.options.urls.loggedOut);
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -5,8 +5,8 @@
|
|||
*/
|
||||
|
||||
import Boom from 'boom';
|
||||
import { ByteSizeValue } from '@kbn/config-schema';
|
||||
import { KibanaRequest } from '../../../../../../src/core/server';
|
||||
import { AuthenticatedUser } from '../../../common/model';
|
||||
import { isInternalURL } from '../../../common/is_internal_url';
|
||||
import { AuthenticationResult } from '../authentication_result';
|
||||
import { DeauthenticationResult } from '../deauthentication_result';
|
||||
|
@ -19,15 +19,11 @@ import { AuthenticationProviderOptions, BaseAuthenticationProvider } from './bas
|
|||
* The state supported by the provider (for the SAML handshake or established session).
|
||||
*/
|
||||
interface ProviderState extends Partial<TokenPair> {
|
||||
/**
|
||||
* Username of the SAML authenticated user.
|
||||
*/
|
||||
username?: string;
|
||||
|
||||
/**
|
||||
* Unique identifier of the SAML request initiated the handshake.
|
||||
*/
|
||||
requestId?: string;
|
||||
|
||||
/**
|
||||
* Stores path component of the URL only or in a combination with URL fragment that was used to
|
||||
* initiate SAML handshake and where we should redirect user after successful authentication.
|
||||
|
@ -59,7 +55,7 @@ export enum SAMLLogin {
|
|||
* Describes the parameters that are required by the provider to process the initial login request.
|
||||
*/
|
||||
type ProviderLoginAttempt =
|
||||
| { type: SAMLLogin.LoginInitiatedByUser; redirectURLPath?: string; redirectURLFragment?: string }
|
||||
| { type: SAMLLogin.LoginInitiatedByUser; redirectURL: string }
|
||||
| { type: SAMLLogin.LoginWithSAMLResponse; samlResponse: string; relayState?: string };
|
||||
|
||||
/**
|
||||
|
@ -102,11 +98,6 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
*/
|
||||
private readonly realm: string;
|
||||
|
||||
/**
|
||||
* Maximum size of the URL we store in the session during SAML handshake.
|
||||
*/
|
||||
private readonly maxRedirectURLSize: ByteSizeValue;
|
||||
|
||||
/**
|
||||
* Indicates if we should treat non-empty `RelayState` as a deep link in Kibana we should redirect
|
||||
* user to after successful IdP initiated login. `RelayState` is ignored for SP initiated login.
|
||||
|
@ -115,11 +106,7 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
|
||||
constructor(
|
||||
protected readonly options: Readonly<AuthenticationProviderOptions>,
|
||||
samlOptions?: Readonly<{
|
||||
realm?: string;
|
||||
maxRedirectURLSize?: ByteSizeValue;
|
||||
useRelayStateDeepLink?: boolean;
|
||||
}>
|
||||
samlOptions?: Readonly<{ realm?: string; useRelayStateDeepLink?: boolean }>
|
||||
) {
|
||||
super(options);
|
||||
|
||||
|
@ -127,12 +114,7 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
throw new Error('Realm name must be specified');
|
||||
}
|
||||
|
||||
if (!samlOptions.maxRedirectURLSize) {
|
||||
throw new Error('Maximum redirect URL size must be specified');
|
||||
}
|
||||
|
||||
this.realm = samlOptions.realm;
|
||||
this.maxRedirectURLSize = samlOptions.maxRedirectURLSize;
|
||||
this.useRelayStateDeepLink = samlOptions.useRelayStateDeepLink ?? false;
|
||||
}
|
||||
|
||||
|
@ -158,14 +140,12 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
}
|
||||
|
||||
if (attempt.type === SAMLLogin.LoginInitiatedByUser) {
|
||||
const redirectURLPath = attempt.redirectURLPath || state?.redirectURL;
|
||||
if (!redirectURLPath) {
|
||||
const message = 'State or login attempt does not include URL path to redirect to.';
|
||||
if (!attempt.redirectURL) {
|
||||
const message = 'Login attempt should include non-empty `redirectURL` string.';
|
||||
this.logger.debug(message);
|
||||
return AuthenticationResult.failed(Boom.badRequest(message));
|
||||
}
|
||||
|
||||
return this.captureRedirectURL(request, redirectURLPath, attempt.redirectURLFragment);
|
||||
return this.authenticateViaHandshake(request, attempt.redirectURL);
|
||||
}
|
||||
|
||||
const { samlResponse, relayState } = attempt;
|
||||
|
@ -251,7 +231,7 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
* @param request Request instance.
|
||||
* @param state State value previously stored by the provider.
|
||||
*/
|
||||
public async logout(request: KibanaRequest, state?: ProviderState) {
|
||||
public async logout(request: KibanaRequest, state?: ProviderState | null) {
|
||||
this.logger.debug(`Trying to log user out via ${request.url.path}.`);
|
||||
|
||||
// Normally when there is no active session in Kibana, `logout` method shouldn't do anything
|
||||
|
@ -269,36 +249,38 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
// redirect to the `loggedOut` URL instead.
|
||||
const isIdPInitiatedSLORequest = isSAMLRequestQuery(request.query);
|
||||
const isSPInitiatedSLOResponse = isSAMLResponseQuery(request.query);
|
||||
if (!state?.accessToken && !isIdPInitiatedSLORequest && !isSPInitiatedSLOResponse) {
|
||||
if (state === undefined && !isIdPInitiatedSLORequest && !isSPInitiatedSLOResponse) {
|
||||
this.logger.debug('There is no SAML session to invalidate.');
|
||||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
try {
|
||||
// It may _theoretically_ (highly unlikely in practice though) happen that when user receives
|
||||
// logout response they may already have a new SAML session (isSPInitiatedSLOResponse == true
|
||||
// and state !== undefined). In this case case it'd be safer to trigger SP initiated logout
|
||||
// for the new session as well.
|
||||
const redirect = isIdPInitiatedSLORequest
|
||||
? await this.performIdPInitiatedSingleLogout(request)
|
||||
: state
|
||||
? await this.performUserInitiatedSingleLogout(state.accessToken!, state.refreshToken!)
|
||||
: // Once Elasticsearch can consume logout response we'll be sending it here. See https://github.com/elastic/elasticsearch/issues/40901
|
||||
null;
|
||||
if (state?.accessToken || isIdPInitiatedSLORequest || isSPInitiatedSLOResponse) {
|
||||
try {
|
||||
// It may _theoretically_ (highly unlikely in practice though) happen that when user receives
|
||||
// logout response they may already have a new SAML session (isSPInitiatedSLOResponse == true
|
||||
// and state !== undefined). In this case case it'd be safer to trigger SP initiated logout
|
||||
// for the new session as well.
|
||||
const redirect = isIdPInitiatedSLORequest
|
||||
? await this.performIdPInitiatedSingleLogout(request)
|
||||
: state
|
||||
? await this.performUserInitiatedSingleLogout(state.accessToken!, state.refreshToken!)
|
||||
: // Once Elasticsearch can consume logout response we'll be sending it here. See https://github.com/elastic/elasticsearch/issues/40901
|
||||
null;
|
||||
|
||||
// Having non-null `redirect` field within logout response means that IdP
|
||||
// supports SAML Single Logout and we should redirect user to the specified
|
||||
// location to properly complete logout.
|
||||
if (redirect != null) {
|
||||
this.logger.debug('Redirecting user to Identity Provider to complete logout.');
|
||||
return DeauthenticationResult.redirectTo(redirect);
|
||||
// Having non-null `redirect` field within logout response means that IdP
|
||||
// supports SAML Single Logout and we should redirect user to the specified
|
||||
// location to properly complete logout.
|
||||
if (redirect != null) {
|
||||
this.logger.debug('Redirecting user to Identity Provider to complete logout.');
|
||||
return DeauthenticationResult.redirectTo(redirect);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to deauthenticate user: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
return DeauthenticationResult.redirectTo(this.options.urls.loggedOut);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to deauthenticate user: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
return DeauthenticationResult.redirectTo(this.options.urls.loggedOut);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -354,46 +336,24 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
: 'Login has been initiated by Identity Provider.'
|
||||
);
|
||||
|
||||
let accessToken;
|
||||
let refreshToken;
|
||||
try {
|
||||
// This operation should be performed on behalf of the user with a privilege that normal
|
||||
// user usually doesn't have `cluster:admin/xpack/security/saml/authenticate`.
|
||||
const {
|
||||
username,
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
} = await this.options.client.callAsInternalUser('shield.samlAuthenticate', {
|
||||
body: {
|
||||
ids: !isIdPInitiatedLogin ? [stateRequestId] : [],
|
||||
content: samlResponse,
|
||||
realm: this.realm,
|
||||
},
|
||||
});
|
||||
|
||||
// IdP can pass `RelayState` with the deep link in Kibana during IdP initiated login and
|
||||
// depending on the configuration we may need to redirect user to this URL.
|
||||
let redirectURLFromRelayState;
|
||||
if (isIdPInitiatedLogin && relayState) {
|
||||
if (!this.useRelayStateDeepLink) {
|
||||
this.options.logger.debug(
|
||||
`"RelayState" is provided, but deep links support is not enabled for "${this.type}/${this.options.name}" provider.`
|
||||
);
|
||||
} else if (!isInternalURL(relayState, this.options.basePath.serverBasePath)) {
|
||||
this.options.logger.debug(
|
||||
`"RelayState" is provided, but it is not a valid Kibana internal URL.`
|
||||
);
|
||||
} else {
|
||||
this.options.logger.debug(
|
||||
`User will be redirected to the Kibana internal URL specified in "RelayState".`
|
||||
);
|
||||
redirectURLFromRelayState = relayState;
|
||||
const authenticateResponse = await this.options.client.callAsInternalUser(
|
||||
'shield.samlAuthenticate',
|
||||
{
|
||||
body: {
|
||||
ids: !isIdPInitiatedLogin ? [stateRequestId] : [],
|
||||
content: samlResponse,
|
||||
realm: this.realm,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug('Login has been performed with SAML response.');
|
||||
return AuthenticationResult.redirectTo(
|
||||
redirectURLFromRelayState || stateRedirectURL || `${this.options.basePath.get(request)}/`,
|
||||
{ state: { username, accessToken, refreshToken, realm: this.realm } }
|
||||
);
|
||||
|
||||
accessToken = authenticateResponse.access_token;
|
||||
refreshToken = authenticateResponse.refresh_token;
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to log in with SAML response: ${err.message}`);
|
||||
|
||||
|
@ -404,6 +364,43 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
? AuthenticationResult.notHandled()
|
||||
: AuthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
// Now we need to retrieve full user information.
|
||||
let user: Readonly<AuthenticatedUser>;
|
||||
try {
|
||||
user = await this.getUser(request, {
|
||||
authorization: new HTTPAuthorizationHeader('Bearer', accessToken).toString(),
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed to retrieve user using access token: ${err.message}`);
|
||||
return AuthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
// IdP can pass `RelayState` with the deep link in Kibana during IdP initiated login and
|
||||
// depending on the configuration we may need to redirect user to this URL.
|
||||
let redirectURLFromRelayState;
|
||||
if (isIdPInitiatedLogin && relayState) {
|
||||
if (!this.useRelayStateDeepLink) {
|
||||
this.options.logger.debug(
|
||||
`"RelayState" is provided, but deep links support is not enabled for "${this.type}/${this.options.name}" provider.`
|
||||
);
|
||||
} else if (!isInternalURL(relayState, this.options.basePath.serverBasePath)) {
|
||||
this.options.logger.debug(
|
||||
`"RelayState" is provided, but it is not a valid Kibana internal URL.`
|
||||
);
|
||||
} else {
|
||||
this.options.logger.debug(
|
||||
`User will be redirected to the Kibana internal URL specified in "RelayState".`
|
||||
);
|
||||
redirectURLFromRelayState = relayState;
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug('Login has been performed with SAML response.');
|
||||
return AuthenticationResult.redirectTo(
|
||||
redirectURLFromRelayState || stateRedirectURL || `${this.options.basePath.get(request)}/`,
|
||||
{ state: { accessToken, refreshToken, realm: this.realm }, user }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -444,8 +441,6 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
);
|
||||
}
|
||||
|
||||
const newState = payloadAuthenticationResult.state as ProviderState;
|
||||
|
||||
// Now let's invalidate tokens from the existing session.
|
||||
try {
|
||||
this.logger.debug('Perform IdP initiated local logout.');
|
||||
|
@ -458,17 +453,7 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
return AuthenticationResult.failed(err);
|
||||
}
|
||||
|
||||
if (newState.username !== existingState.username) {
|
||||
this.logger.debug(
|
||||
'Login initiated by Identity Provider is for a different user than currently authenticated.'
|
||||
);
|
||||
return AuthenticationResult.redirectTo(
|
||||
`${this.options.basePath.serverBasePath}/security/overwritten_session`,
|
||||
{ state: newState }
|
||||
);
|
||||
}
|
||||
|
||||
this.logger.debug('Login initiated by Identity Provider is for currently authenticated user.');
|
||||
this.logger.debug('IdP initiated login completed successfully.');
|
||||
return payloadAuthenticationResult;
|
||||
}
|
||||
|
||||
|
@ -509,7 +494,7 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
*/
|
||||
private async authenticateViaRefreshToken(
|
||||
request: KibanaRequest,
|
||||
{ username, refreshToken }: ProviderState
|
||||
{ refreshToken }: ProviderState
|
||||
) {
|
||||
this.logger.debug('Trying to refresh access token.');
|
||||
|
||||
|
@ -555,7 +540,7 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
this.logger.debug('Request has been authenticated via refreshed token.');
|
||||
return AuthenticationResult.succeeded(user, {
|
||||
authHeaders,
|
||||
state: { username, realm: this.realm, ...refreshedTokenPair },
|
||||
state: { realm: this.realm, ...refreshedTokenPair },
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.debug(
|
||||
|
@ -640,52 +625,19 @@ export class SAMLAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
/**
|
||||
* Tries to capture full redirect URL (both path and fragment) and initiate SAML handshake.
|
||||
* @param request Request instance.
|
||||
* @param [redirectURLPath] Optional URL path user is supposed to be redirected to after successful
|
||||
* login. If not provided the URL path of the specified request is used.
|
||||
* @param [redirectURLFragment] Optional URL fragment of the URL user is supposed to be redirected
|
||||
* to after successful login. If not provided user will be redirected to the client-side page that
|
||||
* will grab it and redirect user back to Kibana to initiate SAML handshake.
|
||||
*/
|
||||
private captureRedirectURL(
|
||||
request: KibanaRequest,
|
||||
redirectURLPath = `${this.options.basePath.get(request)}${request.url.path}`,
|
||||
redirectURLFragment?: string
|
||||
) {
|
||||
// If the size of the path already exceeds the maximum allowed size of the URL to store in the
|
||||
// session there is no reason to try to capture URL fragment and we start handshake immediately.
|
||||
// In this case user will be redirected to the Kibana home/root after successful login.
|
||||
let redirectURLSize = new ByteSizeValue(Buffer.byteLength(redirectURLPath));
|
||||
if (this.maxRedirectURLSize.isLessThan(redirectURLSize)) {
|
||||
this.logger.warn(
|
||||
`Max URL path size should not exceed ${this.maxRedirectURLSize.toString()} but it was ${redirectURLSize.toString()}. URL is not captured.`
|
||||
);
|
||||
return this.authenticateViaHandshake(request, '');
|
||||
}
|
||||
|
||||
// If URL fragment wasn't specified at all, let's try to capture it.
|
||||
if (redirectURLFragment === undefined) {
|
||||
return AuthenticationResult.redirectTo(
|
||||
`${this.options.basePath.serverBasePath}/internal/security/saml/capture-url-fragment`,
|
||||
{ state: { redirectURL: redirectURLPath, realm: this.realm } }
|
||||
);
|
||||
}
|
||||
|
||||
if (redirectURLFragment.length > 0 && !redirectURLFragment.startsWith('#')) {
|
||||
this.logger.warn('Redirect URL fragment does not start with `#`.');
|
||||
redirectURLFragment = `#${redirectURLFragment}`;
|
||||
}
|
||||
|
||||
let redirectURL = `${redirectURLPath}${redirectURLFragment}`;
|
||||
redirectURLSize = new ByteSizeValue(Buffer.byteLength(redirectURL));
|
||||
if (this.maxRedirectURLSize.isLessThan(redirectURLSize)) {
|
||||
this.logger.warn(
|
||||
`Max URL size should not exceed ${this.maxRedirectURLSize.toString()} but it was ${redirectURLSize.toString()}. Only URL path is captured.`
|
||||
);
|
||||
redirectURL = redirectURLPath;
|
||||
} else {
|
||||
this.logger.debug('Captured redirect URL.');
|
||||
}
|
||||
|
||||
return this.authenticateViaHandshake(request, redirectURL);
|
||||
private captureRedirectURL(request: KibanaRequest) {
|
||||
return AuthenticationResult.redirectTo(
|
||||
`${
|
||||
this.options.basePath.serverBasePath
|
||||
}/internal/security/capture-url?next=${encodeURIComponent(
|
||||
`${this.options.basePath.get(request)}${request.url.path}`
|
||||
)}&providerType=${encodeURIComponent(this.type)}&providerName=${encodeURIComponent(
|
||||
this.options.name
|
||||
)}`,
|
||||
// Here we indicate that current session, if any, should be invalidated. It is a no-op for the
|
||||
// initial handshake, but is essential when both access and refresh tokens are expired.
|
||||
{ state: null }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -427,8 +427,14 @@ describe('TokenAuthenticationProvider', () => {
|
|||
|
||||
await expect(provider.logout(request)).resolves.toEqual(DeauthenticationResult.notHandled());
|
||||
|
||||
expect(mockOptions.tokens.invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to login view if state is `null`.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
await expect(provider.logout(request, null)).resolves.toEqual(
|
||||
DeauthenticationResult.notHandled()
|
||||
DeauthenticationResult.redirectTo('/mock-server-basepath/login?msg=LOGGED_OUT')
|
||||
);
|
||||
|
||||
expect(mockOptions.tokens.invalidate).not.toHaveBeenCalled();
|
||||
|
|
|
@ -128,17 +128,21 @@ export class TokenAuthenticationProvider extends BaseAuthenticationProvider {
|
|||
public async logout(request: KibanaRequest, state?: ProviderState | null) {
|
||||
this.logger.debug(`Trying to log user out via ${request.url.path}.`);
|
||||
|
||||
if (!state) {
|
||||
// Having a `null` state means that provider was specifically called to do a logout, but when
|
||||
// session isn't defined then provider is just being probed whether or not it can perform logout.
|
||||
if (state === undefined) {
|
||||
this.logger.debug('There are no access and refresh tokens to invalidate.');
|
||||
return DeauthenticationResult.notHandled();
|
||||
}
|
||||
|
||||
this.logger.debug('Token-based logout has been initiated by the user.');
|
||||
try {
|
||||
await this.options.tokens.invalidate(state);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed invalidating user's access token: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
if (state) {
|
||||
try {
|
||||
await this.options.tokens.invalidate(state);
|
||||
} catch (err) {
|
||||
this.logger.debug(`Failed invalidating user's access token: ${err.message}`);
|
||||
return DeauthenticationResult.failed(err);
|
||||
}
|
||||
}
|
||||
|
||||
const queryString = request.url.search || `?msg=LOGGED_OUT`;
|
||||
|
|
|
@ -13,8 +13,8 @@ import {
|
|||
mockRegisterPrivilegesWithCluster,
|
||||
} from './service.test.mocks';
|
||||
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
import { CoreStatus, ServiceStatusLevels } from '../../../../../src/core/server';
|
||||
import { Subject } from 'rxjs';
|
||||
import { OnlineStatusRetryScheduler } from '../elasticsearch';
|
||||
import { checkPrivilegesWithRequestFactory } from './check_privileges';
|
||||
import { checkPrivilegesDynamicallyWithRequestFactory } from './check_privileges_dynamically';
|
||||
import { checkSavedObjectsPrivilegesWithRequestFactory } from './check_saved_objects_privileges';
|
||||
|
@ -22,6 +22,7 @@ import { authorizationModeFactory } from './mode';
|
|||
import { privilegesFactory } from './privileges';
|
||||
import { AuthorizationService } from '.';
|
||||
|
||||
import { nextTick } from 'test_utils/enzyme_helpers';
|
||||
import {
|
||||
coreMock,
|
||||
elasticsearchServiceMock,
|
||||
|
@ -29,8 +30,6 @@ import {
|
|||
} from '../../../../../src/core/server/mocks';
|
||||
import { featuresPluginMock } from '../../../features/server/mocks';
|
||||
import { licenseMock } from '../../common/licensing/index.mock';
|
||||
import { SecurityLicense, SecurityLicenseFeatures } from '../../common/licensing';
|
||||
import { nextTick } from 'test_utils/enzyme_helpers';
|
||||
|
||||
const kibanaIndexName = '.a-kibana-index';
|
||||
const application = `kibana-${kibanaIndexName}`;
|
||||
|
@ -68,7 +67,6 @@ it(`#setup returns exposed services`, () => {
|
|||
const authz = authorizationService.setup({
|
||||
http: mockCoreSetup.http,
|
||||
capabilities: mockCoreSetup.capabilities,
|
||||
status: mockCoreSetup.status,
|
||||
clusterClient: mockClusterClient,
|
||||
license: mockLicense,
|
||||
loggers: loggingSystemMock.create(),
|
||||
|
@ -115,31 +113,19 @@ it(`#setup returns exposed services`, () => {
|
|||
});
|
||||
|
||||
describe('#start', () => {
|
||||
let statusSubject: BehaviorSubject<CoreStatus>;
|
||||
let licenseSubject: BehaviorSubject<SecurityLicenseFeatures>;
|
||||
let mockLicense: jest.Mocked<SecurityLicense>;
|
||||
let statusSubject: Subject<OnlineStatusRetryScheduler>;
|
||||
beforeEach(() => {
|
||||
statusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
|
||||
const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient();
|
||||
|
||||
licenseSubject = new BehaviorSubject(({} as unknown) as SecurityLicenseFeatures);
|
||||
mockLicense = licenseMock.create();
|
||||
mockLicense.isEnabled.mockReturnValue(false);
|
||||
mockLicense.features$ = licenseSubject;
|
||||
|
||||
statusSubject = new BehaviorSubject<CoreStatus>({
|
||||
elasticsearch: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
mockCoreSetup.status.core$ = statusSubject;
|
||||
|
||||
const authorizationService = new AuthorizationService();
|
||||
authorizationService.setup({
|
||||
http: mockCoreSetup.http,
|
||||
capabilities: mockCoreSetup.capabilities,
|
||||
status: mockCoreSetup.status,
|
||||
clusterClient: mockClusterClient,
|
||||
license: mockLicense,
|
||||
license: licenseMock.create(),
|
||||
loggers: loggingSystemMock.create(),
|
||||
kibanaIndexName,
|
||||
packageVersion: 'some-version',
|
||||
|
@ -152,95 +138,64 @@ describe('#start', () => {
|
|||
const featuresStart = featuresPluginMock.createStart();
|
||||
featuresStart.getFeatures.mockReturnValue([]);
|
||||
|
||||
authorizationService.start({ clusterClient: mockClusterClient, features: featuresStart });
|
||||
authorizationService.start({
|
||||
clusterClient: mockClusterClient,
|
||||
features: featuresStart,
|
||||
online$: statusSubject.asObservable(),
|
||||
});
|
||||
|
||||
// ES and license aren't available yet.
|
||||
expect(mockRegisterPrivilegesWithCluster).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('registers cluster privileges', async () => {
|
||||
// ES is available now, but not license.
|
||||
statusSubject.next({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
expect(mockRegisterPrivilegesWithCluster).not.toHaveBeenCalled();
|
||||
|
||||
// Both ES and license are available now.
|
||||
mockLicense.isEnabled.mockReturnValue(true);
|
||||
licenseSubject.next(({} as unknown) as SecurityLicenseFeatures);
|
||||
const retryScheduler = jest.fn();
|
||||
statusSubject.next({ scheduleRetry: retryScheduler });
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(1);
|
||||
|
||||
await nextTick();
|
||||
|
||||
// New changes still trigger privileges re-registration.
|
||||
licenseSubject.next(({} as unknown) as SecurityLicenseFeatures);
|
||||
statusSubject.next({ scheduleRetry: retryScheduler });
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(2);
|
||||
expect(retryScheduler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('schedules retries if fails to register cluster privileges', async () => {
|
||||
jest.useFakeTimers();
|
||||
|
||||
mockRegisterPrivilegesWithCluster.mockRejectedValue(new Error('Some error'));
|
||||
|
||||
// Both ES and license are available.
|
||||
mockLicense.isEnabled.mockReturnValue(true);
|
||||
statusSubject.next({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(1);
|
||||
const retryScheduler = jest.fn();
|
||||
statusSubject.next({ scheduleRetry: retryScheduler });
|
||||
await nextTick();
|
||||
|
||||
// Next retry isn't performed immediately, retry happens only after a timeout.
|
||||
await nextTick();
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(1);
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(2);
|
||||
expect(retryScheduler).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Delay between consequent retries is increasing.
|
||||
statusSubject.next({ scheduleRetry: retryScheduler });
|
||||
await nextTick();
|
||||
jest.advanceTimersByTime(100);
|
||||
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(2);
|
||||
await nextTick();
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(3);
|
||||
expect(retryScheduler).toHaveBeenCalledTimes(2);
|
||||
|
||||
// When call finally succeeds retries aren't scheduled anymore.
|
||||
mockRegisterPrivilegesWithCluster.mockResolvedValue(undefined);
|
||||
statusSubject.next({ scheduleRetry: retryScheduler });
|
||||
await nextTick();
|
||||
jest.runAllTimers();
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(4);
|
||||
await nextTick();
|
||||
jest.runAllTimers();
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(4);
|
||||
|
||||
// New changes still trigger privileges re-registration.
|
||||
licenseSubject.next(({} as unknown) as SecurityLicenseFeatures);
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(5);
|
||||
expect(mockRegisterPrivilegesWithCluster).toHaveBeenCalledTimes(3);
|
||||
expect(retryScheduler).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('#stop unsubscribes from license and ES updates.', () => {
|
||||
it('#stop unsubscribes from license and ES updates.', async () => {
|
||||
const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient();
|
||||
|
||||
const licenseSubject = new BehaviorSubject(({} as unknown) as SecurityLicenseFeatures);
|
||||
const mockLicense = licenseMock.create();
|
||||
mockLicense.isEnabled.mockReturnValue(false);
|
||||
mockLicense.features$ = licenseSubject;
|
||||
|
||||
const statusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
mockCoreSetup.status.core$ = new BehaviorSubject<CoreStatus>({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
});
|
||||
|
||||
const authorizationService = new AuthorizationService();
|
||||
authorizationService.setup({
|
||||
http: mockCoreSetup.http,
|
||||
capabilities: mockCoreSetup.capabilities,
|
||||
status: mockCoreSetup.status,
|
||||
clusterClient: mockClusterClient,
|
||||
license: mockLicense,
|
||||
license: licenseMock.create(),
|
||||
loggers: loggingSystemMock.create(),
|
||||
kibanaIndexName,
|
||||
packageVersion: 'some-version',
|
||||
|
@ -252,12 +207,19 @@ it('#stop unsubscribes from license and ES updates.', () => {
|
|||
|
||||
const featuresStart = featuresPluginMock.createStart();
|
||||
featuresStart.getFeatures.mockReturnValue([]);
|
||||
authorizationService.start({ clusterClient: mockClusterClient, features: featuresStart });
|
||||
authorizationService.start({
|
||||
clusterClient: mockClusterClient,
|
||||
features: featuresStart,
|
||||
online$: statusSubject.asObservable(),
|
||||
});
|
||||
|
||||
authorizationService.stop();
|
||||
|
||||
// After stop we don't register privileges even if all requirements are met.
|
||||
mockLicense.isEnabled.mockReturnValue(true);
|
||||
licenseSubject.next(({} as unknown) as SecurityLicenseFeatures);
|
||||
// After stop we don't register privileges even if status changes.
|
||||
const retryScheduler = jest.fn();
|
||||
statusSubject.next({ scheduleRetry: retryScheduler });
|
||||
await nextTick();
|
||||
|
||||
expect(mockRegisterPrivilegesWithCluster).not.toHaveBeenCalled();
|
||||
expect(retryScheduler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
|
|
@ -4,16 +4,13 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { combineLatest, BehaviorSubject, Subscription } from 'rxjs';
|
||||
import { distinctUntilChanged, filter } from 'rxjs/operators';
|
||||
import { Subscription, Observable } from 'rxjs';
|
||||
import { UICapabilities } from 'ui/capabilities';
|
||||
import {
|
||||
LoggerFactory,
|
||||
KibanaRequest,
|
||||
ILegacyClusterClient,
|
||||
ServiceStatusLevels,
|
||||
Logger,
|
||||
StatusServiceSetup,
|
||||
HttpServiceSetup,
|
||||
CapabilitiesSetup,
|
||||
} from '../../../../../src/core/server';
|
||||
|
@ -44,6 +41,7 @@ import { validateReservedPrivileges } from './validate_reserved_privileges';
|
|||
import { registerPrivilegesWithCluster } from './register_privileges_with_cluster';
|
||||
import { APPLICATION_PREFIX } from '../../common/constants';
|
||||
import { SecurityLicense } from '../../common/licensing';
|
||||
import { OnlineStatusRetryScheduler } from '../elasticsearch';
|
||||
|
||||
export { Actions } from './actions';
|
||||
export { CheckSavedObjectsPrivileges } from './check_saved_objects_privileges';
|
||||
|
@ -52,7 +50,6 @@ export { featurePrivilegeIterator } from './privileges';
|
|||
interface AuthorizationServiceSetupParams {
|
||||
packageVersion: string;
|
||||
http: HttpServiceSetup;
|
||||
status: StatusServiceSetup;
|
||||
capabilities: CapabilitiesSetup;
|
||||
clusterClient: ILegacyClusterClient;
|
||||
license: SecurityLicense;
|
||||
|
@ -65,6 +62,7 @@ interface AuthorizationServiceSetupParams {
|
|||
interface AuthorizationServiceStartParams {
|
||||
features: FeaturesPluginStart;
|
||||
clusterClient: ILegacyClusterClient;
|
||||
online$: Observable<OnlineStatusRetryScheduler>;
|
||||
}
|
||||
|
||||
export interface AuthorizationServiceSetup {
|
||||
|
@ -79,8 +77,6 @@ export interface AuthorizationServiceSetup {
|
|||
|
||||
export class AuthorizationService {
|
||||
private logger!: Logger;
|
||||
private license!: SecurityLicense;
|
||||
private status!: StatusServiceSetup;
|
||||
private applicationName!: string;
|
||||
private privileges!: PrivilegesService;
|
||||
|
||||
|
@ -89,7 +85,6 @@ export class AuthorizationService {
|
|||
setup({
|
||||
http,
|
||||
capabilities,
|
||||
status,
|
||||
packageVersion,
|
||||
clusterClient,
|
||||
license,
|
||||
|
@ -99,8 +94,6 @@ export class AuthorizationService {
|
|||
getSpacesService,
|
||||
}: AuthorizationServiceSetupParams): AuthorizationServiceSetup {
|
||||
this.logger = loggers.get('authorization');
|
||||
this.license = license;
|
||||
this.status = status;
|
||||
this.applicationName = `${APPLICATION_PREFIX}${kibanaIndexName}`;
|
||||
|
||||
const mode = authorizationModeFactory(license);
|
||||
|
@ -158,12 +151,23 @@ export class AuthorizationService {
|
|||
return authz;
|
||||
}
|
||||
|
||||
start({ clusterClient, features }: AuthorizationServiceStartParams) {
|
||||
start({ clusterClient, features, online$ }: AuthorizationServiceStartParams) {
|
||||
const allFeatures = features.getFeatures();
|
||||
validateFeaturePrivileges(allFeatures);
|
||||
validateReservedPrivileges(allFeatures);
|
||||
|
||||
this.registerPrivileges(clusterClient);
|
||||
this.statusSubscription = online$.subscribe(async ({ scheduleRetry }) => {
|
||||
try {
|
||||
await registerPrivilegesWithCluster(
|
||||
this.logger,
|
||||
this.privileges,
|
||||
this.applicationName,
|
||||
clusterClient
|
||||
);
|
||||
} catch (err) {
|
||||
scheduleRetry();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
stop() {
|
||||
|
@ -172,50 +176,4 @@ export class AuthorizationService {
|
|||
this.statusSubscription = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private registerPrivileges(clusterClient: ILegacyClusterClient) {
|
||||
const RETRY_SCALE_DURATION = 100;
|
||||
const RETRY_TIMEOUT_MAX = 10000;
|
||||
const retries$ = new BehaviorSubject(0);
|
||||
let retryTimeout: NodeJS.Timeout;
|
||||
|
||||
// Register cluster privileges once Elasticsearch is available and Security plugin is enabled.
|
||||
this.statusSubscription = combineLatest([
|
||||
this.status.core$,
|
||||
this.license.features$,
|
||||
retries$.asObservable().pipe(
|
||||
// We shouldn't emit new value if retry counter is reset. This comparator isn't called for
|
||||
// the initial value.
|
||||
distinctUntilChanged((prev, curr) => prev === curr || curr === 0)
|
||||
),
|
||||
])
|
||||
.pipe(
|
||||
filter(
|
||||
([status]) =>
|
||||
this.license.isEnabled() && status.elasticsearch.level === ServiceStatusLevels.available
|
||||
)
|
||||
)
|
||||
.subscribe(async () => {
|
||||
// If status or license change occurred before retry timeout we should cancel it.
|
||||
if (retryTimeout) {
|
||||
clearTimeout(retryTimeout);
|
||||
}
|
||||
|
||||
try {
|
||||
await registerPrivilegesWithCluster(
|
||||
this.logger,
|
||||
this.privileges,
|
||||
this.applicationName,
|
||||
clusterClient
|
||||
);
|
||||
retries$.next(0);
|
||||
} catch (err) {
|
||||
const retriesElapsed = retries$.getValue() + 1;
|
||||
retryTimeout = setTimeout(
|
||||
() => retries$.next(retriesElapsed),
|
||||
Math.min(retriesElapsed * RETRY_SCALE_DURATION, RETRY_TIMEOUT_MAX)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -50,6 +50,7 @@ describe('config schema', () => {
|
|||
"loginAssistanceMessage": "",
|
||||
"secureCookies": false,
|
||||
"session": Object {
|
||||
"cleanupInterval": "PT1H",
|
||||
"idleTimeout": null,
|
||||
"lifespan": null,
|
||||
},
|
||||
|
@ -95,6 +96,7 @@ describe('config schema', () => {
|
|||
"loginAssistanceMessage": "",
|
||||
"secureCookies": false,
|
||||
"session": Object {
|
||||
"cleanupInterval": "PT1H",
|
||||
"idleTimeout": null,
|
||||
"lifespan": null,
|
||||
},
|
||||
|
@ -139,6 +141,7 @@ describe('config schema', () => {
|
|||
"loginAssistanceMessage": "",
|
||||
"secureCookies": false,
|
||||
"session": Object {
|
||||
"cleanupInterval": "PT1H",
|
||||
"idleTimeout": null,
|
||||
"lifespan": null,
|
||||
},
|
||||
|
@ -272,9 +275,6 @@ describe('config schema', () => {
|
|||
"saml",
|
||||
],
|
||||
"saml": Object {
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"realm": "realm-1",
|
||||
},
|
||||
"selector": Object {},
|
||||
|
@ -294,13 +294,10 @@ describe('config schema', () => {
|
|||
authc: { providers: ['saml'], saml: { realm: 'realm-1' } },
|
||||
}).authc.saml
|
||||
).toMatchInlineSnapshot(`
|
||||
Object {
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"realm": "realm-1",
|
||||
}
|
||||
`);
|
||||
Object {
|
||||
"realm": "realm-1",
|
||||
}
|
||||
`);
|
||||
|
||||
expect(
|
||||
ConfigSchema.validate({
|
||||
|
@ -665,9 +662,6 @@ describe('config schema', () => {
|
|||
"saml": Object {
|
||||
"saml1": Object {
|
||||
"enabled": true,
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"order": 0,
|
||||
"realm": "saml1",
|
||||
"showInSelector": true,
|
||||
|
@ -685,9 +679,6 @@ describe('config schema', () => {
|
|||
},
|
||||
"saml3": Object {
|
||||
"enabled": true,
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"order": 2,
|
||||
"realm": "saml3",
|
||||
"showInSelector": true,
|
||||
|
@ -774,9 +765,6 @@ describe('config schema', () => {
|
|||
"saml": Object {
|
||||
"basic1": Object {
|
||||
"enabled": false,
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"order": 3,
|
||||
"realm": "saml3",
|
||||
"showInSelector": true,
|
||||
|
@ -784,9 +772,6 @@ describe('config schema', () => {
|
|||
},
|
||||
"saml1": Object {
|
||||
"enabled": true,
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"order": 1,
|
||||
"realm": "saml1",
|
||||
"showInSelector": true,
|
||||
|
@ -794,9 +779,6 @@ describe('config schema', () => {
|
|||
},
|
||||
"saml2": Object {
|
||||
"enabled": true,
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"order": 2,
|
||||
"realm": "saml2",
|
||||
"showInSelector": true,
|
||||
|
@ -807,6 +789,16 @@ describe('config schema', () => {
|
|||
`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('session', () => {
|
||||
it('should throw error if xpack.security.session.cleanupInterval is less than 10 seconds', () => {
|
||||
expect(() =>
|
||||
ConfigSchema.validate({ session: { cleanupInterval: '9s' } })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[session.cleanupInterval]: the value must be greater or equal to 10 seconds."`
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createConfig()', () => {
|
||||
|
@ -901,9 +893,6 @@ describe('createConfig()', () => {
|
|||
"saml": Object {
|
||||
"saml": Object {
|
||||
"enabled": true,
|
||||
"maxRedirectURLSize": ByteSizeValue {
|
||||
"valueInBytes": 2048,
|
||||
},
|
||||
"order": 0,
|
||||
"realm": "saml-realm",
|
||||
"showInSelector": true,
|
||||
|
|
|
@ -96,7 +96,7 @@ const providersConfigSchema = schema.object(
|
|||
schema.object({
|
||||
...getCommonProviderSchemaProperties(),
|
||||
realm: schema.string(),
|
||||
maxRedirectURLSize: schema.byteSize({ defaultValue: '2kb' }),
|
||||
maxRedirectURLSize: schema.maybe(schema.byteSize()),
|
||||
useRelayStateDeepLink: schema.boolean({ defaultValue: false }),
|
||||
})
|
||||
)
|
||||
|
@ -149,6 +149,14 @@ export const ConfigSchema = schema.object({
|
|||
session: schema.object({
|
||||
idleTimeout: schema.nullable(schema.duration()),
|
||||
lifespan: schema.nullable(schema.duration()),
|
||||
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(
|
||||
|
@ -181,7 +189,7 @@ export const ConfigSchema = schema.object({
|
|||
'saml',
|
||||
schema.object({
|
||||
realm: schema.string(),
|
||||
maxRedirectURLSize: schema.byteSize({ defaultValue: '2kb' }),
|
||||
maxRedirectURLSize: schema.maybe(schema.byteSize()),
|
||||
})
|
||||
),
|
||||
http: schema.object({
|
||||
|
|
|
@ -0,0 +1,222 @@
|
|||
/*
|
||||
* 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 { BehaviorSubject } from 'rxjs';
|
||||
import {
|
||||
ILegacyCustomClusterClient,
|
||||
ServiceStatusLevels,
|
||||
CoreStatus,
|
||||
} from '../../../../../src/core/server';
|
||||
import { SecurityLicense, SecurityLicenseFeatures } from '../../common/licensing';
|
||||
import { elasticsearchClientPlugin } from './elasticsearch_client_plugin';
|
||||
import { ElasticsearchService } from './elasticsearch_service';
|
||||
|
||||
import {
|
||||
coreMock,
|
||||
elasticsearchServiceMock,
|
||||
loggingSystemMock,
|
||||
} from '../../../../../src/core/server/mocks';
|
||||
import { licenseMock } from '../../common/licensing/index.mock';
|
||||
import { nextTick } from 'test_utils/enzyme_helpers';
|
||||
|
||||
describe('ElasticsearchService', () => {
|
||||
let service: ElasticsearchService;
|
||||
beforeEach(() => {
|
||||
service = new ElasticsearchService(loggingSystemMock.createLogger());
|
||||
});
|
||||
|
||||
describe('setup()', () => {
|
||||
it('exposes proper contract', () => {
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
const mockClusterClient = elasticsearchServiceMock.createLegacyCustomClusterClient();
|
||||
mockCoreSetup.elasticsearch.legacy.createClient.mockReturnValue(mockClusterClient);
|
||||
|
||||
expect(
|
||||
service.setup({
|
||||
elasticsearch: mockCoreSetup.elasticsearch,
|
||||
status: mockCoreSetup.status,
|
||||
license: licenseMock.create(),
|
||||
})
|
||||
).toEqual({ clusterClient: mockClusterClient });
|
||||
|
||||
expect(mockCoreSetup.elasticsearch.legacy.createClient).toHaveBeenCalledTimes(1);
|
||||
expect(mockCoreSetup.elasticsearch.legacy.createClient).toHaveBeenCalledWith('security', {
|
||||
plugins: [elasticsearchClientPlugin],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('start()', () => {
|
||||
let mockClusterClient: ILegacyCustomClusterClient;
|
||||
let mockLicense: jest.Mocked<SecurityLicense>;
|
||||
let mockStatusSubject: BehaviorSubject<CoreStatus>;
|
||||
let mockLicenseSubject: BehaviorSubject<SecurityLicenseFeatures>;
|
||||
beforeEach(() => {
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
mockClusterClient = elasticsearchServiceMock.createLegacyCustomClusterClient();
|
||||
mockCoreSetup.elasticsearch.legacy.createClient.mockReturnValue(mockClusterClient);
|
||||
|
||||
mockLicenseSubject = new BehaviorSubject(({} as unknown) as SecurityLicenseFeatures);
|
||||
mockLicense = licenseMock.create();
|
||||
mockLicense.isEnabled.mockReturnValue(false);
|
||||
mockLicense.features$ = mockLicenseSubject;
|
||||
|
||||
mockStatusSubject = new BehaviorSubject<CoreStatus>({
|
||||
elasticsearch: {
|
||||
level: ServiceStatusLevels.unavailable,
|
||||
summary: 'Service is NOT working',
|
||||
},
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
mockCoreSetup.status.core$ = mockStatusSubject;
|
||||
|
||||
service.setup({
|
||||
elasticsearch: mockCoreSetup.elasticsearch,
|
||||
status: mockCoreSetup.status,
|
||||
license: mockLicense,
|
||||
});
|
||||
});
|
||||
|
||||
it('exposes proper contract', () => {
|
||||
expect(service.start()).toEqual({
|
||||
clusterClient: mockClusterClient,
|
||||
watchOnlineStatus$: expect.any(Function),
|
||||
});
|
||||
});
|
||||
|
||||
it('`watchOnlineStatus$` allows tracking of Elasticsearch status', () => {
|
||||
const mockHandler = jest.fn();
|
||||
service.start().watchOnlineStatus$().subscribe(mockHandler);
|
||||
|
||||
// Neither ES nor license is available yet.
|
||||
expect(mockHandler).not.toHaveBeenCalled();
|
||||
|
||||
// ES is available now, but not license.
|
||||
mockStatusSubject.next({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
expect(mockHandler).not.toHaveBeenCalled();
|
||||
|
||||
// Both ES and license are available.
|
||||
mockLicense.isEnabled.mockReturnValue(true);
|
||||
mockStatusSubject.next({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
expect(mockHandler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('`watchOnlineStatus$` allows to schedule retry', async () => {
|
||||
jest.useFakeTimers();
|
||||
|
||||
// Both ES and license are available.
|
||||
mockLicense.isEnabled.mockReturnValue(true);
|
||||
mockStatusSubject.next({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
|
||||
const mockHandler = jest.fn();
|
||||
service.start().watchOnlineStatus$().subscribe(mockHandler);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [[{ scheduleRetry }]] = mockHandler.mock.calls;
|
||||
|
||||
// Next retry isn't performed immediately, retry happens only after a timeout.
|
||||
scheduleRetry();
|
||||
await nextTick();
|
||||
expect(mockHandler).toHaveBeenCalledTimes(1);
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Delay between consequent retries is increasing.
|
||||
scheduleRetry();
|
||||
await nextTick();
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(2);
|
||||
await nextTick();
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(3);
|
||||
|
||||
// Delay between consequent retries is increasing.
|
||||
scheduleRetry();
|
||||
await nextTick();
|
||||
jest.advanceTimersByTime(200);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(3);
|
||||
await nextTick();
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(4);
|
||||
|
||||
// If `scheduleRetry` isn't called retries aren't scheduled anymore.
|
||||
await nextTick();
|
||||
jest.runAllTimers();
|
||||
expect(mockHandler).toHaveBeenCalledTimes(4);
|
||||
|
||||
// New changes still trigger handler once again and reset retry timer.
|
||||
mockLicenseSubject.next(({} as unknown) as SecurityLicenseFeatures);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(5);
|
||||
|
||||
// Retry timer is reset.
|
||||
scheduleRetry();
|
||||
await nextTick();
|
||||
expect(mockHandler).toHaveBeenCalledTimes(5);
|
||||
jest.advanceTimersByTime(100);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(6);
|
||||
});
|
||||
|
||||
it('`watchOnlineStatus$` cancels scheduled retry if status changes before retry timeout fires', async () => {
|
||||
jest.useFakeTimers();
|
||||
|
||||
// Both ES and license are available.
|
||||
mockLicense.isEnabled.mockReturnValue(true);
|
||||
mockStatusSubject.next({
|
||||
elasticsearch: { level: ServiceStatusLevels.available, summary: 'Service is working' },
|
||||
savedObjects: { level: ServiceStatusLevels.unavailable, summary: 'Service is NOT working' },
|
||||
});
|
||||
|
||||
const mockHandler = jest.fn();
|
||||
service.start().watchOnlineStatus$().subscribe(mockHandler);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [[{ scheduleRetry }]] = mockHandler.mock.calls;
|
||||
|
||||
// Schedule a retry.
|
||||
scheduleRetry();
|
||||
await nextTick();
|
||||
expect(mockHandler).toHaveBeenCalledTimes(1);
|
||||
|
||||
// New changes should immediately call handler.
|
||||
mockLicenseSubject.next(({} as unknown) as SecurityLicenseFeatures);
|
||||
expect(mockHandler).toHaveBeenCalledTimes(2);
|
||||
|
||||
// Retry timeout should have been cancelled.
|
||||
await nextTick();
|
||||
jest.runAllTimers();
|
||||
expect(mockHandler).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stop()', () => {
|
||||
it('properly closes cluster client instance', () => {
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
const mockClusterClient = elasticsearchServiceMock.createLegacyCustomClusterClient();
|
||||
mockCoreSetup.elasticsearch.legacy.createClient.mockReturnValue(mockClusterClient);
|
||||
|
||||
service.setup({
|
||||
elasticsearch: mockCoreSetup.elasticsearch,
|
||||
status: mockCoreSetup.status,
|
||||
license: licenseMock.create(),
|
||||
});
|
||||
|
||||
expect(mockClusterClient.close).not.toHaveBeenCalled();
|
||||
|
||||
service.stop();
|
||||
|
||||
expect(mockClusterClient.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,130 @@
|
|||
/*
|
||||
* 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 { BehaviorSubject, combineLatest, Observable } from 'rxjs';
|
||||
import { distinctUntilChanged, filter, map, shareReplay, tap } from 'rxjs/operators';
|
||||
import {
|
||||
ILegacyClusterClient,
|
||||
ILegacyCustomClusterClient,
|
||||
Logger,
|
||||
ServiceStatusLevels,
|
||||
StatusServiceSetup,
|
||||
ElasticsearchServiceSetup as CoreElasticsearchServiceSetup,
|
||||
} from '../../../../../src/core/server';
|
||||
import { SecurityLicense } from '../../common/licensing';
|
||||
import { elasticsearchClientPlugin } from './elasticsearch_client_plugin';
|
||||
|
||||
export interface ElasticsearchServiceSetupParams {
|
||||
readonly elasticsearch: CoreElasticsearchServiceSetup;
|
||||
readonly status: StatusServiceSetup;
|
||||
readonly license: SecurityLicense;
|
||||
}
|
||||
|
||||
export interface ElasticsearchServiceSetup {
|
||||
readonly clusterClient: ILegacyClusterClient;
|
||||
}
|
||||
|
||||
export interface ElasticsearchServiceStart {
|
||||
readonly clusterClient: ILegacyClusterClient;
|
||||
readonly watchOnlineStatus$: () => Observable<OnlineStatusRetryScheduler>;
|
||||
}
|
||||
|
||||
export interface OnlineStatusRetryScheduler {
|
||||
scheduleRetry: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service responsible for interactions with the Elasticsearch.
|
||||
*/
|
||||
export class ElasticsearchService {
|
||||
readonly #logger: Logger;
|
||||
#clusterClient?: ILegacyCustomClusterClient;
|
||||
#coreStatus$!: Observable<boolean>;
|
||||
|
||||
constructor(logger: Logger) {
|
||||
this.#logger = logger;
|
||||
}
|
||||
|
||||
setup({
|
||||
elasticsearch,
|
||||
status,
|
||||
license,
|
||||
}: ElasticsearchServiceSetupParams): ElasticsearchServiceSetup {
|
||||
this.#clusterClient = elasticsearch.legacy.createClient('security', {
|
||||
plugins: [elasticsearchClientPlugin],
|
||||
});
|
||||
|
||||
this.#coreStatus$ = combineLatest([status.core$, license.features$]).pipe(
|
||||
map(
|
||||
([coreStatus]) =>
|
||||
license.isEnabled() && coreStatus.elasticsearch.level === ServiceStatusLevels.available
|
||||
),
|
||||
shareReplay(1)
|
||||
);
|
||||
|
||||
return { clusterClient: this.#clusterClient };
|
||||
}
|
||||
|
||||
start(): ElasticsearchServiceStart {
|
||||
return {
|
||||
clusterClient: this.#clusterClient!,
|
||||
|
||||
// We'll need to get rid of this as soon as Core's Elasticsearch service exposes this
|
||||
// functionality in the scope of https://github.com/elastic/kibana/issues/41983.
|
||||
watchOnlineStatus$: () => {
|
||||
const RETRY_SCALE_DURATION = 100;
|
||||
const RETRY_TIMEOUT_MAX = 10000;
|
||||
const retries$ = new BehaviorSubject(0);
|
||||
|
||||
const retryScheduler = {
|
||||
scheduleRetry: () => {
|
||||
const retriesElapsed = retries$.getValue() + 1;
|
||||
const nextRetryTimeout = Math.min(
|
||||
retriesElapsed * RETRY_SCALE_DURATION,
|
||||
RETRY_TIMEOUT_MAX
|
||||
);
|
||||
|
||||
this.#logger.debug(`Scheduling re-try in ${nextRetryTimeout} ms.`);
|
||||
|
||||
retryTimeout = setTimeout(() => retries$.next(retriesElapsed), nextRetryTimeout);
|
||||
},
|
||||
};
|
||||
|
||||
let retryTimeout: NodeJS.Timeout;
|
||||
return combineLatest([
|
||||
this.#coreStatus$.pipe(
|
||||
tap(() => {
|
||||
// If status or license change occurred before retry timeout we should cancel
|
||||
// it and reset retry counter.
|
||||
if (retryTimeout) {
|
||||
clearTimeout(retryTimeout);
|
||||
}
|
||||
|
||||
if (retries$.value > 0) {
|
||||
retries$.next(0);
|
||||
}
|
||||
})
|
||||
),
|
||||
retries$.asObservable().pipe(
|
||||
// We shouldn't emit new value if retry counter is reset. This comparator isn't called for
|
||||
// the initial value.
|
||||
distinctUntilChanged((prev, curr) => prev === curr || curr === 0)
|
||||
),
|
||||
]).pipe(
|
||||
filter(([isAvailable]) => isAvailable),
|
||||
map(() => retryScheduler)
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.#clusterClient) {
|
||||
this.#clusterClient.close();
|
||||
this.#clusterClient = undefined;
|
||||
}
|
||||
}
|
||||
}
|
12
x-pack/plugins/security/server/elasticsearch/index.ts
Normal file
12
x-pack/plugins/security/server/elasticsearch/index.ts
Normal file
|
@ -0,0 +1,12 @@
|
|||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export {
|
||||
ElasticsearchService,
|
||||
ElasticsearchServiceSetup,
|
||||
ElasticsearchServiceStart,
|
||||
OnlineStatusRetryScheduler,
|
||||
} from './elasticsearch_service';
|
|
@ -36,6 +36,7 @@ export const config: PluginConfigDescriptor<TypeOf<typeof ConfigSchema>> = {
|
|||
deprecations: ({ rename, unused }) => [
|
||||
rename('sessionTimeout', 'session.idleTimeout'),
|
||||
unused('authorization.legacyFallback.enabled'),
|
||||
unused('authc.saml.maxRedirectURLSize'),
|
||||
// Deprecation warning for the old array-based format of `xpack.security.authc.providers`.
|
||||
(settings, fromPath, log) => {
|
||||
if (Array.isArray(settings?.xpack?.security?.authc?.providers)) {
|
||||
|
@ -65,6 +66,19 @@ export const config: PluginConfigDescriptor<TypeOf<typeof ConfigSchema>> = {
|
|||
}
|
||||
return settings;
|
||||
},
|
||||
(settings, fromPath, log) => {
|
||||
const samlProviders = (settings?.xpack?.security?.authc?.providers?.saml ?? {}) as Record<
|
||||
string,
|
||||
any
|
||||
>;
|
||||
if (Object.values(samlProviders).find((provider) => !!provider.maxRedirectURLSize)) {
|
||||
log(
|
||||
'`xpack.security.authc.providers.saml.<provider-name>.maxRedirectURLSize` is deprecated and is no longer used'
|
||||
);
|
||||
}
|
||||
|
||||
return settings;
|
||||
},
|
||||
],
|
||||
exposeToBrowser: {
|
||||
loginAssistanceMessage: true,
|
||||
|
|
|
@ -7,10 +7,11 @@
|
|||
import { of } from 'rxjs';
|
||||
import { ByteSizeValue } from '@kbn/config-schema';
|
||||
import { ILegacyCustomClusterClient } from '../../../../src/core/server';
|
||||
import { elasticsearchClientPlugin } from './elasticsearch_client_plugin';
|
||||
import { ConfigSchema } from './config';
|
||||
import { Plugin, PluginSetupDependencies } from './plugin';
|
||||
|
||||
import { coreMock, elasticsearchServiceMock } from '../../../../src/core/server/mocks';
|
||||
import { taskManagerMock } from '../../task_manager/server/mocks';
|
||||
|
||||
describe('Security Plugin', () => {
|
||||
let plugin: Plugin;
|
||||
|
@ -19,20 +20,15 @@ describe('Security Plugin', () => {
|
|||
let mockDependencies: PluginSetupDependencies;
|
||||
beforeEach(() => {
|
||||
plugin = new Plugin(
|
||||
coreMock.createPluginInitializerContext({
|
||||
cookieName: 'sid',
|
||||
session: {
|
||||
idleTimeout: 1500,
|
||||
lifespan: null,
|
||||
},
|
||||
audit: { enabled: false },
|
||||
authc: {
|
||||
selector: { enabled: false },
|
||||
providers: ['saml', 'token'],
|
||||
saml: { realm: 'saml1', maxRedirectURLSize: new ByteSizeValue(2048) },
|
||||
http: { enabled: true, autoSchemesEnabled: true, schemes: ['apikey'] },
|
||||
},
|
||||
})
|
||||
coreMock.createPluginInitializerContext(
|
||||
ConfigSchema.validate({
|
||||
session: { idleTimeout: 1500 },
|
||||
authc: {
|
||||
providers: ['saml', 'token'],
|
||||
saml: { realm: 'saml1', maxRedirectURLSize: new ByteSizeValue(2048) },
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
mockCoreSetup = coreMock.createSetup();
|
||||
|
@ -48,6 +44,7 @@ describe('Security Plugin', () => {
|
|||
|
||||
mockDependencies = ({
|
||||
licensing: { license$: of({}), featureUsage: { register: jest.fn() } },
|
||||
taskManager: taskManagerMock.createSetup(),
|
||||
} as unknown) as PluginSetupDependencies;
|
||||
});
|
||||
|
||||
|
@ -116,26 +113,13 @@ describe('Security Plugin', () => {
|
|||
}
|
||||
`);
|
||||
});
|
||||
|
||||
it('properly creates cluster client instance', async () => {
|
||||
await plugin.setup(mockCoreSetup, mockDependencies);
|
||||
|
||||
expect(mockCoreSetup.elasticsearch.legacy.createClient).toHaveBeenCalledTimes(1);
|
||||
expect(mockCoreSetup.elasticsearch.legacy.createClient).toHaveBeenCalledWith('security', {
|
||||
plugins: [elasticsearchClientPlugin],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('stop()', () => {
|
||||
beforeEach(async () => await plugin.setup(mockCoreSetup, mockDependencies));
|
||||
|
||||
it('properly closes cluster client instance', async () => {
|
||||
expect(mockClusterClient.close).not.toHaveBeenCalled();
|
||||
|
||||
it('close does not throw', async () => {
|
||||
await plugin.stop();
|
||||
|
||||
expect(mockClusterClient.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -9,7 +9,6 @@ import { first, map } from 'rxjs/operators';
|
|||
import { TypeOf } from '@kbn/config-schema';
|
||||
import {
|
||||
deepFreeze,
|
||||
ILegacyCustomClusterClient,
|
||||
CoreSetup,
|
||||
CoreStart,
|
||||
Logger,
|
||||
|
@ -21,6 +20,7 @@ import {
|
|||
PluginStartContract as FeaturesPluginStart,
|
||||
} from '../../features/server';
|
||||
import { LicensingPluginSetup, LicensingPluginStart } from '../../licensing/server';
|
||||
import { TaskManagerSetupContract, TaskManagerStartContract } from '../../task_manager/server';
|
||||
|
||||
import { Authentication, setupAuthentication } from './authentication';
|
||||
import { AuthorizationService, AuthorizationServiceSetup } from './authorization';
|
||||
|
@ -29,8 +29,9 @@ import { defineRoutes } from './routes';
|
|||
import { SecurityLicenseService, SecurityLicense } from '../common/licensing';
|
||||
import { setupSavedObjects } from './saved_objects';
|
||||
import { AuditService, SecurityAuditLogger, AuditServiceSetup } from './audit';
|
||||
import { elasticsearchClientPlugin } from './elasticsearch_client_plugin';
|
||||
import { SecurityFeatureUsageService, SecurityFeatureUsageServiceStart } from './feature_usage';
|
||||
import { ElasticsearchService } from './elasticsearch';
|
||||
import { SessionManagementService } from './session_management';
|
||||
|
||||
export type SpacesService = Pick<
|
||||
SpacesPluginSetup['spacesService'],
|
||||
|
@ -72,11 +73,13 @@ export interface SecurityPluginSetup {
|
|||
export interface PluginSetupDependencies {
|
||||
features: FeaturesPluginSetup;
|
||||
licensing: LicensingPluginSetup;
|
||||
taskManager: TaskManagerSetupContract;
|
||||
}
|
||||
|
||||
export interface PluginStartDependencies {
|
||||
features: FeaturesPluginStart;
|
||||
licensing: LicensingPluginStart;
|
||||
taskManager: TaskManagerStartContract;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -84,7 +87,6 @@ export interface PluginStartDependencies {
|
|||
*/
|
||||
export class Plugin {
|
||||
private readonly logger: Logger;
|
||||
private clusterClient?: ILegacyCustomClusterClient;
|
||||
private spacesService?: SpacesService | symbol = Symbol('not accessed');
|
||||
private securityLicenseService?: SecurityLicenseService;
|
||||
|
||||
|
@ -99,6 +101,12 @@ export class Plugin {
|
|||
|
||||
private readonly auditService = new AuditService(this.initializerContext.logger.get('audit'));
|
||||
private readonly authorizationService = new AuthorizationService();
|
||||
private readonly elasticsearchService = new ElasticsearchService(
|
||||
this.initializerContext.logger.get('elasticsearch')
|
||||
);
|
||||
private readonly sessionManagementService = new SessionManagementService(
|
||||
this.initializerContext.logger.get('session')
|
||||
);
|
||||
|
||||
private readonly getSpacesService = () => {
|
||||
// Changing property value from Symbol to undefined denotes the fact that property was accessed.
|
||||
|
@ -115,7 +123,7 @@ export class Plugin {
|
|||
|
||||
public async setup(
|
||||
core: CoreSetup<PluginStartDependencies>,
|
||||
{ features, licensing }: PluginSetupDependencies
|
||||
{ features, licensing, taskManager }: PluginSetupDependencies
|
||||
) {
|
||||
const [config, legacyConfig] = await combineLatest([
|
||||
this.initializerContext.config.create<TypeOf<typeof ConfigSchema>>().pipe(
|
||||
|
@ -130,35 +138,45 @@ export class Plugin {
|
|||
.pipe(first())
|
||||
.toPromise();
|
||||
|
||||
this.clusterClient = core.elasticsearch.legacy.createClient('security', {
|
||||
plugins: [elasticsearchClientPlugin],
|
||||
});
|
||||
|
||||
this.securityLicenseService = new SecurityLicenseService();
|
||||
const { license } = this.securityLicenseService.setup({
|
||||
license$: licensing.license$,
|
||||
});
|
||||
|
||||
const { clusterClient } = this.elasticsearchService.setup({
|
||||
elasticsearch: core.elasticsearch,
|
||||
license,
|
||||
status: core.status,
|
||||
});
|
||||
|
||||
this.featureUsageService.setup({ featureUsage: licensing.featureUsage });
|
||||
|
||||
const audit = this.auditService.setup({ license, config: config.audit });
|
||||
const auditLogger = new SecurityAuditLogger(audit.getLogger());
|
||||
|
||||
const { session } = this.sessionManagementService.setup({
|
||||
config,
|
||||
clusterClient,
|
||||
http: core.http,
|
||||
kibanaIndexName: legacyConfig.kibana.index,
|
||||
taskManager,
|
||||
});
|
||||
|
||||
const authc = await setupAuthentication({
|
||||
auditLogger,
|
||||
getFeatureUsageService: this.getFeatureUsageService,
|
||||
http: core.http,
|
||||
clusterClient: this.clusterClient,
|
||||
clusterClient,
|
||||
config,
|
||||
license,
|
||||
loggers: this.initializerContext.logger,
|
||||
session,
|
||||
});
|
||||
|
||||
const authz = this.authorizationService.setup({
|
||||
http: core.http,
|
||||
capabilities: core.capabilities,
|
||||
status: core.status,
|
||||
clusterClient: this.clusterClient,
|
||||
clusterClient,
|
||||
license,
|
||||
loggers: this.initializerContext.logger,
|
||||
kibanaIndexName: legacyConfig.kibana.index,
|
||||
|
@ -179,11 +197,12 @@ export class Plugin {
|
|||
basePath: core.http.basePath,
|
||||
httpResources: core.http.resources,
|
||||
logger: this.initializerContext.logger.get('routes'),
|
||||
clusterClient: this.clusterClient,
|
||||
clusterClient,
|
||||
config,
|
||||
authc,
|
||||
authz,
|
||||
license,
|
||||
session,
|
||||
getFeatures: () =>
|
||||
core
|
||||
.getStartServices()
|
||||
|
@ -225,22 +244,22 @@ export class Plugin {
|
|||
});
|
||||
}
|
||||
|
||||
public start(core: CoreStart, { features, licensing }: PluginStartDependencies) {
|
||||
public start(core: CoreStart, { features, licensing, taskManager }: PluginStartDependencies) {
|
||||
this.logger.debug('Starting plugin');
|
||||
|
||||
this.featureUsageServiceStart = this.featureUsageService.start({
|
||||
featureUsage: licensing.featureUsage,
|
||||
});
|
||||
this.authorizationService.start({ features, clusterClient: this.clusterClient! });
|
||||
|
||||
const { clusterClient, watchOnlineStatus$ } = this.elasticsearchService.start();
|
||||
|
||||
this.sessionManagementService.start({ online$: watchOnlineStatus$(), taskManager });
|
||||
this.authorizationService.start({ features, clusterClient, online$: watchOnlineStatus$() });
|
||||
}
|
||||
|
||||
public stop() {
|
||||
this.logger.debug('Stopping plugin');
|
||||
|
||||
if (this.clusterClient) {
|
||||
this.clusterClient.close();
|
||||
this.clusterClient = undefined;
|
||||
}
|
||||
|
||||
if (this.securityLicenseService) {
|
||||
this.securityLicenseService.stop();
|
||||
this.securityLicenseService = undefined;
|
||||
|
@ -249,8 +268,11 @@ export class Plugin {
|
|||
if (this.featureUsageServiceStart) {
|
||||
this.featureUsageServiceStart = undefined;
|
||||
}
|
||||
|
||||
this.auditService.stop();
|
||||
this.authorizationService.stop();
|
||||
this.elasticsearchService.stop();
|
||||
this.sessionManagementService.stop();
|
||||
}
|
||||
|
||||
private wasSpacesServiceAccessed() {
|
||||
|
|
|
@ -1,173 +0,0 @@
|
|||
/*
|
||||
* 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 } from '@kbn/config-schema';
|
||||
import {
|
||||
IRouter,
|
||||
kibanaResponseFactory,
|
||||
RequestHandler,
|
||||
RequestHandlerContext,
|
||||
RouteConfig,
|
||||
} from '../../../../../../src/core/server';
|
||||
import { Authentication, AuthenticationResult } from '../../authentication';
|
||||
import { defineBasicRoutes } from './basic';
|
||||
|
||||
import { httpServerMock } from '../../../../../../src/core/server/mocks';
|
||||
import { mockAuthenticatedUser } from '../../../common/model/authenticated_user.mock';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
|
||||
describe('Basic authentication routes', () => {
|
||||
let router: jest.Mocked<IRouter>;
|
||||
let authc: jest.Mocked<Authentication>;
|
||||
let mockContext: RequestHandlerContext;
|
||||
beforeEach(() => {
|
||||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
router = routeParamsMock.router;
|
||||
|
||||
authc = routeParamsMock.authc;
|
||||
authc.isProviderTypeEnabled.mockImplementation((provider) => provider === 'basic');
|
||||
|
||||
mockContext = ({
|
||||
licensing: {
|
||||
license: { check: jest.fn().mockReturnValue({ check: 'valid' }) },
|
||||
},
|
||||
} as unknown) as RequestHandlerContext;
|
||||
|
||||
defineBasicRoutes(routeParamsMock);
|
||||
});
|
||||
|
||||
describe('login', () => {
|
||||
let routeHandler: RequestHandler<any, any, any>;
|
||||
let routeConfig: RouteConfig<any, any, any, any>;
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest({
|
||||
body: { username: 'user', password: 'password' },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
const [loginRouteConfig, loginRouteHandler] = router.post.mock.calls.find(
|
||||
([{ path }]) => path === '/internal/security/login'
|
||||
)!;
|
||||
|
||||
routeConfig = loginRouteConfig;
|
||||
routeHandler = loginRouteHandler;
|
||||
});
|
||||
|
||||
it('correctly defines route.', async () => {
|
||||
expect(routeConfig.options).toEqual({ authRequired: false });
|
||||
expect(routeConfig.validate).toEqual({
|
||||
body: expect.any(Type),
|
||||
query: undefined,
|
||||
params: undefined,
|
||||
});
|
||||
|
||||
const bodyValidator = (routeConfig.validate as any).body as Type<any>;
|
||||
expect(bodyValidator.validate({ username: 'user', password: 'password' })).toEqual({
|
||||
username: 'user',
|
||||
password: 'password',
|
||||
});
|
||||
|
||||
expect(() => bodyValidator.validate({})).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[username]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
expect(() => bodyValidator.validate({ username: 'user' })).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[password]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
expect(() =>
|
||||
bodyValidator.validate({ password: 'password' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[username]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
expect(() =>
|
||||
bodyValidator.validate({ username: '', password: '' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[username]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
expect(() =>
|
||||
bodyValidator.validate({ username: 'user', password: '' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[password]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
expect(() =>
|
||||
bodyValidator.validate({ username: '', password: 'password' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[username]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
});
|
||||
|
||||
it('returns 500 if authentication throws unhandled exception.', async () => {
|
||||
const unhandledException = new Error('Something went wrong.');
|
||||
authc.login.mockRejectedValue(unhandledException);
|
||||
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.payload).toEqual(unhandledException);
|
||||
expect(authc.login).toHaveBeenCalledWith(mockRequest, {
|
||||
provider: { type: 'basic' },
|
||||
value: { username: 'user', password: 'password' },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 401 if authentication fails.', async () => {
|
||||
const failureReason = new Error('Something went wrong.');
|
||||
authc.login.mockResolvedValue(AuthenticationResult.failed(failureReason));
|
||||
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.payload).toEqual(failureReason);
|
||||
expect(authc.login).toHaveBeenCalledWith(mockRequest, {
|
||||
provider: { type: 'basic' },
|
||||
value: { username: 'user', password: 'password' },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 401 if authentication is not handled.', async () => {
|
||||
authc.login.mockResolvedValue(AuthenticationResult.notHandled());
|
||||
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.payload).toEqual('Unauthorized');
|
||||
expect(authc.login).toHaveBeenCalledWith(mockRequest, {
|
||||
provider: { type: 'basic' },
|
||||
value: { username: 'user', password: 'password' },
|
||||
});
|
||||
});
|
||||
|
||||
describe('authentication succeeds', () => {
|
||||
it(`returns user data`, async () => {
|
||||
authc.login.mockResolvedValue(AuthenticationResult.succeeded(mockAuthenticatedUser()));
|
||||
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(response.payload).toBeUndefined();
|
||||
expect(authc.login).toHaveBeenCalledWith(mockRequest, {
|
||||
provider: { type: 'basic' },
|
||||
value: { username: 'user', password: 'password' },
|
||||
});
|
||||
});
|
||||
|
||||
it('prefers `token` authentication provider if it is enabled', async () => {
|
||||
authc.login.mockResolvedValue(AuthenticationResult.succeeded(mockAuthenticatedUser()));
|
||||
authc.isProviderTypeEnabled.mockImplementation(
|
||||
(provider) => provider === 'token' || provider === 'basic'
|
||||
);
|
||||
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
expect(response.payload).toBeUndefined();
|
||||
expect(authc.login).toHaveBeenCalledWith(mockRequest, {
|
||||
provider: { type: 'token' },
|
||||
value: { username: 'user', password: 'password' },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -1,46 +0,0 @@
|
|||
/*
|
||||
* 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 { schema } from '@kbn/config-schema';
|
||||
import { wrapIntoCustomErrorResponse } from '../../errors';
|
||||
import { createLicensedRouteHandler } from '../licensed_route_handler';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
/**
|
||||
* Defines routes required for Basic/Token authentication.
|
||||
*/
|
||||
export function defineBasicRoutes({ router, authc, config }: RouteDefinitionParams) {
|
||||
router.post(
|
||||
{
|
||||
path: '/internal/security/login',
|
||||
validate: {
|
||||
body: schema.object({
|
||||
username: schema.string({ minLength: 1 }),
|
||||
password: schema.string({ minLength: 1 }),
|
||||
}),
|
||||
},
|
||||
options: { authRequired: false },
|
||||
},
|
||||
createLicensedRouteHandler(async (context, request, response) => {
|
||||
// We should prefer `token` over `basic` if possible.
|
||||
const loginAttempt = {
|
||||
provider: { type: authc.isProviderTypeEnabled('token') ? 'token' : 'basic' },
|
||||
value: request.body,
|
||||
};
|
||||
|
||||
try {
|
||||
const authenticationResult = await authc.login(request, loginAttempt);
|
||||
if (!authenticationResult.succeeded()) {
|
||||
return response.unauthorized({ body: authenticationResult.error });
|
||||
}
|
||||
|
||||
return response.noContent();
|
||||
} catch (error) {
|
||||
return response.customError(wrapIntoCustomErrorResponse(error));
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
|
@ -181,12 +181,12 @@ describe('Common authentication routes', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('login_with', () => {
|
||||
describe('login', () => {
|
||||
let routeHandler: RequestHandler<any, any, any>;
|
||||
let routeConfig: RouteConfig<any, any, any, any>;
|
||||
beforeEach(() => {
|
||||
const [acsRouteConfig, acsRouteHandler] = router.post.mock.calls.find(
|
||||
([{ path }]) => path === '/internal/security/login_with'
|
||||
([{ path }]) => path === '/internal/security/login'
|
||||
)!;
|
||||
|
||||
routeConfig = acsRouteConfig;
|
||||
|
@ -226,6 +226,39 @@ describe('Common authentication routes', () => {
|
|||
currentURL: '',
|
||||
});
|
||||
|
||||
for (const [providerType, providerName] of [
|
||||
['basic', 'basic1'],
|
||||
['token', 'token1'],
|
||||
]) {
|
||||
expect(
|
||||
bodyValidator.validate({
|
||||
providerType,
|
||||
providerName,
|
||||
currentURL: '',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
})
|
||||
).toEqual({
|
||||
providerType,
|
||||
providerName,
|
||||
currentURL: '',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
});
|
||||
|
||||
expect(
|
||||
bodyValidator.validate({
|
||||
providerType,
|
||||
providerName,
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
})
|
||||
).toEqual({
|
||||
providerType,
|
||||
providerName,
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
});
|
||||
}
|
||||
|
||||
expect(() => bodyValidator.validate({})).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerType]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
@ -250,6 +283,123 @@ describe('Common authentication routes', () => {
|
|||
UnknownArg: 'arg',
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(`"[UnknownArg]: definition for this key is missing"`);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(`"[params]: a value wasn't expected to be present"`);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: '/some-url',
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.username]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.password]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: '/some-url',
|
||||
params: { password: 'some-password' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.username]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: '', password: 'some-password' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.username]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user', password: '' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.password]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'token',
|
||||
providerName: 'token1',
|
||||
currentURL: '/some-url',
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.username]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'token',
|
||||
providerName: 'token1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.password]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'token',
|
||||
providerName: 'token1',
|
||||
currentURL: '/some-url',
|
||||
params: { password: 'some-password' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.username]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'token',
|
||||
providerName: 'token1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: '', password: 'some-password' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.username]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
bodyValidator.validate({
|
||||
providerType: 'token',
|
||||
providerName: 'token1',
|
||||
currentURL: '/some-url',
|
||||
params: { username: 'some-user', password: '' },
|
||||
})
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[params.password]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
});
|
||||
|
||||
it('returns 500 if login throws unhandled exception.', async () => {
|
||||
|
@ -378,10 +528,10 @@ describe('Common authentication routes', () => {
|
|||
expect(authc.login).toHaveBeenCalledTimes(1);
|
||||
expect(authc.login).toHaveBeenCalledWith(request, {
|
||||
provider: { name: 'saml1' },
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
value: {
|
||||
type: SAMLLogin.LoginInitiatedByUser,
|
||||
redirectURLPath: '/mock-server-basepath/some-url',
|
||||
redirectURLFragment: '#/app/nav',
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
@ -406,13 +556,66 @@ describe('Common authentication routes', () => {
|
|||
expect(authc.login).toHaveBeenCalledTimes(1);
|
||||
expect(authc.login).toHaveBeenCalledWith(request, {
|
||||
provider: { name: 'oidc1' },
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
value: {
|
||||
type: OIDCLogin.LoginInitiatedByUser,
|
||||
redirectURLPath: '/mock-server-basepath/some-url',
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('correctly performs Basic login.', async () => {
|
||||
authc.login.mockResolvedValue(AuthenticationResult.redirectTo('http://redirect-to/path'));
|
||||
|
||||
const request = httpServerMock.createKibanaRequest({
|
||||
body: {
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: 'https://kibana.com/?next=/mock-server-basepath/some-url#/app/nav',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({
|
||||
status: 200,
|
||||
payload: { location: 'http://redirect-to/path' },
|
||||
options: { body: { location: 'http://redirect-to/path' } },
|
||||
});
|
||||
|
||||
expect(authc.login).toHaveBeenCalledTimes(1);
|
||||
expect(authc.login).toHaveBeenCalledWith(request, {
|
||||
provider: { name: 'basic1' },
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
value: { username: 'some-user', password: 'some-password' },
|
||||
});
|
||||
});
|
||||
|
||||
it('correctly performs Token login.', async () => {
|
||||
authc.login.mockResolvedValue(AuthenticationResult.redirectTo('http://redirect-to/path'));
|
||||
|
||||
const request = httpServerMock.createKibanaRequest({
|
||||
body: {
|
||||
providerType: 'token',
|
||||
providerName: 'token1',
|
||||
currentURL: 'https://kibana.com/?next=/mock-server-basepath/some-url#/app/nav',
|
||||
params: { username: 'some-user', password: 'some-password' },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({
|
||||
status: 200,
|
||||
payload: { location: 'http://redirect-to/path' },
|
||||
options: { body: { location: 'http://redirect-to/path' } },
|
||||
});
|
||||
|
||||
expect(authc.login).toHaveBeenCalledTimes(1);
|
||||
expect(authc.login).toHaveBeenCalledWith(request, {
|
||||
provider: { name: 'token1' },
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
value: { username: 'some-user', password: 'some-password' },
|
||||
});
|
||||
});
|
||||
|
||||
it('correctly performs generic login.', async () => {
|
||||
authc.login.mockResolvedValue(AuthenticationResult.redirectTo('http://redirect-to/path'));
|
||||
|
||||
|
@ -433,6 +636,7 @@ describe('Common authentication routes', () => {
|
|||
expect(authc.login).toHaveBeenCalledTimes(1);
|
||||
expect(authc.login).toHaveBeenCalledWith(request, {
|
||||
provider: { name: 'some-name' },
|
||||
redirectURL: '/mock-server-basepath/some-url#/app/nav',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -4,15 +4,19 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { schema } from '@kbn/config-schema';
|
||||
import { schema, TypeOf } from '@kbn/config-schema';
|
||||
import { parseNext } from '../../../common/parse_next';
|
||||
import { canRedirectRequest, OIDCLogin, SAMLLogin } from '../../authentication';
|
||||
import { wrapIntoCustomErrorResponse } from '../../errors';
|
||||
import { createLicensedRouteHandler } from '../licensed_route_handler';
|
||||
import {
|
||||
canRedirectRequest,
|
||||
OIDCLogin,
|
||||
SAMLLogin,
|
||||
BasicAuthenticationProvider,
|
||||
OIDCAuthenticationProvider,
|
||||
SAMLAuthenticationProvider,
|
||||
} from '../../authentication/providers';
|
||||
TokenAuthenticationProvider,
|
||||
} from '../../authentication';
|
||||
import { wrapIntoCustomErrorResponse } from '../../errors';
|
||||
import { createLicensedRouteHandler } from '../licensed_route_handler';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
/**
|
||||
|
@ -83,19 +87,29 @@ export function defineCommonRoutes({
|
|||
);
|
||||
}
|
||||
|
||||
function getLoginAttemptForProviderType(providerType: string, redirectURL: string) {
|
||||
const [redirectURLPath] = redirectURL.split('#');
|
||||
const redirectURLFragment =
|
||||
redirectURL.length > redirectURLPath.length
|
||||
? redirectURL.substring(redirectURLPath.length)
|
||||
: '';
|
||||
const basicParamsSchema = schema.object({
|
||||
username: schema.string({ minLength: 1 }),
|
||||
password: schema.string({ minLength: 1 }),
|
||||
});
|
||||
|
||||
function getLoginAttemptForProviderType<T extends string>(
|
||||
providerType: T,
|
||||
redirectURL: string,
|
||||
params: T extends 'basic' | 'token' ? TypeOf<typeof basicParamsSchema> : {}
|
||||
) {
|
||||
if (providerType === SAMLAuthenticationProvider.type) {
|
||||
return { type: SAMLLogin.LoginInitiatedByUser, redirectURLPath, redirectURLFragment };
|
||||
return { type: SAMLLogin.LoginInitiatedByUser, redirectURL };
|
||||
}
|
||||
|
||||
if (providerType === OIDCAuthenticationProvider.type) {
|
||||
return { type: OIDCLogin.LoginInitiatedByUser, redirectURLPath };
|
||||
return { type: OIDCLogin.LoginInitiatedByUser, redirectURL };
|
||||
}
|
||||
|
||||
if (
|
||||
providerType === BasicAuthenticationProvider.type ||
|
||||
providerType === TokenAuthenticationProvider.type
|
||||
) {
|
||||
return params;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
@ -103,25 +117,35 @@ export function defineCommonRoutes({
|
|||
|
||||
router.post(
|
||||
{
|
||||
path: '/internal/security/login_with',
|
||||
path: '/internal/security/login',
|
||||
validate: {
|
||||
body: schema.object({
|
||||
providerType: schema.string(),
|
||||
providerName: schema.string(),
|
||||
currentURL: schema.string(),
|
||||
params: schema.conditional(
|
||||
schema.siblingRef('providerType'),
|
||||
schema.oneOf([
|
||||
schema.literal(BasicAuthenticationProvider.type),
|
||||
schema.literal(TokenAuthenticationProvider.type),
|
||||
]),
|
||||
basicParamsSchema,
|
||||
schema.never()
|
||||
),
|
||||
}),
|
||||
},
|
||||
options: { authRequired: false },
|
||||
},
|
||||
createLicensedRouteHandler(async (context, request, response) => {
|
||||
const { providerType, providerName, currentURL } = request.body;
|
||||
const { providerType, providerName, currentURL, params } = request.body;
|
||||
logger.info(`Logging in with provider "${providerName}" (${providerType})`);
|
||||
|
||||
const redirectURL = parseNext(currentURL, basePath.serverBasePath);
|
||||
try {
|
||||
const authenticationResult = await authc.login(request, {
|
||||
provider: { name: providerName },
|
||||
value: getLoginAttemptForProviderType(providerType, redirectURL),
|
||||
redirectURL,
|
||||
value: getLoginAttemptForProviderType(providerType, redirectURL, params),
|
||||
});
|
||||
|
||||
if (authenticationResult.redirected() || authenticationResult.succeeded()) {
|
||||
|
|
|
@ -4,21 +4,14 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { defineSessionRoutes } from './session';
|
||||
import { defineSAMLRoutes } from './saml';
|
||||
import { defineBasicRoutes } from './basic';
|
||||
import { defineCommonRoutes } from './common';
|
||||
import { defineOIDCRoutes } from './oidc';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
export function defineAuthenticationRoutes(params: RouteDefinitionParams) {
|
||||
defineSessionRoutes(params);
|
||||
defineCommonRoutes(params);
|
||||
|
||||
if (params.authc.isProviderTypeEnabled('basic') || params.authc.isProviderTypeEnabled('token')) {
|
||||
defineBasicRoutes(params);
|
||||
}
|
||||
|
||||
if (params.authc.isProviderTypeEnabled('saml')) {
|
||||
defineSAMLRoutes(params);
|
||||
}
|
||||
|
|
|
@ -12,79 +12,7 @@ import { RouteDefinitionParams } from '..';
|
|||
/**
|
||||
* Defines routes required for SAML authentication.
|
||||
*/
|
||||
export function defineSAMLRoutes({
|
||||
router,
|
||||
httpResources,
|
||||
logger,
|
||||
authc,
|
||||
basePath,
|
||||
}: RouteDefinitionParams) {
|
||||
httpResources.register(
|
||||
{
|
||||
path: '/internal/security/saml/capture-url-fragment',
|
||||
validate: false,
|
||||
options: { authRequired: false },
|
||||
},
|
||||
(context, request, response) => {
|
||||
// We're also preventing `favicon.ico` request since it can cause new SAML handshake.
|
||||
return response.renderHtml({
|
||||
body: `
|
||||
<!DOCTYPE html>
|
||||
<title>Kibana SAML Login</title>
|
||||
<link rel="icon" href="data:,">
|
||||
<script src="${basePath.serverBasePath}/internal/security/saml/capture-url-fragment.js"></script>
|
||||
`,
|
||||
});
|
||||
}
|
||||
);
|
||||
httpResources.register(
|
||||
{
|
||||
path: '/internal/security/saml/capture-url-fragment.js',
|
||||
validate: false,
|
||||
options: { authRequired: false },
|
||||
},
|
||||
(context, request, response) => {
|
||||
return response.renderJs({
|
||||
body: `
|
||||
window.location.replace(
|
||||
'${basePath.serverBasePath}/internal/security/saml/start?redirectURLFragment=' + encodeURIComponent(window.location.hash)
|
||||
);
|
||||
`,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
router.get(
|
||||
{
|
||||
path: '/internal/security/saml/start',
|
||||
validate: {
|
||||
query: schema.object({ redirectURLFragment: schema.string() }),
|
||||
},
|
||||
options: { authRequired: false },
|
||||
},
|
||||
async (context, request, response) => {
|
||||
try {
|
||||
const authenticationResult = await authc.login(request, {
|
||||
provider: { type: SAMLAuthenticationProvider.type },
|
||||
value: {
|
||||
type: SAMLLogin.LoginInitiatedByUser,
|
||||
redirectURLFragment: request.query.redirectURLFragment,
|
||||
},
|
||||
});
|
||||
|
||||
// When authenticating using SAML we _expect_ to redirect to the SAML Identity provider.
|
||||
if (authenticationResult.redirected()) {
|
||||
return response.redirected({ headers: { location: authenticationResult.redirectURL! } });
|
||||
}
|
||||
|
||||
return response.unauthorized();
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
return response.internalError();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function defineSAMLRoutes({ router, logger, authc }: RouteDefinitionParams) {
|
||||
router.post(
|
||||
{
|
||||
path: '/api/security/saml/callback',
|
||||
|
|
|
@ -14,6 +14,7 @@ import { authenticationMock } from '../authentication/index.mock';
|
|||
import { authorizationMock } from '../authorization/index.mock';
|
||||
import { ConfigSchema, createConfig } from '../config';
|
||||
import { licenseMock } from '../../common/licensing/index.mock';
|
||||
import { sessionMock } from '../session_management/session.mock';
|
||||
|
||||
export const routeDefinitionParamsMock = {
|
||||
create: (config: Record<string, unknown> = {}) => ({
|
||||
|
@ -31,5 +32,6 @@ export const routeDefinitionParamsMock = {
|
|||
httpResources: httpResourcesMock.createRegistrar(),
|
||||
getFeatures: jest.fn(),
|
||||
getFeatureUsageService: jest.fn(),
|
||||
session: sessionMock.create(),
|
||||
}),
|
||||
};
|
||||
|
|
|
@ -6,8 +6,8 @@
|
|||
|
||||
import { Feature } from '../../../features/server';
|
||||
import {
|
||||
CoreSetup,
|
||||
HttpResources,
|
||||
IBasePath,
|
||||
ILegacyClusterClient,
|
||||
IRouter,
|
||||
Logger,
|
||||
|
@ -23,21 +23,24 @@ import { defineApiKeysRoutes } from './api_keys';
|
|||
import { defineIndicesRoutes } from './indices';
|
||||
import { defineUsersRoutes } from './users';
|
||||
import { defineRoleMappingRoutes } from './role_mapping';
|
||||
import { defineSessionManagementRoutes } from './session_management';
|
||||
import { defineViewRoutes } from './views';
|
||||
import { SecurityFeatureUsageServiceStart } from '../feature_usage';
|
||||
import { Session } from '../session_management';
|
||||
|
||||
/**
|
||||
* Describes parameters used to define HTTP routes.
|
||||
*/
|
||||
export interface RouteDefinitionParams {
|
||||
router: IRouter;
|
||||
basePath: CoreSetup['http']['basePath'];
|
||||
basePath: IBasePath;
|
||||
httpResources: HttpResources;
|
||||
logger: Logger;
|
||||
clusterClient: ILegacyClusterClient;
|
||||
config: ConfigType;
|
||||
authc: Authentication;
|
||||
authz: AuthorizationServiceSetup;
|
||||
session: PublicMethodsOf<Session>;
|
||||
license: SecurityLicense;
|
||||
getFeatures: () => Promise<Feature[]>;
|
||||
getFeatureUsageService: () => SecurityFeatureUsageServiceStart;
|
||||
|
@ -46,6 +49,7 @@ export interface RouteDefinitionParams {
|
|||
export function defineRoutes(params: RouteDefinitionParams) {
|
||||
defineAuthenticationRoutes(params);
|
||||
defineAuthorizationRoutes(params);
|
||||
defineSessionManagementRoutes(params);
|
||||
defineApiKeysRoutes(params);
|
||||
defineIndicesRoutes(params);
|
||||
defineUsersRoutes(params);
|
||||
|
|
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
* 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 {
|
||||
IRouter,
|
||||
kibanaResponseFactory,
|
||||
RequestHandler,
|
||||
RequestHandlerContext,
|
||||
RouteConfig,
|
||||
} from '../../../../../../src/core/server';
|
||||
import { defineSessionExtendRoutes } from './extend';
|
||||
|
||||
import { httpServerMock } from '../../../../../../src/core/server/mocks';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
|
||||
describe('Extend session routes', () => {
|
||||
let router: jest.Mocked<IRouter>;
|
||||
beforeEach(() => {
|
||||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
router = routeParamsMock.router;
|
||||
|
||||
defineSessionExtendRoutes(routeParamsMock);
|
||||
});
|
||||
|
||||
describe('extend session', () => {
|
||||
let routeHandler: RequestHandler<any, any, any>;
|
||||
let routeConfig: RouteConfig<any, any, any, any>;
|
||||
beforeEach(() => {
|
||||
const [extendRouteConfig, extendRouteHandler] = router.post.mock.calls.find(
|
||||
([{ path }]) => path === '/internal/security/session'
|
||||
)!;
|
||||
|
||||
routeConfig = extendRouteConfig;
|
||||
routeHandler = extendRouteHandler;
|
||||
});
|
||||
|
||||
it('correctly defines route.', () => {
|
||||
expect(routeConfig.options).toBeUndefined();
|
||||
expect(routeConfig.validate).toBe(false);
|
||||
});
|
||||
|
||||
it('always returns 302.', async () => {
|
||||
await expect(
|
||||
routeHandler(
|
||||
({} as unknown) as RequestHandlerContext,
|
||||
httpServerMock.createKibanaRequest(),
|
||||
kibanaResponseFactory
|
||||
)
|
||||
).resolves.toEqual({
|
||||
status: 302,
|
||||
options: { headers: { location: '/mock-server-basepath/internal/security/session' } },
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -7,26 +7,9 @@
|
|||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
/**
|
||||
* Defines routes required for all authentication realms.
|
||||
* Defines routes required for the session extension.
|
||||
*/
|
||||
export function defineSessionRoutes({ router, logger, authc, basePath }: RouteDefinitionParams) {
|
||||
router.get(
|
||||
{
|
||||
path: '/internal/security/session',
|
||||
validate: false,
|
||||
},
|
||||
async (_context, request, response) => {
|
||||
try {
|
||||
const sessionInfo = await authc.getSessionInfo(request);
|
||||
// This is an authenticated request, so sessionInfo will always be non-null.
|
||||
return response.ok({ body: sessionInfo! });
|
||||
} catch (err) {
|
||||
logger.error(`Error retrieving user session: ${err.message}`);
|
||||
return response.internalError();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function defineSessionExtendRoutes({ router, basePath }: RouteDefinitionParams) {
|
||||
router.post(
|
||||
{
|
||||
path: '/internal/security/session',
|
|
@ -0,0 +1,14 @@
|
|||
/*
|
||||
* 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 { defineSessionExtendRoutes } from './extend';
|
||||
import { defineSessionInfoRoutes } from './info';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
export function defineSessionManagementRoutes(params: RouteDefinitionParams) {
|
||||
defineSessionInfoRoutes(params);
|
||||
defineSessionExtendRoutes(params);
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
/*
|
||||
* 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 {
|
||||
IRouter,
|
||||
kibanaResponseFactory,
|
||||
RequestHandler,
|
||||
RequestHandlerContext,
|
||||
RouteConfig,
|
||||
} from '../../../../../../src/core/server';
|
||||
import { Session } from '../../session_management';
|
||||
import { defineSessionInfoRoutes } from './info';
|
||||
|
||||
import { httpServerMock } from '../../../../../../src/core/server/mocks';
|
||||
import { sessionMock } from '../../session_management/session.mock';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
|
||||
describe('Info session routes', () => {
|
||||
let router: jest.Mocked<IRouter>;
|
||||
let session: jest.Mocked<PublicMethodsOf<Session>>;
|
||||
beforeEach(() => {
|
||||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
router = routeParamsMock.router;
|
||||
session = routeParamsMock.session;
|
||||
|
||||
defineSessionInfoRoutes(routeParamsMock);
|
||||
});
|
||||
|
||||
describe('extend session', () => {
|
||||
let routeHandler: RequestHandler<any, any, any>;
|
||||
let routeConfig: RouteConfig<any, any, any, any>;
|
||||
beforeEach(() => {
|
||||
const [extendRouteConfig, extendRouteHandler] = router.get.mock.calls.find(
|
||||
([{ path }]) => path === '/internal/security/session'
|
||||
)!;
|
||||
|
||||
routeConfig = extendRouteConfig;
|
||||
routeHandler = extendRouteHandler;
|
||||
});
|
||||
|
||||
it('correctly defines route.', () => {
|
||||
expect(routeConfig.options).toBeUndefined();
|
||||
expect(routeConfig.validate).toBe(false);
|
||||
});
|
||||
|
||||
it('returns 500 if unhandled exception is thrown when session is retrieved.', async () => {
|
||||
const unhandledException = new Error('Something went wrong.');
|
||||
session.get.mockRejectedValue(unhandledException);
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
routeHandler(({} as unknown) as RequestHandlerContext, request, kibanaResponseFactory)
|
||||
).resolves.toEqual({
|
||||
status: 500,
|
||||
options: {},
|
||||
payload: 'Internal Error',
|
||||
});
|
||||
|
||||
expect(session.get).toHaveBeenCalledWith(request);
|
||||
});
|
||||
|
||||
it('returns session info.', async () => {
|
||||
session.get.mockResolvedValue(
|
||||
sessionMock.createValue({ idleTimeoutExpiration: 100, lifespanExpiration: 200 })
|
||||
);
|
||||
|
||||
const dateSpy = jest.spyOn(Date, 'now');
|
||||
dateSpy.mockReturnValue(1234);
|
||||
|
||||
const expectedBody = {
|
||||
now: 1234,
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: 100,
|
||||
lifespanExpiration: 200,
|
||||
};
|
||||
await expect(
|
||||
routeHandler(
|
||||
({} as unknown) as RequestHandlerContext,
|
||||
httpServerMock.createKibanaRequest(),
|
||||
kibanaResponseFactory
|
||||
)
|
||||
).resolves.toEqual({
|
||||
status: 200,
|
||||
payload: expectedBody,
|
||||
options: { body: expectedBody },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns empty response if session is not available.', async () => {
|
||||
session.get.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
routeHandler(
|
||||
({} as unknown) as RequestHandlerContext,
|
||||
httpServerMock.createKibanaRequest(),
|
||||
kibanaResponseFactory
|
||||
)
|
||||
).resolves.toEqual({ status: 204, options: {} });
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,39 @@
|
|||
/*
|
||||
* 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 { SessionInfo } from '../../../common/types';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
/**
|
||||
* Defines routes required for the session info.
|
||||
*/
|
||||
export function defineSessionInfoRoutes({ router, logger, session }: RouteDefinitionParams) {
|
||||
router.get(
|
||||
{ path: '/internal/security/session', validate: false },
|
||||
async (_context, request, response) => {
|
||||
try {
|
||||
const sessionValue = await session.get(request);
|
||||
if (sessionValue) {
|
||||
return response.ok({
|
||||
body: {
|
||||
// We can't rely on the client's system clock, so in addition to returning expiration timestamps, we also return
|
||||
// the current server time -- that way the client can calculate the relative time to expiration.
|
||||
now: Date.now(),
|
||||
idleTimeoutExpiration: sessionValue.idleTimeoutExpiration,
|
||||
lifespanExpiration: sessionValue.lifespanExpiration,
|
||||
provider: sessionValue.provider,
|
||||
} as SessionInfo,
|
||||
});
|
||||
}
|
||||
|
||||
return response.noContent();
|
||||
} catch (err) {
|
||||
logger.error(`Error retrieving user session: ${err.message}`);
|
||||
return response.internalError();
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
|
@ -17,15 +17,18 @@ import {
|
|||
ScopeableRequest,
|
||||
} from '../../../../../../src/core/server';
|
||||
import { Authentication, AuthenticationResult } from '../../authentication';
|
||||
import { Session } from '../../session_management';
|
||||
import { defineChangeUserPasswordRoutes } from './change_password';
|
||||
|
||||
import { elasticsearchServiceMock, httpServerMock } from '../../../../../../src/core/server/mocks';
|
||||
import { mockAuthenticatedUser } from '../../../common/model/authenticated_user.mock';
|
||||
import { sessionMock } from '../../session_management/session.mock';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
|
||||
describe('Change password', () => {
|
||||
let router: jest.Mocked<IRouter>;
|
||||
let authc: jest.Mocked<Authentication>;
|
||||
let session: jest.Mocked<PublicMethodsOf<Session>>;
|
||||
let mockClusterClient: jest.Mocked<ILegacyClusterClient>;
|
||||
let mockScopedClusterClient: jest.Mocked<ILegacyScopedClusterClient>;
|
||||
let routeHandler: RequestHandler<any, any, any>;
|
||||
|
@ -46,15 +49,11 @@ describe('Change password', () => {
|
|||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
router = routeParamsMock.router;
|
||||
authc = routeParamsMock.authc;
|
||||
session = routeParamsMock.session;
|
||||
|
||||
authc.getCurrentUser.mockReturnValue(mockAuthenticatedUser({ username: 'user' }));
|
||||
authc.getCurrentUser.mockReturnValue(mockAuthenticatedUser(mockAuthenticatedUser()));
|
||||
authc.login.mockResolvedValue(AuthenticationResult.succeeded(mockAuthenticatedUser()));
|
||||
authc.getSessionInfo.mockResolvedValue({
|
||||
now: Date.now(),
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
provider: { type: 'basic', name: 'basic' },
|
||||
});
|
||||
session.get.mockResolvedValue(sessionMock.createValue());
|
||||
|
||||
mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient();
|
||||
mockClusterClient = routeParamsMock.clusterClient;
|
||||
|
@ -199,6 +198,9 @@ describe('Change password', () => {
|
|||
});
|
||||
authc.getCurrentUser.mockReturnValue(mockUser);
|
||||
authc.login.mockResolvedValue(AuthenticationResult.succeeded(mockUser));
|
||||
session.get.mockResolvedValue(
|
||||
sessionMock.createValue({ provider: { type: 'token', name: 'token1' } })
|
||||
);
|
||||
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
|
@ -220,7 +222,7 @@ describe('Change password', () => {
|
|||
});
|
||||
|
||||
it('successfully changes own password but does not re-login if current session does not exist.', async () => {
|
||||
authc.getSessionInfo.mockResolvedValue(null);
|
||||
session.get.mockResolvedValue(null);
|
||||
const response = await routeHandler(mockContext, mockRequest, kibanaResponseFactory);
|
||||
|
||||
expect(response.status).toBe(204);
|
||||
|
|
|
@ -16,6 +16,7 @@ import { RouteDefinitionParams } from '..';
|
|||
|
||||
export function defineChangeUserPasswordRoutes({
|
||||
authc,
|
||||
session,
|
||||
router,
|
||||
clusterClient,
|
||||
}: RouteDefinitionParams) {
|
||||
|
@ -37,7 +38,7 @@ export function defineChangeUserPasswordRoutes({
|
|||
const currentUser = authc.getCurrentUser(request);
|
||||
const isUserChangingOwnPassword =
|
||||
currentUser && currentUser.username === username && canUserChangePassword(currentUser);
|
||||
const currentSession = isUserChangingOwnPassword ? await authc.getSessionInfo(request) : null;
|
||||
const currentSession = isUserChangingOwnPassword ? await session.get(request) : null;
|
||||
|
||||
// If user is changing their own password they should provide a proof of knowledge their
|
||||
// current password via sending it in `Authorization: Basic base64(username:current password)`
|
||||
|
@ -81,7 +82,7 @@ export function defineChangeUserPasswordRoutes({
|
|||
if (isUserChangingOwnPassword && currentSession) {
|
||||
try {
|
||||
const authenticationResult = await authc.login(request, {
|
||||
provider: { name: currentUser!.authentication_provider },
|
||||
provider: { name: currentSession.provider.name },
|
||||
value: { username, password: newPassword },
|
||||
});
|
||||
|
||||
|
|
|
@ -16,24 +16,25 @@ import {
|
|||
import { SecurityLicense, SecurityLicenseFeatures } from '../../../common/licensing';
|
||||
import { AuthenticationProvider } from '../../../common/types';
|
||||
import { ConfigType } from '../../config';
|
||||
import { Session } from '../../session_management';
|
||||
import { defineAccessAgreementRoutes } from './access_agreement';
|
||||
|
||||
import { httpResourcesMock, httpServerMock } from '../../../../../../src/core/server/mocks';
|
||||
import { sessionMock } from '../../session_management/session.mock';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
import { Authentication } from '../../authentication';
|
||||
|
||||
describe('Access agreement view routes', () => {
|
||||
let httpResources: jest.Mocked<HttpResources>;
|
||||
let router: jest.Mocked<IRouter>;
|
||||
let config: ConfigType;
|
||||
let authc: jest.Mocked<Authentication>;
|
||||
let session: jest.Mocked<PublicMethodsOf<Session>>;
|
||||
let license: jest.Mocked<SecurityLicense>;
|
||||
let mockContext: RequestHandlerContext;
|
||||
beforeEach(() => {
|
||||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
router = routeParamsMock.router;
|
||||
httpResources = routeParamsMock.httpResources;
|
||||
authc = routeParamsMock.authc;
|
||||
session = routeParamsMock.session;
|
||||
config = routeParamsMock.config;
|
||||
license = routeParamsMock.license;
|
||||
|
||||
|
@ -125,7 +126,7 @@ describe('Access agreement view routes', () => {
|
|||
it('returns empty `accessAgreement` if session info is not available.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
authc.getSessionInfo.mockResolvedValue(null);
|
||||
session.get.mockResolvedValue(null);
|
||||
|
||||
await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({
|
||||
options: { body: { accessAgreement: '' } },
|
||||
|
@ -159,12 +160,7 @@ describe('Access agreement view routes', () => {
|
|||
];
|
||||
|
||||
for (const [sessionProvider, expectedAccessAgreement] of cases) {
|
||||
authc.getSessionInfo.mockResolvedValue({
|
||||
now: Date.now(),
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
provider: sessionProvider,
|
||||
});
|
||||
session.get.mockResolvedValue(sessionMock.createValue({ provider: sessionProvider }));
|
||||
|
||||
await expect(routeHandler(mockContext, request, kibanaResponseFactory)).resolves.toEqual({
|
||||
options: { body: { accessAgreement: expectedAccessAgreement } },
|
||||
|
|
|
@ -12,7 +12,7 @@ import { RouteDefinitionParams } from '..';
|
|||
* Defines routes required for the Access Agreement view.
|
||||
*/
|
||||
export function defineAccessAgreementRoutes({
|
||||
authc,
|
||||
session,
|
||||
httpResources,
|
||||
license,
|
||||
config,
|
||||
|
@ -46,12 +46,12 @@ export function defineAccessAgreementRoutes({
|
|||
// authenticated with the help of HTTP authentication), that means we should safely check if
|
||||
// we have it and can get a corresponding configuration.
|
||||
try {
|
||||
const session = await authc.getSessionInfo(request);
|
||||
const sessionValue = await session.get(request);
|
||||
const accessAgreement =
|
||||
(session &&
|
||||
(sessionValue &&
|
||||
config.authc.providers[
|
||||
session.provider.type as keyof ConfigType['authc']['providers']
|
||||
]?.[session.provider.name]?.accessAgreement?.message) ||
|
||||
sessionValue.provider.type as keyof ConfigType['authc']['providers']
|
||||
]?.[sessionValue.provider.name]?.accessAgreement?.message) ||
|
||||
'';
|
||||
|
||||
return response.ok({ body: { accessAgreement } });
|
||||
|
|
|
@ -0,0 +1,99 @@
|
|||
/*
|
||||
* 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 } from '@kbn/config-schema';
|
||||
import {
|
||||
RouteConfig,
|
||||
HttpResources,
|
||||
HttpResourcesRequestHandler,
|
||||
RequestHandlerContext,
|
||||
} from '../../../../../../src/core/server';
|
||||
import { defineCaptureURLRoutes } from './capture_url';
|
||||
|
||||
import { httpResourcesMock, httpServerMock } from '../../../../../../src/core/server/mocks';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
|
||||
describe('Capture URL view routes', () => {
|
||||
let httpResources: jest.Mocked<HttpResources>;
|
||||
beforeEach(() => {
|
||||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
httpResources = routeParamsMock.httpResources;
|
||||
|
||||
defineCaptureURLRoutes(routeParamsMock);
|
||||
});
|
||||
|
||||
let routeHandler: HttpResourcesRequestHandler<any, any, any>;
|
||||
let routeConfig: RouteConfig<any, any, any, 'get'>;
|
||||
beforeEach(() => {
|
||||
const [viewRouteConfig, viewRouteHandler] = httpResources.register.mock.calls.find(
|
||||
([{ path }]) => path === '/internal/security/capture-url'
|
||||
)!;
|
||||
|
||||
routeConfig = viewRouteConfig;
|
||||
routeHandler = viewRouteHandler;
|
||||
});
|
||||
|
||||
it('correctly defines route.', () => {
|
||||
expect(routeConfig.options).toEqual({ authRequired: false });
|
||||
|
||||
expect(routeConfig.validate).toEqual({
|
||||
body: undefined,
|
||||
query: expect.any(Type),
|
||||
params: undefined,
|
||||
});
|
||||
|
||||
const queryValidator = (routeConfig.validate as any).query as Type<any>;
|
||||
expect(
|
||||
queryValidator.validate({ providerType: 'basic', providerName: 'basic1', next: '/some-url' })
|
||||
).toEqual({ providerType: 'basic', providerName: 'basic1', next: '/some-url' });
|
||||
|
||||
expect(queryValidator.validate({ providerType: 'basic', providerName: 'basic1' })).toEqual({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
});
|
||||
|
||||
expect(() => queryValidator.validate({ providerType: '' })).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerType]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
queryValidator.validate({ providerType: 'basic' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerName]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() => queryValidator.validate({ providerName: '' })).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerType]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
queryValidator.validate({ providerName: 'basic1' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerType]: expected value of type [string] but got [undefined]"`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
queryValidator.validate({ providerType: 'basic', providerName: '' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerName]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
queryValidator.validate({ providerType: '', providerName: 'basic1' })
|
||||
).toThrowErrorMatchingInlineSnapshot(
|
||||
`"[providerType]: value has length [0] but it must have a minimum length of [1]."`
|
||||
);
|
||||
});
|
||||
|
||||
it('renders view.', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
const responseFactory = httpResourcesMock.createResponseFactory();
|
||||
|
||||
await routeHandler(({} as unknown) as RequestHandlerContext, request, responseFactory);
|
||||
|
||||
expect(responseFactory.renderAnonymousCoreApp).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
28
x-pack/plugins/security/server/routes/views/capture_url.ts
Normal file
28
x-pack/plugins/security/server/routes/views/capture_url.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
/*
|
||||
* 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 { schema } from '@kbn/config-schema';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
/**
|
||||
* Defines routes required for the Capture URL view.
|
||||
*/
|
||||
export function defineCaptureURLRoutes({ httpResources }: RouteDefinitionParams) {
|
||||
httpResources.register(
|
||||
{
|
||||
path: '/internal/security/capture-url',
|
||||
validate: {
|
||||
query: schema.object({
|
||||
providerType: schema.string({ minLength: 1 }),
|
||||
providerName: schema.string({ minLength: 1 }),
|
||||
next: schema.maybe(schema.string()),
|
||||
}),
|
||||
},
|
||||
options: { authRequired: false },
|
||||
},
|
||||
(context, request, response) => response.renderAnonymousCoreApp()
|
||||
);
|
||||
}
|
|
@ -25,6 +25,7 @@ describe('View routes', () => {
|
|||
"/security/logged_out",
|
||||
"/logout",
|
||||
"/security/overwritten_session",
|
||||
"/internal/security/capture-url",
|
||||
]
|
||||
`);
|
||||
expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(`
|
||||
|
@ -51,6 +52,7 @@ describe('View routes', () => {
|
|||
"/security/logged_out",
|
||||
"/logout",
|
||||
"/security/overwritten_session",
|
||||
"/internal/security/capture-url",
|
||||
]
|
||||
`);
|
||||
expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(`
|
||||
|
@ -78,6 +80,7 @@ describe('View routes', () => {
|
|||
"/security/logged_out",
|
||||
"/logout",
|
||||
"/security/overwritten_session",
|
||||
"/internal/security/capture-url",
|
||||
]
|
||||
`);
|
||||
expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(`
|
||||
|
@ -105,6 +108,7 @@ describe('View routes', () => {
|
|||
"/security/logged_out",
|
||||
"/logout",
|
||||
"/security/overwritten_session",
|
||||
"/internal/security/capture-url",
|
||||
]
|
||||
`);
|
||||
expect(routeParamsMock.router.get.mock.calls.map(([{ path }]) => path)).toMatchInlineSnapshot(`
|
||||
|
|
|
@ -10,6 +10,7 @@ import { defineLoggedOutRoutes } from './logged_out';
|
|||
import { defineLoginRoutes } from './login';
|
||||
import { defineLogoutRoutes } from './logout';
|
||||
import { defineOverwrittenSessionRoutes } from './overwritten_session';
|
||||
import { defineCaptureURLRoutes } from './capture_url';
|
||||
import { RouteDefinitionParams } from '..';
|
||||
|
||||
export function defineViewRoutes(params: RouteDefinitionParams) {
|
||||
|
@ -26,4 +27,5 @@ export function defineViewRoutes(params: RouteDefinitionParams) {
|
|||
defineLoggedOutRoutes(params);
|
||||
defineLogoutRoutes(params);
|
||||
defineOverwrittenSessionRoutes(params);
|
||||
defineCaptureURLRoutes(params);
|
||||
}
|
||||
|
|
|
@ -5,19 +5,20 @@
|
|||
*/
|
||||
|
||||
import { HttpResourcesRequestHandler, RouteConfig } from '../../../../../../src/core/server';
|
||||
import { Authentication } from '../../authentication';
|
||||
import { Session } from '../../session_management';
|
||||
import { defineLoggedOutRoutes } from './logged_out';
|
||||
|
||||
import { httpServerMock, httpResourcesMock } from '../../../../../../src/core/server/mocks';
|
||||
import { sessionMock } from '../../session_management/session.mock';
|
||||
import { routeDefinitionParamsMock } from '../index.mock';
|
||||
|
||||
describe('LoggedOut view routes', () => {
|
||||
let authc: jest.Mocked<Authentication>;
|
||||
let session: jest.Mocked<PublicMethodsOf<Session>>;
|
||||
let routeHandler: HttpResourcesRequestHandler<any, any, any>;
|
||||
let routeConfig: RouteConfig<any, any, any, 'get'>;
|
||||
beforeEach(() => {
|
||||
const routeParamsMock = routeDefinitionParamsMock.create();
|
||||
authc = routeParamsMock.authc;
|
||||
session = routeParamsMock.session;
|
||||
|
||||
defineLoggedOutRoutes(routeParamsMock);
|
||||
|
||||
|
@ -38,12 +39,7 @@ describe('LoggedOut view routes', () => {
|
|||
});
|
||||
|
||||
it('redirects user to the root page if they have a session already.', async () => {
|
||||
authc.getSessionInfo.mockResolvedValue({
|
||||
provider: { type: 'basic', name: 'basic' },
|
||||
now: 0,
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
});
|
||||
session.get.mockResolvedValue(sessionMock.createValue());
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
|
||||
|
@ -54,17 +50,17 @@ describe('LoggedOut view routes', () => {
|
|||
headers: { location: '/mock-server-basepath/' },
|
||||
});
|
||||
|
||||
expect(authc.getSessionInfo).toHaveBeenCalledWith(request);
|
||||
expect(session.get).toHaveBeenCalledWith(request);
|
||||
});
|
||||
|
||||
it('renders view if user does not have an active session.', async () => {
|
||||
authc.getSessionInfo.mockResolvedValue(null);
|
||||
session.get.mockResolvedValue(null);
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
const responseFactory = httpResourcesMock.createResponseFactory();
|
||||
await routeHandler({} as any, request, responseFactory);
|
||||
|
||||
expect(authc.getSessionInfo).toHaveBeenCalledWith(request);
|
||||
expect(session.get).toHaveBeenCalledWith(request);
|
||||
expect(responseFactory.renderAnonymousCoreApp).toHaveBeenCalledWith();
|
||||
});
|
||||
});
|
||||
|
|
|
@ -17,7 +17,7 @@ import { RouteDefinitionParams } from '..';
|
|||
*/
|
||||
export function defineLoggedOutRoutes({
|
||||
logger,
|
||||
authc,
|
||||
session,
|
||||
httpResources,
|
||||
basePath,
|
||||
}: RouteDefinitionParams) {
|
||||
|
@ -30,7 +30,7 @@ export function defineLoggedOutRoutes({
|
|||
async (context, request, response) => {
|
||||
// Authentication flow isn't triggered automatically for this route, so we should explicitly
|
||||
// check whether user has an active session already.
|
||||
const isUserAlreadyLoggedIn = (await authc.getSessionInfo(request)) !== null;
|
||||
const isUserAlreadyLoggedIn = (await session.get(request)) !== null;
|
||||
if (isUserAlreadyLoggedIn) {
|
||||
logger.debug('User is already authenticated, redirecting...');
|
||||
return response.redirected({
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export { sessionMock } from './session.mock';
|
||||
export { sessionCookieMock } from './session_cookie.mock';
|
||||
export { sessionIndexMock } from './session_index.mock';
|
11
x-pack/plugins/security/server/session_management/index.ts
Normal file
11
x-pack/plugins/security/server/session_management/index.ts
Normal file
|
@ -0,0 +1,11 @@
|
|||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export { Session, SessionValue } from './session';
|
||||
export {
|
||||
SessionManagementServiceSetup,
|
||||
SessionManagementService,
|
||||
} from './session_management_service';
|
|
@ -0,0 +1,30 @@
|
|||
/*
|
||||
* 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 { mockAuthenticatedUser } from '../../common/model/authenticated_user.mock';
|
||||
import { Session, SessionValue } from './session';
|
||||
import { sessionIndexMock } from './session_index.mock';
|
||||
|
||||
export const sessionMock = {
|
||||
create: (): jest.Mocked<PublicMethodsOf<Session>> => ({
|
||||
get: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
extend: jest.fn(),
|
||||
clear: jest.fn(),
|
||||
}),
|
||||
|
||||
createValue: (sessionValue: Partial<SessionValue> = {}): SessionValue => ({
|
||||
sid: 'some-long-sid',
|
||||
username: mockAuthenticatedUser().username,
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
state: undefined,
|
||||
metadata: { index: sessionIndexMock.createValue(sessionValue.metadata?.index) },
|
||||
...sessionValue,
|
||||
}),
|
||||
};
|
|
@ -0,0 +1,794 @@
|
|||
/*
|
||||
* 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 nodeCrypto from '@elastic/node-crypto';
|
||||
import { ConfigSchema, createConfig } from '../config';
|
||||
import { Session, SessionValueContentToEncrypt } from './session';
|
||||
import { SessionIndex } from './session_index';
|
||||
import { SessionCookie } from './session_cookie';
|
||||
|
||||
import { loggingSystemMock, httpServerMock } from '../../../../../src/core/server/mocks';
|
||||
import { sessionMock, sessionCookieMock, sessionIndexMock } from './index.mock';
|
||||
import { mockAuthenticatedUser } from '../../common/model/authenticated_user.mock';
|
||||
|
||||
describe('Session', () => {
|
||||
const now = 123456;
|
||||
const mockEncryptionKey = 'a'.repeat(32);
|
||||
const encryptContent = (contentToEncrypt: SessionValueContentToEncrypt, aad: string) =>
|
||||
nodeCrypto({ encryptionKey: mockEncryptionKey }).encrypt(JSON.stringify(contentToEncrypt), aad);
|
||||
|
||||
let mockSessionIndex: jest.Mocked<PublicMethodsOf<SessionIndex>>;
|
||||
let mockSessionCookie: jest.Mocked<PublicMethodsOf<SessionCookie>>;
|
||||
let session: Session;
|
||||
beforeEach(() => {
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
|
||||
let callCount = 0;
|
||||
jest.spyOn(crypto, 'randomBytes').mockImplementation((num, callback) => {
|
||||
// We still need _some_ randomness here to distinguish generated bytes for SID and AAD.
|
||||
const buffer = Buffer.from([++callCount, ...Array(num - 1).keys()]);
|
||||
if (typeof callback !== 'function') {
|
||||
return buffer;
|
||||
}
|
||||
callback(null, buffer);
|
||||
});
|
||||
|
||||
mockSessionCookie = sessionCookieMock.create();
|
||||
mockSessionIndex = sessionIndexMock.create();
|
||||
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({
|
||||
encryptionKey: mockEncryptionKey,
|
||||
session: { idleTimeout: 123, lifespan: 456 },
|
||||
}),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
});
|
||||
|
||||
describe('#get', () => {
|
||||
const mockAAD = Buffer.from([2, ...Array(255).keys()]).toString('base64');
|
||||
|
||||
it('returns `null` if session cookie does not exist', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(null);
|
||||
mockSessionIndex.get.mockResolvedValue(
|
||||
sessionIndexMock.createValue({
|
||||
content: await encryptContent({ username: 'some-user', state: 'some-state' }, mockAAD),
|
||||
})
|
||||
);
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('clears session value if session is expired because of idle timeout', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now - 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
);
|
||||
mockSessionIndex.get.mockResolvedValue(
|
||||
sessionIndexMock.createValue({
|
||||
content: await encryptContent({ username: 'some-user', state: 'some-state' }, mockAAD),
|
||||
})
|
||||
);
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toBeNull();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('clears session value if session is expired because of lifespan', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now - 1,
|
||||
})
|
||||
);
|
||||
mockSessionIndex.get.mockResolvedValue(
|
||||
sessionIndexMock.createValue({
|
||||
content: await encryptContent({ username: 'some-user', state: 'some-state' }, mockAAD),
|
||||
})
|
||||
);
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toBeNull();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('clears session value if session cookie does not have corresponding session index value', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
);
|
||||
mockSessionIndex.get.mockResolvedValue(null);
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toBeNull();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('clears session value if session index value content cannot be decrypted', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
);
|
||||
mockSessionIndex.get.mockResolvedValue(sessionIndexMock.createValue({ content: 'Uh! Oh!' }));
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toBeNull();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('clears session value if session index value content cannot be decrypted because of wrong AAD', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: 'some-wrong-aad',
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
);
|
||||
mockSessionIndex.get.mockResolvedValue(
|
||||
sessionIndexMock.createValue({
|
||||
content: await encryptContent({ username: 'some-user', state: 'some-state' }, mockAAD),
|
||||
})
|
||||
);
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toBeNull();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('returns session value with decrypted content', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
);
|
||||
|
||||
const mockSessionIndexValue = sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: now - 1,
|
||||
lifespanExpiration: now + 1,
|
||||
content: await encryptContent({ username: 'some-user', state: 'some-state' }, mockAAD),
|
||||
});
|
||||
mockSessionIndex.get.mockResolvedValue(mockSessionIndexValue);
|
||||
|
||||
await expect(session.get(httpServerMock.createKibanaRequest())).resolves.toEqual({
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
metadata: { index: mockSessionIndexValue },
|
||||
provider: { name: 'basic1', type: 'basic' },
|
||||
sid: 'some-long-sid',
|
||||
state: 'some-state',
|
||||
username: 'some-user',
|
||||
});
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('#create', () => {
|
||||
it('creates session value', async () => {
|
||||
const mockSID = Buffer.from([1, ...Array(31).keys()]).toString('base64');
|
||||
const mockAAD = Buffer.from([2, ...Array(31).keys()]).toString('base64');
|
||||
|
||||
const mockSessionIndexValue = sessionIndexMock.createValue({
|
||||
sid: mockSID,
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 456,
|
||||
});
|
||||
mockSessionIndex.create.mockResolvedValue(mockSessionIndexValue);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.create(mockRequest, {
|
||||
username: mockAuthenticatedUser().username,
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
state: 'some-state',
|
||||
})
|
||||
).resolves.toEqual({
|
||||
sid: mockSID,
|
||||
username: 'user',
|
||||
state: 'some-state',
|
||||
provider: { name: 'basic1', type: 'basic' },
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 456,
|
||||
metadata: { index: mockSessionIndexValue },
|
||||
});
|
||||
|
||||
// Properly creates session index value.
|
||||
expect(mockSessionIndex.create).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.create).toHaveBeenCalledWith({
|
||||
sid: mockSID,
|
||||
content:
|
||||
'AwABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9PgQAAQIDBAUGBwgJCpgMitlj6jACf9fYYa66WkuUpJsdgbWevIEfo6mN827f0lGcKDNPzN+vDMMPFetOkRITDI+NMz7e3JcMofnDboRnvg==',
|
||||
provider: { name: 'basic1', type: 'basic' },
|
||||
usernameHash: '8ac76453d769d4fd14b3f41ad4933f9bd64321972cd002de9b847e117435b08b',
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 456,
|
||||
});
|
||||
|
||||
// Properly creates session cookie value.
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(mockRequest, {
|
||||
sid: mockSID,
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 456,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#update', () => {
|
||||
const mockAAD = Buffer.from([2, ...Array(255).keys()]).toString('base64');
|
||||
|
||||
it('returns `null` if there is no corresponding session cookie value', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(null);
|
||||
// To make sure we aren't even calling this method.
|
||||
mockSessionIndex.update.mockResolvedValue(
|
||||
sessionIndexMock.createValue({
|
||||
content: await encryptContent({ username: 'some-user', state: 'some-state' }, mockAAD),
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
session.update(httpServerMock.createKibanaRequest(), sessionMock.createValue())
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns `null` and clears cookie if there is no corresponding session index value', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(sessionCookieMock.createValue());
|
||||
mockSessionIndex.update.mockResolvedValue(null);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(session.update(mockRequest, sessionMock.createValue())).resolves.toBeNull();
|
||||
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledWith(mockRequest);
|
||||
});
|
||||
|
||||
it('updates session value', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
aad: mockAAD,
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
);
|
||||
|
||||
const mockSessionIndexValue = sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 1,
|
||||
metadata: { primaryTerm: 2, sequenceNumber: 2 },
|
||||
});
|
||||
mockSessionIndex.update.mockResolvedValue(mockSessionIndexValue);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.update(
|
||||
mockRequest,
|
||||
sessionMock.createValue({
|
||||
username: 'new-user',
|
||||
state: 'new-state',
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 1,
|
||||
})
|
||||
)
|
||||
).resolves.toEqual({
|
||||
sid: 'some-long-sid',
|
||||
username: 'new-user',
|
||||
state: 'new-state',
|
||||
provider: { name: 'basic1', type: 'basic' },
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 1,
|
||||
metadata: { index: mockSessionIndexValue },
|
||||
});
|
||||
|
||||
// Properly updates session index value.
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith({
|
||||
sid: 'some-long-sid',
|
||||
content:
|
||||
'AQABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9PgIAAQIDBAUGBwgJCt8yPPMsaNAxn7qtLtc57UN967e9FpjmJgEIipe6nD20F47TtNIZnAuzd75zc8TNWvPMgRTzpHnYz7cT9m5ouv2V8TZ+ow==',
|
||||
provider: { name: 'basic1', type: 'basic' },
|
||||
usernameHash: '35133597af273830c3f139c72501e676338f28a39dca8ff62d5c2b8bfba75f69',
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 1,
|
||||
metadata: { primaryTerm: 1, sequenceNumber: 1 },
|
||||
});
|
||||
|
||||
// Properly updates session cookie value.
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(mockRequest, {
|
||||
sid: 'some-long-sid',
|
||||
aad: mockAAD,
|
||||
path: '/mock-base-path',
|
||||
idleTimeoutExpiration: now + 123,
|
||||
lifespanExpiration: now + 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('properly extends session expiration if idle timeout is defined.', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ aad: mockAAD, idleTimeoutExpiration: now + 1 })
|
||||
);
|
||||
mockSessionIndex.update.mockResolvedValue(
|
||||
sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: now + 123,
|
||||
})
|
||||
);
|
||||
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { idleTimeout: 123 } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.update(mockRequest, sessionMock.createValue({ idleTimeoutExpiration: now + 1 }))
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({ idleTimeoutExpiration: now + 123, lifespanExpiration: null })
|
||||
);
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ idleTimeoutExpiration: now + 123, lifespanExpiration: null })
|
||||
);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({ idleTimeoutExpiration: now + 123, lifespanExpiration: null })
|
||||
);
|
||||
});
|
||||
|
||||
describe('conditionally updates the session lifespan expiration', () => {
|
||||
const hr = 1000 * 60 * 60;
|
||||
async function updateSession(
|
||||
lifespan: number | null,
|
||||
oldExpiration: number | null,
|
||||
newExpiration: number | null
|
||||
) {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ aad: mockAAD, lifespanExpiration: oldExpiration })
|
||||
);
|
||||
mockSessionIndex.update.mockResolvedValue(
|
||||
sessionIndexMock.createValue({ lifespanExpiration: newExpiration })
|
||||
);
|
||||
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { lifespan } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.update(
|
||||
mockRequest,
|
||||
sessionMock.createValue({ lifespanExpiration: oldExpiration })
|
||||
)
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: newExpiration,
|
||||
})
|
||||
);
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: newExpiration,
|
||||
})
|
||||
);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: newExpiration,
|
||||
})
|
||||
);
|
||||
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
it('does not change a non-null lifespan expiration when configured to non-null value.', async () => {
|
||||
await updateSession(hr * 8, 1234, 1234);
|
||||
});
|
||||
|
||||
it('does not change a null lifespan expiration when configured to null value.', async () => {
|
||||
await updateSession(null, null, null);
|
||||
});
|
||||
|
||||
it('does change a non-null lifespan expiration when configured to null value.', async () => {
|
||||
await updateSession(null, 1234, null);
|
||||
});
|
||||
|
||||
it('does change a null lifespan expiration when configured to non-null value', async () => {
|
||||
await updateSession(hr * 8, null, now + hr * 8);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#extend', () => {
|
||||
it('returns `null` if there is no corresponding session cookie value', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
session.extend(httpServerMock.createKibanaRequest(), sessionMock.createValue())
|
||||
).resolves.toBeNull();
|
||||
|
||||
expect(mockSessionCookie.set).not.toHaveBeenCalled();
|
||||
expect(mockSessionIndex.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns specified session unmodified if neither idle timeout nor lifespan is specified', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(sessionCookieMock.createValue());
|
||||
mockSessionIndex.update.mockResolvedValue(sessionIndexMock.createValue());
|
||||
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(ConfigSchema.validate({}), loggingSystemMock.createLogger(), {
|
||||
isTLSEnabled: false,
|
||||
}),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(session.extend(mockRequest, sessionMock.createValue())).resolves.toEqual(
|
||||
sessionMock.createValue()
|
||||
);
|
||||
expect(mockSessionIndex.update).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.set).not.toHaveBeenCalled();
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('properly extends session expiration if both idle timeout and lifespan are defined.', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 2,
|
||||
})
|
||||
);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.extend(
|
||||
mockRequest,
|
||||
sessionMock.createValue({
|
||||
idleTimeoutExpiration: now + 1,
|
||||
lifespanExpiration: now + 2,
|
||||
metadata: {
|
||||
index: sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: now - 123,
|
||||
lifespanExpiration: now + 2,
|
||||
}),
|
||||
},
|
||||
})
|
||||
)
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({ idleTimeoutExpiration: now + 123, lifespanExpiration: now + 2 })
|
||||
);
|
||||
expect(mockSessionIndex.update).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({ idleTimeoutExpiration: now + 123, lifespanExpiration: now + 2 })
|
||||
);
|
||||
});
|
||||
|
||||
describe('updates the session idle timeout expiration', () => {
|
||||
beforeEach(() => {
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { idleTimeout: 123 } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not update session index value if idle timeout is below threshold.', async () => {
|
||||
const expectedNewExpiration = now + 123;
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ idleTimeoutExpiration: now + 1 })
|
||||
);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.extend(
|
||||
mockRequest,
|
||||
sessionMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration - 123,
|
||||
metadata: {
|
||||
index: sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration - 2 * 123,
|
||||
}),
|
||||
},
|
||||
})
|
||||
)
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionIndex.update).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns `null` and clears cookie if session index value does not exist.', async () => {
|
||||
const expectedNewExpiration = now + 123;
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ idleTimeoutExpiration: now + 1 })
|
||||
);
|
||||
mockSessionIndex.update.mockResolvedValue(null);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.extend(
|
||||
mockRequest,
|
||||
sessionMock.createValue({ idleTimeoutExpiration: expectedNewExpiration - 2 * 123 - 1 })
|
||||
)
|
||||
).resolves.toBeNull();
|
||||
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledWith(mockRequest);
|
||||
});
|
||||
|
||||
it('updates session index value if idle timeout exceeds threshold.', async () => {
|
||||
const expectedNewExpiration = now + 123;
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ idleTimeoutExpiration: now + 1 })
|
||||
);
|
||||
|
||||
const mockSessionIndexValue = sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration,
|
||||
metadata: { primaryTerm: 2, sequenceNumber: 2 },
|
||||
});
|
||||
mockSessionIndex.update.mockResolvedValue(mockSessionIndexValue);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.extend(
|
||||
mockRequest,
|
||||
sessionMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration - 123,
|
||||
metadata: {
|
||||
index: sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration - 2 * 123 - 1,
|
||||
}),
|
||||
},
|
||||
})
|
||||
)
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: expectedNewExpiration,
|
||||
metadata: { index: mockSessionIndexValue },
|
||||
})
|
||||
);
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updates session index value if idle timeout was not configured before.', async () => {
|
||||
const expectedNewExpiration = now + 123;
|
||||
mockSessionCookie.get.mockResolvedValue(sessionCookieMock.createValue());
|
||||
|
||||
const mockSessionIndexValue = sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration,
|
||||
metadata: { primaryTerm: 2, sequenceNumber: 2 },
|
||||
});
|
||||
mockSessionIndex.update.mockResolvedValue(mockSessionIndexValue);
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(session.extend(mockRequest, sessionMock.createValue())).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: expectedNewExpiration,
|
||||
metadata: { index: mockSessionIndexValue },
|
||||
})
|
||||
);
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updates session index value if idle timeout is not configured anymore.', async () => {
|
||||
const expectedNewExpiration = null;
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ idleTimeoutExpiration: now + 1 })
|
||||
);
|
||||
|
||||
const mockSessionIndexValue = sessionIndexMock.createValue({
|
||||
idleTimeoutExpiration: expectedNewExpiration,
|
||||
metadata: { primaryTerm: 2, sequenceNumber: 2 },
|
||||
});
|
||||
mockSessionIndex.update.mockResolvedValue(mockSessionIndexValue);
|
||||
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { idleTimeout: null } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.extend(mockRequest, sessionMock.createValue({ idleTimeoutExpiration: now + 1 }))
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: expectedNewExpiration,
|
||||
metadata: { index: mockSessionIndexValue },
|
||||
})
|
||||
);
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({ idleTimeoutExpiration: expectedNewExpiration })
|
||||
);
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('conditionally updates the session lifespan expiration', () => {
|
||||
const hr = 1000 * 60 * 60;
|
||||
async function updateSession(
|
||||
lifespan: number | null,
|
||||
oldExpiration: number | null,
|
||||
newExpiration: number | null
|
||||
) {
|
||||
mockSessionCookie.get.mockResolvedValue(
|
||||
sessionCookieMock.createValue({ lifespanExpiration: oldExpiration })
|
||||
);
|
||||
mockSessionIndex.update.mockResolvedValue(
|
||||
sessionIndexMock.createValue({ lifespanExpiration: newExpiration })
|
||||
);
|
||||
|
||||
session = new Session({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { lifespan } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
sessionCookie: mockSessionCookie,
|
||||
sessionIndex: mockSessionIndex,
|
||||
});
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await expect(
|
||||
session.extend(
|
||||
mockRequest,
|
||||
sessionMock.createValue({ lifespanExpiration: oldExpiration })
|
||||
)
|
||||
).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: newExpiration,
|
||||
})
|
||||
);
|
||||
|
||||
if (oldExpiration === newExpiration) {
|
||||
expect(mockSessionIndex.update).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.set).not.toHaveBeenCalled();
|
||||
} else {
|
||||
// We update session index only when lifespan configuration changes.
|
||||
if (oldExpiration === null || newExpiration === null) {
|
||||
expect(mockSessionIndex.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: newExpiration,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
expect(mockSessionIndex.update).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
expect(mockSessionCookie.set).toHaveBeenCalledWith(
|
||||
mockRequest,
|
||||
expect.objectContaining({
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: newExpiration,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
it('does not change a non-null lifespan expiration when configured to non-null value.', async () => {
|
||||
await updateSession(hr * 8, 1234, 1234);
|
||||
});
|
||||
|
||||
it('does not change a null lifespan expiration when configured to null value.', async () => {
|
||||
await updateSession(null, null, null);
|
||||
});
|
||||
|
||||
it('does change a non-null lifespan expiration when configured to null value.', async () => {
|
||||
await updateSession(null, 1234, null);
|
||||
});
|
||||
|
||||
it('does change a null lifespan expiration when configured to non-null value', async () => {
|
||||
await updateSession(hr * 8, null, now + hr * 8);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#clear', () => {
|
||||
it('does not clear anything if session does not exist', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(null);
|
||||
|
||||
await session.clear(httpServerMock.createKibanaRequest());
|
||||
|
||||
expect(mockSessionIndex.clear).not.toHaveBeenCalled();
|
||||
expect(mockSessionCookie.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears both session cookie and session index', async () => {
|
||||
mockSessionCookie.get.mockResolvedValue(sessionCookieMock.createValue());
|
||||
|
||||
const mockRequest = httpServerMock.createKibanaRequest();
|
||||
await session.clear(mockRequest);
|
||||
|
||||
expect(mockSessionIndex.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionIndex.clear).toHaveBeenCalledWith('some-long-sid');
|
||||
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionCookie.clear).toHaveBeenCalledWith(mockRequest);
|
||||
});
|
||||
});
|
||||
});
|
414
x-pack/plugins/security/server/session_management/session.ts
Normal file
414
x-pack/plugins/security/server/session_management/session.ts
Normal file
|
@ -0,0 +1,414 @@
|
|||
/*
|
||||
* 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 nodeCrypto, { Crypto } from '@elastic/node-crypto';
|
||||
import { promisify } from 'util';
|
||||
import { randomBytes, createHash } from 'crypto';
|
||||
import { Duration } from 'moment';
|
||||
import { KibanaRequest, Logger } from '../../../../../src/core/server';
|
||||
import { AuthenticationProvider } from '../../common/types';
|
||||
import { ConfigType } from '../config';
|
||||
import { SessionIndex, SessionIndexValue } from './session_index';
|
||||
import { SessionCookie } from './session_cookie';
|
||||
|
||||
/**
|
||||
* The shape of the value that represents user's session information.
|
||||
*/
|
||||
export interface SessionValue {
|
||||
/**
|
||||
* Unique session ID.
|
||||
*/
|
||||
sid: string;
|
||||
|
||||
/**
|
||||
* Username this session belongs. It's defined only if session is authenticated, otherwise session
|
||||
* is considered unauthenticated (e.g. intermediate session used during SSO handshake).
|
||||
*/
|
||||
username?: string;
|
||||
|
||||
/**
|
||||
* Name and type of the provider this session belongs to.
|
||||
*/
|
||||
provider: AuthenticationProvider;
|
||||
|
||||
/**
|
||||
* The Unix time in ms when the session should be considered expired. If `null`, session will stay
|
||||
* active until the browser is closed.
|
||||
*/
|
||||
idleTimeoutExpiration: number | null;
|
||||
|
||||
/**
|
||||
* The Unix time in ms which is the max total lifespan of the session. If `null`, session expire
|
||||
* time can be extended indefinitely.
|
||||
*/
|
||||
lifespanExpiration: number | null;
|
||||
|
||||
/**
|
||||
* Session value that is fed to the authentication provider. The shape is unknown upfront and
|
||||
* entirely determined by the authentication provider that owns the current session.
|
||||
*/
|
||||
state: unknown;
|
||||
|
||||
/**
|
||||
* Indicates whether user acknowledged access agreement or not.
|
||||
*/
|
||||
accessAgreementAcknowledged?: boolean;
|
||||
|
||||
/**
|
||||
* Additional information about the session value.
|
||||
*/
|
||||
metadata: { index: SessionIndexValue };
|
||||
}
|
||||
|
||||
export interface SessionOptions {
|
||||
readonly logger: Logger;
|
||||
readonly sessionIndex: PublicMethodsOf<SessionIndex>;
|
||||
readonly sessionCookie: PublicMethodsOf<SessionCookie>;
|
||||
readonly config: Pick<ConfigType, 'encryptionKey' | 'session'>;
|
||||
}
|
||||
|
||||
export interface SessionValueContentToEncrypt {
|
||||
username?: string;
|
||||
state: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SIDs and AAD must be unpredictable to prevent guessing attacks, where an attacker is able to
|
||||
* guess or predict the ID of a valid session through statistical analysis techniques. That's why we
|
||||
* generate SIDs and AAD using a secure PRNG and current OWASP guidance suggests a minimum of 16
|
||||
* bytes (128 bits), but to be on the safe side we decided to use 32 bytes (256 bits).
|
||||
*/
|
||||
const SID_BYTE_LENGTH = 32;
|
||||
const AAD_BYTE_LENGTH = 32;
|
||||
|
||||
export class Session {
|
||||
/**
|
||||
* Session idle timeout in ms. If `null`, a session will stay active until its max lifespan is reached.
|
||||
*/
|
||||
private readonly idleTimeout: Duration | null;
|
||||
|
||||
/**
|
||||
* Timeout after which idle timeout property is updated in the index.
|
||||
*/
|
||||
private readonly idleIndexUpdateTimeout: number | null;
|
||||
|
||||
/**
|
||||
* Session max lifespan in ms. If `null` session may live indefinitely.
|
||||
*/
|
||||
private readonly lifespan: Duration | null;
|
||||
|
||||
/**
|
||||
* Used to encrypt and decrypt portion of the session value using configured encryption key.
|
||||
*/
|
||||
private readonly crypto: Crypto;
|
||||
|
||||
/**
|
||||
* Promise-based version of the NodeJS native `randomBytes`.
|
||||
*/
|
||||
private readonly randomBytes = promisify(randomBytes);
|
||||
|
||||
constructor(private readonly options: Readonly<SessionOptions>) {
|
||||
this.crypto = nodeCrypto({ encryptionKey: this.options.config.encryptionKey });
|
||||
this.idleTimeout = this.options.config.session.idleTimeout;
|
||||
this.lifespan = this.options.config.session.lifespan;
|
||||
|
||||
// The timeout after which we update index is two times longer than configured idle timeout
|
||||
// since index updates are costly and we want to minimize them.
|
||||
this.idleIndexUpdateTimeout = this.options.config.session.idleTimeout
|
||||
? this.options.config.session.idleTimeout.asMilliseconds() * 2
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts session value for the specified request. Under the hood it can clear session if it is
|
||||
* invalid or created by the legacy versions of Kibana.
|
||||
* @param request Request instance to get session value for.
|
||||
*/
|
||||
async get(request: KibanaRequest) {
|
||||
const sessionCookieValue = await this.options.sessionCookie.get(request);
|
||||
if (!sessionCookieValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionLogger = this.getLoggerForSID(sessionCookieValue.sid);
|
||||
const now = Date.now();
|
||||
if (
|
||||
(sessionCookieValue.idleTimeoutExpiration &&
|
||||
sessionCookieValue.idleTimeoutExpiration < now) ||
|
||||
(sessionCookieValue.lifespanExpiration && sessionCookieValue.lifespanExpiration < now)
|
||||
) {
|
||||
sessionLogger.debug('Session has expired and will be invalidated.');
|
||||
await this.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionIndexValue = await this.options.sessionIndex.get(sessionCookieValue.sid);
|
||||
if (!sessionIndexValue) {
|
||||
sessionLogger.debug(
|
||||
'Session value is not available in the index, session cookie will be invalidated.'
|
||||
);
|
||||
await this.options.sessionCookie.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
let decryptedContent: SessionValueContentToEncrypt;
|
||||
try {
|
||||
decryptedContent = JSON.parse(
|
||||
(await this.crypto.decrypt(sessionIndexValue.content, sessionCookieValue.aad)) as string
|
||||
);
|
||||
} catch (err) {
|
||||
sessionLogger.warn(
|
||||
`Unable to decrypt session content, session will be invalidated: ${err.message}`
|
||||
);
|
||||
await this.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...Session.sessionIndexValueToSessionValue(sessionIndexValue, decryptedContent),
|
||||
// Unlike session index, session cookie contains the most up to date idle timeout expiration.
|
||||
idleTimeoutExpiration: sessionCookieValue.idleTimeoutExpiration,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates new session document in the session index encrypting sensitive state.
|
||||
* @param request Request instance to create session value for.
|
||||
* @param sessionValue Session value parameters.
|
||||
*/
|
||||
async create(
|
||||
request: KibanaRequest,
|
||||
sessionValue: Readonly<
|
||||
Omit<SessionValue, 'sid' | 'idleTimeoutExpiration' | 'lifespanExpiration' | 'metadata'>
|
||||
>
|
||||
) {
|
||||
const [sid, aad] = await Promise.all([
|
||||
this.randomBytes(SID_BYTE_LENGTH).then((sidBuffer) => sidBuffer.toString('base64')),
|
||||
this.randomBytes(AAD_BYTE_LENGTH).then((aadBuffer) => aadBuffer.toString('base64')),
|
||||
]);
|
||||
|
||||
const sessionLogger = this.getLoggerForSID(sid);
|
||||
sessionLogger.debug('Creating a new session.');
|
||||
|
||||
const sessionExpirationInfo = this.calculateExpiry();
|
||||
const { username, state, ...publicSessionValue } = sessionValue;
|
||||
|
||||
// First try to store session in the index and only then in the cookie to make sure cookie is
|
||||
// only updated if server side session is created successfully.
|
||||
const sessionIndexValue = await this.options.sessionIndex.create({
|
||||
...publicSessionValue,
|
||||
...sessionExpirationInfo,
|
||||
sid,
|
||||
usernameHash: username && createHash('sha3-256').update(username).digest('hex'),
|
||||
content: await this.crypto.encrypt(JSON.stringify({ username, state }), aad),
|
||||
});
|
||||
|
||||
await this.options.sessionCookie.set(request, { ...sessionExpirationInfo, sid, aad });
|
||||
|
||||
sessionLogger.debug('Successfully created a new session.');
|
||||
|
||||
return Session.sessionIndexValueToSessionValue(sessionIndexValue, { username, state });
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates session value for the specified request.
|
||||
* @param request Request instance to set session value for.
|
||||
* @param sessionValue Session value parameters.
|
||||
*/
|
||||
async update(request: KibanaRequest, sessionValue: Readonly<SessionValue>) {
|
||||
const sessionCookieValue = await this.options.sessionCookie.get(request);
|
||||
const sessionLogger = this.getLoggerForSID(sessionValue.sid);
|
||||
if (!sessionCookieValue) {
|
||||
sessionLogger.warn('Session cannot be updated since it does not exist.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionExpirationInfo = this.calculateExpiry(sessionCookieValue.lifespanExpiration);
|
||||
const { username, state, metadata, ...publicSessionInfo } = sessionValue;
|
||||
|
||||
// First try to store session in the index and only then in the cookie to make sure cookie is
|
||||
// only updated if server side session is created successfully.
|
||||
const sessionIndexValue = await this.options.sessionIndex.update({
|
||||
...sessionValue.metadata.index,
|
||||
...publicSessionInfo,
|
||||
...sessionExpirationInfo,
|
||||
usernameHash: username && createHash('sha3-256').update(username).digest('hex'),
|
||||
content: await this.crypto.encrypt(
|
||||
JSON.stringify({ username, state }),
|
||||
sessionCookieValue.aad
|
||||
),
|
||||
});
|
||||
|
||||
// Session may be already invalidated by another concurrent request, in this case we should
|
||||
// clear cookie for the request as well.
|
||||
if (sessionIndexValue === null) {
|
||||
sessionLogger.warn('Session cannot be updated as it has been invalidated already.');
|
||||
await this.options.sessionCookie.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
await this.options.sessionCookie.set(request, {
|
||||
...sessionCookieValue,
|
||||
...sessionExpirationInfo,
|
||||
});
|
||||
|
||||
sessionLogger.debug('Successfully updated existing session.');
|
||||
|
||||
return Session.sessionIndexValueToSessionValue(sessionIndexValue, { username, state });
|
||||
}
|
||||
|
||||
/**
|
||||
* Extends existing session.
|
||||
* @param request Request instance to set session value for.
|
||||
* @param sessionValue Session value parameters.
|
||||
*/
|
||||
async extend(request: KibanaRequest, sessionValue: Readonly<SessionValue>) {
|
||||
const sessionCookieValue = await this.options.sessionCookie.get(request);
|
||||
const sessionLogger = this.getLoggerForSID(sessionValue.sid);
|
||||
if (!sessionCookieValue) {
|
||||
sessionLogger.warn('Session cannot be extended since it does not exist.');
|
||||
return null;
|
||||
}
|
||||
|
||||
// We calculate actual expiration values based on the information extracted from the portion of
|
||||
// the session value that is stored in the cookie since it always contains the most recent value.
|
||||
const sessionExpirationInfo = this.calculateExpiry(sessionCookieValue.lifespanExpiration);
|
||||
if (
|
||||
sessionExpirationInfo.idleTimeoutExpiration === sessionValue.idleTimeoutExpiration &&
|
||||
sessionExpirationInfo.lifespanExpiration === sessionValue.lifespanExpiration
|
||||
) {
|
||||
return sessionValue;
|
||||
}
|
||||
|
||||
// Session index updates are costly and should be minimized, but these are the cases when we
|
||||
// should update session index:
|
||||
let updateSessionIndex = false;
|
||||
if (
|
||||
(sessionExpirationInfo.idleTimeoutExpiration === null &&
|
||||
sessionValue.idleTimeoutExpiration !== null) ||
|
||||
(sessionExpirationInfo.idleTimeoutExpiration !== null &&
|
||||
sessionValue.idleTimeoutExpiration === null)
|
||||
) {
|
||||
// 1. If idle timeout wasn't configured when session was initially created and is configured
|
||||
// now or vice versa.
|
||||
sessionLogger.debug(
|
||||
'Session idle timeout configuration has changed, session index will be updated.'
|
||||
);
|
||||
updateSessionIndex = true;
|
||||
} else if (
|
||||
(sessionExpirationInfo.lifespanExpiration === null &&
|
||||
sessionValue.lifespanExpiration !== null) ||
|
||||
(sessionExpirationInfo.lifespanExpiration !== null &&
|
||||
sessionValue.lifespanExpiration === null)
|
||||
) {
|
||||
// 2. If lifespan wasn't configured when session was initially created and is configured now
|
||||
// or vice versa.
|
||||
sessionLogger.debug(
|
||||
'Session lifespan configuration has changed, session index will be updated.'
|
||||
);
|
||||
updateSessionIndex = true;
|
||||
} else if (
|
||||
this.idleIndexUpdateTimeout !== null &&
|
||||
this.idleIndexUpdateTimeout <
|
||||
sessionExpirationInfo.idleTimeoutExpiration! -
|
||||
sessionValue.metadata.index.idleTimeoutExpiration!
|
||||
) {
|
||||
// 3. If idle timeout was updated a while ago.
|
||||
sessionLogger.debug(
|
||||
'Session idle timeout stored in the index is too old and will be updated.'
|
||||
);
|
||||
updateSessionIndex = true;
|
||||
}
|
||||
|
||||
// First try to store session in the index and only then in the cookie to make sure cookie is
|
||||
// only updated if server side session is created successfully.
|
||||
if (updateSessionIndex) {
|
||||
const sessionIndexValue = await this.options.sessionIndex.update({
|
||||
...sessionValue.metadata.index,
|
||||
...sessionExpirationInfo,
|
||||
});
|
||||
|
||||
// Session may be already invalidated by another concurrent request, in this case we should
|
||||
// clear cookie for the request as well.
|
||||
if (sessionIndexValue === null) {
|
||||
sessionLogger.warn('Session cannot be extended as it has been invalidated already.');
|
||||
await this.options.sessionCookie.clear(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
sessionValue.metadata.index = sessionIndexValue;
|
||||
}
|
||||
|
||||
await this.options.sessionCookie.set(request, {
|
||||
...sessionCookieValue,
|
||||
...sessionExpirationInfo,
|
||||
});
|
||||
|
||||
sessionLogger.debug('Successfully extended existing session.');
|
||||
|
||||
return { ...sessionValue, ...sessionExpirationInfo } as Readonly<SessionValue>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears session value for the specified request.
|
||||
* @param request Request instance to clear session value for.
|
||||
*/
|
||||
async clear(request: KibanaRequest) {
|
||||
const sessionCookieValue = await this.options.sessionCookie.get(request);
|
||||
if (!sessionCookieValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionLogger = this.getLoggerForSID(sessionCookieValue.sid);
|
||||
sessionLogger.debug('Invalidating session.');
|
||||
|
||||
await Promise.all([
|
||||
this.options.sessionCookie.clear(request),
|
||||
this.options.sessionIndex.clear(sessionCookieValue.sid),
|
||||
]);
|
||||
|
||||
sessionLogger.debug('Successfully invalidated session.');
|
||||
}
|
||||
|
||||
private calculateExpiry(
|
||||
currentLifespanExpiration?: number | null
|
||||
): { idleTimeoutExpiration: number | null; lifespanExpiration: number | null } {
|
||||
const now = Date.now();
|
||||
// if we are renewing an existing session, use its `lifespanExpiration` -- otherwise, set this value
|
||||
// based on the configured server `lifespan`.
|
||||
// note, if the server had a `lifespan` set and then removes it, remove `lifespanExpiration` on renewed sessions
|
||||
// also, if the server did not have a `lifespan` set and then adds it, add `lifespanExpiration` on renewed sessions
|
||||
const lifespanExpiration =
|
||||
currentLifespanExpiration && this.lifespan
|
||||
? currentLifespanExpiration
|
||||
: this.lifespan && now + this.lifespan.asMilliseconds();
|
||||
const idleTimeoutExpiration = this.idleTimeout && now + this.idleTimeout.asMilliseconds();
|
||||
|
||||
return { idleTimeoutExpiration, lifespanExpiration };
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts value retrieved from the index to the value returned to the API consumers.
|
||||
* @param sessionIndexValue The value returned from the index.
|
||||
* @param decryptedContent Decrypted session value content.
|
||||
*/
|
||||
private static sessionIndexValueToSessionValue(
|
||||
sessionIndexValue: Readonly<SessionIndexValue>,
|
||||
{ username, state }: SessionValueContentToEncrypt
|
||||
): Readonly<SessionValue> {
|
||||
// Extract values that are specific to session index value.
|
||||
const { usernameHash, content, ...publicSessionValue } = sessionIndexValue;
|
||||
return { ...publicSessionValue, username, state, metadata: { index: sessionIndexValue } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates logger scoped to a specified session ID.
|
||||
* @param sid Session ID to create logger for.
|
||||
*/
|
||||
private getLoggerForSID(sid: string) {
|
||||
return this.options.logger.get(sid?.slice(-10));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
* 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 { SessionCookie, SessionCookieValue } from './session_cookie';
|
||||
|
||||
export const sessionCookieMock = {
|
||||
create: (): jest.Mocked<PublicMethodsOf<SessionCookie>> => ({
|
||||
get: jest.fn(),
|
||||
set: jest.fn(),
|
||||
clear: jest.fn(),
|
||||
}),
|
||||
|
||||
createValue: (sessionValue: Partial<SessionCookieValue> = {}): SessionCookieValue => ({
|
||||
sid: 'some-long-sid',
|
||||
aad: 'some-aad',
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
path: '/mock-base-path',
|
||||
...sessionValue,
|
||||
}),
|
||||
};
|
|
@ -0,0 +1,150 @@
|
|||
/*
|
||||
* 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 { SessionStorage } from '../../../../../src/core/server';
|
||||
import { SessionCookie, SessionCookieOptions } from './session_cookie';
|
||||
|
||||
import {
|
||||
loggingSystemMock,
|
||||
httpServiceMock,
|
||||
sessionStorageMock,
|
||||
httpServerMock,
|
||||
} from '../../../../../src/core/server/mocks';
|
||||
import { sessionCookieMock } from './session_cookie.mock';
|
||||
|
||||
describe('Session cookie', () => {
|
||||
let sessionCookieOptions: SessionCookieOptions;
|
||||
let sessionCookie: SessionCookie;
|
||||
let mockSessionStorageFactory: ReturnType<typeof sessionStorageMock.createFactory>;
|
||||
let mockSessionStorage: jest.Mocked<SessionStorage<any>>;
|
||||
beforeEach(() => {
|
||||
const config = {
|
||||
encryptionKey: 'ab'.repeat(16),
|
||||
secureCookies: true,
|
||||
cookieName: 'my-sid-cookie',
|
||||
sameSiteCookies: 'Strict' as 'Strict',
|
||||
};
|
||||
|
||||
const httpSetupMock = httpServiceMock.createSetupContract();
|
||||
mockSessionStorage = sessionStorageMock.create();
|
||||
mockSessionStorageFactory = sessionStorageMock.createFactory();
|
||||
mockSessionStorageFactory.asScoped.mockReturnValue(mockSessionStorage);
|
||||
httpSetupMock.createCookieSessionStorageFactory.mockResolvedValue(mockSessionStorageFactory);
|
||||
|
||||
sessionCookieOptions = {
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
serverBasePath: '/mock-base-path',
|
||||
config,
|
||||
createCookieSessionStorageFactory: httpSetupMock.createCookieSessionStorageFactory,
|
||||
};
|
||||
|
||||
sessionCookie = new SessionCookie(sessionCookieOptions);
|
||||
});
|
||||
|
||||
describe('#constructor', () => {
|
||||
it('properly creates CookieSessionStorageFactory', () => {
|
||||
expect(sessionCookieOptions.createCookieSessionStorageFactory).toHaveBeenCalledTimes(1);
|
||||
expect(sessionCookieOptions.createCookieSessionStorageFactory).toHaveBeenCalledWith({
|
||||
encryptionKey: sessionCookieOptions.config.encryptionKey,
|
||||
isSecure: sessionCookieOptions.config.secureCookies,
|
||||
name: sessionCookieOptions.config.cookieName,
|
||||
sameSite: sessionCookieOptions.config.sameSiteCookies,
|
||||
validate: expect.any(Function),
|
||||
});
|
||||
});
|
||||
|
||||
it('cookie validator properly handles cookies with different base path', () => {
|
||||
const [
|
||||
[{ validate }],
|
||||
] = (sessionCookieOptions.createCookieSessionStorageFactory as jest.Mock).mock.calls;
|
||||
|
||||
expect(
|
||||
validate(sessionCookieMock.createValue({ path: sessionCookieOptions.serverBasePath }))
|
||||
).toEqual({ isValid: true });
|
||||
|
||||
expect(
|
||||
validate([
|
||||
sessionCookieMock.createValue({ path: sessionCookieOptions.serverBasePath }),
|
||||
sessionCookieMock.createValue({ path: sessionCookieOptions.serverBasePath }),
|
||||
])
|
||||
).toEqual({ isValid: true });
|
||||
|
||||
expect(validate(sessionCookieMock.createValue({ path: '/some-old-path' }))).toEqual({
|
||||
isValid: false,
|
||||
path: '/some-old-path',
|
||||
});
|
||||
|
||||
expect(
|
||||
validate([
|
||||
sessionCookieMock.createValue({ path: sessionCookieOptions.serverBasePath }),
|
||||
sessionCookieMock.createValue({ path: '/some-old-path' }),
|
||||
])
|
||||
).toEqual({ isValid: false, path: '/some-old-path' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('#get', () => {
|
||||
it('returns `null` if session storage returns `null`', async () => {
|
||||
mockSessionStorage.get.mockResolvedValue(null);
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
await expect(sessionCookie.get(request)).resolves.toBeNull();
|
||||
|
||||
expect(mockSessionStorageFactory.asScoped).toHaveBeenCalledWith(request);
|
||||
expect(mockSessionStorage.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns value if session is in compatible format', async () => {
|
||||
const sessionValue = sessionCookieMock.createValue();
|
||||
mockSessionStorage.get.mockResolvedValue(sessionValue);
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
await expect(sessionCookie.get(request)).resolves.toBe(sessionValue);
|
||||
|
||||
expect(mockSessionStorageFactory.asScoped).toHaveBeenCalledWith(request);
|
||||
expect(mockSessionStorage.clear).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns `null` and clears session value if it is in incompatible format', async () => {
|
||||
const invalidValue = sessionCookieMock.createValue();
|
||||
delete invalidValue.sid;
|
||||
|
||||
mockSessionStorage.get.mockResolvedValue(invalidValue);
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
await expect(sessionCookie.get(request)).resolves.toBeNull();
|
||||
|
||||
expect(mockSessionStorageFactory.asScoped).toHaveBeenCalledWith(request);
|
||||
expect(mockSessionStorage.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#set', () => {
|
||||
it('properly sets value in the session storage', async () => {
|
||||
const sessionValue = sessionCookieMock.createValue();
|
||||
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
await sessionCookie.set(request, sessionValue);
|
||||
|
||||
expect(mockSessionStorageFactory.asScoped).toHaveBeenCalledWith(request);
|
||||
expect(mockSessionStorage.set).toHaveBeenCalledTimes(1);
|
||||
expect(mockSessionStorage.set).toHaveBeenCalledWith({
|
||||
...sessionValue,
|
||||
path: '/mock-base-path',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#clear', () => {
|
||||
it('properly clears value in the session storage', async () => {
|
||||
const request = httpServerMock.createKibanaRequest();
|
||||
await sessionCookie.clear(request);
|
||||
|
||||
expect(mockSessionStorageFactory.asScoped).toHaveBeenCalledWith(request);
|
||||
expect(mockSessionStorage.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,149 @@
|
|||
/*
|
||||
* 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 {
|
||||
HttpServiceSetup,
|
||||
KibanaRequest,
|
||||
Logger,
|
||||
SessionStorageFactory,
|
||||
} from '../../../../../src/core/server';
|
||||
import { ConfigType } from '../config';
|
||||
|
||||
/**
|
||||
* Represents shape of the session value stored in the cookie.
|
||||
*/
|
||||
export interface SessionCookieValue {
|
||||
/**
|
||||
* Unique session ID.
|
||||
*/
|
||||
sid: string;
|
||||
|
||||
/**
|
||||
* Unique random value used as Additional authenticated data (AAD) while encrypting/decrypting
|
||||
* sensitive or PII session content stored in the Elasticsearch index. This value is only stored
|
||||
* in the user cookie.
|
||||
*/
|
||||
aad: string;
|
||||
|
||||
/**
|
||||
* Kibana server base path the session was created for.
|
||||
*/
|
||||
path: string;
|
||||
|
||||
/**
|
||||
* The Unix time in ms when the session should be considered expired. If `null`, session will stay
|
||||
* active until the max lifespan is reached.
|
||||
*/
|
||||
idleTimeoutExpiration: number | null;
|
||||
|
||||
/**
|
||||
* The Unix time in ms which is the max total lifespan of the session. If `null`, session expire
|
||||
* time can be extended indefinitely.
|
||||
*/
|
||||
lifespanExpiration: number | null;
|
||||
}
|
||||
|
||||
export interface SessionCookieOptions {
|
||||
logger: Logger;
|
||||
serverBasePath: string;
|
||||
createCookieSessionStorageFactory: HttpServiceSetup['createCookieSessionStorageFactory'];
|
||||
config: Pick<ConfigType, 'encryptionKey' | 'secureCookies' | 'cookieName' | 'sameSiteCookies'>;
|
||||
}
|
||||
|
||||
export class SessionCookie {
|
||||
/**
|
||||
* Promise containing initialized cookie session storage factory.
|
||||
*/
|
||||
private readonly cookieSessionValueStorage: Promise<
|
||||
SessionStorageFactory<Readonly<SessionCookieValue>>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Session cookie logger.
|
||||
*/
|
||||
private readonly logger: Logger;
|
||||
|
||||
/**
|
||||
* Base path of the Kibana server instance.
|
||||
*/
|
||||
private readonly serverBasePath: string;
|
||||
|
||||
constructor({
|
||||
config,
|
||||
createCookieSessionStorageFactory,
|
||||
logger,
|
||||
serverBasePath,
|
||||
}: Readonly<SessionCookieOptions>) {
|
||||
this.logger = logger;
|
||||
this.serverBasePath = serverBasePath;
|
||||
|
||||
this.cookieSessionValueStorage = createCookieSessionStorageFactory({
|
||||
encryptionKey: config.encryptionKey,
|
||||
isSecure: config.secureCookies,
|
||||
name: config.cookieName,
|
||||
sameSite: config.sameSiteCookies,
|
||||
validate: (sessionValue: SessionCookieValue | SessionCookieValue[]) => {
|
||||
// ensure that this cookie was created with the current Kibana configuration
|
||||
const invalidSessionValue = (Array.isArray(sessionValue)
|
||||
? sessionValue
|
||||
: [sessionValue]
|
||||
).find((sess) => sess.path !== undefined && sess.path !== serverBasePath);
|
||||
|
||||
if (invalidSessionValue) {
|
||||
this.logger.debug(`Outdated session value with path "${invalidSessionValue.path}"`);
|
||||
return { isValid: false, path: invalidSessionValue.path };
|
||||
}
|
||||
|
||||
return { isValid: true };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts session value for the specified request.
|
||||
* @param request Request instance to get session value for.
|
||||
*/
|
||||
async get(request: KibanaRequest) {
|
||||
const sessionStorage = (await this.cookieSessionValueStorage).asScoped(request);
|
||||
const sessionValue = await sessionStorage.get();
|
||||
|
||||
// If we detect that cookie session value is in incompatible format, then we should clear such
|
||||
// cookie.
|
||||
if (sessionValue && !SessionCookie.isSupportedSessionValue(sessionValue)) {
|
||||
sessionStorage.clear();
|
||||
return null;
|
||||
}
|
||||
|
||||
return sessionValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or updates session value for the specified request.
|
||||
* @param request Request instance to set session value for.
|
||||
* @param sessionValue Session value parameters.
|
||||
*/
|
||||
async set(request: KibanaRequest, sessionValue: Readonly<Omit<SessionCookieValue, 'path'>>) {
|
||||
(await this.cookieSessionValueStorage)
|
||||
.asScoped(request)
|
||||
.set({ ...sessionValue, path: this.serverBasePath });
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears session value for the specified request.
|
||||
* @param request Request instance to clear session value for.
|
||||
*/
|
||||
async clear(request: KibanaRequest) {
|
||||
(await this.cookieSessionValueStorage).asScoped(request).clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if session value was created by the current Kibana version. Previous versions had a different session value format.
|
||||
* @param sessionValue The session value to check.
|
||||
*/
|
||||
private static isSupportedSessionValue(sessionValue: any): sessionValue is SessionCookieValue {
|
||||
return typeof sessionValue?.sid === 'string' && typeof sessionValue?.aad === 'string';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
/*
|
||||
* 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 { SessionIndex, SessionIndexValue } from './session_index';
|
||||
|
||||
export const sessionIndexMock = {
|
||||
create: (): jest.Mocked<PublicMethodsOf<SessionIndex>> => ({
|
||||
get: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
clear: jest.fn(),
|
||||
initialize: jest.fn(),
|
||||
cleanUp: jest.fn(),
|
||||
}),
|
||||
|
||||
createValue: (sessionValue: Partial<SessionIndexValue> = {}): SessionIndexValue => ({
|
||||
sid: 'some-long-sid',
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
content: 'some-encrypted-content',
|
||||
metadata: { primaryTerm: 1, sequenceNumber: 1 },
|
||||
...sessionValue,
|
||||
}),
|
||||
};
|
|
@ -0,0 +1,518 @@
|
|||
/*
|
||||
* 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 { ILegacyClusterClient } from '../../../../../src/core/server';
|
||||
import { ConfigSchema, createConfig } from '../config';
|
||||
import { getSessionIndexTemplate, SessionIndex } from './session_index';
|
||||
|
||||
import { loggingSystemMock, elasticsearchServiceMock } from '../../../../../src/core/server/mocks';
|
||||
import { sessionIndexMock } from './session_index.mock';
|
||||
|
||||
describe('Session index', () => {
|
||||
let mockClusterClient: jest.Mocked<ILegacyClusterClient>;
|
||||
let sessionIndex: SessionIndex;
|
||||
const indexName = '.kibana_some_tenant_security_session_1';
|
||||
const indexTemplateName = '.kibana_some_tenant_security_session_index_template_1';
|
||||
beforeEach(() => {
|
||||
mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient();
|
||||
const sessionIndexOptions = {
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
kibanaIndexName: '.kibana_some_tenant',
|
||||
config: createConfig(ConfigSchema.validate({}), loggingSystemMock.createLogger(), {
|
||||
isTLSEnabled: false,
|
||||
}),
|
||||
clusterClient: mockClusterClient,
|
||||
};
|
||||
|
||||
sessionIndex = new SessionIndex(sessionIndexOptions);
|
||||
});
|
||||
|
||||
describe('#initialize', () => {
|
||||
function assertExistenceChecksPerformed() {
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('indices.existsTemplate', {
|
||||
name: indexTemplateName,
|
||||
});
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('indices.exists', {
|
||||
index: getSessionIndexTemplate(indexName).index_patterns,
|
||||
});
|
||||
}
|
||||
|
||||
it('debounces initialize calls', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'indices.existsTemplate' || method === 'indices.exists') {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new Error('Unexpected call');
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
sessionIndex.initialize(),
|
||||
sessionIndex.initialize(),
|
||||
sessionIndex.initialize(),
|
||||
sessionIndex.initialize(),
|
||||
]);
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);
|
||||
assertExistenceChecksPerformed();
|
||||
});
|
||||
|
||||
it('creates neither index template nor index if they exist', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'indices.existsTemplate' || method === 'indices.exists') {
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new Error('Unexpected call');
|
||||
});
|
||||
|
||||
await sessionIndex.initialize();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);
|
||||
assertExistenceChecksPerformed();
|
||||
});
|
||||
|
||||
it('creates both index template and index if they do not exist', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'indices.existsTemplate' || method === 'indices.exists') {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
await sessionIndex.initialize();
|
||||
|
||||
const expectedIndexTemplate = getSessionIndexTemplate(indexName);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(4);
|
||||
assertExistenceChecksPerformed();
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('indices.putTemplate', {
|
||||
name: indexTemplateName,
|
||||
body: expectedIndexTemplate,
|
||||
});
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('indices.create', {
|
||||
index: expectedIndexTemplate.index_patterns,
|
||||
});
|
||||
});
|
||||
|
||||
it('creates only index template if it does not exist even if index exists', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'indices.existsTemplate') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (method === 'indices.exists') {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
await sessionIndex.initialize();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(3);
|
||||
assertExistenceChecksPerformed();
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('indices.putTemplate', {
|
||||
name: indexTemplateName,
|
||||
body: getSessionIndexTemplate(indexName),
|
||||
});
|
||||
});
|
||||
|
||||
it('creates only index if it does not exist even if index template exists', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'indices.existsTemplate') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (method === 'indices.exists') {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
await sessionIndex.initialize();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(3);
|
||||
assertExistenceChecksPerformed();
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('indices.create', {
|
||||
index: getSessionIndexTemplate(indexName).index_patterns,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not fail if tries to create index when it exists already', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'indices.existsTemplate') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (method === 'indices.exists') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (method === 'indices.create') {
|
||||
// eslint-disable-next-line no-throw-literal
|
||||
throw { body: { error: { type: 'resource_already_exists_exception' } } };
|
||||
}
|
||||
});
|
||||
|
||||
await sessionIndex.initialize();
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanUp', () => {
|
||||
const now = 123456;
|
||||
beforeEach(() => {
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({});
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
});
|
||||
|
||||
it('throws if call to Elasticsearch fails', async () => {
|
||||
const failureReason = new Error('Uh oh.');
|
||||
mockClusterClient.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(sessionIndex.cleanUp()).rejects.toBe(failureReason);
|
||||
});
|
||||
|
||||
it('when neither `lifespan` nor `idleTimeout` is configured', async () => {
|
||||
await sessionIndex.cleanUp();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('deleteByQuery', {
|
||||
index: indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409, 404],
|
||||
body: {
|
||||
query: {
|
||||
bool: {
|
||||
should: [
|
||||
{ range: { lifespanExpiration: { lte: now } } },
|
||||
{ range: { idleTimeoutExpiration: { lte: now } } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('when only `lifespan` is configured', async () => {
|
||||
sessionIndex = new SessionIndex({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
kibanaIndexName: '.kibana_some_tenant',
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { lifespan: 456 } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
clusterClient: mockClusterClient,
|
||||
});
|
||||
|
||||
await sessionIndex.cleanUp();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('deleteByQuery', {
|
||||
index: indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409, 404],
|
||||
body: {
|
||||
query: {
|
||||
bool: {
|
||||
should: [
|
||||
{ range: { lifespanExpiration: { lte: now } } },
|
||||
{ bool: { must_not: { exists: { field: 'lifespanExpiration' } } } },
|
||||
{ range: { idleTimeoutExpiration: { lte: now } } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('when only `idleTimeout` is configured', async () => {
|
||||
const idleTimeout = 123;
|
||||
sessionIndex = new SessionIndex({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
kibanaIndexName: '.kibana_some_tenant',
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { idleTimeout } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
clusterClient: mockClusterClient,
|
||||
});
|
||||
|
||||
await sessionIndex.cleanUp();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('deleteByQuery', {
|
||||
index: indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409, 404],
|
||||
body: {
|
||||
query: {
|
||||
bool: {
|
||||
should: [
|
||||
{ range: { lifespanExpiration: { lte: now } } },
|
||||
{ range: { idleTimeoutExpiration: { lte: now - 3 * idleTimeout } } },
|
||||
{ bool: { must_not: { exists: { field: 'idleTimeoutExpiration' } } } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('when both `lifespan` and `idleTimeout` are configured', async () => {
|
||||
const idleTimeout = 123;
|
||||
sessionIndex = new SessionIndex({
|
||||
logger: loggingSystemMock.createLogger(),
|
||||
kibanaIndexName: '.kibana_some_tenant',
|
||||
config: createConfig(
|
||||
ConfigSchema.validate({ session: { idleTimeout, lifespan: 456 } }),
|
||||
loggingSystemMock.createLogger(),
|
||||
{ isTLSEnabled: false }
|
||||
),
|
||||
clusterClient: mockClusterClient,
|
||||
});
|
||||
|
||||
await sessionIndex.cleanUp();
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('deleteByQuery', {
|
||||
index: indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409, 404],
|
||||
body: {
|
||||
query: {
|
||||
bool: {
|
||||
should: [
|
||||
{ range: { lifespanExpiration: { lte: now } } },
|
||||
{ bool: { must_not: { exists: { field: 'lifespanExpiration' } } } },
|
||||
{ range: { idleTimeoutExpiration: { lte: now - 3 * idleTimeout } } },
|
||||
{ bool: { must_not: { exists: { field: 'idleTimeoutExpiration' } } } },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#get', () => {
|
||||
it('throws if call to Elasticsearch fails', async () => {
|
||||
const failureReason = new Error('Uh oh.');
|
||||
mockClusterClient.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(sessionIndex.get('some-sid')).rejects.toBe(failureReason);
|
||||
});
|
||||
|
||||
it('returns `null` if index is not found', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({ status: 404 });
|
||||
|
||||
await expect(sessionIndex.get('some-sid')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns `null` if session index value document is not found', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({
|
||||
found: false,
|
||||
status: 200,
|
||||
});
|
||||
|
||||
await expect(sessionIndex.get('some-sid')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('properly returns session index value', async () => {
|
||||
const indexDocumentSource = {
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: 123,
|
||||
lifespanExpiration: null,
|
||||
content: 'some-encrypted-content',
|
||||
};
|
||||
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({
|
||||
found: true,
|
||||
status: 200,
|
||||
_source: indexDocumentSource,
|
||||
_primary_term: 1,
|
||||
_seq_no: 456,
|
||||
});
|
||||
|
||||
await expect(sessionIndex.get('some-sid')).resolves.toEqual({
|
||||
...indexDocumentSource,
|
||||
sid: 'some-sid',
|
||||
metadata: { primaryTerm: 1, sequenceNumber: 456 },
|
||||
});
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('get', {
|
||||
id: 'some-sid',
|
||||
ignore: [404],
|
||||
index: indexName,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#create', () => {
|
||||
it('throws if call to Elasticsearch fails', async () => {
|
||||
const failureReason = new Error('Uh oh.');
|
||||
mockClusterClient.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(
|
||||
sessionIndex.create({
|
||||
sid: 'some-long-sid',
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
content: 'some-encrypted-content',
|
||||
})
|
||||
).rejects.toBe(failureReason);
|
||||
});
|
||||
|
||||
it('properly stores session value in the index', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({
|
||||
_primary_term: 321,
|
||||
_seq_no: 654,
|
||||
});
|
||||
|
||||
const sid = 'some-long-sid';
|
||||
const sessionValue = {
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
content: 'some-encrypted-content',
|
||||
};
|
||||
|
||||
await expect(sessionIndex.create({ sid, ...sessionValue })).resolves.toEqual({
|
||||
...sessionValue,
|
||||
sid,
|
||||
metadata: { primaryTerm: 321, sequenceNumber: 654 },
|
||||
});
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('create', {
|
||||
id: sid,
|
||||
index: indexName,
|
||||
body: sessionValue,
|
||||
refresh: 'wait_for',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#update', () => {
|
||||
it('throws if call to Elasticsearch fails', async () => {
|
||||
const failureReason = new Error('Uh oh.');
|
||||
mockClusterClient.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(sessionIndex.update(sessionIndexMock.createValue())).rejects.toBe(failureReason);
|
||||
});
|
||||
|
||||
it('refetches latest session value if update fails due to conflict', async () => {
|
||||
const latestSessionValue = {
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: 100,
|
||||
lifespanExpiration: 200,
|
||||
content: 'some-updated-encrypted-content',
|
||||
};
|
||||
|
||||
mockClusterClient.callAsInternalUser.mockImplementation(async (method) => {
|
||||
if (method === 'get') {
|
||||
return {
|
||||
found: true,
|
||||
status: 200,
|
||||
_source: latestSessionValue,
|
||||
_primary_term: 321,
|
||||
_seq_no: 654,
|
||||
};
|
||||
}
|
||||
|
||||
if (method === 'index') {
|
||||
return { status: 409 };
|
||||
}
|
||||
});
|
||||
|
||||
const sid = 'some-long-sid';
|
||||
const metadata = { primaryTerm: 123, sequenceNumber: 456 };
|
||||
const sessionValue = {
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
content: 'some-encrypted-content',
|
||||
};
|
||||
|
||||
await expect(sessionIndex.update({ sid, metadata, ...sessionValue })).resolves.toEqual({
|
||||
...latestSessionValue,
|
||||
sid,
|
||||
metadata: { primaryTerm: 321, sequenceNumber: 654 },
|
||||
});
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(2);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('index', {
|
||||
id: sid,
|
||||
index: indexName,
|
||||
body: sessionValue,
|
||||
ifSeqNo: 456,
|
||||
ifPrimaryTerm: 123,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409],
|
||||
});
|
||||
});
|
||||
|
||||
it('properly stores session value in the index', async () => {
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({
|
||||
_primary_term: 321,
|
||||
_seq_no: 654,
|
||||
status: 200,
|
||||
});
|
||||
|
||||
const sid = 'some-long-sid';
|
||||
const metadata = { primaryTerm: 123, sequenceNumber: 456 };
|
||||
const sessionValue = {
|
||||
usernameHash: 'some-username-hash',
|
||||
provider: { type: 'basic', name: 'basic1' },
|
||||
idleTimeoutExpiration: null,
|
||||
lifespanExpiration: null,
|
||||
content: 'some-encrypted-content',
|
||||
};
|
||||
|
||||
await expect(sessionIndex.update({ sid, metadata, ...sessionValue })).resolves.toEqual({
|
||||
...sessionValue,
|
||||
sid,
|
||||
metadata: { primaryTerm: 321, sequenceNumber: 654 },
|
||||
});
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('index', {
|
||||
id: sid,
|
||||
index: indexName,
|
||||
body: sessionValue,
|
||||
ifSeqNo: 456,
|
||||
ifPrimaryTerm: 123,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#clear', () => {
|
||||
it('throws if call to Elasticsearch fails', async () => {
|
||||
const failureReason = new Error('Uh oh.');
|
||||
mockClusterClient.callAsInternalUser.mockRejectedValue(failureReason);
|
||||
|
||||
await expect(sessionIndex.clear('some-long-sid')).rejects.toBe(failureReason);
|
||||
});
|
||||
|
||||
it('properly removes session value from the index', async () => {
|
||||
await sessionIndex.clear('some-long-sid');
|
||||
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledTimes(1);
|
||||
expect(mockClusterClient.callAsInternalUser).toHaveBeenCalledWith('delete', {
|
||||
id: 'some-long-sid',
|
||||
index: indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [404],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,395 @@
|
|||
/*
|
||||
* 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 { ILegacyClusterClient, Logger } from '../../../../../src/core/server';
|
||||
import { AuthenticationProvider } from '../../common/types';
|
||||
import { ConfigType } from '../config';
|
||||
|
||||
export interface SessionIndexOptions {
|
||||
readonly clusterClient: ILegacyClusterClient;
|
||||
readonly kibanaIndexName: string;
|
||||
readonly config: Pick<ConfigType, 'session'>;
|
||||
readonly logger: Logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Version of the current session index template.
|
||||
*/
|
||||
const SESSION_INDEX_TEMPLATE_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Returns index template that is used for the current version of the session index.
|
||||
*/
|
||||
export function getSessionIndexTemplate(indexName: string) {
|
||||
return Object.freeze({
|
||||
index_patterns: indexName,
|
||||
order: 1000,
|
||||
settings: {
|
||||
index: {
|
||||
number_of_shards: 1,
|
||||
number_of_replicas: 0,
|
||||
auto_expand_replicas: '0-1',
|
||||
priority: 1000,
|
||||
refresh_interval: '1s',
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
mappings: {
|
||||
dynamic: 'strict',
|
||||
properties: {
|
||||
usernameHash: { type: 'keyword' },
|
||||
provider: { properties: { name: { type: 'keyword' }, type: { type: 'keyword' } } },
|
||||
idleTimeoutExpiration: { type: 'date' },
|
||||
lifespanExpiration: { type: 'date' },
|
||||
accessAgreementAcknowledged: { type: 'boolean' },
|
||||
content: { type: 'binary' },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents shape of the session value stored in the index.
|
||||
*/
|
||||
export interface SessionIndexValue {
|
||||
/**
|
||||
* Unique session ID.
|
||||
*/
|
||||
sid: string;
|
||||
|
||||
/**
|
||||
* Hash of the username. It's defined only if session is authenticated, otherwise session
|
||||
* is considered unauthenticated (e.g. intermediate session used during SSO handshake).
|
||||
*/
|
||||
usernameHash?: string;
|
||||
|
||||
/**
|
||||
* Name and type of the provider this session belongs to.
|
||||
*/
|
||||
provider: AuthenticationProvider;
|
||||
|
||||
/**
|
||||
* The Unix time in ms when the session should be considered expired. If `null`, session will stay
|
||||
* active until the browser is closed.
|
||||
*/
|
||||
idleTimeoutExpiration: number | null;
|
||||
|
||||
/**
|
||||
* The Unix time in ms which is the max total lifespan of the session. If `null`, session expire
|
||||
* time can be extended indefinitely.
|
||||
*/
|
||||
lifespanExpiration: number | null;
|
||||
|
||||
/**
|
||||
* Indicates whether user acknowledged access agreement or not.
|
||||
*/
|
||||
accessAgreementAcknowledged?: boolean;
|
||||
|
||||
/**
|
||||
* Content of the session value represented as an encrypted JSON string.
|
||||
*/
|
||||
content: string;
|
||||
|
||||
/**
|
||||
* Additional index specific information about the session value.
|
||||
*/
|
||||
metadata: SessionIndexValueMetadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Additional index specific information about the session value.
|
||||
*/
|
||||
interface SessionIndexValueMetadata {
|
||||
/**
|
||||
* Primary term of the last modification of the document.
|
||||
*/
|
||||
primaryTerm: number;
|
||||
|
||||
/**
|
||||
* Sequence number of the last modification of the document.
|
||||
*/
|
||||
sequenceNumber: number;
|
||||
}
|
||||
|
||||
export class SessionIndex {
|
||||
/**
|
||||
* Name of the index to store session information in.
|
||||
*/
|
||||
private readonly indexName = `${this.options.kibanaIndexName}_security_session_${SESSION_INDEX_TEMPLATE_VERSION}`;
|
||||
|
||||
/**
|
||||
* Timeout after which session with the expired idle timeout _may_ be removed from the index
|
||||
* during regular cleanup routine.
|
||||
*/
|
||||
private readonly idleIndexCleanupTimeout: number | null;
|
||||
|
||||
/**
|
||||
* Promise that tracks session index initialization process. We'll need to get rid of this as soon
|
||||
* as Core provides support for plugin statuses (https://github.com/elastic/kibana/issues/41983).
|
||||
* With this we won't mark Security as `Green` until index is fully initialized and hence consumers
|
||||
* won't be able to call any APIs we provide.
|
||||
*/
|
||||
private indexInitialization?: Promise<void>;
|
||||
|
||||
constructor(private readonly options: Readonly<SessionIndexOptions>) {
|
||||
// This timeout is intentionally larger than the `idleIndexUpdateTimeout` (idleTimeout * 2)
|
||||
// configured in `Session` to be sure that the session value is definitely expired and may be
|
||||
// safely cleaned up.
|
||||
this.idleIndexCleanupTimeout = this.options.config.session.idleTimeout
|
||||
? this.options.config.session.idleTimeout.asMilliseconds() * 3
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves session value with the specified ID from the index. If session value isn't found
|
||||
* `null` will be returned.
|
||||
* @param sid Session ID.
|
||||
*/
|
||||
async get(sid: string) {
|
||||
try {
|
||||
const response = await this.options.clusterClient.callAsInternalUser('get', {
|
||||
id: sid,
|
||||
ignore: [404],
|
||||
index: this.indexName,
|
||||
});
|
||||
|
||||
const docNotFound = response.found === false;
|
||||
const indexNotFound = response.status === 404;
|
||||
if (docNotFound || indexNotFound) {
|
||||
this.options.logger.debug('Cannot find session value with the specified ID.');
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...response._source,
|
||||
sid,
|
||||
metadata: { primaryTerm: response._primary_term, sequenceNumber: response._seq_no },
|
||||
} as Readonly<SessionIndexValue>;
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to retrieve session value: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new document for the specified session value.
|
||||
* @param sessionValue Session index value.
|
||||
*/
|
||||
async create(sessionValue: Readonly<Omit<SessionIndexValue, 'metadata'>>) {
|
||||
if (this.indexInitialization) {
|
||||
this.options.logger.warn(
|
||||
'Attempted to create a new session while session index is initializing.'
|
||||
);
|
||||
await this.indexInitialization;
|
||||
}
|
||||
|
||||
const { sid, ...sessionValueToStore } = sessionValue;
|
||||
try {
|
||||
const {
|
||||
_primary_term: primaryTerm,
|
||||
_seq_no: sequenceNumber,
|
||||
} = await this.options.clusterClient.callAsInternalUser('create', {
|
||||
id: sid,
|
||||
// We cannot control whether index is created automatically during this operation or not.
|
||||
// But we can reduce probability of getting into a weird state when session is being created
|
||||
// while session index is missing for some reason. This way we'll recreate index with a
|
||||
// proper name and alias. But this will only work if we still have a proper index template.
|
||||
index: this.indexName,
|
||||
body: sessionValueToStore,
|
||||
refresh: 'wait_for',
|
||||
});
|
||||
|
||||
return { ...sessionValue, metadata: { primaryTerm, sequenceNumber } } as SessionIndexValue;
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to create session value: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-indexes updated session value.
|
||||
* @param sessionValue Session index value.
|
||||
*/
|
||||
async update(sessionValue: Readonly<SessionIndexValue>) {
|
||||
const { sid, metadata, ...sessionValueToStore } = sessionValue;
|
||||
try {
|
||||
const response = await this.options.clusterClient.callAsInternalUser('index', {
|
||||
id: sid,
|
||||
index: this.indexName,
|
||||
body: sessionValueToStore,
|
||||
ifSeqNo: metadata.sequenceNumber,
|
||||
ifPrimaryTerm: metadata.primaryTerm,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409],
|
||||
});
|
||||
|
||||
// We don't want to override changes that were made after we fetched session value or
|
||||
// re-create it if has been deleted already. If we detect such a case we discard changes and
|
||||
// return latest copy of the session value instead or `null` if doesn't exist anymore.
|
||||
const sessionIndexValueUpdateConflict = response.status === 409;
|
||||
if (sessionIndexValueUpdateConflict) {
|
||||
this.options.logger.debug(
|
||||
'Cannot update session value due to conflict, session either does not exist or was already updated.'
|
||||
);
|
||||
return await this.get(sid);
|
||||
}
|
||||
|
||||
return {
|
||||
...sessionValue,
|
||||
metadata: { primaryTerm: response._primary_term, sequenceNumber: response._seq_no },
|
||||
} as SessionIndexValue;
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to update session value: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears session value with the specified ID.
|
||||
* @param sid Session ID to clear.
|
||||
*/
|
||||
async clear(sid: string) {
|
||||
try {
|
||||
// We don't specify primary term and sequence number as delete should always take precedence
|
||||
// over any updates that could happen in the meantime.
|
||||
await this.options.clusterClient.callAsInternalUser('delete', {
|
||||
id: sid,
|
||||
index: this.indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [404],
|
||||
});
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to clear session value: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes index that is used to store session values.
|
||||
*/
|
||||
async initialize() {
|
||||
if (this.indexInitialization) {
|
||||
return await this.indexInitialization;
|
||||
}
|
||||
|
||||
const sessionIndexTemplateName = `${this.options.kibanaIndexName}_security_session_index_template_${SESSION_INDEX_TEMPLATE_VERSION}`;
|
||||
return (this.indexInitialization = new Promise(async (resolve) => {
|
||||
// Check if required index template exists.
|
||||
let indexTemplateExists = false;
|
||||
try {
|
||||
indexTemplateExists = await this.options.clusterClient.callAsInternalUser(
|
||||
'indices.existsTemplate',
|
||||
{ name: sessionIndexTemplateName }
|
||||
);
|
||||
} catch (err) {
|
||||
this.options.logger.error(
|
||||
`Failed to check if session index template exists: ${err.message}`
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Create index template if it doesn't exist.
|
||||
if (indexTemplateExists) {
|
||||
this.options.logger.debug('Session index template already exists.');
|
||||
} else {
|
||||
try {
|
||||
await this.options.clusterClient.callAsInternalUser('indices.putTemplate', {
|
||||
name: sessionIndexTemplateName,
|
||||
body: getSessionIndexTemplate(this.indexName),
|
||||
});
|
||||
this.options.logger.debug('Successfully created session index template.');
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to create session index template: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if required index exists. We cannot be sure that automatic creation of indices is
|
||||
// always enabled, so we create session index explicitly.
|
||||
let indexExists = false;
|
||||
try {
|
||||
indexExists = await this.options.clusterClient.callAsInternalUser('indices.exists', {
|
||||
index: this.indexName,
|
||||
});
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to check if session index exists: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Create index if it doesn't exist.
|
||||
if (indexExists) {
|
||||
this.options.logger.debug('Session index already exists.');
|
||||
} else {
|
||||
try {
|
||||
await this.options.clusterClient.callAsInternalUser('indices.create', {
|
||||
index: this.indexName,
|
||||
});
|
||||
this.options.logger.debug('Successfully created session index.');
|
||||
} catch (err) {
|
||||
// There can be a race condition if index is created by another Kibana instance.
|
||||
if (err?.body?.error?.type === 'resource_already_exists_exception') {
|
||||
this.options.logger.debug('Session index already exists.');
|
||||
} else {
|
||||
this.options.logger.error(`Failed to create session index: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notify any consumers that are awaiting on this promise and immediately reset it.
|
||||
resolve();
|
||||
this.indexInitialization = undefined;
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a removal of any outdated session values.
|
||||
*/
|
||||
async cleanUp() {
|
||||
this.options.logger.debug(`Running cleanup routine.`);
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
// Always try to delete sessions with expired lifespan (even if it's not configured right now).
|
||||
const deleteQueries: object[] = [{ range: { lifespanExpiration: { lte: now } } }];
|
||||
|
||||
// If lifespan is configured we should remove any sessions that were created without one.
|
||||
if (this.options.config.session.lifespan) {
|
||||
deleteQueries.push({ bool: { must_not: { exists: { field: 'lifespanExpiration' } } } });
|
||||
}
|
||||
|
||||
// If idle timeout is configured we should delete all sessions without specified idle timeout
|
||||
// or if that session hasn't been updated for a while meaning that session is expired.
|
||||
if (this.idleIndexCleanupTimeout) {
|
||||
deleteQueries.push(
|
||||
{ range: { idleTimeoutExpiration: { lte: now - this.idleIndexCleanupTimeout } } },
|
||||
{ bool: { must_not: { exists: { field: 'idleTimeoutExpiration' } } } }
|
||||
);
|
||||
} else {
|
||||
// Otherwise just delete all expired sessions that were previously created with the idle
|
||||
// timeout.
|
||||
deleteQueries.push({ range: { idleTimeoutExpiration: { lte: now } } });
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.options.clusterClient.callAsInternalUser('deleteByQuery', {
|
||||
index: this.indexName,
|
||||
refresh: 'wait_for',
|
||||
ignore: [409, 404],
|
||||
body: { query: { bool: { should: deleteQueries } } },
|
||||
});
|
||||
|
||||
if (response.deleted > 0) {
|
||||
this.options.logger.debug(
|
||||
`Cleaned up ${response.deleted} invalid or expired session values.`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.options.logger.error(`Failed to clean up sessions: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,313 @@
|
|||
/*
|
||||
* 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 { Subject } from 'rxjs';
|
||||
import { ConfigSchema, createConfig } from '../config';
|
||||
import { OnlineStatusRetryScheduler } from '../elasticsearch';
|
||||
import {
|
||||
SessionManagementService,
|
||||
SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
} from './session_management_service';
|
||||
import { Session } from './session';
|
||||
import { SessionIndex } from './session_index';
|
||||
|
||||
import { nextTick } from 'test_utils/enzyme_helpers';
|
||||
import {
|
||||
coreMock,
|
||||
elasticsearchServiceMock,
|
||||
loggingSystemMock,
|
||||
} from '../../../../../src/core/server/mocks';
|
||||
import { taskManagerMock } from '../../../task_manager/server/mocks';
|
||||
import { TaskManagerStartContract } from '../../../task_manager/server';
|
||||
|
||||
describe('SessionManagementService', () => {
|
||||
let service: SessionManagementService;
|
||||
beforeEach(() => {
|
||||
service = new SessionManagementService(loggingSystemMock.createLogger());
|
||||
});
|
||||
|
||||
describe('setup()', () => {
|
||||
it('exposes proper contract', () => {
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
const mockTaskManager = taskManagerMock.createSetup();
|
||||
|
||||
expect(
|
||||
service.setup({
|
||||
clusterClient: elasticsearchServiceMock.createLegacyClusterClient(),
|
||||
http: mockCoreSetup.http,
|
||||
config: createConfig(ConfigSchema.validate({}), loggingSystemMock.createLogger(), {
|
||||
isTLSEnabled: false,
|
||||
}),
|
||||
kibanaIndexName: '.kibana',
|
||||
taskManager: mockTaskManager,
|
||||
})
|
||||
).toEqual({ session: expect.any(Session) });
|
||||
|
||||
expect(mockTaskManager.registerTaskDefinitions).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.registerTaskDefinitions).toHaveBeenCalledWith({
|
||||
[SESSION_INDEX_CLEANUP_TASK_NAME]: {
|
||||
title: 'Cleanup expired or invalid user sessions',
|
||||
type: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
createTaskRunner: expect.any(Function),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('registers proper session index cleanup task runner', () => {
|
||||
const mockSessionIndexCleanUp = jest.spyOn(SessionIndex.prototype, 'cleanUp');
|
||||
const mockTaskManager = taskManagerMock.createSetup();
|
||||
|
||||
const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient();
|
||||
mockClusterClient.callAsInternalUser.mockResolvedValue({});
|
||||
service.setup({
|
||||
clusterClient: mockClusterClient,
|
||||
http: coreMock.createSetup().http,
|
||||
config: createConfig(ConfigSchema.validate({}), loggingSystemMock.createLogger(), {
|
||||
isTLSEnabled: false,
|
||||
}),
|
||||
kibanaIndexName: '.kibana',
|
||||
taskManager: mockTaskManager,
|
||||
});
|
||||
|
||||
const [
|
||||
[
|
||||
{
|
||||
[SESSION_INDEX_CLEANUP_TASK_NAME]: { createTaskRunner },
|
||||
},
|
||||
],
|
||||
] = mockTaskManager.registerTaskDefinitions.mock.calls;
|
||||
expect(mockSessionIndexCleanUp).not.toHaveBeenCalled();
|
||||
|
||||
const runner = createTaskRunner({} as any);
|
||||
runner.run();
|
||||
expect(mockSessionIndexCleanUp).toHaveBeenCalledTimes(1);
|
||||
|
||||
runner.run();
|
||||
expect(mockSessionIndexCleanUp).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('start()', () => {
|
||||
let mockSessionIndexInitialize: jest.SpyInstance;
|
||||
let mockTaskManager: jest.Mocked<TaskManagerStartContract>;
|
||||
beforeEach(() => {
|
||||
mockSessionIndexInitialize = jest.spyOn(SessionIndex.prototype, 'initialize');
|
||||
|
||||
mockTaskManager = taskManagerMock.createStart();
|
||||
mockTaskManager.ensureScheduled.mockResolvedValue(undefined as any);
|
||||
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
service.setup({
|
||||
clusterClient: elasticsearchServiceMock.createLegacyClusterClient(),
|
||||
http: mockCoreSetup.http,
|
||||
config: createConfig(ConfigSchema.validate({}), loggingSystemMock.createLogger(), {
|
||||
isTLSEnabled: false,
|
||||
}),
|
||||
kibanaIndexName: '.kibana',
|
||||
taskManager: taskManagerMock.createSetup(),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockSessionIndexInitialize.mockReset();
|
||||
});
|
||||
|
||||
it('exposes proper contract', () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
expect(
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager })
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('initializes session index and schedules session index cleanup task when Elasticsearch goes online', async () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager });
|
||||
|
||||
// ES isn't online yet.
|
||||
expect(mockSessionIndexInitialize).not.toHaveBeenCalled();
|
||||
expect(mockTaskManager.ensureScheduled).not.toHaveBeenCalled();
|
||||
|
||||
const mockScheduleRetry = jest.fn();
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledWith({
|
||||
id: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
taskType: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
scope: ['security'],
|
||||
schedule: { interval: '3600s' },
|
||||
params: {},
|
||||
state: {},
|
||||
});
|
||||
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(2);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(2);
|
||||
|
||||
expect(mockScheduleRetry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('removes old cleanup task if cleanup interval changes', async () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager });
|
||||
|
||||
mockTaskManager.get.mockResolvedValue({ schedule: { interval: '2000s' } } as any);
|
||||
|
||||
// ES isn't online yet.
|
||||
expect(mockTaskManager.ensureScheduled).not.toHaveBeenCalled();
|
||||
|
||||
const mockScheduleRetry = jest.fn();
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
|
||||
expect(mockTaskManager.get).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.get).toHaveBeenCalledWith(SESSION_INDEX_CLEANUP_TASK_NAME);
|
||||
|
||||
expect(mockTaskManager.remove).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.remove).toHaveBeenCalledWith(SESSION_INDEX_CLEANUP_TASK_NAME);
|
||||
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledWith({
|
||||
id: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
taskType: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
scope: ['security'],
|
||||
schedule: { interval: '3600s' },
|
||||
params: {},
|
||||
state: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('does not remove old cleanup task if cleanup interval does not change', async () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager });
|
||||
|
||||
mockTaskManager.get.mockResolvedValue({ schedule: { interval: '3600s' } } as any);
|
||||
|
||||
// ES isn't online yet.
|
||||
expect(mockTaskManager.ensureScheduled).not.toHaveBeenCalled();
|
||||
|
||||
const mockScheduleRetry = jest.fn();
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
|
||||
expect(mockTaskManager.get).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.get).toHaveBeenCalledWith(SESSION_INDEX_CLEANUP_TASK_NAME);
|
||||
|
||||
expect(mockTaskManager.remove).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledWith({
|
||||
id: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
taskType: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
scope: ['security'],
|
||||
schedule: { interval: '3600s' },
|
||||
params: {},
|
||||
state: {},
|
||||
});
|
||||
});
|
||||
|
||||
it('schedules retry if index initialization fails', async () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager });
|
||||
|
||||
mockSessionIndexInitialize.mockRejectedValue(new Error('ugh :/'));
|
||||
|
||||
const mockScheduleRetry = jest.fn();
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(1);
|
||||
expect(mockScheduleRetry).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Still fails.
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(2);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(2);
|
||||
expect(mockScheduleRetry).toHaveBeenCalledTimes(2);
|
||||
|
||||
// And finally succeeds, retry is not scheduled.
|
||||
mockSessionIndexInitialize.mockResolvedValue(undefined);
|
||||
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(3);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(3);
|
||||
expect(mockScheduleRetry).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('schedules retry if cleanup task registration fails', async () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager });
|
||||
|
||||
mockTaskManager.ensureScheduled.mockRejectedValue(new Error('ugh :/'));
|
||||
|
||||
const mockScheduleRetry = jest.fn();
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(1);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(1);
|
||||
expect(mockScheduleRetry).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Still fails.
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(2);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(2);
|
||||
expect(mockScheduleRetry).toHaveBeenCalledTimes(2);
|
||||
|
||||
// And finally succeeds, retry is not scheduled.
|
||||
mockTaskManager.ensureScheduled.mockResolvedValue(undefined as any);
|
||||
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
await nextTick();
|
||||
expect(mockSessionIndexInitialize).toHaveBeenCalledTimes(3);
|
||||
expect(mockTaskManager.ensureScheduled).toHaveBeenCalledTimes(3);
|
||||
expect(mockScheduleRetry).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stop()', () => {
|
||||
let mockSessionIndexInitialize: jest.SpyInstance;
|
||||
let mockTaskManager: jest.Mocked<TaskManagerStartContract>;
|
||||
beforeEach(() => {
|
||||
mockSessionIndexInitialize = jest.spyOn(SessionIndex.prototype, 'initialize');
|
||||
|
||||
mockTaskManager = taskManagerMock.createStart();
|
||||
mockTaskManager.ensureScheduled.mockResolvedValue(undefined as any);
|
||||
|
||||
const mockCoreSetup = coreMock.createSetup();
|
||||
service.setup({
|
||||
clusterClient: elasticsearchServiceMock.createLegacyClusterClient(),
|
||||
http: mockCoreSetup.http,
|
||||
config: createConfig(ConfigSchema.validate({}), loggingSystemMock.createLogger(), {
|
||||
isTLSEnabled: false,
|
||||
}),
|
||||
kibanaIndexName: '.kibana',
|
||||
taskManager: taskManagerMock.createSetup(),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockSessionIndexInitialize.mockReset();
|
||||
});
|
||||
|
||||
it('properly unsubscribes from status updates', () => {
|
||||
const mockStatusSubject = new Subject<OnlineStatusRetryScheduler>();
|
||||
service.start({ online$: mockStatusSubject.asObservable(), taskManager: mockTaskManager });
|
||||
|
||||
service.stop();
|
||||
|
||||
const mockScheduleRetry = jest.fn();
|
||||
mockStatusSubject.next({ scheduleRetry: mockScheduleRetry });
|
||||
|
||||
expect(mockSessionIndexInitialize).not.toHaveBeenCalled();
|
||||
expect(mockScheduleRetry).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
|
@ -0,0 +1,160 @@
|
|||
/*
|
||||
* 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 { Observable, Subscription } from 'rxjs';
|
||||
import {
|
||||
HttpServiceSetup,
|
||||
ILegacyClusterClient,
|
||||
Logger,
|
||||
SavedObjectsErrorHelpers,
|
||||
} from '../../../../../src/core/server';
|
||||
import { TaskManagerSetupContract, TaskManagerStartContract } from '../../../task_manager/server';
|
||||
import { ConfigType } from '../config';
|
||||
import { OnlineStatusRetryScheduler } from '../elasticsearch';
|
||||
import { SessionCookie } from './session_cookie';
|
||||
import { SessionIndex } from './session_index';
|
||||
import { Session } from './session';
|
||||
|
||||
export interface SessionManagementServiceSetupParams {
|
||||
readonly http: Pick<HttpServiceSetup, 'basePath' | 'createCookieSessionStorageFactory'>;
|
||||
readonly config: ConfigType;
|
||||
readonly clusterClient: ILegacyClusterClient;
|
||||
readonly kibanaIndexName: string;
|
||||
readonly taskManager: TaskManagerSetupContract;
|
||||
}
|
||||
|
||||
export interface SessionManagementServiceStartParams {
|
||||
readonly online$: Observable<OnlineStatusRetryScheduler>;
|
||||
readonly taskManager: TaskManagerStartContract;
|
||||
}
|
||||
|
||||
export interface SessionManagementServiceSetup {
|
||||
readonly session: Session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name of the task that is periodically run and performs session index cleanup.
|
||||
*/
|
||||
export const SESSION_INDEX_CLEANUP_TASK_NAME = 'session_cleanup';
|
||||
|
||||
/**
|
||||
* Service responsible for the user session management.
|
||||
*/
|
||||
export class SessionManagementService {
|
||||
private statusSubscription?: Subscription;
|
||||
private sessionIndex!: SessionIndex;
|
||||
private config!: ConfigType;
|
||||
|
||||
constructor(private readonly logger: Logger) {}
|
||||
|
||||
setup({
|
||||
config,
|
||||
clusterClient,
|
||||
http,
|
||||
kibanaIndexName,
|
||||
taskManager,
|
||||
}: SessionManagementServiceSetupParams): SessionManagementServiceSetup {
|
||||
this.config = config;
|
||||
|
||||
const sessionCookie = new SessionCookie({
|
||||
config,
|
||||
createCookieSessionStorageFactory: http.createCookieSessionStorageFactory,
|
||||
serverBasePath: http.basePath.serverBasePath || '/',
|
||||
logger: this.logger.get('cookie'),
|
||||
});
|
||||
|
||||
this.sessionIndex = new SessionIndex({
|
||||
config,
|
||||
clusterClient,
|
||||
kibanaIndexName,
|
||||
logger: this.logger.get('index'),
|
||||
});
|
||||
|
||||
// Register task that will perform periodic session index cleanup.
|
||||
taskManager.registerTaskDefinitions({
|
||||
[SESSION_INDEX_CLEANUP_TASK_NAME]: {
|
||||
title: 'Cleanup expired or invalid user sessions',
|
||||
type: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
createTaskRunner: () => ({ run: () => this.sessionIndex.cleanUp() }),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
session: new Session({
|
||||
logger: this.logger,
|
||||
sessionCookie,
|
||||
sessionIndex: this.sessionIndex,
|
||||
config,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
start({ online$, taskManager }: SessionManagementServiceStartParams) {
|
||||
this.statusSubscription = online$.subscribe(async ({ scheduleRetry }) => {
|
||||
try {
|
||||
await Promise.all([this.sessionIndex.initialize(), this.scheduleCleanupTask(taskManager)]);
|
||||
} catch (err) {
|
||||
scheduleRetry();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.statusSubscription !== undefined) {
|
||||
this.statusSubscription.unsubscribe();
|
||||
this.statusSubscription = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async scheduleCleanupTask(taskManager: TaskManagerStartContract) {
|
||||
let currentTask;
|
||||
try {
|
||||
currentTask = await taskManager.get(SESSION_INDEX_CLEANUP_TASK_NAME);
|
||||
} catch (err) {
|
||||
if (!SavedObjectsErrorHelpers.isNotFoundError(err)) {
|
||||
this.logger.error(`Failed to retrieve session index cleanup task: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
|
||||
this.logger.debug('Session index cleanup task is not scheduled yet.');
|
||||
}
|
||||
|
||||
// Check if currently scheduled task is scheduled with the correct interval.
|
||||
const cleanupInterval = `${this.config.session.cleanupInterval.asSeconds()}s`;
|
||||
if (currentTask && currentTask.schedule?.interval !== cleanupInterval) {
|
||||
this.logger.debug(
|
||||
'Session index cleanup interval has changed, the cleanup task will be rescheduled.'
|
||||
);
|
||||
|
||||
try {
|
||||
await taskManager.remove(SESSION_INDEX_CLEANUP_TASK_NAME);
|
||||
} catch (err) {
|
||||
// We may have multiple instances of Kibana that are removing old task definition at the
|
||||
// same time. If we get 404 here then task was removed by another instance, it's fine.
|
||||
if (!SavedObjectsErrorHelpers.isNotFoundError(err)) {
|
||||
this.logger.error(`Failed to remove old session index cleanup task: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await taskManager.ensureScheduled({
|
||||
id: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
taskType: SESSION_INDEX_CLEANUP_TASK_NAME,
|
||||
scope: ['security'],
|
||||
schedule: { interval: cleanupInterval },
|
||||
params: {},
|
||||
state: {},
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error(`Failed to register session index cleanup task: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
|
||||
this.logger.debug('Successfully scheduled session index cleanup task.');
|
||||
}
|
||||
}
|
|
@ -78,8 +78,13 @@ const loginViaEnvironmentCredentials = () => {
|
|||
// programmatically authenticate without interacting with the Kibana login page
|
||||
cy.request({
|
||||
body: {
|
||||
username: Cypress.env(ELASTICSEARCH_USERNAME),
|
||||
password: Cypress.env(ELASTICSEARCH_PASSWORD),
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: {
|
||||
username: Cypress.env(ELASTICSEARCH_USERNAME),
|
||||
password: Cypress.env(ELASTICSEARCH_PASSWORD),
|
||||
},
|
||||
},
|
||||
headers: { 'kbn-xsrf': 'cypress-creds-via-env' },
|
||||
method: 'POST',
|
||||
|
@ -104,8 +109,13 @@ const loginViaConfig = () => {
|
|||
// programmatically authenticate without interacting with the Kibana login page
|
||||
cy.request({
|
||||
body: {
|
||||
username: config.elasticsearch.username,
|
||||
password: config.elasticsearch.password,
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: {
|
||||
username: config.elasticsearch.username,
|
||||
password: config.elasticsearch.password,
|
||||
},
|
||||
},
|
||||
headers: { 'kbn-xsrf': 'cypress-creds-via-config' },
|
||||
method: 'POST',
|
||||
|
|
|
@ -9,7 +9,9 @@ const alwaysImportedTests = [
|
|||
require.resolve('../test/security_solution_endpoint/config.ts'),
|
||||
require.resolve('../test/functional_with_es_ssl/config.ts'),
|
||||
require.resolve('../test/functional/config_security_basic.ts'),
|
||||
require.resolve('../test/functional/config_security_trial.ts'),
|
||||
require.resolve('../test/security_functional/login_selector.config.ts'),
|
||||
require.resolve('../test/security_functional/oidc.config.ts'),
|
||||
require.resolve('../test/security_functional/saml.config.ts'),
|
||||
require.resolve('../test/functional_embedded/config.ts'),
|
||||
require.resolve('../test/functional_enterprise_search/without_host_configured.config.ts'),
|
||||
];
|
||||
|
@ -28,6 +30,8 @@ const onlyNotInCoverageTests = [
|
|||
require.resolve('../test/kerberos_api_integration/config.ts'),
|
||||
require.resolve('../test/kerberos_api_integration/anonymous_access.config.ts'),
|
||||
require.resolve('../test/saml_api_integration/config.ts'),
|
||||
require.resolve('../test/security_api_integration/session_idle.config.ts'),
|
||||
require.resolve('../test/security_api_integration/session_lifespan.config.ts'),
|
||||
require.resolve('../test/token_api_integration/config.js'),
|
||||
require.resolve('../test/oidc_api_integration/config.ts'),
|
||||
require.resolve('../test/oidc_api_integration/implicit_flow.config.ts'),
|
||||
|
|
|
@ -39,19 +39,34 @@ export default function ({ getService }) {
|
|||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: wrongUsername, password: wrongPassword })
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: wrongUsername, password: wrongPassword },
|
||||
})
|
||||
.expect(401);
|
||||
|
||||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: validUsername, password: wrongPassword })
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: validUsername, password: wrongPassword },
|
||||
})
|
||||
.expect(401);
|
||||
|
||||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: wrongUsername, password: validPassword })
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: wrongUsername, password: validPassword },
|
||||
})
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
|
@ -59,8 +74,13 @@ export default function ({ getService }) {
|
|||
const loginResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: validUsername, password: validPassword })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: validUsername, password: validPassword },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = loginResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
@ -134,8 +154,13 @@ export default function ({ getService }) {
|
|||
const loginResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: validUsername, password: validPassword })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: validUsername, password: validPassword },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
sessionCookie = request.cookie(loginResponse.headers['set-cookie'][0]);
|
||||
});
|
||||
|
|
|
@ -22,8 +22,13 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
const loginResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: mockUserName, password: mockUserPassword })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: mockUserName, password: mockUserPassword },
|
||||
})
|
||||
.expect(200);
|
||||
sessionCookie = cookie(loginResponse.headers['set-cookie'][0])!;
|
||||
});
|
||||
|
||||
|
@ -44,22 +49,37 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: mockUserName, password: wrongPassword })
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: mockUserName, password: wrongPassword },
|
||||
})
|
||||
.expect(401);
|
||||
|
||||
// Let's check that we can't login with the password we were supposed to set.
|
||||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: mockUserName, password: newPassword })
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: mockUserName, password: newPassword },
|
||||
})
|
||||
.expect(401);
|
||||
|
||||
// And can login with the current password.
|
||||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: mockUserName, password: mockUserPassword })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: mockUserName, password: mockUserPassword },
|
||||
})
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('should allow password change if current password is correct', async () => {
|
||||
|
@ -74,21 +94,26 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
const newSessionCookie = cookie(passwordChangeResponse.headers['set-cookie'][0])!;
|
||||
|
||||
// Let's check that previous cookie isn't valid anymore.
|
||||
// Old cookie is still valid (since it's still the same user and cookie doesn't store password).
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(401);
|
||||
.expect(200);
|
||||
|
||||
// And that we can't login with the old password.
|
||||
// But we can't login with the old password.
|
||||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: mockUserName, password: mockUserPassword })
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: mockUserName, password: mockUserPassword },
|
||||
})
|
||||
.expect(401);
|
||||
|
||||
// But new cookie should be valid.
|
||||
// New cookie should be valid.
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
|
@ -99,8 +124,13 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: mockUserName, password: newPassword })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username: mockUserName, password: newPassword },
|
||||
})
|
||||
.expect(200);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -18,6 +18,5 @@ export default function ({ loadTestFile }) {
|
|||
loadTestFile(require.resolve('./index_fields'));
|
||||
loadTestFile(require.resolve('./roles'));
|
||||
loadTestFile(require.resolve('./privileges'));
|
||||
loadTestFile(require.resolve('./session'));
|
||||
});
|
||||
}
|
||||
|
|
|
@ -20,6 +20,5 @@ export default function ({ loadTestFile }: FtrProviderContext) {
|
|||
loadTestFile(require.resolve('./index_fields'));
|
||||
loadTestFile(require.resolve('./roles'));
|
||||
loadTestFile(require.resolve('./privileges_basic'));
|
||||
loadTestFile(require.resolve('./session'));
|
||||
});
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import { format as formatUrl } from 'url';
|
|||
|
||||
import * as legacyElasticsearch from 'elasticsearch';
|
||||
|
||||
import { elasticsearchClientPlugin as securityEsClientPlugin } from '../../../plugins/security/server/elasticsearch_client_plugin';
|
||||
import { elasticsearchClientPlugin as securityEsClientPlugin } from '../../../plugins/security/server/elasticsearch/elasticsearch_client_plugin';
|
||||
import { elasticsearchJsPlugin as indexManagementEsClientPlugin } from '../../../plugins/index_management/server/client/elasticsearch';
|
||||
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
|
||||
import { DEFAULT_API_VERSION } from '../../../../src/core/server/elasticsearch/elasticsearch_config';
|
||||
|
|
|
@ -58,8 +58,13 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
const response = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username, password })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username, password },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = response.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
|
|
@ -76,7 +76,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
it('should allow access to login selector with intermediate authentication cookie', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ providerType: 'saml', providerName: 'saml1', currentURL: 'https://kibana.com/' })
|
||||
|
@ -176,19 +176,24 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
});
|
||||
|
||||
it('should be able to log in via IdP initiated login even if session with other provider type exists', async () => {
|
||||
const basicAuthenticationResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username: validUsername, password: validPassword })
|
||||
.expect(204);
|
||||
|
||||
const basicSessionCookie = request.cookie(
|
||||
basicAuthenticationResponse.headers['set-cookie'][0]
|
||||
)!;
|
||||
await checkSessionCookie(basicSessionCookie, 'elastic', 'basic1');
|
||||
|
||||
for (const providerName of ['saml1', 'saml2']) {
|
||||
const basicAuthenticationResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic1',
|
||||
currentURL: '/',
|
||||
params: { username: validUsername, password: validPassword },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const basicSessionCookie = request.cookie(
|
||||
basicAuthenticationResponse.headers['set-cookie'][0]
|
||||
)!;
|
||||
await checkSessionCookie(basicSessionCookie, 'elastic', 'basic1');
|
||||
|
||||
const authenticationResponse = await supertest
|
||||
.post('/api/security/saml/callback')
|
||||
.ca(CA_CERT)
|
||||
|
@ -200,8 +205,9 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
})
|
||||
.expect(302);
|
||||
|
||||
// It should be `/overwritten_session` instead of `/` once it's generalized.
|
||||
expect(authenticationResponse.headers.location).to.be('/');
|
||||
expect(authenticationResponse.headers.location).to.be(
|
||||
'/security/overwritten_session?next=%2F'
|
||||
);
|
||||
|
||||
const cookies = authenticationResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
@ -235,8 +241,9 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
})
|
||||
.expect(302);
|
||||
|
||||
// It should be `/overwritten_session` instead of `/` once it's generalized.
|
||||
expect(saml2AuthenticationResponse.headers.location).to.be('/');
|
||||
expect(saml2AuthenticationResponse.headers.location).to.be(
|
||||
'/security/overwritten_session?next=%2F'
|
||||
);
|
||||
|
||||
const saml2SessionCookie = request.cookie(
|
||||
saml2AuthenticationResponse.headers['set-cookie'][0]
|
||||
|
@ -271,9 +278,9 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
.send({ RelayState: '/app/kibana#/dashboards' })
|
||||
.expect(302);
|
||||
|
||||
// It should be `/overwritten_session` with `?next='/app/kibana#/dashboards'` instead of just
|
||||
// `'/app/kibana#/dashboards'` once it's generalized.
|
||||
expect(saml2AuthenticationResponse.headers.location).to.be('/app/kibana#/dashboards');
|
||||
expect(saml2AuthenticationResponse.headers.location).to.be(
|
||||
'/security/overwritten_session?next=%2Fapp%2Fkibana%23%2Fdashboards'
|
||||
);
|
||||
|
||||
const saml2SessionCookie = request.cookie(
|
||||
saml2AuthenticationResponse.headers['set-cookie'][0]
|
||||
|
@ -288,7 +295,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
it('should fail for IdP initiated login if intermediate session with other SAML provider exists', async () => {
|
||||
// First start authentication flow with `saml1`.
|
||||
const saml1HandshakeResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
|
@ -320,7 +327,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
it('should be able to log in via SP initiated login with any configured realm', async () => {
|
||||
for (const providerName of ['saml1', 'saml2']) {
|
||||
const handshakeResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
|
@ -366,7 +373,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
it('should be able to log in via SP initiated login even if intermediate session with other SAML provider exists', async () => {
|
||||
// First start authentication flow with `saml1`.
|
||||
const saml1HandshakeResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
|
@ -386,7 +393,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
// And now try to login with `saml2`.
|
||||
const saml2HandshakeResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', saml1HandshakeCookie.cookieString())
|
||||
|
@ -428,7 +435,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
describe('Kerberos', () => {
|
||||
it('should be able to log in from Login Selector', async () => {
|
||||
const spnegoResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
|
@ -442,7 +449,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(spnegoResponse.headers['www-authenticate']).to.be('Negotiate');
|
||||
|
||||
const authenticationResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Authorization', `Negotiate ${getSPNEGOToken()}`)
|
||||
|
@ -470,7 +477,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
it('should be able to log in from Login Selector even if client provides certificate and PKI is enabled', async () => {
|
||||
const spnegoResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.pfx(CLIENT_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
|
@ -485,7 +492,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(spnegoResponse.headers['www-authenticate']).to.be('Negotiate');
|
||||
|
||||
const authenticationResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.pfx(CLIENT_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
|
@ -547,7 +554,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
it('should be able to log in via SP initiated login', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
|
@ -612,7 +619,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
it('should be able to log in from Login Selector', async () => {
|
||||
const authenticationResponse = await supertest
|
||||
.post('/internal/security/login_with')
|
||||
.post('/internal/security/login')
|
||||
.ca(CA_CERT)
|
||||
.pfx(CLIENT_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
|
|
|
@ -4,7 +4,9 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
export default function ({ loadTestFile }) {
|
||||
import { FtrProviderContext } from '../../ftr_provider_context';
|
||||
|
||||
export default function ({ loadTestFile }: FtrProviderContext) {
|
||||
describe('apis', function () {
|
||||
this.tags('ciGroup6');
|
||||
loadTestFile(require.resolve('./oidc_auth'));
|
|
@ -5,41 +5,85 @@
|
|||
*/
|
||||
|
||||
import expect from '@kbn/expect';
|
||||
import request from 'request';
|
||||
import request, { Cookie } from 'request';
|
||||
import url from 'url';
|
||||
import { getStateAndNonce } from '../../fixtures/oidc_tools';
|
||||
import { delay } from 'bluebird';
|
||||
import { getStateAndNonce } from '../../fixtures/oidc_tools';
|
||||
import { FtrProviderContext } from '../../ftr_provider_context';
|
||||
|
||||
export default function ({ getService }) {
|
||||
export default function ({ getService }: FtrProviderContext) {
|
||||
const supertest = getService('supertestWithoutAuth');
|
||||
const config = getService('config');
|
||||
|
||||
describe('OpenID Connect authentication', () => {
|
||||
it('should reject API requests if client is not authenticated', async () => {
|
||||
await supertest.get('/internal/security/me').set('kbn-xsrf', 'xxx').expect(401);
|
||||
});
|
||||
|
||||
it('does not prevent basic login', async () => {
|
||||
const [username, password] = config.get('servers.elasticsearch.auth').split(':');
|
||||
const response = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username, password },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = response.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const { body: user } = await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', request.cookie(cookies[0])!.cookieString())
|
||||
.expect(200);
|
||||
|
||||
expect(user.username).to.eql(username);
|
||||
expect(user.authentication_realm).to.eql({ name: 'reserved', type: 'reserved' });
|
||||
expect(user.authentication_provider).to.eql('basic');
|
||||
});
|
||||
|
||||
describe('initiating handshake', () => {
|
||||
it('should properly set cookie, return all parameters and redirect user', async () => {
|
||||
it('should redirect user to a page that would capture URL fragment', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
|
||||
expect(handshakeResponse.headers['set-cookie']).to.be(undefined);
|
||||
expect(handshakeResponse.headers.location).to.be(
|
||||
'/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc'
|
||||
);
|
||||
});
|
||||
|
||||
it('should properly set cookie, return all parameters and redirect user', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const handshakeCookie = request.cookie(cookies[0]);
|
||||
const handshakeCookie = request.cookie(cookies[0])!;
|
||||
expect(handshakeCookie.key).to.be('sid');
|
||||
expect(handshakeCookie.value).to.not.be.empty();
|
||||
expect(handshakeCookie.path).to.be('/');
|
||||
expect(handshakeCookie.httpOnly).to.be(true);
|
||||
|
||||
const redirectURL = url.parse(
|
||||
handshakeResponse.headers.location,
|
||||
true /* parseQueryString */
|
||||
);
|
||||
expect(redirectURL.href.startsWith(`https://test-op.elastic.co/oauth2/v1/authorize`)).to.be(
|
||||
true
|
||||
);
|
||||
const redirectURL = url.parse(handshakeResponse.body.location, true /* parseQueryString */);
|
||||
expect(
|
||||
redirectURL.href!.startsWith(`https://test-op.elastic.co/oauth2/v1/authorize`)
|
||||
).to.be(true);
|
||||
expect(redirectURL.query.scope).to.not.be.empty();
|
||||
expect(redirectURL.query.response_type).to.not.be.empty();
|
||||
expect(redirectURL.query.client_id).to.not.be.empty();
|
||||
|
@ -57,7 +101,7 @@ export default function ({ getService }) {
|
|||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const handshakeCookie = request.cookie(cookies[0]);
|
||||
const handshakeCookie = request.cookie(cookies[0])!;
|
||||
expect(handshakeCookie.key).to.be('sid');
|
||||
expect(handshakeCookie.value).to.not.be.empty();
|
||||
expect(handshakeCookie.path).to.be('/');
|
||||
|
@ -67,9 +111,9 @@ export default function ({ getService }) {
|
|||
handshakeResponse.headers.location,
|
||||
true /* parseQueryString */
|
||||
);
|
||||
expect(redirectURL.href.startsWith(`https://test-op.elastic.co/oauth2/v1/authorize`)).to.be(
|
||||
true
|
||||
);
|
||||
expect(
|
||||
redirectURL.href!.startsWith(`https://test-op.elastic.co/oauth2/v1/authorize`)
|
||||
).to.be(true);
|
||||
expect(redirectURL.query.scope).to.not.be.empty();
|
||||
expect(redirectURL.query.response_type).to.not.be.empty();
|
||||
expect(redirectURL.query.client_id).to.not.be.empty();
|
||||
|
@ -80,10 +124,17 @@ export default function ({ getService }) {
|
|||
|
||||
it('should not allow access to the API with the handshake cookie', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
|
@ -102,16 +153,23 @@ export default function ({ getService }) {
|
|||
});
|
||||
|
||||
describe('finishing handshake', () => {
|
||||
let stateAndNonce;
|
||||
let handshakeCookie;
|
||||
let stateAndNonce: { state: string; nonce: string };
|
||||
let handshakeCookie: Cookie;
|
||||
|
||||
beforeEach(async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
stateAndNonce = getStateAndNonce(handshakeResponse.body.location);
|
||||
// Set the nonce in our mock OIDC Provider so that it can generate the ID Tokens
|
||||
await supertest
|
||||
.post('/api/oidc_provider/setup')
|
||||
|
@ -144,13 +202,13 @@ export default function ({ getService }) {
|
|||
|
||||
// User should be redirected to the URL that initiated handshake.
|
||||
expect(oidcAuthenticationResponse.headers.location).to.be(
|
||||
'/abc/xyz/handshake?one=two%20three'
|
||||
'/abc/xyz/handshake?one=two%20three#/workpad'
|
||||
);
|
||||
|
||||
const cookies = oidcAuthenticationResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const sessionCookie = request.cookie(cookies[0]);
|
||||
const sessionCookie = request.cookie(cookies[0])!;
|
||||
expect(sessionCookie.key).to.be('sid');
|
||||
expect(sessionCookie.value).to.not.be.empty();
|
||||
expect(sessionCookie.path).to.be('/');
|
||||
|
@ -182,7 +240,7 @@ export default function ({ getService }) {
|
|||
const handshakeResponse = await supertest
|
||||
.get('/api/security/oidc/initiate_login?iss=https://test-op.elastic.co')
|
||||
.expect(302);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
|
||||
// Set the nonce in our mock OIDC Provider so that it can generate the ID Tokens
|
||||
|
@ -200,7 +258,7 @@ export default function ({ getService }) {
|
|||
const cookies = oidcAuthenticationResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const sessionCookie = request.cookie(cookies[0]);
|
||||
const sessionCookie = request.cookie(cookies[0])!;
|
||||
expect(sessionCookie.key).to.be('sid');
|
||||
expect(sessionCookie.value).to.not.be.empty();
|
||||
expect(sessionCookie.path).to.be('/');
|
||||
|
@ -228,14 +286,23 @@ export default function ({ getService }) {
|
|||
});
|
||||
|
||||
describe('API access with active session', () => {
|
||||
let stateAndNonce;
|
||||
let sessionCookie;
|
||||
let stateAndNonce: { state: string; nonce: string };
|
||||
let sessionCookie: Cookie;
|
||||
|
||||
beforeEach(async () => {
|
||||
const handshakeResponse = await supertest.get('/abc/xyz').expect(302);
|
||||
const handshakeResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
sessionCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
sessionCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
stateAndNonce = getStateAndNonce(handshakeResponse.body.location);
|
||||
// Set the nonce in our mock OIDC Provider so that it can generate the ID Tokens
|
||||
await supertest
|
||||
.post('/api/oidc_provider/setup')
|
||||
|
@ -249,7 +316,7 @@ export default function ({ getService }) {
|
|||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(302);
|
||||
|
||||
sessionCookie = request.cookie(oidcAuthenticationResponse.headers['set-cookie'][0]);
|
||||
sessionCookie = request.cookie(oidcAuthenticationResponse.headers['set-cookie'][0])!;
|
||||
});
|
||||
|
||||
it('should extend cookie on every successful non-system API call', async () => {
|
||||
|
@ -260,7 +327,7 @@ export default function ({ getService }) {
|
|||
.expect(200);
|
||||
|
||||
expect(apiResponseOne.headers['set-cookie']).to.not.be(undefined);
|
||||
const sessionCookieOne = request.cookie(apiResponseOne.headers['set-cookie'][0]);
|
||||
const sessionCookieOne = request.cookie(apiResponseOne.headers['set-cookie'][0])!;
|
||||
|
||||
expect(sessionCookieOne.value).to.not.be.empty();
|
||||
expect(sessionCookieOne.value).to.not.equal(sessionCookie.value);
|
||||
|
@ -272,7 +339,7 @@ export default function ({ getService }) {
|
|||
.expect(200);
|
||||
|
||||
expect(apiResponseTwo.headers['set-cookie']).to.not.be(undefined);
|
||||
const sessionCookieTwo = request.cookie(apiResponseTwo.headers['set-cookie'][0]);
|
||||
const sessionCookieTwo = request.cookie(apiResponseTwo.headers['set-cookie'][0])!;
|
||||
|
||||
expect(sessionCookieTwo.value).to.not.be.empty();
|
||||
expect(sessionCookieTwo.value).to.not.equal(sessionCookieOne.value);
|
||||
|
@ -302,15 +369,22 @@ export default function ({ getService }) {
|
|||
});
|
||||
|
||||
describe('logging out', () => {
|
||||
let sessionCookie;
|
||||
let sessionCookie: Cookie;
|
||||
|
||||
beforeEach(async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.body.location);
|
||||
// Set the nonce in our mock OIDC Provider so that it can generate the ID Tokens
|
||||
await supertest
|
||||
.post('/api/oidc_provider/setup')
|
||||
|
@ -327,7 +401,7 @@ export default function ({ getService }) {
|
|||
const cookies = oidcAuthenticationResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
sessionCookie = request.cookie(cookies[0]);
|
||||
sessionCookie = request.cookie(cookies[0])!;
|
||||
});
|
||||
|
||||
it('should redirect to home page if session cookie is not provided', async () => {
|
||||
|
@ -346,7 +420,7 @@ export default function ({ getService }) {
|
|||
const cookies = logoutResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const logoutCookie = request.cookie(cookies[0]);
|
||||
const logoutCookie = request.cookie(cookies[0])!;
|
||||
expect(logoutCookie.key).to.be('sid');
|
||||
expect(logoutCookie.value).to.be.empty();
|
||||
expect(logoutCookie.path).to.be('/');
|
||||
|
@ -355,23 +429,16 @@ export default function ({ getService }) {
|
|||
|
||||
const redirectURL = url.parse(logoutResponse.headers.location, true /* parseQueryString */);
|
||||
expect(
|
||||
redirectURL.href.startsWith(`https://test-op.elastic.co/oauth2/v1/endsession`)
|
||||
redirectURL.href!.startsWith(`https://test-op.elastic.co/oauth2/v1/endsession`)
|
||||
).to.be(true);
|
||||
expect(redirectURL.query.id_token_hint).to.not.be.empty();
|
||||
|
||||
// Tokens that were stored in the previous cookie should be invalidated as well and old
|
||||
// session cookie should not allow API access.
|
||||
const apiResponse = await supertest
|
||||
// Session should be invalidated and old session cookie should not allow API access.
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(400);
|
||||
|
||||
expect(apiResponse.body).to.eql({
|
||||
error: 'Bad Request',
|
||||
message: 'Both access and refresh tokens are expired.',
|
||||
statusCode: 400,
|
||||
});
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('should reject AJAX requests', async () => {
|
||||
|
@ -391,15 +458,22 @@ export default function ({ getService }) {
|
|||
});
|
||||
|
||||
describe('API access with expired access token.', () => {
|
||||
let sessionCookie;
|
||||
let sessionCookie: Cookie;
|
||||
|
||||
beforeEach(async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.body.location);
|
||||
// Set the nonce in our mock OIDC Provider so that it can generate the ID Tokens
|
||||
await supertest
|
||||
.post('/api/oidc_provider/setup')
|
||||
|
@ -416,10 +490,10 @@ export default function ({ getService }) {
|
|||
const cookies = oidcAuthenticationResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
sessionCookie = request.cookie(cookies[0]);
|
||||
sessionCookie = request.cookie(cookies[0])!;
|
||||
});
|
||||
|
||||
const expectNewSessionCookie = (cookie) => {
|
||||
const expectNewSessionCookie = (cookie: Cookie) => {
|
||||
expect(cookie.key).to.be('sid');
|
||||
expect(cookie.value).to.not.be.empty();
|
||||
expect(cookie.path).to.be('/');
|
||||
|
@ -445,7 +519,7 @@ export default function ({ getService }) {
|
|||
const firstResponseCookies = firstResponse.headers['set-cookie'];
|
||||
expect(firstResponseCookies).to.have.length(1);
|
||||
|
||||
const firstNewCookie = request.cookie(firstResponseCookies[0]);
|
||||
const firstNewCookie = request.cookie(firstResponseCookies[0])!;
|
||||
expectNewSessionCookie(firstNewCookie);
|
||||
|
||||
// Request with old cookie should reuse the same refresh token if within 60 seconds.
|
||||
|
@ -459,7 +533,7 @@ export default function ({ getService }) {
|
|||
const secondResponseCookies = secondResponse.headers['set-cookie'];
|
||||
expect(secondResponseCookies).to.have.length(1);
|
||||
|
||||
const secondNewCookie = request.cookie(secondResponseCookies[0]);
|
||||
const secondNewCookie = request.cookie(secondResponseCookies[0])!;
|
||||
expectNewSessionCookie(secondNewCookie);
|
||||
|
||||
expect(firstNewCookie.value).not.to.eql(secondNewCookie.value);
|
||||
|
@ -481,15 +555,22 @@ export default function ({ getService }) {
|
|||
});
|
||||
|
||||
describe('API access with missing access token document.', () => {
|
||||
let sessionCookie;
|
||||
let sessionCookie: Cookie;
|
||||
|
||||
beforeEach(async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0]);
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const stateAndNonce = getStateAndNonce(handshakeResponse.body.location);
|
||||
// Set the nonce in our mock OIDC Provider so that it can generate the ID Tokens
|
||||
await supertest
|
||||
.post('/api/oidc_provider/setup')
|
||||
|
@ -506,7 +587,7 @@ export default function ({ getService }) {
|
|||
const cookies = oidcAuthenticationResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
sessionCookie = request.cookie(cookies[0]);
|
||||
sessionCookie = request.cookie(cookies[0])!;
|
||||
});
|
||||
|
||||
it('should properly set cookie and start new OIDC handshake', async function () {
|
||||
|
@ -521,26 +602,30 @@ export default function ({ getService }) {
|
|||
expect(esResponse).to.have.property('deleted').greaterThan(0);
|
||||
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(302);
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const handshakeCookie = request.cookie(cookies[0]);
|
||||
const handshakeCookie = request.cookie(cookies[0])!;
|
||||
expect(handshakeCookie.key).to.be('sid');
|
||||
expect(handshakeCookie.value).to.not.be.empty();
|
||||
expect(handshakeCookie.path).to.be('/');
|
||||
expect(handshakeCookie.httpOnly).to.be(true);
|
||||
|
||||
const redirectURL = url.parse(
|
||||
handshakeResponse.headers.location,
|
||||
true /* parseQueryString */
|
||||
);
|
||||
expect(redirectURL.href.startsWith(`https://test-op.elastic.co/oauth2/v1/authorize`)).to.be(
|
||||
true
|
||||
);
|
||||
const redirectURL = url.parse(handshakeResponse.body.location, true /* parseQueryString */);
|
||||
expect(
|
||||
redirectURL.href!.startsWith(`https://test-op.elastic.co/oauth2/v1/authorize`)
|
||||
).to.be(true);
|
||||
expect(redirectURL.query.scope).to.not.be.empty();
|
||||
expect(redirectURL.query.response_type).to.not.be.empty();
|
||||
expect(redirectURL.query.client_id).to.not.be.empty();
|
|
@ -22,11 +22,18 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
beforeEach(async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'oidc',
|
||||
providerName: 'oidc',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=oidc&providerName=oidc#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
stateAndNonce = getStateAndNonce(handshakeResponse.headers.location);
|
||||
stateAndNonce = getStateAndNonce(handshakeResponse.body.location);
|
||||
});
|
||||
|
||||
it('should return an HTML page that will parse URL fragment', async () => {
|
||||
|
@ -117,7 +124,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
|
||||
// User should be redirected to the URL that initiated handshake.
|
||||
expect(oidcAuthenticationResponse.headers.location).to.be(
|
||||
'/abc/xyz/handshake?one=two%20three'
|
||||
'/abc/xyz/handshake?one=two%20three#/workpad'
|
||||
);
|
||||
|
||||
const cookies = oidcAuthenticationResponse.headers['set-cookie'];
|
||||
|
|
|
@ -49,7 +49,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) {
|
|||
serverArgs: [
|
||||
...xPackAPITestsConfig.get('kbnTestServer.serverArgs'),
|
||||
`--plugin-path=${plugin}`,
|
||||
'--xpack.security.authc.providers=["oidc"]',
|
||||
`--xpack.security.authc.providers=${JSON.stringify(['oidc', 'basic'])}`,
|
||||
'--xpack.security.authc.oidc.realm="oidc1"',
|
||||
],
|
||||
},
|
||||
|
|
|
@ -4,11 +4,48 @@
|
|||
* you may not use this file except in compliance with the Elastic License.
|
||||
*/
|
||||
|
||||
import { schema } from '@kbn/config-schema';
|
||||
import { IRouter } from '../../../../../../src/core/server';
|
||||
import { createTokens } from '../../oidc_tools';
|
||||
|
||||
export function initRoutes(router: IRouter) {
|
||||
let nonce = '';
|
||||
router.get(
|
||||
{
|
||||
path: '/oidc_provider/authorize',
|
||||
validate: {
|
||||
query: schema.object(
|
||||
{ redirect_uri: schema.string(), state: schema.string(), nonce: schema.string() },
|
||||
{ unknowns: 'ignore' }
|
||||
),
|
||||
},
|
||||
options: { authRequired: false },
|
||||
},
|
||||
async (context, request, response) => {
|
||||
nonce = request.query.nonce;
|
||||
|
||||
return response.redirected({
|
||||
headers: {
|
||||
location: `${request.query.redirect_uri}?code=code1&state=${request.query.state}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
router.get(
|
||||
{
|
||||
path: '/oidc_provider/endsession',
|
||||
validate: {
|
||||
query: schema.object({ post_logout_redirect_uri: schema.string() }, { unknowns: 'ignore' }),
|
||||
},
|
||||
options: { authRequired: false },
|
||||
},
|
||||
async (context, request, response) => {
|
||||
return response.redirected({
|
||||
headers: { location: request.query.post_logout_redirect_uri || '/' },
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
{
|
||||
|
|
|
@ -70,8 +70,13 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
.ca(CA_CERT)
|
||||
.pfx(UNTRUSTED_CLIENT_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username, password })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username, password },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = response.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
@ -147,6 +152,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
.get('/internal/security/me')
|
||||
.ca(CA_CERT)
|
||||
.pfx(SECOND_CLIENT_CERT)
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(200, {
|
||||
username: 'second_client',
|
||||
|
|
|
@ -9,7 +9,6 @@ import url from 'url';
|
|||
import { delay } from 'bluebird';
|
||||
import expect from '@kbn/expect';
|
||||
import request, { Cookie } from 'request';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { getLogoutRequest, getSAMLRequestId, getSAMLResponse } from '../../fixtures/saml_tools';
|
||||
import { FtrProviderContext } from '../../ftr_provider_context';
|
||||
|
||||
|
@ -72,8 +71,13 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
const response = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({ username, password })
|
||||
.expect(204);
|
||||
.send({
|
||||
providerType: 'basic',
|
||||
providerName: 'basic',
|
||||
currentURL: '/',
|
||||
params: { username, password },
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = response.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
@ -89,88 +93,28 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(user.authentication_provider).to.eql('basic');
|
||||
});
|
||||
|
||||
describe('capture URL fragment', () => {
|
||||
describe('initiating handshake', () => {
|
||||
it('should redirect user to a page that would capture URL fragment', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
|
||||
// The cookie should capture current path.
|
||||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const handshakeCookie = request.cookie(cookies[0])!;
|
||||
expect(handshakeCookie.key).to.be('sid');
|
||||
expect(handshakeCookie.value).to.not.be.empty();
|
||||
expect(handshakeCookie.path).to.be('/');
|
||||
expect(handshakeCookie.httpOnly).to.be(true);
|
||||
|
||||
expect(handshakeResponse.headers['set-cookie']).to.be(undefined);
|
||||
expect(handshakeResponse.headers.location).to.be(
|
||||
'/internal/security/saml/capture-url-fragment'
|
||||
'/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml'
|
||||
);
|
||||
});
|
||||
|
||||
it('should return an HTML page that will extract URL fragment', async () => {
|
||||
const response = await supertest
|
||||
.get('/internal/security/saml/capture-url-fragment')
|
||||
.expect(200);
|
||||
|
||||
const kibanaBaseURL = url.format({ ...config.get('servers.kibana'), auth: false });
|
||||
const dom = new JSDOM(response.text, {
|
||||
url: kibanaBaseURL,
|
||||
runScripts: 'dangerously',
|
||||
resources: 'usable',
|
||||
beforeParse(window) {
|
||||
// JSDOM doesn't support changing of `window.location` and throws an exception if script
|
||||
// tries to do that and we have to workaround this behaviour. We also need to wait until our
|
||||
// script is loaded and executed, __isScriptExecuted__ is used exactly for that.
|
||||
(window as Record<string, any>).__isScriptExecuted__ = new Promise((resolve) => {
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: {
|
||||
hash: '#/workpad',
|
||||
href: `${kibanaBaseURL}/internal/security/saml/capture-url-fragment#/workpad`,
|
||||
replace(newLocation: string) {
|
||||
this.href = newLocation;
|
||||
resolve();
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await (dom.window as Record<string, any>).__isScriptExecuted__;
|
||||
|
||||
// Check that proxy page is returned with proper headers.
|
||||
expect(response.headers['content-type']).to.be('text/html; charset=utf-8');
|
||||
expect(response.headers['cache-control']).to.be(
|
||||
'private, no-cache, no-store, must-revalidate'
|
||||
);
|
||||
expect(response.headers['content-security-policy']).to.be(
|
||||
`script-src 'unsafe-eval' 'self'; worker-src blob: 'self'; style-src 'unsafe-inline' 'self'`
|
||||
);
|
||||
|
||||
// Check that script that forwards URL fragment worked correctly.
|
||||
expect(dom.window.location.href).to.be(
|
||||
'/internal/security/saml/start?redirectURLFragment=%23%2Fworkpad'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('initiating handshake', () => {
|
||||
const initiateHandshakeURL = `/internal/security/saml/start?redirectURLFragment=%23%2Fworkpad`;
|
||||
|
||||
let captureURLCookie: Cookie;
|
||||
beforeEach(async () => {
|
||||
const response = await supertest.get('/abc/xyz/handshake?one=two three').expect(302);
|
||||
captureURLCookie = request.cookie(response.headers['set-cookie'][0])!;
|
||||
});
|
||||
|
||||
it('should properly set cookie and redirect user to IdP', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get(initiateHandshakeURL)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL: `https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad`,
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
@ -181,19 +125,21 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(handshakeCookie.path).to.be('/');
|
||||
expect(handshakeCookie.httpOnly).to.be(true);
|
||||
|
||||
const redirectURL = url.parse(
|
||||
handshakeResponse.headers.location,
|
||||
true /* parseQueryString */
|
||||
);
|
||||
const redirectURL = url.parse(handshakeResponse.body.location, true /* parseQueryString */);
|
||||
expect(redirectURL.href!.startsWith(`https://elastic.co/sso/saml`)).to.be(true);
|
||||
expect(redirectURL.query.SAMLRequest).to.not.be.empty();
|
||||
});
|
||||
|
||||
it('should not allow access to the API', async () => {
|
||||
it('should not allow access to the API with the handshake cookie', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get(initiateHandshakeURL)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL: `https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad`,
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
await supertest
|
||||
|
@ -218,18 +164,19 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
let samlRequestId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
const captureURLResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
const captureURLCookie = request.cookie(captureURLResponse.headers['set-cookie'][0])!;
|
||||
|
||||
const handshakeResponse = await supertest
|
||||
.get(`/internal/security/saml/start?redirectURLFragment=%23%2Fworkpad`)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
samlRequestId = await getSAMLRequestId(handshakeResponse.body.location);
|
||||
});
|
||||
|
||||
it('should fail if SAML response is not complemented with handshake cookie', async () => {
|
||||
|
@ -356,20 +303,19 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
let idpSessionIndex: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
const captureURLResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
const captureURLCookie = request.cookie(captureURLResponse.headers['set-cookie'][0])!;
|
||||
|
||||
const handshakeResponse = await supertest
|
||||
.get(
|
||||
`/internal/security/saml/start?redirectURLFragment=${encodeURIComponent('#workpad')}`
|
||||
)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.body.location);
|
||||
|
||||
idpSessionIndex = String(randomness.naturalNumber());
|
||||
const samlAuthenticationResponse = await supertest
|
||||
|
@ -407,19 +353,12 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(redirectURL.href!.startsWith(`https://elastic.co/slo/saml`)).to.be(true);
|
||||
expect(redirectURL.query.SAMLRequest).to.not.be.empty();
|
||||
|
||||
// Tokens that were stored in the previous cookie should be invalidated as well and old
|
||||
// session cookie should not allow API access.
|
||||
const apiResponse = await supertest
|
||||
// Session should be invalidated and old session cookie should not allow API access.
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(400);
|
||||
|
||||
expect(apiResponse.body).to.eql({
|
||||
error: 'Bad Request',
|
||||
message: 'Both access and refresh tokens are expired.',
|
||||
statusCode: 400,
|
||||
});
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('should redirect to home page if session cookie is not provided', async () => {
|
||||
|
@ -465,19 +404,12 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(redirectURL.href!.startsWith(`https://elastic.co/slo/saml`)).to.be(true);
|
||||
expect(redirectURL.query.SAMLResponse).to.not.be.empty();
|
||||
|
||||
// Tokens that were stored in the previous cookie should be invalidated as well and old session
|
||||
// cookie should not allow API access.
|
||||
const apiResponse = await supertest
|
||||
// Session should be invalidated and old session cookie should not allow API access.
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.expect(400);
|
||||
|
||||
expect(apiResponse.body).to.eql({
|
||||
error: 'Bad Request',
|
||||
message: 'Both access and refresh tokens are expired.',
|
||||
statusCode: 400,
|
||||
});
|
||||
.expect(401);
|
||||
});
|
||||
|
||||
it('should invalidate access token on IdP initiated logout even if there is no Kibana session', async () => {
|
||||
|
@ -515,20 +447,19 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
beforeEach(async function () {
|
||||
this.timeout(40000);
|
||||
|
||||
const captureURLResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
const captureURLCookie = request.cookie(captureURLResponse.headers['set-cookie'][0])!;
|
||||
|
||||
const handshakeResponse = await supertest
|
||||
.get(
|
||||
`/internal/security/saml/start?redirectURLFragment=${encodeURIComponent('#workpad')}`
|
||||
)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.body.location);
|
||||
|
||||
const samlAuthenticationResponse = await supertest
|
||||
.post('/api/security/saml/callback')
|
||||
|
@ -616,20 +547,19 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
let sessionCookie: Cookie;
|
||||
|
||||
beforeEach(async () => {
|
||||
const captureURLResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
const captureURLCookie = request.cookie(captureURLResponse.headers['set-cookie'][0])!;
|
||||
|
||||
const handshakeResponse = await supertest
|
||||
.get(
|
||||
`/internal/security/saml/start?redirectURLFragment=${encodeURIComponent('#workpad')}`
|
||||
)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL:
|
||||
'https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad',
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.body.location);
|
||||
|
||||
const samlAuthenticationResponse = await supertest
|
||||
.post('/api/security/saml/callback')
|
||||
|
@ -651,7 +581,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(esResponse).to.have.property('deleted').greaterThan(0);
|
||||
});
|
||||
|
||||
it('should properly set cookie and start new SAML handshake', async () => {
|
||||
it('should redirect user to a page that would capture URL fragment', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
|
@ -660,15 +590,42 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const handshakeCookie = request.cookie(cookies[0])!;
|
||||
expect(handshakeCookie.key).to.be('sid');
|
||||
expect(handshakeCookie.value).to.be.empty();
|
||||
expect(handshakeCookie.path).to.be('/');
|
||||
expect(handshakeCookie.httpOnly).to.be(true);
|
||||
expect(handshakeCookie.maxAge).to.be(0);
|
||||
|
||||
expect(handshakeResponse.headers.location).to.be(
|
||||
'/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml'
|
||||
);
|
||||
});
|
||||
|
||||
it('should properly set cookie and redirect user to IdP', async () => {
|
||||
const handshakeResponse = await supertest
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', sessionCookie.cookieString())
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL: `https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad`,
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const cookies = handshakeResponse.headers['set-cookie'];
|
||||
expect(cookies).to.have.length(1);
|
||||
|
||||
const handshakeCookie = request.cookie(cookies[0])!;
|
||||
expect(handshakeCookie.key).to.be('sid');
|
||||
expect(handshakeCookie.value).to.not.be.empty();
|
||||
expect(handshakeCookie.path).to.be('/');
|
||||
expect(handshakeCookie.httpOnly).to.be(true);
|
||||
|
||||
expect(handshakeResponse.headers.location).to.be(
|
||||
'/internal/security/saml/capture-url-fragment'
|
||||
);
|
||||
const redirectURL = url.parse(handshakeResponse.body.location, true /* parseQueryString */);
|
||||
expect(redirectURL.href!.startsWith(`https://elastic.co/sso/saml`)).to.be(true);
|
||||
expect(redirectURL.query.SAMLRequest).to.not.be.empty();
|
||||
});
|
||||
|
||||
it('should start new SAML handshake even if multiple concurrent requests try to refresh access token', async () => {
|
||||
|
@ -711,20 +668,18 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
];
|
||||
|
||||
beforeEach(async () => {
|
||||
const captureURLResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
const captureURLCookie = request.cookie(captureURLResponse.headers['set-cookie'][0])!;
|
||||
|
||||
const handshakeResponse = await supertest
|
||||
.get(
|
||||
`/internal/security/saml/start?redirectURLFragment=${encodeURIComponent('#workpad')}`
|
||||
)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
.post('/internal/security/login')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.send({
|
||||
providerType: 'saml',
|
||||
providerName: 'saml',
|
||||
currentURL: `https://kibana.com/internal/security/capture-url?next=%2Fabc%2Fxyz%2Fhandshake%3Fone%3Dtwo%2520three&providerType=saml&providerName=saml#/workpad`,
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.body.location);
|
||||
|
||||
const samlAuthenticationResponse = await supertest
|
||||
.post('/api/security/saml/callback')
|
||||
|
@ -762,18 +717,14 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(newSessionCookie.value).to.not.be.empty();
|
||||
expect(newSessionCookie.value).to.not.equal(existingSessionCookie.value);
|
||||
|
||||
// Tokens from old cookie are invalidated.
|
||||
const rejectedResponse = await supertest
|
||||
// Same user, same provider - session ID hasn't changed and cookie should still be valid.
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', existingSessionCookie.cookieString())
|
||||
.expect(400);
|
||||
expect(rejectedResponse.body).to.have.property(
|
||||
'message',
|
||||
'Both access and refresh tokens are expired.'
|
||||
);
|
||||
.expect(200);
|
||||
|
||||
// Only tokens from new session are valid.
|
||||
// New session cookie is also valid.
|
||||
await checkSessionCookie(newSessionCookie);
|
||||
});
|
||||
|
||||
|
@ -789,7 +740,7 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
.expect(302);
|
||||
|
||||
expect(samlAuthenticationResponse.headers.location).to.be(
|
||||
'/security/overwritten_session'
|
||||
'/security/overwritten_session?next=%2F'
|
||||
);
|
||||
|
||||
const newSessionCookie = request.cookie(
|
||||
|
@ -798,99 +749,17 @@ export default function ({ getService }: FtrProviderContext) {
|
|||
expect(newSessionCookie.value).to.not.be.empty();
|
||||
expect(newSessionCookie.value).to.not.equal(existingSessionCookie.value);
|
||||
|
||||
// Tokens from old cookie are invalidated.
|
||||
const rejectedResponse = await supertest
|
||||
// New username - old session is invalidated and session ID in the cookie no longer valid.
|
||||
await supertest
|
||||
.get('/internal/security/me')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', existingSessionCookie.cookieString())
|
||||
.expect(400);
|
||||
expect(rejectedResponse.body).to.have.property(
|
||||
'message',
|
||||
'Both access and refresh tokens are expired.'
|
||||
);
|
||||
.expect(401);
|
||||
|
||||
// Only tokens from new session are valid.
|
||||
await checkSessionCookie(newSessionCookie, newUsername);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('handshake with very long URL path or fragment', () => {
|
||||
it('should not try to capture URL fragment if path is too big already', async () => {
|
||||
// 1. Initiate SAML handshake.
|
||||
const handshakeResponse = await supertest
|
||||
.get(`/abc/xyz/${'handshake'.repeat(10)}?one=two three`)
|
||||
.expect(302);
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const redirectURL = url.parse(
|
||||
handshakeResponse.headers.location,
|
||||
true /* parseQueryString */
|
||||
);
|
||||
|
||||
expect(redirectURL.href!.startsWith(`https://elastic.co/sso/saml`)).to.be(true);
|
||||
expect(redirectURL.query.SAMLRequest).to.not.be.empty();
|
||||
|
||||
// 2. Finish SAML handshake
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
const samlAuthenticationResponse = await supertest
|
||||
.post('/api/security/saml/callback')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', handshakeCookie.cookieString())
|
||||
.send({ SAMLResponse: await createSAMLResponse({ inResponseTo: samlRequestId }) })
|
||||
.expect(302);
|
||||
|
||||
// User should be redirected to the root URL since we couldn't even save URL path.
|
||||
expect(samlAuthenticationResponse.headers.location).to.be('/');
|
||||
|
||||
await checkSessionCookie(
|
||||
request.cookie(samlAuthenticationResponse.headers['set-cookie'][0])!
|
||||
);
|
||||
});
|
||||
|
||||
it('should capture only URL path if URL fragment is too big', async () => {
|
||||
// 1. Capture current path
|
||||
const captureURLResponse = await supertest
|
||||
.get('/abc/xyz/handshake?one=two three')
|
||||
.expect(302);
|
||||
const captureURLCookie = request.cookie(captureURLResponse.headers['set-cookie'][0])!;
|
||||
|
||||
expect(captureURLResponse.headers.location).to.be(
|
||||
'/internal/security/saml/capture-url-fragment'
|
||||
);
|
||||
|
||||
// 2. Initiate SAML handshake.
|
||||
const handshakeResponse = await supertest
|
||||
.get(`/internal/security/saml/start?redirectURLFragment=%23%2F${'workpad'.repeat(10)}`)
|
||||
.set('Cookie', captureURLCookie.cookieString())
|
||||
.expect(302);
|
||||
|
||||
const handshakeCookie = request.cookie(handshakeResponse.headers['set-cookie'][0])!;
|
||||
const redirectURL = url.parse(
|
||||
handshakeResponse.headers.location,
|
||||
true /* parseQueryString */
|
||||
);
|
||||
|
||||
expect(redirectURL.href!.startsWith(`https://elastic.co/sso/saml`)).to.be(true);
|
||||
expect(redirectURL.query.SAMLRequest).to.not.be.empty();
|
||||
|
||||
// 3. Finish SAML handshake
|
||||
const samlRequestId = await getSAMLRequestId(handshakeResponse.headers.location);
|
||||
const samlAuthenticationResponse = await supertest
|
||||
.post('/api/security/saml/callback')
|
||||
.set('kbn-xsrf', 'xxx')
|
||||
.set('Cookie', handshakeCookie.cookieString())
|
||||
.send({ SAMLResponse: await createSAMLResponse({ inResponseTo: samlRequestId }) })
|
||||
.expect(302);
|
||||
|
||||
// User should be redirected to the URL path that initiated SAML handshake.
|
||||
expect(samlAuthenticationResponse.headers.location).to.be(
|
||||
'/abc/xyz/handshake?one=two%20three'
|
||||
);
|
||||
|
||||
await checkSessionCookie(
|
||||
request.cookie(samlAuthenticationResponse.headers['set-cookie'][0])!
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
|
@ -43,4 +43,15 @@ export function initRoutes(core: CoreSetup) {
|
|||
return response.renderJs({ body: 'document.getElementById("loginForm").submit();' });
|
||||
}
|
||||
);
|
||||
|
||||
core.http.resources.register(
|
||||
{
|
||||
path: '/saml_provider/logout',
|
||||
validate: false,
|
||||
options: { authRequired: false },
|
||||
},
|
||||
async (context, request, response) => {
|
||||
return response.redirected({ headers: { location: '/logout?SAMLResponse=something' } });
|
||||
}
|
||||
);
|
||||
}
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue