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

Allow base path to be influenced by the current request #23367

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions docs/development/core/development-basepath.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,15 @@ $http.get(chrome.addBasePath('/api/plugin/things'));
[float]
==== Server side

Append `config.get('server.basePath')` to any absolute URL path.
Append `request.getBasePath()` to any absolute URL path.

["source","shell"]
-----------
const basePath = server.config().get('server.basePath');
server.route({
path: '/redirect',
handler(req, reply) {
reply.redirect(`${basePath}/otherLocation`);
handler(request, reply) {
reply.redirect(`${request.getBasePath()}/otherLocation`);
}
});
-----------
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`setupBasePathProvider getBasePath/setBasePath should not allow request.setBasePath to be called more than once 1`] = `"Request basePath was previously set. Setting multiple times is not supported."`;
7 changes: 5 additions & 2 deletions src/server/http/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import Boom from 'boom';
import Hapi from 'hapi';
import { setupVersionCheck } from './version_check';
import { registerHapiPlugins } from './register_hapi_plugins';
import { setupBasePathProvider } from './setup_base_path_provider';
import { setupXsrf } from './xsrf';

export default async function (kbnServer, server, config) {
Expand All @@ -32,6 +33,8 @@ export default async function (kbnServer, server, config) {

server.connection(kbnServer.core.serverOptions);

setupBasePathProvider(server, config);

registerHapiPlugins(server);

// provide a simple way to expose static directories
Expand Down Expand Up @@ -86,7 +89,7 @@ export default async function (kbnServer, server, config) {
path: '/',
method: 'GET',
handler(req, reply) {
const basePath = config.get('server.basePath');
const basePath = req.getBasePath();
const defaultRoute = config.get('server.defaultRoute');
reply.redirect(`${basePath}${defaultRoute}`);
}
Expand All @@ -100,7 +103,7 @@ export default async function (kbnServer, server, config) {
if (path === '/' || path.charAt(path.length - 1) !== '/') {
return reply(Boom.notFound());
}
const pathPrefix = config.get('server.basePath') ? `${config.get('server.basePath')}/` : '';
const pathPrefix = req.getBasePath() ? `${req.getBasePath()}/` : '';
return reply.redirect(format({
search: req.url.search,
pathname: pathPrefix + path.slice(0, -1),
Expand Down
38 changes: 38 additions & 0 deletions src/server/http/setup_base_path_provider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

export function setupBasePathProvider(server, config) {

server.decorate('request', 'setBasePath', function (basePath) {
const request = this;
if (request.app._basePath) {
throw new Error(`Request basePath was previously set. Setting multiple times is not supported.`);
}
request.app._basePath = basePath;
});

server.decorate('request', 'getBasePath', function () {
const request = this;

const serverBasePath = config.get('server.basePath');
const requestBasePath = request.app._basePath || '';

return `${serverBasePath}${requestBasePath}`;
});
}
134 changes: 134 additions & 0 deletions src/server/http/setup_base_path_provider.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Server } from 'hapi';
import { setupBasePathProvider } from './setup_base_path_provider';

describe('setupBasePathProvider', () => {
it('registers two request decorations', () => {
const configValues = {};

const server = {
decorate: jest.fn()
};

const config = {
get: jest.fn(() => configValues)
};

setupBasePathProvider(server, config);

expect(server.decorate).toHaveBeenCalledTimes(2);
expect(server.decorate).toHaveBeenCalledWith('request', 'getBasePath', expect.any(Function));
expect(server.decorate).toHaveBeenCalledWith('request', 'setBasePath', expect.any(Function));
});

describe('getBasePath/setBasePath', () => {

const defaultSetupFn = () => {
return;
};

let request;
const teardowns = [];

beforeEach(() => {
request = async (url, serverConfig = {}, setupFn = defaultSetupFn) => {
const server = new Server();
server.connection({ port: 0 });

server.route({
path: '/',
method: 'GET',
handler(req, reply) {
setupFn(req, reply);
return reply({ basePath: req.getBasePath() });
}
});

setupBasePathProvider(server, {
get: (key) => serverConfig[key]
});

teardowns.push(() => server.stop());

return server.inject({
method: 'GET',
url,
});
};
});

afterEach(async () => {
await Promise.all(teardowns.splice(0).map(fn => fn()));
});


it('should return an empty string when server.basePath is not set', async () => {
const response = await request('/', {
['server.basePath']: ''
});

const { statusCode, payload } = response;

expect(statusCode).toEqual(200);
expect(JSON.parse(payload)).toEqual({
basePath: ''
});
});

it('should return the server.basePath unmodified when request.setBasePath is not called', async () => {
const response = await request('/', {
['server.basePath']: '/path'
});

const { statusCode, payload } = response;

expect(statusCode).toEqual(200);
expect(JSON.parse(payload)).toEqual({
basePath: '/path'
});
});

it('should add the request basePath to the server.basePath', async () => {
const response = await request('/', {
['server.basePath']: '/path'
}, (req) => {
req.setBasePath('/request/base/path');
});

const { statusCode, payload } = response;

expect(statusCode).toEqual(200);
expect(JSON.parse(payload)).toEqual({
basePath: '/path/request/base/path'
});
});

it('should not allow request.setBasePath to be called more than once', async () => {
const response = request('/', {
['server.basePath']: '/path'
}, (req) => {
req.setBasePath('/request/base/path');
req.setBasePath('/request/base/path/again');
});

expect(response).rejects.toThrowErrorMatchingSnapshot();
});
});
});
5 changes: 3 additions & 2 deletions src/ui/public/chrome/api/__tests__/nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const basePath = '/someBasePath';

function init(customInternals = { basePath }) {
const chrome = {
addBasePath: (path) => path,
getBasePath: () => customInternals.basePath || '',
};
const internals = {
Expand All @@ -39,7 +40,7 @@ function init(customInternals = { basePath }) {

describe('chrome nav apis', function () {
describe('#getNavLinkById', () => {
it ('retrieves the correct nav link, given its ID', () => {
it('retrieves the correct nav link, given its ID', () => {
const appUrlStore = new StubBrowserStorage();
const nav = [
{ id: 'kibana:discover', title: 'Discover' }
Expand All @@ -52,7 +53,7 @@ describe('chrome nav apis', function () {
expect(navLink).to.eql(nav[0]);
});

it ('throws an error if the nav link with the given ID is not found', () => {
it('throws an error if the nav link with the given ID is not found', () => {
const appUrlStore = new StubBrowserStorage();
const nav = [
{ id: 'kibana:discover', title: 'Discover' }
Expand Down
4 changes: 2 additions & 2 deletions src/ui/public/chrome/api/nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ export function initChromeNavApi(chrome, internals) {
};

internals.nav.forEach(link => {
link.url = relativeToAbsolute(link.url);
link.subUrlBase = relativeToAbsolute(link.subUrlBase);
link.url = relativeToAbsolute(chrome.addBasePath(link.url));
link.subUrlBase = relativeToAbsolute(chrome.addBasePath(link.subUrlBase));
});

// simulate a possible change in url to initialize the
Expand Down
2 changes: 1 addition & 1 deletion src/ui/ui_apps/ui_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class UiApp {
// unless an app is hidden it gets a navlink, but we only respond to `getNavLink()`
// if the app is also listed. This means that all apps in the kibanaPayload will
// have a navLink property since that list includes all normally accessible apps
this._navLink = new UiNavLink(kbnServer.config.get('server.basePath'), {
this._navLink = new UiNavLink({
id: this._id,
title: this._title,
order: this._order,
Expand Down
Loading