Skip to content
Merged
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
41 changes: 29 additions & 12 deletions x-pack/test/api_integration/services/usage_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,38 @@ export interface UsageStatsPayloadTestFriendly extends UsageStatsPayload {
export function UsageAPIProvider({ getService }: FtrProviderContext) {
const supertest = getService('supertest');

async function getTelemetryStats(payload: {
unencrypted: true;
refreshCache?: boolean;
}): Promise<Array<{ clusterUuid: string; stats: UsageStatsPayloadTestFriendly }>>;
async function getTelemetryStats(payload: {
unencrypted: false;
refreshCache?: boolean;
}): Promise<Array<{ clusterUuid: string; stats: string }>>;
async function getTelemetryStats(payload: {
unencrypted?: boolean;
refreshCache?: boolean;
}): Promise<Array<{ clusterUuid: string; stats: UsageStatsPayloadTestFriendly | string }>> {
async function getTelemetryStats(
payload: {
unencrypted: true;
refreshCache?: boolean;
},
options?: { authHeader: Record<string, string> }
): Promise<Array<{ clusterUuid: string; stats: UsageStatsPayloadTestFriendly }>>;
async function getTelemetryStats(
payload: {
unencrypted: false;
refreshCache?: boolean;
},
options?: { authHeader: Record<string, string> }
): Promise<Array<{ clusterUuid: string; stats: string }>>;
async function getTelemetryStats(
payload: {
unencrypted: false;
refreshCache?: boolean;
},
options?: { authHeader: Record<string, string> }
): Promise<Array<{ clusterUuid: string; stats: string }>>;
async function getTelemetryStats(
payload: {
unencrypted?: boolean;
refreshCache?: boolean;
},
options?: { authHeader: Record<string, string> }
): Promise<Array<{ clusterUuid: string; stats: UsageStatsPayloadTestFriendly | string }>> {
const { body } = await supertest
.post('/internal/telemetry/clusters/_stats')
.set('kbn-xsrf', 'xxx')
.set(options?.authHeader ?? {})
.set(ELASTIC_HTTP_VERSION_HEADER, '2')
.set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana')
.send({ refreshCache: true, ...payload })
Expand Down
45 changes: 26 additions & 19 deletions x-pack/test_serverless/api_integration/services/slo_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
FetchHistoricalSummaryResponse,
} from '@kbn/slo-schema';
import * as t from 'io-ts';
import type { RoleCredentials } from '../../shared/services';
import { FtrProviderContext } from '../ftr_provider_context';

type DurationUnit = 'm' | 'h' | 'd' | 'w' | 'M';
Expand Down Expand Up @@ -70,50 +71,58 @@ type FetchHistoricalSummaryParams = t.OutputOf<
export function SloApiProvider({ getService }: FtrProviderContext) {
const es = getService('es');
const supertest = getService('supertest');
const svlCommonApi = getService('svlCommonApi');
const retry = getService('retry');
const requestTimeout = 30 * 1000;
const retryTimeout = 180 * 1000;

return {
async create(slo: SloParams) {
async create(slo: SloParams, roleAuthc: RoleCredentials) {
const { body } = await supertest
.post(`/api/observability/slos`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.send(slo);

return body;
},

async delete(sloId: string) {
async delete({ sloId, roleAuthc }: { sloId: string; roleAuthc: RoleCredentials }) {
const response = await supertest
.delete(`/api/observability/slos/${sloId}`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo');
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader);
return response;
},

async fetchHistoricalSummary(
params: FetchHistoricalSummaryParams
params: FetchHistoricalSummaryParams,
roleAuthc: RoleCredentials
): Promise<FetchHistoricalSummaryResponse> {
const { body } = await supertest
.post(`/internal/observability/slos/_historical_summary`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.send(params);

return body;
},

async waitForSloToBeDeleted(sloId: string) {
async waitForSloToBeDeleted({
sloId,
roleAuthc,
}: {
sloId: string;
roleAuthc: RoleCredentials;
}) {
if (!sloId) {
throw new Error(`sloId is undefined`);
}
return await retry.tryForTime(retryTimeout, async () => {
const response = await supertest
.delete(`/api/observability/slos/${sloId}`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.timeout(requestTimeout);
if (!response.ok) {
throw new Error(`slodId [${sloId}] was not deleted`);
Expand All @@ -122,15 +131,15 @@ export function SloApiProvider({ getService }: FtrProviderContext) {
});
},

async waitForSloCreated({ sloId }: { sloId: string }) {
async waitForSloCreated({ sloId, roleAuthc }: { sloId: string; roleAuthc: RoleCredentials }) {
if (!sloId) {
throw new Error(`'sloId is undefined`);
}
return await retry.tryForTime(retryTimeout, async () => {
const response = await supertest
.get(`/api/observability/slos/${sloId}`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.timeout(requestTimeout);
if (response.body.id === undefined) {
throw new Error(`No slo with id ${sloId} found`);
Expand Down Expand Up @@ -187,16 +196,14 @@ export function SloApiProvider({ getService }: FtrProviderContext) {
async deleteAllSLOs() {
const response = await supertest
.get(`/api/observability/slos/_definitions`)
.set('kbn-xsrf', 'true')
.set('x-elastic-internal-origin', 'foo')
.set(svlCommonApi.getInternalRequestHeader())
.send()
.expect(200);
await Promise.all(
response.body.results.map(({ id }: { id: string }) => {
return supertest
.delete(`/api/observability/slos/${id}`)
.set('kbn-xsrf', 'true')
.set('x-elastic-internal-origin', 'foo')
.set(svlCommonApi.getInternalRequestHeader())
.send()
.expect(204);
})
Expand Down
105 changes: 42 additions & 63 deletions x-pack/test_serverless/api_integration/services/svl_cases/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
* 2.0.
*/

import type SuperTest from 'supertest';
import { CASES_URL } from '@kbn/cases-plugin/common';
import { Case, CaseSeverity, CaseStatuses } from '@kbn/cases-plugin/common/types/domain';
import type { CasePostRequest } from '@kbn/cases-plugin/common/types/api';
import { ConnectorTypes } from '@kbn/cases-plugin/common/types/domain';
import { CasesFindResponse } from '@kbn/cases-plugin/common/types/api';
import { kbnTestConfig, kibanaTestSuperuserServerless } from '@kbn/test';
import type { RoleCredentials } from '../../../shared/services';
import { FtrProviderContext } from '../../ftr_provider_context';

export interface User {
Expand All @@ -23,13 +23,8 @@ export interface User {

export function SvlCasesApiServiceProvider({ getService }: FtrProviderContext) {
const kbnServer = getService('kibanaServer');
const supertest = getService('supertest');

const superUser: User = {
username: 'superuser',
password: 'superuser',
roles: ['superuser'],
};
const supertestWithoutAuth = getService('supertestWithoutAuth');
const svlCommonApi = getService('svlCommonApi');

const defaultUser = {
email: null,
Expand Down Expand Up @@ -57,22 +52,6 @@ export function SvlCasesApiServiceProvider({ getService }: FtrProviderContext) {
};

return {
setupAuth({
apiCall,
headers,
auth,
}: {
apiCall: SuperTest.Test;
headers: Record<string, unknown>;
auth?: { user: User; space: string | null } | null;
}): SuperTest.Test {
if (!Object.hasOwn(headers, 'Cookie') && auth != null) {
return apiCall.auth(auth.user.username, auth.user.password);
}

return apiCall;
},

getSpaceUrlPrefix(spaceId: string | undefined | null) {
return spaceId && spaceId !== 'default' ? `/s/${spaceId}` : ``;
},
Expand Down Expand Up @@ -139,65 +118,65 @@ export function SvlCasesApiServiceProvider({ getService }: FtrProviderContext) {

async createCase(
params: CasePostRequest,
expectedHttpCode: number = 200,
auth: { user: User; space: string | null } | null = { user: superUser, space: null },
headers: Record<string, string | string[]> = {}
roleAuthc: RoleCredentials,
expectedHttpCode: number = 200
): Promise<Case> {
const apiCall = supertest.post(`${CASES_URL}`);

this.setupAuth({ apiCall, headers, auth });
const apiCall = supertestWithoutAuth.post(`${CASES_URL}`);

const response = await apiCall
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.set(headers)
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.send(params)
.expect(expectedHttpCode);

return response.body;
},

async findCases({
query = {},
expectedHttpCode = 200,
auth = { user: superUser, space: null },
}: {
query?: Record<string, unknown>;
expectedHttpCode?: number;
auth?: { user: User; space: string | null };
}): Promise<CasesFindResponse> {
const { body: res } = await supertest
.get(`${this.getSpaceUrlPrefix(auth.space)}${CASES_URL}/_find`)
.auth(auth.user.username, auth.user.password)
async findCases(
{
query = {},
expectedHttpCode = 200,
space = 'default',
}: {
query?: Record<string, unknown>;
expectedHttpCode?: number;
space?: string;
},
roleAuthc: RoleCredentials
): Promise<CasesFindResponse> {
const { body: res } = await supertestWithoutAuth
.get(`${this.getSpaceUrlPrefix(space)}${CASES_URL}/_find`)
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.query({ sortOrder: 'asc', ...query })
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.send()
.expect(expectedHttpCode);

return res;
},

async getCase({
caseId,
includeComments = false,
expectedHttpCode = 200,
auth = { user: superUser, space: null },
}: {
caseId: string;
includeComments?: boolean;
expectedHttpCode?: number;
auth?: { user: User; space: string | null };
}): Promise<Case> {
const { body: theCase } = await supertest
async getCase(
{
caseId,
space = 'default',
includeComments = false,
expectedHttpCode = 200,
}: {
caseId: string;
space?: string;
includeComments?: boolean;
expectedHttpCode?: number;
},
roleAuthc: RoleCredentials
): Promise<Case> {
const { body: theCase } = await supertestWithoutAuth
.get(
`${this.getSpaceUrlPrefix(
auth?.space
space
)}${CASES_URL}/${caseId}?includeComments=${includeComments}`
)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo')
.auth(auth.user.username, auth.user.password)
.set(svlCommonApi.getInternalRequestHeader())
.set(roleAuthc.apiKeyHeader)
.expect(expectedHttpCode);

return theCase;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export default function ({ getService }: FtrProviderContext) {
let roleAdmin: RoleCredentials;
let internalReqHeader: InternalRequestHeader;
const supertest = getService('supertest');

const esClient = getService('es');
const objectRemover = new ObjectRemover(supertest);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
waitForExecutionEventLog,
waitForNumRuleRuns,
} from './helpers/alerting_wait_for_helpers';
import { InternalRequestHeader, RoleCredentials } from '../../../../shared/services';
import type { InternalRequestHeader, RoleCredentials } from '../../../../shared/services';

export default function ({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
Expand Down Expand Up @@ -60,14 +60,8 @@ export default function ({ getService }: FtrProviderContext) {
});

afterEach(async () => {
await supertest
.delete(`/api/actions/connector/${connectorId}`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo');
await supertest
.delete(`/api/alerting/rule/${ruleId}`)
.set('kbn-xsrf', 'foo')
.set('x-elastic-internal-origin', 'foo');
await supertest.delete(`/api/actions/connector/${connectorId}`).set(internalReqHeader);
await supertest.delete(`/api/alerting/rule/${ruleId}`).set(internalReqHeader);
await esClient.deleteByQuery({
index: '.kibana-event-log-*',
conflicts: 'proceed',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,26 @@ import type {
import { Config, kbnTestConfig, kibanaTestSuperuserServerless } from '@kbn/test';
import type { APIEndpoint } from '@kbn/apm-plugin/server';
import { formatRequest } from '@kbn/server-route-repository';
import type { InternalRequestHeader, RoleCredentials } from '../../../../../shared/services';
import { InheritedFtrProviderContext } from '../../../../services';

export function createApmApiClient(st: supertest.Agent) {
return async <TEndpoint extends APIEndpoint>(
options: {
type?: 'form-data';
endpoint: TEndpoint;
roleAuthc: RoleCredentials;
internalReqHeader: InternalRequestHeader;
} & APIClientRequestParamsOf<TEndpoint> & { params?: { query?: { _inspect?: boolean } } }
): Promise<SupertestReturnType<TEndpoint>> => {
const { endpoint, type } = options;
const { endpoint, type, roleAuthc, internalReqHeader } = options;

const params = 'params' in options ? (options.params as Record<string, any>) : {};

const { method, pathname, version } = formatRequest(endpoint, params.path);
const url = format({ pathname, query: params?.query });

const headers: Record<string, string> = {
'kbn-xsrf': 'foo',
'x-elastic-internal-origin': 'foo',
};

const headers: Record<string, string> = { ...internalReqHeader, ...roleAuthc.apiKeyHeader };
if (version) {
headers['Elastic-Api-Version'] = version;
}
Expand Down
Loading