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

Adding deprecation warning for Interactive Users using ApiKeys #136422

Merged
merged 16 commits into from
Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
5 changes: 5 additions & 0 deletions docs/user/security/api-keys/index.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ curl --location --request GET 'http://localhost:5601/api/security/role' \
--header 'kbn-xsrf: true' \
--header 'Authorization: ApiKey aVZlLUMzSUJuYndxdDJvN0k1bU46aGxlYUpNS2lTa2FKeVZua1FnY1VEdw==' \

[IMPORTANT]
============================================================================
API keys are intended for programmatic access to {kib} and {es}, and should not be used to authenticate access via a web browser.
kc13greiner marked this conversation as resolved.
Show resolved Hide resolved
============================================================================

[float]
[[view-api-keys]]
=== View and delete API keys
Expand Down
6 changes: 6 additions & 0 deletions docs/user/security/authentication/index.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,12 @@ HTTP protocol provides a simple authentication framework that can be used by a c

This type of authentication is usually useful for machine-to-machine interaction that requires authentication and where human intervention is not desired or just infeasible. There are a number of use cases when HTTP authentication support comes in handy for {kib} users as well.

[IMPORTANT]
============================================================================
API keys are intended for programmatic access to {kib} and {es}, and should not be used to authenticate access via a web browser.
kc13greiner marked this conversation as resolved.
Show resolved Hide resolved
============================================================================


By default {kib} supports <<api-keys, `ApiKey`>> authentication scheme _and_ any scheme supported by the currently enabled authentication provider. For example, `Basic` authentication scheme is automatically supported when basic authentication provider is enabled, or `Bearer` scheme when any of the token based authentication providers is enabled (Token, SAML, OpenID Connect, PKI or Kerberos). But it's also possible to add support for any other authentication scheme in the `kibana.yml` configuration file, as follows:

NOTE: Don't forget to explicitly specify the default `apikey` and `bearer` schemes when you just want to add a new one to the list.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { routeDefinitionParamsMock } from '../index.mock';
import { defineRecordAnalyticsOnAuthTypeRoutes } from './authentication_type';

const FAKE_TIMESTAMP = 1637665318135;

function getMockContext(
licenseCheckResult: { state: string; message?: string } = { state: 'valid' }
) {
Expand All @@ -33,14 +34,18 @@ describe('POST /internal/security/analytics/_record_auth_type', () => {
});

let routeHandler: RequestHandler<any, any, any, any>;

kc13greiner marked this conversation as resolved.
Show resolved Hide resolved
let routeParamsMock: DeeplyMockedKeys<RouteDefinitionParams>;

beforeEach(() => {
routeParamsMock = routeDefinitionParamsMock.create();

defineRecordAnalyticsOnAuthTypeRoutes(routeParamsMock);

const [, recordAnalyticsOnAuthTypeRouteHandler] = routeParamsMock.router.post.mock.calls.find(
([{ path }]) => path === '/internal/security/analytics/_record_auth_type'
)!;

routeHandler = recordAnalyticsOnAuthTypeRouteHandler;
});

Expand All @@ -49,6 +54,10 @@ describe('POST /internal/security/analytics/_record_auth_type', () => {
const response = await routeHandler(getMockContext(), request, kibanaResponseFactory);

expect(response.status).toBe(204);
expect(routeParamsMock.logger.warn).toBeCalledWith(
'Cannot record authentication type: current user could not be retrieved.'
);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).not.toHaveBeenCalled();
});

Expand Down Expand Up @@ -286,19 +295,23 @@ describe('POST /internal/security/analytics/_record_auth_type', () => {
});

const mockAuthc = authenticationServiceMock.createStart();

mockAuthc.getCurrentUser.mockReturnValue(
mockAuthenticatedUser({
authentication_provider: { type: HTTPAuthenticationProvider.type, name: '__http__' },
})
);

routeParamsMock.getAuthenticationService.mockReturnValue(mockAuthc);

const response = await routeHandler(getMockContext(), request, kibanaResponseFactory);

expect(response.status).toBe(200);
expect(response.payload).toEqual({
timestamp: FAKE_TIMESTAMP,
signature: 'f4f6b485690816127c33d5aa13cd6cd12c9892641ba23b5d58e5c6590cd43db0',
});

routeParamsMock.analyticsService.reportAuthenticationTypeEvent.mockClear();

initialTimestamp = response.payload.timestamp;
Expand All @@ -312,21 +325,95 @@ describe('POST /internal/security/analytics/_record_auth_type', () => {
});

const response = await routeHandler(getMockContext(), request, kibanaResponseFactory);

expect(response.status).toBe(200);

expect(response.payload).toEqual({
timestamp: initialTimestamp,
signature: '46d5841ad21d29ca6c7c1c639adc6294c176c394adb0b40dfc05797cfe29218e',
});

expect(response.payload.signature).not.toEqual(initialSignature);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).toHaveBeenCalledTimes(
1
);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).toHaveBeenCalledWith({
authenticationProviderType: 'http',
authenticationRealmType: 'native',
httpAuthenticationScheme: 'Custom',
});
});
});

describe('logApiKeyWithInteractiveUserDeprecated', () => {
it('should log a deprecation warning if interactive user is using API Key', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

"interactive user" is not a term I normally see. Can we drop "interactive" or find another way to explain what is meant here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

How about something like:

should log a deprecation warning if a user is authenticating via API key while accessing the application through a web browser

const request = httpServerMock.createKibanaRequest({
headers: { authorization: 'ApiKey' },
kc13greiner marked this conversation as resolved.
Show resolved Hide resolved
});

const mockAuthc = authenticationServiceMock.createStart();

mockAuthc.getCurrentUser.mockReturnValue(
mockAuthenticatedUser({
authentication_provider: { type: 'http', name: '__http__' },
})
);

routeParamsMock.getAuthenticationService.mockReturnValue(mockAuthc);

const response = await routeHandler(getMockContext(), request, kibanaResponseFactory);

expect(response.status).toBe(200);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).toHaveBeenCalledTimes(
1
);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).toHaveBeenCalledWith({
authenticationProviderType: 'http',
authenticationRealmType: 'native',
httpAuthenticationScheme: 'ApiKey',
});

expect(routeParamsMock.logger.warn).toHaveBeenCalledTimes(1);
expect(routeParamsMock.logger.warn).toBeCalledWith(
'Using API Key authentication as an interactive user is deprecated and will not be supported in a future version',
{ tags: ['deprecation'] }
);
});

it('should not log a deprecation warning if interactive user is using API Key', async () => {
const request = httpServerMock.createKibanaRequest({
headers: { authorization: 'Basic' },
});

const mockAuthc = authenticationServiceMock.createStart();

mockAuthc.getCurrentUser.mockReturnValue(
mockAuthenticatedUser({
authentication_provider: { type: 'http', name: '__http__' },
})
);

routeParamsMock.getAuthenticationService.mockReturnValue(mockAuthc);

const response = await routeHandler(getMockContext(), request, kibanaResponseFactory);

expect(response.status).toBe(200);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).toHaveBeenCalledTimes(
1
);

expect(routeParamsMock.analyticsService.reportAuthenticationTypeEvent).toHaveBeenCalledWith({
authenticationProviderType: 'http',
authenticationRealmType: 'native',
httpAuthenticationScheme: 'Basic',
});

expect(routeParamsMock.logger.warn).toHaveBeenCalledTimes(0);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { createHash } from 'crypto';

import { schema } from '@kbn/config-schema';
import type { Logger } from '@kbn/logging';

import type { RouteDefinitionParams } from '..';
import type { AuthenticationTypeAnalyticsEvent } from '../../analytics';
Expand Down Expand Up @@ -39,12 +40,15 @@ export function defineRecordAnalyticsOnAuthTypeRoutes({
createLicensedRouteHandler(async (context, request, response) => {
try {
const authUser = getAuthenticationService().getCurrentUser(request);

if (!authUser) {
logger.warn('Cannot record authentication type: current user could not be retrieved.');

return response.noContent();
}

let timestamp = new Date().getTime();

const {
signature: previouslyRegisteredSignature,
timestamp: previousRegistrationTimestamp,
Expand All @@ -69,11 +73,17 @@ export function defineRecordAnalyticsOnAuthTypeRoutes({
.digest('hex');

const elapsedTimeInHrs = (timestamp - previousRegistrationTimestamp) / (1000 * 60 * 60);

if (
elapsedTimeInHrs >= MINIMUM_ELAPSED_TIME_HOURS ||
previouslyRegisteredSignature !== signature
) {
analyticsService.reportAuthenticationTypeEvent(authTypeEventToReport);

logApiKeyWithInteractiveUserDeprecated(
authTypeEventToReport.httpAuthenticationScheme,
logger
);
} else {
timestamp = previousRegistrationTimestamp;
}
Expand All @@ -88,3 +98,23 @@ export function defineRecordAnalyticsOnAuthTypeRoutes({
})
);
}

/**
* API Key authentication by interactive users is deprecated, this method logs a deprecation warning
*
* @param httpAuthenticationScheme A string representing the authentication type event's scheme (ApiKey, etc.) by an interactive user
* @param logger A reference to the Logger to log the deprecation message
*/
kc13greiner marked this conversation as resolved.
Show resolved Hide resolved
function logApiKeyWithInteractiveUserDeprecated(
httpAuthenticationScheme: string = '',
logger: Logger
): void {
const isUsingApiKey = httpAuthenticationScheme?.toLowerCase() === 'apikey';

if (isUsingApiKey) {
logger.warn(
`Using API Key authentication as an interactive user is deprecated and will not be supported in a future version`,
{ tags: ['deprecation'] }
);
}
}