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

[console] support HEAD requests #10611

Merged
merged 4 commits into from
Mar 29, 2017
Merged
Show file tree
Hide file tree
Changes from 2 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
107 changes: 27 additions & 80 deletions src/core_plugins/console/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import Joi from 'joi';
import Boom from 'boom';
import apiServer from './api_server/server';
import { existsSync } from 'fs';
import { resolve, join, sep } from 'path';
import { has } from 'lodash';
import { ProxyConfigCollection } from './server/proxy_config_collection';
import { getElasticsearchProxyConfig } from './server/elasticsearch_proxy_config';

import {
ProxyConfigCollection,
getElasticsearchProxyConfig,
createProxyRoute
} from './server';

export default function (kibana) {
const modules = resolve(__dirname, 'public/webpackShims/');
Expand Down Expand Up @@ -66,91 +69,35 @@ export default function (kibana) {
},

init: function (server, options) {
const filters = options.proxyFilter.map(str => new RegExp(str));

if (options.ssl && options.ssl.verify) {
throw new Error('sense.ssl.verify is no longer supported.');
}

const config = server.config();
const { filterHeaders } = server.plugins.elasticsearch;
const proxyConfigCollection = new ProxyConfigCollection(options.proxyConfig);
const proxyRouteConfig = {
validate: {
query: Joi.object().keys({
uri: Joi.string()
}).unknown(true),
},

pre: [
function filterUri(req, reply) {
const { uri } = req.query;

if (!filters.some(re => re.test(uri))) {
const err = Boom.forbidden();
err.output.payload = `Error connecting to '${uri}':\n\nUnable to send requests to that url.`;
err.output.headers['content-type'] = 'text/plain';
reply(err);
} else {
reply();
}
}
],

handler(req, reply) {
let baseUri = server.config().get('elasticsearch.url');
let { uri:path } = req.query;

baseUri = baseUri.replace(/\/+$/, '');
path = path.replace(/^\/+/, '');
const uri = baseUri + '/' + path;

const requestHeadersWhitelist = server.config().get('elasticsearch.requestHeadersWhitelist');
const filterHeaders = server.plugins.elasticsearch.filterHeaders;

let additionalConfig;
if (server.config().get('console.proxyConfig')) {
additionalConfig = proxyConfigCollection.configForUri(uri);
} else {
additionalConfig = getElasticsearchProxyConfig(server);
}

reply.proxy({
mapUri: function (request, done) {
done(null, uri, filterHeaders(request.headers, requestHeadersWhitelist));
},
xforward: true,
onResponse(err, res, request, reply) {
if (err != null) {
reply(`Error connecting to '${uri}':\n\n${err.message}`).type('text/plain').statusCode = 502;
} else {
reply(null, res);
}
},

...additionalConfig
});
}
};

server.route({
path: '/api/console/proxy',
method: '*',
config: {
...proxyRouteConfig,

payload: {
output: 'stream',
parse: false
const proxyPathFilters = options.proxyFilter.map(str => new RegExp(str));

server.route(createProxyRoute({
baseUrl: config.get('elasticsearch.url'),
pathFilters: proxyPathFilters,
getConfigForReq(req, uri) {
const whitelist = config.get('elasticsearch.requestHeadersWhitelist');
const headers = filterHeaders(req.headers, whitelist);

if (config.has('console.proxyConfig')) {
return {
...proxyConfigCollection.configForUri(uri),
headers,
};
}
}
});

server.route({
path: '/api/console/proxy',
method: 'GET',
config: {
...proxyRouteConfig
return {
...getElasticsearchProxyConfig(server),
headers,
};
}
});
}));

server.route({
path: '/api/console/api_server',
Expand Down
12 changes: 7 additions & 5 deletions src/core_plugins/console/public/src/es.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
let $ = require('jquery');
import { stringify as formatQueryString } from 'querystring'

import $ from 'jquery';

let esVersion = [];

Expand Down Expand Up @@ -34,13 +36,13 @@ module.exports.send = function (method, path, data) {
}

var options = {
url: '../api/console/proxy?uri=' + encodeURIComponent(path),
data: method == "GET" ? null : data,
url: '../api/console/proxy?' + formatQueryString({ path, method }),
data,
contentType,
cache: false,
crossDomain: true,
type: method,
dataType: "text", // disable automatic guessing
type: 'POST',
dataType: 'text', // disable automatic guessing
};


Expand Down
85 changes: 85 additions & 0 deletions src/core_plugins/console/server/__tests__/proxy_route/body.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { createServer, ClientRequest, Agent } from 'http';
import { Readable } from 'stream';
import { stringify as formatQueryString } from 'querystring';

import sinon from 'sinon';
import Wreck from 'wreck';
import expect from 'expect.js';
import { Server } from 'hapi';

import { createProxyRoute } from '../../';

import { createWreckResponseStub } from './stubs';

describe('Console Proxy Route', () => {
const sandbox = sinon.sandbox.create();
const teardowns = [];
let request;

beforeEach(() => {
teardowns.push(() => sandbox.restore());
request = async (method, path, response) => {
sandbox.stub(Wreck, 'request', createWreckResponseStub(response));

const server = new Server();

server.connection({ port: 0 });
server.route(createProxyRoute({
baseUrl: 'http://localhost:9200'
}));

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

const params = [];
if (path != null) params.push(`path=${path}`);
if (method != null) params.push(`method=${method}`);
return await server.inject({
method: 'POST',
url: `/api/console/proxy${params.length ? `?${params.join('&')}` : ''}`,
});
};
});

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

describe('response body', () => {
context('GET request', () => {
it('returns the exact body', async () => {
const { payload } = await request('GET', '/', 'foobar');
expect(payload).to.be('foobar');
});
});
context('POST request', () => {
it('returns the exact body', async () => {
const { payload } = await request('POST', '/', 'foobar');
expect(payload).to.be('foobar');
});
});
context('PUT request', () => {
it('returns the exact body', async () => {
const { payload } = await request('PUT', '/', 'foobar');
expect(payload).to.be('foobar');
});
});
context('DELETE request', () => {
it('returns the exact body', async () => {
const { payload } = await request('DELETE', '/', 'foobar');
expect(payload).to.be('foobar');
});
});
context('HEAD request', () => {
it('returns the status code and text', async () => {
const { payload } = await request('HEAD', '/');
expect(payload).to.be('200 - OK');
});
context('mixed casing', () => {
it('returns the status code and text', async () => {
const { payload } = await request('HeAd', '/');
expect(payload).to.be('200 - OK');
});
});
});
});
});
69 changes: 69 additions & 0 deletions src/core_plugins/console/server/__tests__/proxy_route/headers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { createServer, ClientRequest, Agent, request } from 'http';
import { Readable } from 'stream';
import { stringify as formatQueryString } from 'querystring';

import sinon from 'sinon';
import Wreck from 'wreck';
import expect from 'expect.js';
import { Server } from 'hapi';

import { createProxyRoute } from '../../';

import { createWreckResponseStub } from './stubs';

describe('Console Proxy Route', () => {
const sandbox = sinon.sandbox.create();
const teardowns = [];
let setup;

beforeEach(() => {
teardowns.push(() => sandbox.restore());

sandbox.stub(Wreck, 'request', createWreckResponseStub());

setup = (remoteAddress) => {
const server = new Server();

server.connection({ port: 0 });
server.route(createProxyRoute({
baseUrl: 'http://localhost:9200'
}));

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

return { server };
};
});

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

describe('headers', function () {
this.timeout(Infinity);

it('forwards the remote header info', async () => {
const { server } = setup();
await server.start();

const resp = await new Promise(resolve => {
request({
protocol: server.info.protocol + ':',
host: server.info.address,
port: server.info.port,
method: 'POST',
path: '/api/console/proxy?method=GET&path=/'
}, resolve).end();
});

resp.destroy();

sinon.assert.calledOnce(Wreck.request);
const { headers } = Wreck.request.getCall(0).args[2];
expect(headers).to.have.property('x-forwarded-for').and.not.be('');
expect(headers).to.have.property('x-forwarded-port').and.not.be('');
expect(headers).to.have.property('x-forwarded-proto').and.not.be('');
expect(headers).to.have.property('x-forwarded-host').and.not.be('');
});
});
});
Loading