Skip to content

Commit

Permalink
Implemented own server for webhook simulator
Browse files Browse the repository at this point in the history
  • Loading branch information
YulNaumenko committed Aug 6, 2020
1 parent 9a1f3a5 commit 1b84ffe
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
* you may not use this file except in compliance with the Elastic License.
*/

import http from 'http';
import { FtrProviderContext } from '../../../../common/ftr_provider_context';
import {
getExternalServiceSimulatorPath,
ExternalServiceSimulator,
getWebhookServer,
} from '../../../../common/fixtures/plugins/actions_simulators/server/plugin';

// eslint-disable-next-line import/no-default-export
Expand All @@ -16,13 +18,13 @@ export default function webhookTest({ getService }: FtrProviderContext) {
const kibanaServer = getService('kibanaServer');

describe('webhook action', () => {
let webhookSimulatorURL: string = '<could not determine kibana url>';

let webhookSimulatorURL: string = '';
let webhookServer: http.Server;
// need to wait for kibanaServer to settle ...
before(() => {
webhookSimulatorURL = kibanaServer.resolveUrl(
getExternalServiceSimulatorPath(ExternalServiceSimulator.WEBHOOK)
);
before(async () => {
webhookServer = await getWebhookServer();
webhookServer.listen(9001);
webhookSimulatorURL = 'http://localhost:9001';
});

it('should return 403 when creating a webhook action', async () => {
Expand All @@ -47,5 +49,9 @@ export default function webhookTest({ getService }: FtrProviderContext) {
'Action type .webhook is disabled because your basic license does not support it. Please upgrade your license.',
});
});

after(() => {
webhookServer.close();
});
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ export function getAllExternalServiceSimulatorPaths(): string[] {
return allPaths;
}

export async function getWebhookServer(): http.Server {
return await initWebhook();
}

interface FixtureSetupDeps {
actions: ActionsPluginSetupContract;
features: FeaturesPluginSetup;
Expand All @@ -54,7 +58,7 @@ interface FixtureStartDeps {
export class FixturePlugin implements Plugin<void, void, FixtureSetupDeps, FixtureStartDeps> {
private webhookHttpServer: http.Server | undefined = undefined;

public async setup(core: CoreSetup<FixtureStartDeps>, { features, actions }: FixtureSetupDeps) {
public setup(core: CoreSetup<FixtureStartDeps>, { features, actions }: FixtureSetupDeps) {
// this action is specifically NOT enabled in ../../config.ts
const notEnabledActionType: ActionType = {
id: 'test.not-enabled',
Expand Down Expand Up @@ -98,17 +102,8 @@ export class FixturePlugin implements Plugin<void, void, FixtureSetupDeps, Fixtu
initJira(router, getExternalServiceSimulatorPath(ExternalServiceSimulator.JIRA));
initResilient(router, getExternalServiceSimulatorPath(ExternalServiceSimulator.RESILIENT));
initSlack(router, getExternalServiceSimulatorPath(ExternalServiceSimulator.SLACK));
this.webhookHttpServer = await initWebhook();
}

public start() {
if (this.webhookHttpServer) {
this.webhookHttpServer.listen(8080);
}
}
public stop() {
if (this.webhookHttpServer) {
this.webhookHttpServer.close();
}
}
public start() {}
public stop() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,13 @@ export async function initPlugin() {
getOrElse(constant({ username: '', password: '' }))
);

if (request.method === 'POST' || 'PUT') {
const data: unknown[] = [];
if (request.method === 'POST' || request.method === 'PUT') {
let data = '';
request.on('data', (chunk) => {
data.push(chunk);
data += chunk;
});
request.on('end', () => {
const body = JSON.parse(data.toString());
switch (body) {
switch (data) {
case 'success':
response.statusCode = 200;
response.end('OK');
Expand Down Expand Up @@ -73,7 +72,7 @@ function validateAuthentication(credentials: any, res: any) {

function validateRequestUsesMethod(requestMethod: string, method: string, res: any) {
try {
expect(requestMethod).to.eql(method);
expect(requestMethod.toLowerCase()).to.eql(method);
res.statusCode = 200;
res.end('OK');
} catch (ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
* you may not use this file except in compliance with the Elastic License.
*/

import http from 'http';
import expect from '@kbn/expect';
import { URL, format as formatUrl } from 'url';
import { FtrProviderContext } from '../../../../common/ftr_provider_context';
import {
getExternalServiceSimulatorPath,
ExternalServiceSimulator,
getWebhookServer,
} from '../../../../common/fixtures/plugins/actions_simulators/server/plugin';

const defaultValues: Record<string, any> = {
Expand All @@ -30,11 +32,13 @@ export default function webhookTest({ getService }: FtrProviderContext) {
const kibanaServer = getService('kibanaServer');

async function createWebhookAction(
urlWithCreds: string,
config: Record<string, string | Record<string, string>> = {}
webhookSimulatorURL: string,
config: Record<string, string | Record<string, string>> = {},
kibanaUrlWithCreds: string
): Promise<string> {
const { url: fullUrl, user, password } = extractCredentialsFromUrl(urlWithCreds);
const url = config.url && typeof config.url === 'object' ? parsePort(config.url) : fullUrl;
const { user, password } = extractCredentialsFromUrl(kibanaUrlWithCreds);
const url =
config.url && typeof config.url === 'object' ? parsePort(config.url) : webhookSimulatorURL;
const composedConfig = {
headers: {
'Content-Type': 'text/plain',
Expand All @@ -61,11 +65,18 @@ export default function webhookTest({ getService }: FtrProviderContext) {
}

describe('webhook action', () => {
let webhookSimulatorURL: string = '<could not determine kibana url>';

let webhookSimulatorURL: string = '';
let webhookServer: http.Server;
let kibanaURL: string = '<could not determine kibana url>';
// need to wait for kibanaServer to settle ...
before(() => {
webhookSimulatorURL = 'http://localhost:8080';
before(async () => {
webhookServer = await getWebhookServer();
webhookServer.listen(9002);
webhookSimulatorURL = 'http://localhost:9002';

kibanaURL = kibanaServer.resolveUrl(
getExternalServiceSimulatorPath(ExternalServiceSimulator.WEBHOOK)
);
});

it('should return 200 when creating a webhook action successfully', async () => {
Expand Down Expand Up @@ -115,7 +126,7 @@ export default function webhookTest({ getService }: FtrProviderContext) {
});

it('should send authentication to the webhook target', async () => {
const webhookActionId = await createWebhookAction(webhookSimulatorURL);
const webhookActionId = await createWebhookAction(webhookSimulatorURL, {}, kibanaURL);
const { body: result } = await supertest
.post(`/api/actions/action/${webhookActionId}/_execute`)
.set('kbn-xsrf', 'test')
Expand All @@ -130,7 +141,11 @@ export default function webhookTest({ getService }: FtrProviderContext) {
});

it('should support the POST method against webhook target', async () => {
const webhookActionId = await createWebhookAction(webhookSimulatorURL, { method: 'post' });
const webhookActionId = await createWebhookAction(
webhookSimulatorURL,
{ method: 'post' },
kibanaURL
);
const { body: result } = await supertest
.post(`/api/actions/action/${webhookActionId}/_execute`)
.set('kbn-xsrf', 'test')
Expand All @@ -145,7 +160,11 @@ export default function webhookTest({ getService }: FtrProviderContext) {
});

it('should support the PUT method against webhook target', async () => {
const webhookActionId = await createWebhookAction(webhookSimulatorURL, { method: 'put' });
const webhookActionId = await createWebhookAction(
webhookSimulatorURL,
{ method: 'put' },
kibanaURL
);
const { body: result } = await supertest
.post(`/api/actions/action/${webhookActionId}/_execute`)
.set('kbn-xsrf', 'test')
Expand Down Expand Up @@ -181,7 +200,11 @@ export default function webhookTest({ getService }: FtrProviderContext) {
});

it('should handle unreachable webhook targets', async () => {
const webhookActionId = await createWebhookAction('http://some.non.existent.com/endpoint');
const webhookActionId = await createWebhookAction(
'http://some.non.existent.com/endpoint',
{},
kibanaURL
);
const { body: result } = await supertest
.post(`/api/actions/action/${webhookActionId}/_execute`)
.set('kbn-xsrf', 'test')
Expand All @@ -197,7 +220,7 @@ export default function webhookTest({ getService }: FtrProviderContext) {
});

it('should handle failing webhook targets', async () => {
const webhookActionId = await createWebhookAction(webhookSimulatorURL);
const webhookActionId = await createWebhookAction(webhookSimulatorURL, {}, kibanaURL);
const { body: result } = await supertest
.post(`/api/actions/action/${webhookActionId}/_execute`)
.set('kbn-xsrf', 'test')
Expand All @@ -212,6 +235,10 @@ export default function webhookTest({ getService }: FtrProviderContext) {
expect(result.message).to.match(/error calling webhook, retry later/);
expect(result.serviceMessage).to.eql('[500] Internal Server Error');
});

after(() => {
webhookServer.close();
});
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,22 @@
* you may not use this file except in compliance with the Elastic License.
*/

import http from 'http';
import expect from '@kbn/expect';
import { URL, format as formatUrl } from 'url';
import { FtrProviderContext } from '../../../../common/ftr_provider_context';
import {
getExternalServiceSimulatorPath,
ExternalServiceSimulator,
} from '../../../../common/fixtures/plugins/actions_simulators/server/plugin';
import { getWebhookServer } from '../../../../common/fixtures/plugins/actions_simulators/server/plugin';

// eslint-disable-next-line import/no-default-export
export default function webhookTest({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
const kibanaServer = getService('kibanaServer');

async function createWebhookAction(
urlWithCreds: string,
webhookSimulatorURL: string,
config: Record<string, string | Record<string, string>> = {}
): Promise<string> {
const url = formatUrl(new URL(urlWithCreds), { auth: false });
const url = formatUrl(new URL(webhookSimulatorURL), { auth: false });
const composedConfig = {
headers: {
'Content-Type': 'text/plain',
Expand All @@ -45,13 +43,13 @@ export default function webhookTest({ getService }: FtrProviderContext) {
}

describe('webhook action', () => {
let webhookSimulatorURL: string = '<could not determine kibana url>';

let webhookSimulatorURL: string = '';
let webhookServer: http.Server;
// need to wait for kibanaServer to settle ...
before(() => {
webhookSimulatorURL = kibanaServer.resolveUrl(
getExternalServiceSimulatorPath(ExternalServiceSimulator.WEBHOOK)
);
before(async () => {
webhookServer = await getWebhookServer();
webhookServer.listen(9003);
webhookSimulatorURL = 'http://localhost:9003';
});

it('webhook can be executed without username and password', async () => {
Expand All @@ -68,5 +66,9 @@ export default function webhookTest({ getService }: FtrProviderContext) {

expect(result.status).to.eql('ok');
});

after(() => {
webhookServer.close();
});
});
}

0 comments on commit 1b84ffe

Please sign in to comment.