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

[RAC][RBAC] - Update PR tests #12

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 @@ -217,7 +217,7 @@ beforeEach(() => {
});

describe('AlertingAuthorization', () => {
xdescribe('constructor', () => {
describe('constructor', () => {
test(`fetches the user's current space`, async () => {
const space = {
id: uuid.v4(),
Expand All @@ -239,7 +239,7 @@ describe('AlertingAuthorization', () => {
});
});

xdescribe('ensureAuthorized', () => {
describe('ensureAuthorized', () => {
test('is a no-op when there is no authorization api', async () => {
const alertAuthorization = new AlertingAuthorization({
request,
Expand Down Expand Up @@ -886,7 +886,7 @@ describe('AlertingAuthorization', () => {
});
});

xdescribe('getFindAuthorizationFilter', () => {
describe('getFindAuthorizationFilter', () => {
const myOtherAppAlertType: RegistryAlertType = {
actionGroups: [],
actionVariables: undefined,
Expand Down Expand Up @@ -1236,7 +1236,7 @@ describe('AlertingAuthorization', () => {
});
});

xdescribe('filterByRuleTypeAuthorization', () => {
describe('filterByRuleTypeAuthorization', () => {
const myOtherAppAlertType: RegistryAlertType = {
actionGroups: [],
actionVariables: undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
APM_SERVER_FEATURE_ID,
ALERT_TYPES_CONFIG,
} from '../../../common/alert_types';
import { asMutableArray } from '../../../common/utils/as_mutable_array';
import {
PROCESSOR_EVENT,
SERVICE_ENVIRONMENT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const createAlertsClientMock = () => {
get: jest.fn(),
getAlertsIndex: jest.fn(),
update: jest.fn(),
getAuthorizedAlertsIndices: jest.fn(),
};
return mocked;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export interface UpdateOptions<Params extends AlertTypeParams> {
data: {
status: string;
};
indexName: string;
index: string;
}

interface GetAlertParams {
Expand Down Expand Up @@ -94,11 +94,12 @@ export class AlertsClient {
}
}

public async get({ id }: GetAlertParams): Promise<ParsedTechnicalFields> {
public async get({ id, index }: GetAlertParams): Promise<ParsedTechnicalFields> {
try {
// first search for the alert by id, then use the alert info to check if user has access to it
const alert = await this.fetchAlert({
id,
index,
});

// this.authorization leverages the alerting plugin's authorization
Expand Down Expand Up @@ -134,11 +135,12 @@ export class AlertsClient {
public async update<Params extends AlertTypeParams = never>({
id,
data,
indexName,
index,
}: UpdateOptions<Params>): Promise<ParsedTechnicalFields | null | undefined> {
try {
const alert = await this.fetchAlert({
id,
index,
});

await this.authorization.ensureAuthorized({
Expand All @@ -150,7 +152,7 @@ export class AlertsClient {

const updateParameters = {
id,
index: indexName,
index,
body: {
doc: {
[ALERT_STATUS]: data.status,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,11 @@ import { ElasticsearchClient, KibanaRequest } from 'src/core/server';
import { loggingSystemMock } from 'src/core/server/mocks';
import { securityMock } from '../../../security/server/mocks';
import { AuditLogger } from '../../../security/server';
import { ruleDataPluginServiceMock } from '../rule_data_plugin_service/rule_data_plugin_service.mock';
import { alertingAuthorizationMock } from '../../../alerting/server/authorization/alerting_authorization.mock';
import { RuleDataPluginServiceConstructorOptions } from '../rule_data_plugin_service';

jest.mock('./alerts_client');

const securityPluginSetup = securityMock.createSetup();
const ruleDataServiceMock = ruleDataPluginServiceMock.create(
{} as RuleDataPluginServiceConstructorOptions
);
const alertingAuthMock = alertingAuthorizationMock.create();

const alertsClientFactoryParams: AlertsClientFactoryProps = {
Expand Down Expand Up @@ -51,42 +46,33 @@ const auditLogger = {
log: jest.fn(),
} as jest.Mocked<AuditLogger>;

beforeEach(() => {
jest.resetAllMocks();
describe('AlertsClientFactory', () => {
beforeEach(() => {
jest.resetAllMocks();

securityPluginSetup.audit.asScoped.mockReturnValue(auditLogger);
});

test('creates an alerts client with proper constructor arguments', async () => {
const factory = new AlertsClientFactory();
factory.initialize({ ...alertsClientFactoryParams });
const request = KibanaRequest.from(fakeRequest);
await factory.create(request);

expect(jest.requireMock('./alerts_client').AlertsClient).toHaveBeenCalledWith({
authorization: alertingAuthMock,
logger: alertsClientFactoryParams.logger,
auditLogger,
esClient: {},
ruleDataService: ruleDataServiceMock,
securityPluginSetup.audit.asScoped.mockReturnValue(auditLogger);
});
});

test('throws an error if already initialized', () => {
const factory = new AlertsClientFactory();
factory.initialize({ ...alertsClientFactoryParams });
test('creates an alerts client with proper constructor arguments', async () => {
const factory = new AlertsClientFactory();
factory.initialize({ ...alertsClientFactoryParams });
const request = KibanaRequest.from(fakeRequest);
await factory.create(request);

expect(() =>
factory.initialize({ ...alertsClientFactoryParams })
).toThrowErrorMatchingInlineSnapshot(`"AlertsClientFactory (RAC) already initialized"`);
});
expect(jest.requireMock('./alerts_client').AlertsClient).toHaveBeenCalledWith({
authorization: alertingAuthMock,
logger: alertsClientFactoryParams.logger,
auditLogger,
esClient: {},
});
});

test('throws an error if ruleDataService not available', () => {
const factory = new AlertsClientFactory();
test('throws an error if already initialized', () => {
const factory = new AlertsClientFactory();
factory.initialize({ ...alertsClientFactoryParams });

expect(() =>
factory.initialize({
...alertsClientFactoryParams,
})
).toThrowErrorMatchingInlineSnapshot(`"Rule registry data service required for alerts client"`);
expect(() =>
factory.initialize({ ...alertsClientFactoryParams })
).toThrowErrorMatchingInlineSnapshot(`"AlertsClientFactory (RAC) already initialized"`);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,39 @@ beforeEach(() => {
describe('get()', () => {
test('calls ES client with given params', async () => {
const alertsClient = new AlertsClient(alertsClientParams);
esClientMock.get.mockResolvedValueOnce(
esClientMock.search.mockResolvedValueOnce(
elasticsearchClientMock.createApiResponse({
body: {
found: true,
_type: 'alert',
_index: '.alerts-observability-apm',
_id: 'NoxgpHkBqbdrfX07MqXV',
_source: {
'rule.id': 'apm.error_rate',
message: 'hello world 1',
'kibana.rac.alert.owner': 'apm',
'kibana.rac.alert.status': 'open',
took: 5,
timed_out: false,
_shards: {
total: 1,
successful: 1,
failed: 0,
skipped: 0,
},
hits: {
total: 1,
max_score: 999,
hits: [
{
found: true,
_type: 'alert',
_index: '.alerts-observability-apm',
_id: 'NoxgpHkBqbdrfX07MqXV',
_source: {
'rule.id': 'apm.error_rate',
message: 'hello world 1',
'kibana.rac.alert.owner': 'apm',
'kibana.rac.alert.status': 'open',
},
},
],
},
},
})
);
const result = await alertsClient.get({ id: '1', indexName: '.alerts-observability-apm' });
const result = await alertsClient.get({ id: '1', index: '.alerts-observability-apm' });
expect(result).toMatchInlineSnapshot(`
Object {
"kibana.rac.alert.owner": "apm",
Expand All @@ -57,11 +73,17 @@ describe('get()', () => {
"rule.id": "apm.error_rate",
}
`);
expect(esClientMock.get).toHaveBeenCalledTimes(1);
expect(esClientMock.get.mock.calls[0]).toMatchInlineSnapshot(`
expect(esClientMock.search).toHaveBeenCalledTimes(1);
expect(esClientMock.search.mock.calls[0]).toMatchInlineSnapshot(`
Array [
Object {
"id": "1",
"body": Object {
"query": Object {
"term": Object {
"_id": "1",
},
},
},
"index": ".alerts-observability-apm",
},
]
Expand All @@ -70,23 +92,39 @@ describe('get()', () => {

test('logs successful event in audit logger', async () => {
const alertsClient = new AlertsClient(alertsClientParams);
esClientMock.get.mockResolvedValueOnce(
esClientMock.search.mockResolvedValueOnce(
elasticsearchClientMock.createApiResponse({
body: {
found: true,
_type: 'alert',
_index: '.alerts-observability-apm',
_id: 'NoxgpHkBqbdrfX07MqXV',
_source: {
'rule.id': 'apm.error_rate',
message: 'hello world 1',
'kibana.rac.alert.owner': 'apm',
'kibana.rac.alert.status': 'open',
took: 5,
timed_out: false,
_shards: {
total: 1,
successful: 1,
failed: 0,
skipped: 0,
},
hits: {
total: 1,
max_score: 999,
hits: [
{
found: true,
_type: 'alert',
_index: '.alerts-observability-apm',
_id: 'NoxgpHkBqbdrfX07MqXV',
_source: {
'rule.id': 'apm.error_rate',
message: 'hello world 1',
'kibana.rac.alert.owner': 'apm',
'kibana.rac.alert.status': 'open',
},
},
],
},
},
})
);
await alertsClient.get({ id: '1', indexName: '.alerts-observability-apm' });
await alertsClient.get({ id: '1', index: '.alerts-observability-apm' });

expect(auditLogger.log).toHaveBeenCalledWith({
error: undefined,
Expand All @@ -98,10 +136,10 @@ describe('get()', () => {
test(`throws an error if ES client get fails`, async () => {
const error = new Error('something went wrong');
const alertsClient = new AlertsClient(alertsClientParams);
esClientMock.get.mockRejectedValue(error);
esClientMock.search.mockRejectedValue(error);

await expect(
alertsClient.get({ id: '1', indexName: '.alerts-observability-apm' })
alertsClient.get({ id: '1', index: '.alerts-observability-apm' })
).rejects.toThrowErrorMatchingInlineSnapshot(`"something went wrong"`);
expect(auditLogger.log).toHaveBeenCalledWith({
error: { code: 'Error', message: 'something went wrong' },
Expand All @@ -112,18 +150,34 @@ describe('get()', () => {

describe('authorization', () => {
beforeEach(() => {
esClientMock.get.mockResolvedValueOnce(
esClientMock.search.mockResolvedValueOnce(
elasticsearchClientMock.createApiResponse({
body: {
found: true,
_type: 'alert',
_index: '.alerts-observability-apm',
_id: 'NoxgpHkBqbdrfX07MqXV',
_source: {
'rule.id': 'apm.error_rate',
message: 'hello world 1',
'kibana.rac.alert.owner': 'apm',
'kibana.rac.alert.status': 'open',
took: 5,
timed_out: false,
_shards: {
total: 1,
successful: 1,
failed: 0,
skipped: 0,
},
hits: {
total: 1,
max_score: 999,
hits: [
{
found: true,
_type: 'alert',
_index: '.alerts-observability-apm',
_id: 'NoxgpHkBqbdrfX07MqXV',
_source: {
'rule.id': 'apm.error_rate',
message: 'hello world 1',
'kibana.rac.alert.owner': 'apm',
'kibana.rac.alert.status': 'open',
},
},
],
},
},
})
Expand All @@ -132,7 +186,7 @@ describe('get()', () => {

test('returns alert if user is authorized to read alert under the consumer', async () => {
const alertsClient = new AlertsClient(alertsClientParams);
const result = await alertsClient.get({ id: '1', indexName: '.alerts-observability-apm' });
const result = await alertsClient.get({ id: '1', index: '.alerts-observability-apm' });

expect(alertingAuthMock.ensureAuthorized).toHaveBeenCalledWith({
entity: 'alert',
Expand All @@ -157,7 +211,7 @@ describe('get()', () => {
);

await expect(
alertsClient.get({ id: '1', indexName: '.alerts-observability-apm' })
alertsClient.get({ id: '1', index: '.alerts-observability-apm' })
).rejects.toMatchInlineSnapshot(
`[Error: Unauthorized to get a "apm.error_rate" alert for "apm"]`
);
Expand Down
Loading