diff --git a/packages/kbn-router-to-openapispec/src/extract_authz_description.test.ts b/packages/kbn-router-to-openapispec/src/extract_authz_description.test.ts new file mode 100644 index 0000000000000..8da2324e68f02 --- /dev/null +++ b/packages/kbn-router-to-openapispec/src/extract_authz_description.test.ts @@ -0,0 +1,81 @@ +/* + * 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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +import { schema } from '@kbn/config-schema'; +import { extractAuthzDescription } from './extract_authz_description'; +import { InternalRouterRoute } from './type'; +import { RouteSecurity } from '@kbn/core-http-server'; + +describe('extractAuthzDescription', () => { + it('should return empty if route does not require privileges', () => { + const route: InternalRouterRoute = { + path: '/foo', + options: { access: 'internal' }, + handler: jest.fn(), + validationSchemas: { request: { body: schema.object({}) } }, + method: 'get', + isVersioned: false, + }; + const description = extractAuthzDescription(route.security); + expect(description).toBe(''); + }); + + it('should return route authz description for simple privileges', () => { + const routeSecurity: RouteSecurity = { + authz: { + requiredPrivileges: ['manage_spaces'], + }, + }; + const description = extractAuthzDescription(routeSecurity); + expect(description).toBe('[Authz] Route required privileges: ALL of [manage_spaces].'); + }); + + it('should return route authz description for privilege groups', () => { + { + const routeSecurity: RouteSecurity = { + authz: { + requiredPrivileges: [{ allRequired: ['console'] }], + }, + }; + const description = extractAuthzDescription(routeSecurity); + expect(description).toBe('[Authz] Route required privileges: ALL of [console].'); + } + { + const routeSecurity: RouteSecurity = { + authz: { + requiredPrivileges: [ + { + anyRequired: ['manage_spaces', 'taskmanager'], + }, + ], + }, + }; + const description = extractAuthzDescription(routeSecurity); + expect(description).toBe( + '[Authz] Route required privileges: ANY of [manage_spaces OR taskmanager].' + ); + } + { + const routeSecurity: RouteSecurity = { + authz: { + requiredPrivileges: [ + { + allRequired: ['console', 'filesManagement'], + anyRequired: ['manage_spaces', 'taskmanager'], + }, + ], + }, + }; + const description = extractAuthzDescription(routeSecurity); + expect(description).toBe( + '[Authz] Route required privileges: ALL of [console, filesManagement] AND ANY of [manage_spaces OR taskmanager].' + ); + } + }); +}); diff --git a/packages/kbn-router-to-openapispec/src/extract_authz_description.ts b/packages/kbn-router-to-openapispec/src/extract_authz_description.ts new file mode 100644 index 0000000000000..4cd6875913780 --- /dev/null +++ b/packages/kbn-router-to-openapispec/src/extract_authz_description.ts @@ -0,0 +1,60 @@ +/* + * 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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +import type { AuthzEnabled, AuthzDisabled, InternalRouteSecurity } from '@kbn/core-http-server'; + +interface PrivilegeGroupValue { + allRequired: string[]; + anyRequired: string[]; +} + +export const extractAuthzDescription = (routeSecurity: InternalRouteSecurity | undefined) => { + if (!routeSecurity) { + return ''; + } + if (!('authz' in routeSecurity) || (routeSecurity.authz as AuthzDisabled).enabled === false) { + return ''; + } + + const privileges = (routeSecurity.authz as AuthzEnabled).requiredPrivileges; + + const groupedPrivileges = privileges.reduce( + (groups, privilege) => { + if (typeof privilege === 'string') { + groups.allRequired.push(privilege); + + return groups; + } + groups.allRequired.push(...(privilege.allRequired ?? [])); + groups.anyRequired.push(...(privilege.anyRequired ?? [])); + + return groups; + }, + { + anyRequired: [], + allRequired: [], + } + ); + + const getPrivilegesDescription = (allRequired: string[], anyRequired: string[]) => { + const allDescription = allRequired.length ? `ALL of [${allRequired.join(', ')}]` : ''; + const anyDescription = anyRequired.length ? `ANY of [${anyRequired.join(' OR ')}]` : ''; + + return `${allDescription}${allDescription && anyDescription ? ' AND ' : ''}${anyDescription}`; + }; + + const getDescriptionForRoute = () => { + const allRequired = [...groupedPrivileges.allRequired]; + const anyRequired = [...groupedPrivileges.anyRequired]; + + return `Route required privileges: ${getPrivilegesDescription(allRequired, anyRequired)}.`; + }; + + return `[Authz] ${getDescriptionForRoute()}`; +}; diff --git a/packages/kbn-router-to-openapispec/src/process_router.test.ts b/packages/kbn-router-to-openapispec/src/process_router.test.ts index 22e03efdf08fc..96a10b25d648a 100644 --- a/packages/kbn-router-to-openapispec/src/process_router.test.ts +++ b/packages/kbn-router-to-openapispec/src/process_router.test.ts @@ -11,7 +11,8 @@ import { schema } from '@kbn/config-schema'; import { Router } from '@kbn/core-http-router-server-internal'; import { OasConverter } from './oas_converter'; import { createOperationIdCounter } from './operation_id_counter'; -import { extractResponses, processRouter, type InternalRouterRoute } from './process_router'; +import { extractResponses, processRouter } from './process_router'; +import { type InternalRouterRoute } from './type'; describe('extractResponses', () => { let oasConverter: OasConverter; @@ -102,6 +103,24 @@ describe('processRouter', () => { handler: jest.fn(), validationSchemas: { request: { body: schema.object({}) } }, }, + { + path: '/qux', + method: 'post', + options: {}, + handler: jest.fn(), + validationSchemas: { request: { body: schema.object({}) } }, + security: { + authz: { + requiredPrivileges: [ + 'manage_spaces', + { + allRequired: ['taskmanager'], + anyRequired: ['console'], + }, + ], + }, + }, + }, ], } as unknown as Router; @@ -110,11 +129,23 @@ describe('processRouter', () => { version: '2023-10-31', }); - expect(Object.keys(result1.paths!)).toHaveLength(3); + expect(Object.keys(result1.paths!)).toHaveLength(4); const result2 = processRouter(testRouter, new OasConverter(), createOperationIdCounter(), { version: '2024-10-31', }); expect(Object.keys(result2.paths!)).toHaveLength(0); }); + + it('updates description with privileges required', () => { + const result = processRouter(testRouter, new OasConverter(), createOperationIdCounter(), { + version: '2023-10-31', + }); + + expect(result.paths['/qux']?.post).toBeDefined(); + + expect(result.paths['/qux']?.post?.description).toEqual( + '[Authz] Route required privileges: ALL of [manage_spaces, taskmanager] AND ANY of [console].' + ); + }); }); diff --git a/packages/kbn-router-to-openapispec/src/process_router.ts b/packages/kbn-router-to-openapispec/src/process_router.ts index f0d37fd208b7b..cb55af3735b34 100644 --- a/packages/kbn-router-to-openapispec/src/process_router.ts +++ b/packages/kbn-router-to-openapispec/src/process_router.ts @@ -27,7 +27,8 @@ import { } from './util'; import type { OperationIdCounter } from './operation_id_counter'; import type { GenerateOpenApiDocumentOptionsFilters } from './generate_oas'; -import type { CustomOperationObject } from './type'; +import type { CustomOperationObject, InternalRouterRoute } from './type'; +import { extractAuthzDescription } from './extract_authz_description'; export const processRouter = ( appRouter: Router, @@ -63,10 +64,19 @@ export const processRouter = ( parameters.push(...pathObjects, ...queryObjects); } + let description = ''; + if (route.security) { + const authzDescription = extractAuthzDescription(route.security); + + description = `${route.options.description ?? ''}${authzDescription ?? ''}`; + } + const hasDeprecations = !!route.options.deprecated; + const operation: CustomOperationObject = { summary: route.options.summary ?? '', tags: route.options.tags ? extractTags(route.options.tags) : [], + ...(description ? { description } : {}), ...(route.options.description ? { description: route.options.description } : {}), ...(hasDeprecations ? { deprecated: true } : {}), ...(route.options.discontinued ? { 'x-discontinued': route.options.discontinued } : {}), @@ -99,7 +109,6 @@ export const processRouter = ( return { paths }; }; -export type InternalRouterRoute = ReturnType[0]; export const extractResponses = (route: InternalRouterRoute, converter: OasConverter) => { const responses: OpenAPIV3.ResponsesObject = {}; if (!route.validationSchemas) return responses; diff --git a/packages/kbn-router-to-openapispec/src/process_versioned_router.test.ts b/packages/kbn-router-to-openapispec/src/process_versioned_router.test.ts index f9f4f4898c1d0..3738c207f1f78 100644 --- a/packages/kbn-router-to-openapispec/src/process_versioned_router.test.ts +++ b/packages/kbn-router-to-openapispec/src/process_versioned_router.test.ts @@ -144,6 +144,22 @@ describe('processVersionedRouter', () => { 'application/test+json; Elastic-Api-Version=2023-10-31', ]); }); + + it('correctly updates the authz description for routes that require privileges', () => { + const results = processVersionedRouter( + { getRoutes: () => [createTestRoute()] } as unknown as CoreVersionedRouter, + new OasConverter(), + createOperationIdCounter(), + {} + ); + expect(results.paths['/foo']).toBeDefined(); + + expect(results.paths['/foo']!.get).toBeDefined(); + + expect(results.paths['/foo']!.get!.description).toBe( + '[Authz] Route required privileges: ALL of [manage_spaces].' + ); + }); }); const createTestRoute: () => VersionedRouterRoute = () => ({ @@ -155,6 +171,11 @@ const createTestRoute: () => VersionedRouterRoute = () => ({ deprecated: true, discontinued: 'discontinued versioned router', options: { body: { access: ['application/test+json'] } as any }, + security: { + authz: { + requiredPrivileges: ['manage_spaces'], + }, + }, }, handlers: [ { diff --git a/packages/kbn-router-to-openapispec/src/process_versioned_router.ts b/packages/kbn-router-to-openapispec/src/process_versioned_router.ts index 7eee0d20c11d2..5dad5677c94ac 100644 --- a/packages/kbn-router-to-openapispec/src/process_versioned_router.ts +++ b/packages/kbn-router-to-openapispec/src/process_versioned_router.ts @@ -14,6 +14,7 @@ import { } from '@kbn/core-http-router-server-internal'; import type { RouteMethod, VersionedRouterRoute } from '@kbn/core-http-server'; import type { OpenAPIV3 } from 'openapi-types'; +import { extractAuthzDescription } from './extract_authz_description'; import type { GenerateOpenApiDocumentOptionsFilters } from './generate_oas'; import type { OasConverter } from './oas_converter'; import { isReferenceObject } from './oas_converter/common'; @@ -90,6 +91,13 @@ export const processVersionedRouter = ( ]; } + let description = ''; + if (route.options.security) { + const authzDescription = extractAuthzDescription(route.options.security); + + description = `${route.options.description ?? ''}${authzDescription ?? ''}`; + } + const hasBody = Boolean(extractValidationSchemaFromVersionedHandler(handler)?.request?.body); const contentType = extractContentType(route.options.options?.body); const hasVersionFilter = Boolean(filters?.version); @@ -98,6 +106,7 @@ export const processVersionedRouter = ( const operation: OpenAPIV3.OperationObject = { summary: route.options.summary ?? '', tags: route.options.options?.tags ? extractTags(route.options.options.tags) : [], + ...(description ? { description } : {}), ...(route.options.description ? { description: route.options.description } : {}), ...(hasDeprecations ? { deprecated: true } : {}), ...(route.options.discontinued ? { 'x-discontinued': route.options.discontinued } : {}), diff --git a/packages/kbn-router-to-openapispec/src/type.ts b/packages/kbn-router-to-openapispec/src/type.ts index 5c5f992a0de0f..f57e4d00ad7db 100644 --- a/packages/kbn-router-to-openapispec/src/type.ts +++ b/packages/kbn-router-to-openapispec/src/type.ts @@ -7,6 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ +import type { Router } from '@kbn/core-http-router-server-internal'; import type { OpenAPIV3 } from '../openapi-types'; export type { OpenAPIV3 } from '../openapi-types'; export interface KnownParameters { @@ -39,3 +40,5 @@ export type CustomOperationObject = OpenAPIV3.OperationObject<{ // Custom OpenAPI from ES API spec based on @availability 'x-state'?: 'Technical Preview' | 'Beta'; }>; + +export type InternalRouterRoute = ReturnType[0]; diff --git a/packages/kbn-router-to-openapispec/tsconfig.json b/packages/kbn-router-to-openapispec/tsconfig.json index d82ca0bf48910..3536a90a8256f 100644 --- a/packages/kbn-router-to-openapispec/tsconfig.json +++ b/packages/kbn-router-to-openapispec/tsconfig.json @@ -17,6 +17,6 @@ "@kbn/core-http-router-server-internal", "@kbn/core-http-server", "@kbn/config-schema", - "@kbn/zod" + "@kbn/zod", ] }