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

adds getIndex functionality which requires the asset name to be passe… #1

Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,16 @@ import {
import { Logger, ElasticsearchClient, HttpResponsePayload } from '../../../../../src/core/server';
import { buildAlertsSearchQuery, buildAlertsUpdateParameters } from './utils';
import { RacAuthorizationAuditLogger } from './audit_logger';
import { RuleDataPluginService } from '../rule_data_plugin_service';

export interface ConstructorOptions {
logger: Logger;
authorization: PublicMethodsOf<AlertingAuthorization>;
spaceId?: string;
auditLogger: RacAuthorizationAuditLogger;
esClient: ElasticsearchClient;
index: string;
ruleDataService: RuleDataPluginService;
}

interface IndexType {
Expand Down Expand Up @@ -70,6 +73,7 @@ export interface UpdateOptions<Params extends AlertTypeParams> {
data: {
status: string;
};
assetName: string; // observability-apm see here: x-pack/plugins/apm/server/plugin.ts:191
}

export interface BulkUpdateOptions<Params extends AlertTypeParams> {
Expand All @@ -82,6 +86,7 @@ export interface BulkUpdateOptions<Params extends AlertTypeParams> {

interface GetAlertParams {
id: string;
assetName: string; // observability-apm see here: x-pack/plugins/apm/server/plugin.ts:191
}

export interface GetAlertInstanceSummaryParams {
Expand All @@ -98,30 +103,51 @@ export class AlertsClient {
private readonly logger: Logger;
private readonly auditLogger: RacAuthorizationAuditLogger;
private readonly spaceId?: string;
private readonly alertsIndex: string;
private readonly authorization: PublicMethodsOf<AlertingAuthorization>;
private readonly esClient: ElasticsearchClient;
private readonly ruleDataService: RuleDataPluginService;

constructor({ auditLogger, authorization, logger, spaceId, esClient }: ConstructorOptions) {
constructor({
auditLogger,
authorization,
logger,
spaceId,
esClient,
index,
ruleDataService,
}: ConstructorOptions) {
this.logger = logger;
this.spaceId = spaceId;
this.authorization = authorization;
this.esClient = esClient;
this.auditLogger = auditLogger;
this.alertsIndex = index;
this.ruleDataService = ruleDataService;
}

/**
* we are "hard coding" this string similar to how rule registry is doing it
* x-pack/plugins/apm/server/plugin.ts:191
*/
public getAlertsIndex(assetName: string) {
// possibly append spaceId here?
return this.ruleDataService.getFullAssetName(assetName); // await this.authorization.getAuthorizedAlertsIndices();
}

// TODO: Type out alerts (rule registry fields + alerting alerts type)
public async get({ id }: GetAlertParams): Promise<HttpResponsePayload> {
public async get({ id, assetName }: GetAlertParams): Promise<HttpResponsePayload> {
// first search for the alert specified, then check if user has access to it
// and return search results
const query = buildAlertsSearchQuery({
index: '.alerts-observability-apm',
index: this.getAlertsIndex(assetName), // '.alerts-observability-apm',
alertId: id,
});
// TODO: Type out alerts (rule registry fields + alerting alerts type)
try {
console.error('QUERY', JSON.stringify(query, null, 2));
const { body: result } = await this.esClient.get<RawAlert>({
index: '.alerts-observability-apm',
index: this.getAlertsIndex(assetName), // '.alerts-observability-apm',
id,
});
console.error('rule.id', result._source['rule.id']);
Expand Down Expand Up @@ -186,10 +212,11 @@ export class AlertsClient {
id,
owner,
data,
assetName,
}: UpdateOptions<Params>): Promise<PartialAlert<Params>> {
// TODO: Type out alerts (rule registry fields + alerting alerts type)
const result = await this.esClient.get({
index: '.alerts-observability-apm', // '.siem-signals-devin-hurley-default',
index: this.getAlertsIndex(assetName), // '.alerts-observability-apm', // '.siem-signals-devin-hurley-default',
id,
});
console.error('RESULT', result);
Expand All @@ -208,7 +235,7 @@ export class AlertsClient {
console.error('GOT PAST AUTHZ');

try {
const index = this.authorization.getAuthorizedAlertsIndices(hits['kibana.rac.alert.owner']);
const index = this.getAlertsIndex(assetName); // this.authorization.getAuthorizedAlertsIndices(hits['kibana.rac.alert.owner']);

console.error('INDEX', index);
const updateParameters = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@ import { SecurityPluginSetup } from '../../../security/server';
import { AlertingAuthorization } from '../../../alerting/server/authorization';
import { AlertsClient } from './alert_client';
import { RacAuthorizationAuditLogger } from './audit_logger';
import { RuleDataPluginService } from '../rule_data_plugin_service';

export interface RacClientFactoryOpts {
logger: Logger;
getSpaceId: (request: KibanaRequest) => string | undefined;
esClient: ElasticsearchClient;
getAlertingAuthorization: (request: KibanaRequest) => PublicMethodsOf<AlertingAuthorization>;
securityPluginSetup: SecurityPluginSetup | undefined;
ruleDataService: RuleDataPluginService | undefined;
}

export class AlertsClientFactory {
Expand All @@ -30,6 +32,7 @@ export class AlertsClientFactory {
request: KibanaRequest
) => PublicMethodsOf<AlertingAuthorization>;
private securityPluginSetup!: SecurityPluginSetup | undefined;
private ruleDataService!: RuleDataPluginService | undefined;

public initialize(options: RacClientFactoryOpts) {
/**
Expand All @@ -45,18 +48,21 @@ export class AlertsClientFactory {
this.getSpaceId = options.getSpaceId;
this.esClient = options.esClient;
this.securityPluginSetup = options.securityPluginSetup;
this.ruleDataService = options.ruleDataService;
}

public async create(request: KibanaRequest): Promise<AlertsClient> {
public async create(request: KibanaRequest, index: string): Promise<AlertsClient> {
const { securityPluginSetup, getAlertingAuthorization, logger } = this;
const spaceId = this.getSpaceId(request);

return new AlertsClient({
spaceId,
logger,
index,
authorization: getAlertingAuthorization(request),
auditLogger: new RacAuthorizationAuditLogger(securityPluginSetup?.audit.asScoped(request)),
esClient: this.esClient,
ruleDataService: this.ruleDataService,
});
}
}
63 changes: 7 additions & 56 deletions x-pack/plugins/rule_registry/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* 2.0.
*/

import { schema } from '@kbn/config-schema';
import {
PluginInitializerContext,
Plugin,
Expand Down Expand Up @@ -39,6 +38,7 @@ export class RuleRegistryPlugin implements Plugin<RuleRegistryPluginSetupContrac
private readonly logger: Logger;
private readonly config: RuleRegistryPluginConfig;
private readonly alertsClientFactory: AlertsClientFactory;
private ruleDataService: RuleDataPluginService;
private security: SecurityPluginSetup | undefined;

constructor(initContext: PluginInitializerContext) {
Expand Down Expand Up @@ -70,6 +70,7 @@ export class RuleRegistryPlugin implements Plugin<RuleRegistryPluginSetupContrac
error.stack = originalError.stack;
this.logger.error(error);
});
this.ruleDataService = service;

// ALERTS ROUTES
const router = core.http.createRouter<RacRequestHandlerContext>();
Expand All @@ -83,61 +84,10 @@ export class RuleRegistryPlugin implements Plugin<RuleRegistryPluginSetupContrac
router.get({ path: '/rac-myfakepath', validate: false }, async (context, req, res) => {
const racClient = await context.rac.getAlertsClient();
// console.error(`WHATS IN THE RAC CLIENT`, racClient);
racClient?.get({ id: 'hello world' });
racClient?.get({ id: 'hello world', assetName: 'observability-apm' });
return res.ok();
});

router.get(
{
path: '/rac-getalert',
validate: false,
},
async (context, request, response) => {
try {
const alertsClient = await context.rac.getAlertsClient();
const { id } = request.query;
console.error('ID?', id);
const alert = await alertsClient.get({ id });
return response.ok({
body: alert,
});
} catch (exc) {
console.error('ROUTE ERROR', exc);
throw exc;
}
}
);

router.post(
{
path: '/update-alert',
validate: {
body: schema.object({
status: schema.string(),
ids: schema.arrayOf(schema.string()),
}),
},
},
async (context, req, res) => {
try {
const racClient = await context.rac.getAlertsClient();
console.error(req);
const { status, ids } = req.body;
console.error('STATUS', status);
console.error('ID', ids);
const thing = await racClient?.update({
id: ids[0],
owner: 'apm',
data: { status },
});
return res.ok({ body: { success: true, alerts: thing } });
} catch (exc) {
console.error('OOPS', exc);
return res.unauthorized();
}
}
);

return service;
}

Expand All @@ -155,10 +105,11 @@ export class RuleRegistryPlugin implements Plugin<RuleRegistryPluginSetupContrac
return plugins.alerting.getAlertingAuthorizationWithRequest(request);
},
securityPluginSetup: security,
ruleDataService: this.ruleDataService,
});

const getRacClientWithRequest = (request: KibanaRequest) => {
return alertsClientFactory.create(request);
return alertsClientFactory.create(request, this.config.index);
};

return {
Expand All @@ -168,14 +119,14 @@ export class RuleRegistryPlugin implements Plugin<RuleRegistryPluginSetupContrac
}

private createRouteHandlerContext = (): IContextProvider<RacRequestHandlerContext, 'rac'> => {
const { alertsClientFactory } = this;
const { alertsClientFactory, config } = this;
return async function alertsRouteHandlerContext(
context,
request
): Promise<RacApiRequestHandlerContext> {
return {
getAlertsClient: async () => {
const createdClient = alertsClientFactory.create(request);
const createdClient = alertsClientFactory.create(request, config.index);
return createdClient;
},
};
Expand Down
5 changes: 3 additions & 2 deletions x-pack/plugins/rule_registry/server/routes/get_alert_by_id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const getAlertByIdRoute = (router: IRouter<RacRequestHandlerContext>) =>
t.exact(
t.type({
id: _id,
assetName: t.string,
})
)
),
Expand All @@ -34,8 +35,8 @@ export const getAlertByIdRoute = (router: IRouter<RacRequestHandlerContext>) =>
async (context, request, response) => {
try {
const alertsClient = await context.rac.getAlertsClient();
const { id } = request.query;
const alert = await alertsClient.get({ id });
const { id, assetName } = request.query;
const alert = await alertsClient.get({ id, assetName });
return response.ok({
body: alert,
});
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/rule_registry/server/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import { IRouter } from 'kibana/server';
import { RacRequestHandlerContext } from '../types';
import { getAlertByIdRoute } from './get_alert_by_id';
import { updateAlertByIdRoute } from './update_alert_by_id';

export function defineRoutes(router: IRouter<RacRequestHandlerContext>) {
getAlertByIdRoute(router);
updateAlertByIdRoute(router);
}
71 changes: 71 additions & 0 deletions x-pack/plugins/rule_registry/server/routes/update_alert_by_id.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { IRouter } from 'kibana/server';
import * as t from 'io-ts';
import { id as _id } from '@kbn/securitysolution-io-ts-list-types';
import { transformError, getIndexExists } from '@kbn/securitysolution-es-utils';
import { schema } from '@kbn/config-schema';

import { RacRequestHandlerContext } from '../types';
import { BASE_RAC_ALERTS_API_PATH } from '../../common/constants';
import { buildRouteValidation } from './utils/route_validation';

export const updateAlertByIdRoute = (router: IRouter<RacRequestHandlerContext>) => {
router.post(
{
path: BASE_RAC_ALERTS_API_PATH,
validate: {
body: schema.object({
status: schema.string(),
ids: schema.arrayOf(schema.string()),
assetName: schema.string(),
}),
},
options: {
tags: ['access:rac'],
},
},
async (context, req, response) => {
try {
const racClient = await context.rac.getAlertsClient();
console.error(req);
const { status, ids, assetName } = req.body;
console.error('STATUS', status);
console.error('ID', ids);
const thing = await racClient?.update({
id: ids[0],
owner: 'apm',
data: { status },
assetName,
});
return response.ok({ body: { success: true, alerts: thing } });
} catch (exc) {
const err = transformError(exc);
console.error(err.message);
console.error('ROUTE ERROR status code', err.statusCode);
const contentType: CustomHttpResponseOptions<T>['headers'] = {
'content-type': 'application/json',
};
const defaultedHeaders: CustomHttpResponseOptions<T>['headers'] = {
...contentType,
};

return response.custom({
headers: defaultedHeaders,
statusCode: err.statusCode,
body: Buffer.from(
JSON.stringify({
message: err.message,
status_code: err.statusCode,
})
),
});
}
}
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ cd ../observer && sh ./post_detections_role.sh && sh ./post_detections_user.sh
cd ..

# Example: ./find_rules.sh
curl -s -k \
curl -v -k \
-u $USER:changeme \
-X GET ${KIBANA_URL}${SPACE_URL}/api/rac/alerts?id=NoxgpHkBqbdrfX07MqXV | jq .
-X GET "${KIBANA_URL}${SPACE_URL}/api/rac/alerts?id=NoxgpHkBqbdrfX07MqXV&assetName=observability-apm" | jq .
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ curl -s -k \
-H 'kbn-xsrf: 123' \
-u observer:changeme \
-X POST ${KIBANA_URL}${SPACE_URL}/update-alert \
-d "{\"ids\": $IDS, \"status\":\"$STATUS\"}" | jq .
-d "{\"ids\": $IDS, \"status\":\"$STATUS\", \"assetName\":\"observability-apm\"}" | jq .
Loading