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

[HTTP/OAS] Ability to exclude routes from introspection #192675

Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,48 @@ describe('Router', () => {
});
});

it('excludes "hidden" routes', () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
const validation = schema.object({ foo: schema.string() });
router.post(
{
path: '/visible',
validate: { body: validation, query: validation, params: validation },
},
(context, req, res) => res.ok()
);
router.post(
{
path: '/visible-versioned',
validate: { body: validation, query: validation, params: validation },
},
(context, req, res) => res.ok(),
{ isVersioned: true }
);
router.get(
{
path: '/hidden',
options: { hiddenFromIntrospection: true },
validate: { body: validation, query: validation, params: validation },
},
(context, req, res) => res.ok()
);
router.get(
{
path: '/hidden-versioned',
options: { hiddenFromIntrospection: true },
validate: { body: validation, query: validation, params: validation },
},
(context, req, res) => res.ok(),
{ isVersioned: true }
);
const routes = router.getRoutes();
expect(routes).toHaveLength(2);
const [route1, route2] = routes;
expect(route1).toMatchObject({ method: 'post', path: '/visible' });
expect(route2).toMatchObject({ method: 'post', path: '/visible-versioned' });
});

it('can exclude versioned routes', () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
const validation = schema.object({ foo: schema.string() });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,10 +234,11 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
}

public getRoutes({ excludeVersionedRoutes }: InternalGetRoutesOptions = {}) {
const routes = this.routes.filter((route) => route.options.hiddenFromIntrospection !== true);
if (excludeVersionedRoutes) {
return this.routes.filter((route) => !route.isVersioned);
return routes.filter((route) => !route.isVersioned);
}
return [...this.routes];
return routes;
}

public handleLegacyErrors = wrapErrors;
Expand Down
76 changes: 43 additions & 33 deletions packages/core/http/core-http-server-internal/src/http_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@

import { Observable, Subscription, combineLatest, firstValueFrom, of, mergeMap } from 'rxjs';
import { map } from 'rxjs';
import { schema, TypeOf } from '@kbn/config-schema';

import { pick, Semaphore } from '@kbn/std';
import { generateOpenApiDocument } from '@kbn/router-to-openapispec';
import {
generateOpenApiDocument,
type GenerateOpenApiDocumentOptionsFilters,
} from '@kbn/router-to-openapispec';
import { Logger } from '@kbn/logging';
import { Env } from '@kbn/config';
import type { CoreContext, CoreService } from '@kbn/core-base-server-internal';
Expand Down Expand Up @@ -254,49 +258,55 @@ export class HttpService
const baseUrl =
basePath.publicBaseUrl ?? `http://localhost:${config.port}${basePath.serverBasePath}`;

const stringOrStringArraySchema = schema.oneOf([
schema.string(),
schema.arrayOf(schema.string()),
]);
const querySchema = schema.object({
access: schema.maybe(schema.oneOf([schema.literal('public'), schema.literal('internal')])),
excludePathsMatching: schema.maybe(stringOrStringArraySchema),
pathStartsWith: schema.maybe(stringOrStringArraySchema),
pluginId: schema.maybe(schema.string()),
version: schema.maybe(schema.string()),
});

server.route({
path: '/api/oas',
method: 'GET',
handler: async (req, h) => {
const version = req.query?.version;

let pathStartsWith: undefined | string[];
if (typeof req.query?.pathStartsWith === 'string') {
pathStartsWith = [req.query.pathStartsWith];
} else {
pathStartsWith = req.query?.pathStartsWith;
}

let excludePathsMatching: undefined | string[];
if (typeof req.query?.excludePathsMatching === 'string') {
excludePathsMatching = [req.query.excludePathsMatching];
} else {
excludePathsMatching = req.query?.excludePathsMatching;
let filters: GenerateOpenApiDocumentOptionsFilters;
let query: TypeOf<typeof querySchema>;
try {
query = querySchema.validate(req.query);
Copy link
Contributor Author

@jloleysens jloleysens Oct 9, 2024

Choose a reason for hiding this comment

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

Refactor to using config-schema, just cleanup

filters = {
...query,
excludePathsMatching:
typeof query.excludePathsMatching === 'string'
? [query.excludePathsMatching]
: query.excludePathsMatching,
pathStartsWith:
typeof query.pathStartsWith === 'string'
? [query.pathStartsWith]
: query.pathStartsWith,
};
} catch (e) {
return h.response({ message: e.message }).code(400);
}

const pluginId = req.query?.pluginId;

const access = req.query?.access as 'public' | 'internal' | undefined;
if (access && !['public', 'internal'].some((a) => a === access)) {
return h
.response({
message: 'Invalid access query parameter. Must be one of "public" or "internal".',
})
.code(400);
}

return await firstValueFrom(
of(1).pipe(
HttpService.generateOasSemaphore.acquire(),
mergeMap(async () => {
try {
// Potentially quite expensive
const result = generateOpenApiDocument(this.httpServer.getRouters({ pluginId }), {
baseUrl,
title: 'Kibana HTTP APIs',
version: '0.0.0', // TODO get a better version here
filters: { pathStartsWith, excludePathsMatching, access, version },
});
const result = generateOpenApiDocument(
this.httpServer.getRouters({ pluginId: query.pluginId }),
{
baseUrl,
title: 'Kibana HTTP APIs',
version: '0.0.0', // TODO get a better version here
filters,
}
);
return h.response(result);
} catch (e) {
this.log.error(e);
Expand Down
14 changes: 13 additions & 1 deletion packages/core/http/core-http-server/src/router/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export interface RouteConfigOptions<Method extends RouteMethod> {
/**
* Defines intended request origin of the route:
* - public. The route is public, declared stable and intended for external access.
* In the future, may require an incomming request to contain a specified header.
* In the future, may require an incoming request to contain a specified header.
* - internal. The route is internal and intended for internal access only.
*
* Defaults to 'internal' If not declared,
Expand Down Expand Up @@ -284,6 +284,17 @@ export interface RouteConfigOptions<Method extends RouteMethod> {
*/
deprecated?: boolean;

/**
* Whether this route should be treated as "invisible" and excluded from router
* introspection. This primarily concerns outputs like OAS derived from router
* introspection.
*
* @default false
* @remarks Setting this to `true` will make settings related to introspection useless,
* for example "description".
*/
hiddenFromIntrospection?: boolean;

/**
* Release version or date that this route will be removed
* Use with `deprecated: true`
Expand All @@ -292,6 +303,7 @@ export interface RouteConfigOptions<Method extends RouteMethod> {
* @example 9.0.0
*/
discontinued?: string;

/**
* Defines the security requirements for a route, including authorization and authentication.
*
Expand Down
5 changes: 4 additions & 1 deletion packages/kbn-router-to-openapispec/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/

export { generateOpenApiDocument } from './src/generate_oas';
export {
generateOpenApiDocument,
type GenerateOpenApiDocumentOptionsFilters,
} from './src/generate_oas';
4 changes: 3 additions & 1 deletion src/core/server/integration_tests/http/oas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@ it('only accepts "public" or "internal" for "access" query param', async () => {
const server = await startService({ config: { server: { oas: { enabled: true } } } });
const result = await supertest(server.listener).get('/api/oas').query({ access: 'invalid' });
expect(result.body.message).toBe(
'Invalid access query parameter. Must be one of "public" or "internal".'
`[access]: types that failed validation:
- [access.0]: expected value to equal [public]
- [access.1]: expected value to equal [internal]`
);
expect(result.status).toBe(400);
});