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] Make HTTP resource routes respond without the versioned header #195940

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 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 @@ -32,6 +32,7 @@ import type {
HttpResourcesServiceToolkit,
} from '@kbn/core-http-resources-server';

import type { Router } from '@kbn/core-http-router-server-internal';
import type { InternalHttpResourcesSetup } from './types';

/**
Expand Down Expand Up @@ -84,7 +85,7 @@ export class HttpResourcesService implements CoreService<InternalHttpResourcesSe
route: RouteConfig<P, Q, B, 'get'>,
handler: HttpResourcesRequestHandler<P, Q, B, Context>
) => {
return router.get<P, Q, B>(
return (router as unknown as Router<RequestHandlerContext>).get<P, Q, B>(
Copy link
Contributor Author

@jloleysens jloleysens Oct 11, 2024

Choose a reason for hiding this comment

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

This was the simplest way to get this working end-to-end without a larger refactor to pass Router in directly.

IMO it's OK for the internal http resources to have privileged knowledge of Router types (i.e. the internal options). Just didn't want to make this too big of a refactor for now.

Happy to take other ideas.

{
...route,
options: {
Expand All @@ -98,7 +99,8 @@ export class HttpResourcesService implements CoreService<InternalHttpResourcesSe
...response,
...this.createResponseToolkit(deps, context, request, response),
});
}
},
{ isVersioned: false, isHTTPResource: true }
);
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,40 +134,80 @@ describe('Router', () => {
}
);

it('adds versioned header v2023-10-31 to public, unversioned routes', async () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
router.post(
{
path: '/public',
options: {
access: 'public',
describe('elastic-api-version header', () => {
it('adds the header to public, unversioned routes', async () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
router.post(
{
path: '/public',
options: {
access: 'public',
},
validate: false,
},
validate: false,
},
(context, req, res) => res.ok({ headers: { AAAA: 'test' } }) // with some fake headers
);
router.post(
{
path: '/internal',
options: {
access: 'internal',
(context, req, res) => res.ok({ headers: { AAAA: 'test' } }) // with some fake headers
);
router.post(
{
path: '/internal',
options: {
access: 'internal',
},
validate: false,
},
validate: false,
},
(context, req, res) => res.ok()
);
const [{ handler: publicHandler }, { handler: internalHandler }] = router.getRoutes();
(context, req, res) => res.ok()
);
const [{ handler: publicHandler }, { handler: internalHandler }] = router.getRoutes();

await publicHandler(createRequestMock(), mockResponseToolkit);
expect(mockResponse.header).toHaveBeenCalledTimes(2);
const [first, second] = mockResponse.header.mock.calls
.concat()
.sort(([k1], [k2]) => k1.localeCompare(k2));
expect(first).toEqual(['AAAA', 'test']);
expect(second).toEqual(['elastic-api-version', '2023-10-31']);
await publicHandler(createRequestMock(), mockResponseToolkit);
expect(mockResponse.header).toHaveBeenCalledTimes(2);
const [first, second] = mockResponse.header.mock.calls
.concat()
.sort(([k1], [k2]) => k1.localeCompare(k2));
expect(first).toEqual(['AAAA', 'test']);
expect(second).toEqual(['elastic-api-version', '2023-10-31']);

await internalHandler(createRequestMock(), mockResponseToolkit);
expect(mockResponse.header).toHaveBeenCalledTimes(2); // no additional calls
await internalHandler(createRequestMock(), mockResponseToolkit);
expect(mockResponse.header).toHaveBeenCalledTimes(2); // no additional calls
});

it('does not add the header to public http resource routes', async () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
router.post(
{
path: '/public',
options: {
access: 'public',
},
validate: false,
},
(context, req, res) => res.ok({ headers: { AAAA: 'test' } }), // with some fake headers
{ isVersioned: false, isHTTPResource: false }
);
router.post(
{
path: '/public-resource',
options: {
access: 'internal',
},
validate: false,
},
(context, req, res) => res.ok(),
{ isVersioned: false, isHTTPResource: true }
);
const [{ handler: publicHandler }, { handler: resourceHandler }] = router.getRoutes();

await publicHandler(createRequestMock(), mockResponseToolkit);
expect(mockResponse.header).toHaveBeenCalledTimes(2);
const [first, second] = mockResponse.header.mock.calls
.concat()
.sort(([k1], [k2]) => k1.localeCompare(k2));
expect(first).toEqual(['AAAA', 'test']);
expect(second).toEqual(['elastic-api-version', '2023-10-31']);

await resourceHandler(createRequestMock(), mockResponseToolkit);
expect(mockResponse.header).toHaveBeenCalledTimes(2); // no additional calls
});
});

it('constructs lazily provided validations once (idempotency)', async () => {
Expand Down Expand Up @@ -335,4 +375,16 @@ describe('Router', () => {
expect(route.options).toEqual({});
});
});

describe('Internal options', () => {
it('does not allow registering a router as versioned and an HTTP resource', () => {
const router = new Router('', logger, enhanceWithContext, routerOptions);
expect(() => {
router.get({ path: '/', validate: false }, async (ctx, req, res) => res.notFound(), {
isVersioned: true,
isHTTPResource: true,
});
}).toThrowError(/not supported/);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,15 @@ export interface RouterOptions {
}

/** @internal */
export interface InternalRegistrarOptions {
interface InternalRegistrarOptions {
isVersioned: boolean;
/**
* @default false
* @remark cannot be set to `true` if `isVersioned` is true
*/
isHTTPResource?: boolean;
}

/** @internal */
export type VersionedRouteConfig<P, Q, B, M extends RouteMethod> = Omit<
RouteConfig<P, Q, B, M>,
Expand Down Expand Up @@ -201,19 +207,24 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
<P, Q, B>(
route: InternalRouteConfig<P, Q, B, Method>,
handler: RequestHandler<P, Q, B, Context, Method>,
{ isVersioned }: { isVersioned: boolean } = { isVersioned: false }
{ isVersioned, isHTTPResource }: InternalRegistrarOptions = { isVersioned: false }
) => {
if (isVersioned === true && isHTTPResource === true) {
throw new Error('A versioned route as an HTTP resource is not supported');
}
route = prepareRouteConfigValidation(route);
const routeSchemas = routeSchemasFromRouteConfig(route, method);
const isPublicUnversionedRoute = route.options?.access === 'public' && !isVersioned;
// We do not consider HTTP resource routes as APIs
const isPublicUnversionedApi =
!isHTTPResource && route.options?.access === 'public' && !isVersioned;

this.routes.push({
handler: async (req, responseToolkit) =>
await this.handle({
routeSchemas,
request: req,
responseToolkit,
isPublicUnversionedRoute,
isPublicUnversionedApi,
handler: this.enhanceWithContext(handler),
}),
method,
Expand All @@ -223,7 +234,6 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
security: isVersioned
? route.security
: validRouteSecurity(route.security as DeepPartial<RouteSecurity>, route.options),
/** Below is added for introspection */
validationSchemas: route.validate,
isVersioned,
});
Expand Down Expand Up @@ -269,12 +279,12 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
routeSchemas,
request,
responseToolkit,
isPublicUnversionedRoute,
isPublicUnversionedApi,
handler,
}: {
request: Request;
responseToolkit: ResponseToolkit;
isPublicUnversionedRoute: boolean;
isPublicUnversionedApi: boolean;
handler: RequestHandlerEnhanced<
P,
Q,
Expand All @@ -296,7 +306,7 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo
} catch (error) {
this.logError('400 Bad Request', 400, { request, error });
const response = hapiResponseAdapter.toBadRequest(error.message);
if (isPublicUnversionedRoute) {
if (isPublicUnversionedApi) {
response.output.headers = {
...response.output.headers,
...getVersionHeader(ALLOWED_PUBLIC_VERSION),
Expand All @@ -307,7 +317,7 @@ export class Router<Context extends RequestHandlerContextBase = RequestHandlerCo

try {
const kibanaResponse = await handler(kibanaRequest, kibanaResponseFactory);
if (isPublicUnversionedRoute) {
if (isPublicUnversionedApi) {
injectVersionHeader(ALLOWED_PUBLIC_VERSION, kibanaResponse);
}
if (kibanaRequest.protocol === 'http2' && kibanaResponse.options.headers) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,5 +199,29 @@ function applyTestsWithDisableUnsafeEvalSetTo(disableUnsafeEval: boolean) {
expect(response.text).toBe('window.alert(42);');
});
});

it('responses do not contain the elastic-api-version header', async () => {
const { http, httpResources } = await root.setup();

const router = http.createRouter('');
const resources = httpResources.createRegistrar(router);
const htmlBody = `
<!DOCTYPE html>
<html>
<body>
<p>HTML body</p>
</body>
</html>
`;
resources.register({ path: '/render-html', validate: false }, (context, req, res) =>
res.renderHtml({ body: htmlBody })
);

await root.start();
const response = await request.get(root, '/render-html').expect(200);

expect(response.text).toBe(htmlBody);
expect(response.header).not.toMatchObject({ 'elastic-api-version': expect.any(String) });
jloleysens marked this conversation as resolved.
Show resolved Hide resolved
});
});
}