Skip to content

Commit

Permalink
[Security in Core] Exposes apiKeys from core.security.authc (#186910
Browse files Browse the repository at this point in the history
)

## Summary
Expose `apiKeys` as a service under `core.security.authc.apiKeys`.

Closes #184764

### Details
PR introduces a new API Keys Service which is accessible under the
`authc` namespace in core.security. The service exposes the public API
that was already available on the server-side in the security plugin.

The service is initialized and registered with core using the
`delegate_api` - allowing access to the service within the core plugin
without the need for the `security` plugin.

Note: I had to move quite a few types/functions around to prevent
cyclical dependencies.

### Plugins and the APIs that use the current `apiKeys` function from
the security plugin
<details>
<summary> Expand for table with details </summary>

| Plugin | File | API used | Can be migrated |
|--------|--------|--------|--------|
| alerting | x-pack/plugins/alerting/plugin/server.ts |
areApiKeysEnabled() | ✅ |
| | x-pack/plugins/alerting/server/rules_client_factory.ts |
grantAsInternalUser() | ❌ |
| | x-pack/plugins/alerting/server/task.ts | invalidatedAsInternalUser()
| ❌ |
| enterprise_search |
x-pack/plugins/enterprise_search/server/routes/enterprise_search/api_keys
| create() | ✅ |
| |
x-pack/plugins/enterprise_search/server/lib/indices/create_api_key.ts |
create() | ✅ |
| fleet | x-pack/plugins/fleet/server/routes/setup/handlers.ts |
areApiKeysEnabled() | ✅ |
| | x-pack/plugins/fleet/server/services/api_keys/security |
invalidateAsInternalUser() | ❌ |
| | x-pack/plugins/fleet/server/services/api_keys/transform_api_keys.ts
| grantAsInternalUser() | ❌ |
| |
x-pack/plugins/fleet/server/services/setup/fleet_server_policies_enrollment_keys.ts
| areApiKeysEnabled() | ✅ |
| |
x-pack/plugins/fleet/server/services/setup/fleet_server_policies_enrollment_keys.ts
| areAPIKeysEnabled() | ✅ |
| |
x-pack/plugins/observability_solution/apm/server/routes/agent_keys/get_agent_keys_privileges.ts
| areAPIKeysEnabled() | ✅ |
| observability_solution |
x-pack/plugins/observability_solution/entity_manager/server/lib/auth/api_key/api_key.ts
| areAPIKeysEnabled | ✅ |
| | | validate | ✅ |
| | | grantAsInternalUser | ❌ |
| |
x-pack/plugins/observability_solution/entity_manager/server/routes/enablement/disable.ts
| invalidateAsInternalUser | ❌ |
| |
x-pack/plugins/observability_solution/entity_manager/server/routes/enablement/enable.ts
| invalidateAsInternalUser | ❌ |
| |
x-pack/plugins/observability_solution/observability_onboarding/server/routes/flow/route.ts
| create | ✅ |
| |
x-pack/plugins/observability_solution/synthetics/server/routes/synthetics_service/enablement.ts
| invalidateAsInternalUser | ❌ |
| |
x-pack/plugins/observability_solution/synthetics/server/synthetics_service/get_api_key.ts
| validate | ✅ |
| | | areAPIKeysEnabled | ✅ |
| | | grantAsInternalUser | ❌ |
| | | create | ✅ |
| serverless_search |
x-pack/plugins/serverless_search/server/routes/api_key_routes.ts |
create | ✅ |
| |
x-pack/plugins/transform/server/routes/api/reauthorize_transforms/route_handler_factory.ts
| grantAsInternalUser | ❌ |
| |
x-pack/plugins/upgrade_assistant/server/lib/reindexing/credential_store.ts
| grantAsInternalUser | ❌ |
| | | invalidateAsInternalUser | ❌ |
| | | areAPIKeysEnabled() | ✅ |
</details>

---------

Co-authored-by: kibanamachine <[email protected]>
Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
3 people authored Jul 9, 2024
1 parent f484aca commit ff9a48e
Show file tree
Hide file tree
Showing 31 changed files with 644 additions and 269 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ export class CoreSecurityRouteHandlerContext implements SecurityRequestHandlerCo
if (this.#authc == null) {
this.#authc = {
getCurrentUser: () => this.securityStart.authc.getCurrentUser(this.request),
apiKeys: {
areAPIKeysEnabled: () => this.securityStart.authc.apiKeys.areAPIKeysEnabled(),
create: (createParams) =>
this.securityStart.authc.apiKeys.create(this.request, createParams),
update: (updateParams) =>
this.securityStart.authc.apiKeys.update(this.request, updateParams),
validate: (apiKeyParams) => this.securityStart.authc.apiKeys.validate(apiKeyParams),
invalidate: (apiKeyParams) =>
this.securityStart.authc.apiKeys.invalidate(this.request, apiKeyParams),
},
};
}
return this.#authc;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ describe('convertSecurityApi', () => {
const source: CoreSecurityDelegateContract = {
authc: {
getCurrentUser: jest.fn(),
apiKeys: {
areAPIKeysEnabled: jest.fn(),
areCrossClusterAPIKeysEnabled: jest.fn(),
validate: jest.fn(),
invalidate: jest.fn(),
invalidateAsInternalUser: jest.fn(),
grantAsInternalUser: jest.fn(),
create: jest.fn(),
update: jest.fn(),
},
},
audit: {
asScoped: jest.fn().mockReturnValue(createAuditLoggerMock.create()),
Expand All @@ -23,6 +33,7 @@ describe('convertSecurityApi', () => {
};
const output = convertSecurityApi(source);
expect(output.authc.getCurrentUser).toBe(source.authc.getCurrentUser);
expect(output.authc.apiKeys).toBe(source.authc.apiKeys);
expect(output.audit.asScoped).toBe(source.audit.asScoped);
expect(output.audit.withoutRequest).toBe(source.audit.withoutRequest);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ describe('getDefaultSecurityImplementation', () => {
});
});

describe('authc.apiKeys', () => {
it('returns stub object', async () => {
const { apiKeys } = implementation.authc;
const areAPIKeysEnabled = await apiKeys.areAPIKeysEnabled();

expect(areAPIKeysEnabled).toBe(false);
});
});

describe('audit.asScoped', () => {
it('returns null', async () => {
const logger = implementation.audit.asScoped({} as any);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,23 @@

import type { CoreSecurityDelegateContract } from '@kbn/core-security-server';

const API_KEYS_DISABLED_ERROR = new Error('API keys are disabled');
const REJECT_WHEN_API_KEYS_DISABLED = () => Promise.reject(API_KEYS_DISABLED_ERROR);

export const getDefaultSecurityImplementation = (): CoreSecurityDelegateContract => {
return {
authc: {
getCurrentUser: () => null,
apiKeys: {
areAPIKeysEnabled: () => Promise.resolve(false),
areCrossClusterAPIKeysEnabled: () => Promise.resolve(false),
create: REJECT_WHEN_API_KEYS_DISABLED,
update: REJECT_WHEN_API_KEYS_DISABLED,
grantAsInternalUser: REJECT_WHEN_API_KEYS_DISABLED,
validate: REJECT_WHEN_API_KEYS_DISABLED,
invalidate: REJECT_WHEN_API_KEYS_DISABLED,
invalidateAsInternalUser: REJECT_WHEN_API_KEYS_DISABLED,
},
},
audit: {
asScoped: () => {
Expand Down
1 change: 1 addition & 0 deletions packages/core/security/core-security-server-mocks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
export { securityServiceMock } from './src/security_service.mock';
export type { InternalSecurityStartMock, SecurityStartMock } from './src/security_service.mock';
export { auditLoggerMock } from './src/audit.mock';
export { apiKeysMock } from './src/api_keys.mock';
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import type { PublicMethodsOf } from '@kbn/utility-types';

import type { APIKeys } from './api_keys';
import type { APIKeysService } from '@kbn/core-security-server';

export const apiKeysMock = {
create: (): jest.Mocked<PublicMethodsOf<APIKeys>> => ({
create: (): jest.MockedObjectDeep<APIKeysService> => ({
areAPIKeysEnabled: jest.fn(),
areCrossClusterAPIKeysEnabled: jest.fn(),
create: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
InternalSecurityServiceSetup,
InternalSecurityServiceStart,
} from '@kbn/core-security-server-internal';
import { apiKeysMock } from './api_keys.mock';
import { auditServiceMock, type MockedAuditService } from './audit.mock';
import { mockAuthenticatedUser, MockAuthenticatedUserProps } from '@kbn/core-security-common/mocks';

Expand All @@ -35,6 +36,7 @@ const createStartMock = (): SecurityStartMock => {
const mock = {
authc: {
getCurrentUser: jest.fn(),
apiKeys: apiKeysMock.create(),
},
audit: auditServiceMock.create(),
};
Expand All @@ -61,6 +63,7 @@ const createInternalStartMock = (): InternalSecurityStartMock => {
const mock = {
authc: {
getCurrentUser: jest.fn(),
apiKeys: apiKeysMock.create(),
},
audit: auditServiceMock.create(),
};
Expand All @@ -82,6 +85,13 @@ const createRequestHandlerContextMock = () => {
const mock: jest.MockedObjectDeep<SecurityRequestHandlerContext> = {
authc: {
getCurrentUser: jest.fn(),
apiKeys: {
areAPIKeysEnabled: jest.fn(),
create: jest.fn(),
update: jest.fn(),
validate: jest.fn(),
invalidate: jest.fn(),
},
},
audit: {
logger: {
Expand Down
22 changes: 22 additions & 0 deletions packages/core/security/core-security-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,26 @@ export type {
AuditRequest,
} from './src/audit_logging/audit_events';
export type { AuditLogger } from './src/audit_logging/audit_logger';

export type {
APIKeysServiceWithContext,
APIKeysService,
CreateAPIKeyParams,
CreateAPIKeyResult,
InvalidateAPIKeyResult,
InvalidateAPIKeysParams,
ValidateAPIKeyParams,
CreateRestAPIKeyParams,
CreateRestAPIKeyWithKibanaPrivilegesParams,
CreateCrossClusterAPIKeyParams,
GrantAPIKeyResult,
UpdateAPIKeyParams,
UpdateAPIKeyResult,
UpdateCrossClusterAPIKeyParams,
UpdateRestAPIKeyParams,
UpdateRestAPIKeyWithKibanaPrivilegesParams,
} from './src/authentication/api_keys';

export type { KibanaPrivilegesType, ElasticsearchPrivilegesType } from './src/roles';
export { isCreateRestAPIKeyParams } from './src/authentication/api_keys';
export type { CoreFipsService } from './src/fips';
2 changes: 2 additions & 0 deletions packages/core/security/core-security-server/src/authc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import type { KibanaRequest } from '@kbn/core-http-server';
import type { AuthenticatedUser } from '@kbn/core-security-common';
import type { APIKeysService } from './authentication/api_keys';

/**
* Core's authentication service
Expand All @@ -22,4 +23,5 @@ export interface CoreAuthenticationService {
* @param request The request to retrieve the authenticated user for.
*/
getCurrentUser(request: KibanaRequest): AuthenticatedUser | null;
apiKeys: APIKeysService;
}
Loading

0 comments on commit ff9a48e

Please sign in to comment.