Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[skip ci] Check point on token provider #25971

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { getClient } from '../../../../../server/lib/get_client_shield';
import { AuthScopeService } from '../auth_scope_service';
import { BasicAuthenticationProvider } from './providers/basic';
import { TokenAuthenticationProvider } from './providers/token';
import { SAMLAuthenticationProvider } from './providers/saml';
import { AuthenticationResult } from './authentication_result';
import { DeauthenticationResult } from './deauthentication_result';
Expand All @@ -16,6 +17,7 @@ import { Session } from './session';
// provider class that can handle specific authentication mechanism.
const providerMap = new Map([
['basic', BasicAuthenticationProvider],
['token', TokenAuthenticationProvider],
['saml', SAMLAuthenticationProvider]
]);

Expand Down
108 changes: 76 additions & 32 deletions x-pack/plugins/security/server/lib/authentication/providers/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,37 @@ import { canRedirectRequest } from '../../can_redirect_request';
import { AuthenticationResult } from '../authentication_result';
import { DeauthenticationResult } from '../deauthentication_result';

/**
* Utility class that knows how to decorate request with proper Basic authentication headers.
*/
export class BasicCredentials {
Copy link
Contributor Author

@epixa epixa Nov 20, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super annoying, but the linter has a rule that disallows accessing static methods on BasicCredentials before it is defined in the same file. Even though it's all static. Dumb.

Anyway, I copied and pasted BasicCredentials without changes to the top of the file so linting would stop failing

/**
* Takes provided `username` and `password`, transforms them into proper `Basic ***` authorization
* header and decorates passed request with it.
* @param {Hapi.Request} request HapiJS request instance.
* @param {string} username User name.
* @param {string} password User password.
* @returns {Hapi.Request} HapiJS request instance decorated with the proper header.
*/
static decorateRequest(request, username, password) {
if (!request || typeof request !== 'object') {
throw new Error('Request should be a valid object.');
}

if (!username || typeof username !== 'string') {
throw new Error('Username should be a valid non-empty string.');
}

if (!password || typeof password !== 'string') {
throw new Error('Password should be a valid non-empty string.');
}

const basicCredentials = new Buffer(`${username}:${password}`).toString('base64');
request.headers.authorization = `Basic ${basicCredentials}`;
return request;
}
}

/**
* Object that represents available provider options.
* @typedef {{
Expand Down Expand Up @@ -49,8 +80,15 @@ export class BasicAuthenticationProvider {
async authenticate(request, state) {
this._options.log(['debug', 'security', 'basic'], `Trying to authenticate user request to ${request.url.path}.`);

let authenticationResult = await this._authenticateViaHeader(request);
// first try from login payload
let authenticationResult = await this._authenticateViaLoginAttempt(request);

// if there isn't a payload, try header-based token auth
if (authenticationResult.notHandled()) {
authenticationResult = await this._authenticateViaHeader(request);
}

// if we still can't attempt auth, try authenticating via state (session token)
if (authenticationResult.notHandled() && state) {
authenticationResult = await this._authenticateViaState(request, state);
} else if (authenticationResult.notHandled() && canRedirectRequest(request)) {
Expand Down Expand Up @@ -117,6 +155,43 @@ export class BasicAuthenticationProvider {
}
}

/**
* @param {Hapi.Request} request HapiJS request instance.
* @returns {Promise.<AuthenticationResult>}
* @private
*/
async _authenticateViaLoginAttempt(request) {
this._options.log(['debug', 'security', 'basic'], 'Trying to authenticate via login attempt.');

const credentials = request.loginAttempt(request).getCredentials();
if (!credentials) {
this._options.log(['debug', 'security', 'basic'], 'Username and password not found in payload.');
return AuthenticationResult.notHandled();
}

try {
const { username, password } = credentials;

BasicCredentials.decorateRequest(request, username, password);
const user = await this._options.client.callWithRequest(request, 'shield.authenticate');

this._options.log(['debug', 'security', 'basic'], 'Request has been authenticated via login attempt.');

return AuthenticationResult.succeeded(user, { authorization: request.headers.authorization });
} catch(err) {
this._options.log(['debug', 'security', 'basic'], `Failed to authenticate request via login attempt: ${err.message}`);

// Reset `Authorization` header we've just set. We know for sure that it hasn't been defined before,
// otherwise it would have been used or completely rejected by the `authenticateViaHeader`.
// We can't just set `authorization` to `undefined` or `null`, we should remove this property
// entirely, otherwise `authorization` header without value will cause `callWithRequest` to fail if
// it's called with this request once again down the line (e.g. in the next authentication provider).
delete request.headers.authorization;

return AuthenticationResult.failed(err);
}
}

/**
* Tries to extract authorization header from the state and adds it to the request before
* it's forwarded to Elasticsearch backend.
Expand Down Expand Up @@ -155,34 +230,3 @@ export class BasicAuthenticationProvider {
}
}
}

/**
* Utility class that knows how to decorate request with proper Basic authentication headers.
*/
export class BasicCredentials {
/**
* Takes provided `username` and `password`, transforms them into proper `Basic ***` authorization
* header and decorates passed request with it.
* @param {Hapi.Request} request HapiJS request instance.
* @param {string} username User name.
* @param {string} password User password.
* @returns {Hapi.Request} HapiJS request instance decorated with the proper header.
*/
static decorateRequest(request, username, password) {
if (!request || typeof request !== 'object') {
throw new Error('Request should be a valid object.');
}

if (!username || typeof username !== 'string') {
throw new Error('Username should be a valid non-empty string.');
}

if (!password || typeof password !== 'string') {
throw new Error('Password should be a valid non-empty string.');
}

const basicCredentials = new Buffer(`${username}:${password}`).toString('base64');
request.headers.authorization = `Basic ${basicCredentials}`;
return request;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function isAccessTokenExpiredError(err) {
}

/**
* Checks the error returned by Elasticsearch as the result of `samlRefreshAccessToken` call and returns `true` if
* Checks the error returned by Elasticsearch as the result of `getAccessToken` call and returns `true` if
* request has been rejected because of invalid refresh token (expired after 24 hours or have been used already),
* otherwise returns `false`.
* @param {Object} err Error returned from Elasticsearch.
Expand Down Expand Up @@ -269,7 +269,7 @@ export class SAMLAuthenticationProvider {
access_token: newAccessToken,
refresh_token: newRefreshToken
} = await this._options.client.callWithInternalUser(
'shield.samlRefreshAccessToken',
'shield.getAccessToken',
{ body: { grant_type: 'refresh_token', refresh_token: refreshToken } }
);

Expand Down
Loading