Skip to content

Commit

Permalink
Pre work for Task Manager: fixing types and minor stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
tsullivan committed Sep 2, 2020
1 parent 46689b3 commit d90df7a
Show file tree
Hide file tree
Showing 76 changed files with 910 additions and 872 deletions.
2 changes: 1 addition & 1 deletion x-pack/plugins/reporting/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
export { ReportingConfigType } from '../server/config';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
export { LayoutInstance } from '../server/lib/layouts';
export { LayoutParams } from '../server/lib/layouts';

export type JobId = string;
export type JobStatus =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import React from 'react';
import { IUiSettingsClient, ToastsSetup } from 'src/core/public';
import { ShareContext } from '../../../../../src/plugins/share/public';
import { LicensingPluginSetup } from '../../../licensing/public';
import { LayoutInstance } from '../../common/types';
import { LayoutParams } from '../../common/types';
import { JobParamsPNG } from '../../server/export_types/png/types';
import { JobParamsPDF } from '../../server/export_types/printable_pdf/types';
import { ScreenCapturePanelContent } from '../components/screen_capture_panel_content';
Expand Down Expand Up @@ -80,7 +80,7 @@ export const reportingPDFPNGProvider = ({
objectType,
browserTimezone,
relativeUrls: [relativeUrl], // multi URL for PDF
layout: sharingData.layout as LayoutInstance,
layout: sharingData.layout as LayoutParams,
title: sharingData.title as string,
};
};
Expand All @@ -96,7 +96,7 @@ export const reportingPDFPNGProvider = ({
objectType,
browserTimezone,
relativeUrl, // single URL for PNG
layout: sharingData.layout as LayoutInstance,
layout: sharingData.layout as LayoutParams,
title: sharingData.title as string,
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import { parse as parseUrl } from 'url';
import { getDisallowedOutgoingUrlError } from '../';
import { LevelLogger } from '../../../lib';
import { ViewZoomWidthHeight } from '../../../lib/layouts/layout';
import { ConditionalHeaders, ElementPosition } from '../../../types';
import { ElementPosition } from '../../../lib/screenshots';
import { ConditionalHeaders } from '../../../types';
import { allowRequest, NetworkPolicy } from '../../network_policy';

export interface ChromiumDriverOptions {
Expand Down
7 changes: 3 additions & 4 deletions x-pack/plugins/reporting/server/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ import {
} from 'src/core/server';
import { LicensingPluginSetup } from '../../licensing/server';
import { SecurityPluginSetup } from '../../security/server';
import { ScreenshotsObservableFn } from '../server/types';
import { ReportingConfig } from './';
import { HeadlessChromiumDriverFactory } from './browsers/chromium/driver_factory';
import { screenshotsObservableFactory } from './lib/screenshots';
import { checkLicense, getExportTypesRegistry } from './lib';
import { ESQueueInstance } from './lib/create_queue';
import { screenshotsObservableFactory, ScreenshotsObservableFn } from './lib/screenshots';
import { ReportingStore } from './lib/store';

export interface ReportingInternalSetup {
Expand All @@ -42,11 +41,11 @@ export interface ReportingInternalStart {
}

export class ReportingCore {
private exportTypesRegistry = getExportTypesRegistry();
private pluginSetupDeps?: ReportingInternalSetup;
private pluginStartDeps?: ReportingInternalStart;
private readonly pluginSetup$ = new Rx.ReplaySubject<boolean>(); // observe async background setupDeps and config each are done
private readonly pluginStart$ = new Rx.ReplaySubject<ReportingInternalStart>(); // observe async background startDeps
private exportTypesRegistry = getExportTypesRegistry();
private config?: ReportingConfig;

constructor() {}
Expand All @@ -62,7 +61,7 @@ export class ReportingCore {
/*
* Register startDeps
*/
public pluginStart(startDeps: ReportingInternalStart) {
public async pluginStart(startDeps: ReportingInternalStart) {
this.pluginStart$.next(startDeps); // trigger the observer
this.pluginStartDeps = startDeps; // cache
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { cryptoFactory, LevelLogger } from '../../lib';
import { cryptoFactory } from '../../lib';
import { createMockLevelLogger } from '../../test_helpers/create_mock_levellogger';
import { decryptJobHeaders } from './';

const encryptHeaders = async (encryptionKey: string, headers: Record<string, string>) => {
Expand All @@ -13,17 +14,13 @@ const encryptHeaders = async (encryptionKey: string, headers: Record<string, str
};

describe('headers', () => {
const encryptionKey = 'abcsecretsauce';
const logger = createMockLevelLogger();

test(`fails if it can't decrypt headers`, async () => {
const getDecryptedHeaders = () =>
decryptJobHeaders({
encryptionKey: 'abcsecretsauce',
job: {
headers: 'Q53+9A+zf+Xe+ceR/uB/aR/Sw/8e+M+qR+WiG+8z+EY+mo+HiU/zQL+Xn',
},
logger: ({
error: jest.fn(),
} as unknown) as LevelLogger,
});
const headers = 'Q53+9A+zf+Xe+ceR/uB/aR/Sw/8e+M+qR+WiG+8z+EY+mo+HiU/zQL+Xn';

const getDecryptedHeaders = () => decryptJobHeaders(encryptionKey, headers, logger);
await expect(getDecryptedHeaders()).rejects.toMatchInlineSnapshot(
`[Error: Failed to decrypt report job data. Please ensure that xpack.reporting.encryptionKey is set and re-generate this report. Error: Invalid IV length]`
);
Expand All @@ -36,15 +33,7 @@ describe('headers', () => {
};

const encryptedHeaders = await encryptHeaders('abcsecretsauce', headers);
const decryptedHeaders = await decryptJobHeaders({
encryptionKey: 'abcsecretsauce',
job: {
title: 'cool-job-bro',
type: 'csv',
headers: encryptedHeaders,
},
logger: {} as LevelLogger,
});
const decryptedHeaders = await decryptJobHeaders(encryptionKey, encryptedHeaders, logger);
expect(decryptedHeaders).toEqual(headers);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,22 @@
import { i18n } from '@kbn/i18n';
import { cryptoFactory, LevelLogger } from '../../lib';

interface HasEncryptedHeaders {
headers?: string;
}

// TODO merge functionality with CSV execute job
export const decryptJobHeaders = async <
JobParamsType,
ScheduledTaskParamsType extends HasEncryptedHeaders
>({
encryptionKey,
job,
logger,
}: {
encryptionKey?: string;
job: ScheduledTaskParamsType;
logger: LevelLogger;
}): Promise<Record<string, string>> => {
export const decryptJobHeaders = async (
encryptionKey: string | undefined,
headers: string | undefined,
logger: LevelLogger
): Promise<Record<string, string>> => {
try {
if (typeof job.headers !== 'string') {
if (typeof headers !== 'string') {
throw new Error(
i18n.translate('xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage', {
defaultMessage: 'Job headers are missing',
})
);
}
const crypto = cryptoFactory(encryptionKey);
const decryptedHeaders = (await crypto.decrypt(job.headers)) as Record<string, string>;
const decryptedHeaders = (await crypto.decrypt(headers)) as Record<string, string>;
return decryptedHeaders;
} catch (err) {
logger.error(err);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import sinon from 'sinon';
import { ReportingConfig } from '../../';
import { ReportingCore } from '../../core';
import { createMockReportingCore } from '../../test_helpers';
import { ScheduledTaskParams } from '../../types';
import { ScheduledTaskParamsPDF } from '../printable_pdf/types';
import { getConditionalHeaders, getCustomLogo } from './';

let mockConfig: ReportingConfig;
Expand All @@ -36,11 +34,7 @@ describe('conditions', () => {
baz: 'quix',
};

const conditionalHeaders = await getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: permittedHeaders,
config: mockConfig,
});
const conditionalHeaders = getConditionalHeaders(mockConfig, permittedHeaders);

expect(conditionalHeaders.conditions.hostname).toEqual(
mockConfig.get('kibanaServer', 'hostname')
Expand All @@ -55,32 +49,7 @@ describe('conditions', () => {
});
});

test('uses basePath from job when creating saved object service', async () => {
const mockGetSavedObjectsClient = jest.fn();
mockReportingPlugin.getSavedObjectsClient = mockGetSavedObjectsClient;

const permittedHeaders = {
foo: 'bar',
baz: 'quix',
};
const conditionalHeaders = await getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: permittedHeaders,
config: mockConfig,
});
const jobBasePath = '/sbp/s/marketing';
await getCustomLogo({
reporting: mockReportingPlugin,
job: { basePath: jobBasePath } as ScheduledTaskParamsPDF,
conditionalHeaders,
config: mockConfig,
});

const getBasePath = mockGetSavedObjectsClient.mock.calls[0][0].getBasePath;
expect(getBasePath()).toBe(jobBasePath);
});

test(`uses basePath from server if job doesn't have a basePath when creating saved object service`, async () => {
test(`uses basePath from server when creating saved object service`, async () => {
const mockGetSavedObjectsClient = jest.fn();
mockReportingPlugin.getSavedObjectsClient = mockGetSavedObjectsClient;

Expand All @@ -93,18 +62,9 @@ test(`uses basePath from server if job doesn't have a basePath when creating sav
foo: 'bar',
baz: 'quix',
};
const conditionalHeaders = await getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: permittedHeaders,
config: mockConfig,
});
const conditionalHeaders = getConditionalHeaders(mockConfig, permittedHeaders);

await getCustomLogo({
reporting: mockReportingPlugin,
job: {} as ScheduledTaskParamsPDF,
conditionalHeaders,
config: mockConfig,
});
await getCustomLogo(mockReportingPlugin, mockConfig, conditionalHeaders);

const getBasePath = mockGetSavedObjectsClient.mock.calls[0][0].getBasePath;
expect(getBasePath()).toBe(`/sbp`);
Expand Down Expand Up @@ -138,11 +98,7 @@ describe('config formatting', () => {
const mockConfigGet = sinon.stub().withArgs('server', 'host').returns('COOL-HOSTNAME');
mockConfig = getMockConfig(mockConfigGet);

const conditionalHeaders = await getConditionalHeaders({
job: {} as ScheduledTaskParams<any>,
filteredHeaders: {},
config: mockConfig,
});
const conditionalHeaders = getConditionalHeaders(mockConfig, {});
expect(conditionalHeaders.conditions.hostname).toEqual('cool-hostname');
});

Expand All @@ -152,19 +108,7 @@ describe('config formatting', () => {
.withArgs('kibanaServer', 'hostname')
.returns('GREAT-HOSTNAME');
mockConfig = getMockConfig(mockConfigGet);
const conditionalHeaders = await getConditionalHeaders({
job: {
title: 'cool-job-bro',
type: 'csv',
jobParams: {
savedObjectId: 'abc-123',
isImmediate: false,
savedObjectType: 'search',
},
},
filteredHeaders: {},
config: mockConfig,
});
const conditionalHeaders = getConditionalHeaders(mockConfig, {});
expect(conditionalHeaders.conditions.hostname).toEqual('great-hostname');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,10 @@
import { ReportingConfig } from '../../';
import { ConditionalHeaders } from '../../types';

export const getConditionalHeaders = <ScheduledTaskParamsType>({
config,
job,
filteredHeaders,
}: {
config: ReportingConfig;
job: ScheduledTaskParamsType;
filteredHeaders: Record<string, string>;
}) => {
export const getConditionalHeaders = (
config: ReportingConfig,
filteredHeaders: Record<string, string>
) => {
const { kbnConfig } = config;
const [hostname, port, basePath, protocol] = [
config.get('kibanaServer', 'hostname'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import { ReportingCore } from '../../core';
import { createMockReportingCore } from '../../test_helpers';
import { ScheduledTaskParamsPDF } from '../printable_pdf/types';
import { getConditionalHeaders, getCustomLogo } from './';

const mockConfigGet = jest.fn().mockImplementation((key: string) => {
Expand Down Expand Up @@ -36,18 +35,9 @@ test(`gets logo from uiSettings`, async () => {
get: mockGet,
});

const conditionalHeaders = await getConditionalHeaders({
job: {} as ScheduledTaskParamsPDF,
filteredHeaders: permittedHeaders,
config: mockConfig,
});
const conditionalHeaders = getConditionalHeaders(mockConfig, permittedHeaders);

const { logo } = await getCustomLogo({
reporting: mockReportingPlugin,
config: mockConfig,
job: {} as ScheduledTaskParamsPDF,
conditionalHeaders,
});
const { logo } = await getCustomLogo(mockReportingPlugin, mockConfig, conditionalHeaders);

expect(mockGet).toBeCalledWith('xpackReporting:customPdfLogo');
expect(logo).toBe('purple pony');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,19 @@
import { ReportingConfig, ReportingCore } from '../../';
import { UI_SETTINGS_CUSTOM_PDF_LOGO } from '../../../common/constants';
import { ConditionalHeaders } from '../../types';
import { ScheduledTaskParamsPDF } from '../printable_pdf/types'; // Logo is PDF only

export const getCustomLogo = async ({
reporting,
config,
job,
conditionalHeaders,
}: {
reporting: ReportingCore;
config: ReportingConfig;
job: ScheduledTaskParamsPDF;
conditionalHeaders: ConditionalHeaders;
}) => {
export const getCustomLogo = async (
reporting: ReportingCore,
config: ReportingConfig,
conditionalHeaders: ConditionalHeaders
) => {
const serverBasePath: string = config.kbnConfig.get('server', 'basePath');
const fakeRequest: any = {
headers: conditionalHeaders.headers,
// This is used by the spaces SavedObjectClientWrapper to determine the existing space.
// We use the basePath from the saved job, which we'll have post spaces being implemented;
// or we use the server base path, which uses the default space
getBasePath: () => job.basePath || serverBasePath,
getBasePath: () => serverBasePath,
path: '/',
route: { settings: {} },
url: { href: '/' },
Expand Down
Loading

0 comments on commit d90df7a

Please sign in to comment.