Skip to content

Commit

Permalink
Use encryptedSavedObjectClient
Browse files Browse the repository at this point in the history
  • Loading branch information
YulNaumenko committed Nov 17, 2020
1 parent 4092f13 commit 1cc9d52
Show file tree
Hide file tree
Showing 12 changed files with 60 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@ describe('create()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt,
},
references: [],
Expand All @@ -746,7 +746,7 @@ describe('create()', () => {
expect(taskManager.schedule).not.toHaveBeenCalled();
expect(unsecuredSavedObjectsClient.create).toHaveBeenCalledTimes(2);
expect(unsecuredSavedObjectsClient.create.mock.calls[1][1]).toStrictEqual({
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt,
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ describe('delete()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand All @@ -121,7 +121,7 @@ describe('delete()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -156,7 +156,7 @@ describe('delete()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -189,7 +189,7 @@ describe('delete()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down
12 changes: 6 additions & 6 deletions x-pack/plugins/alerts/server/alerts_client/tests/disable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ describe('disable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -156,7 +156,7 @@ describe('disable()', () => {
expect(taskManager.remove).toHaveBeenCalledWith('task-123');
expect(
(unsecuredSavedObjectsClient.create.mock.calls[0][1] as InvalidatePendingApiKey).apiKeyId
).toBe('MTIz');
).toBe('123');
});

test('falls back when getDecryptedAsInternalUser throws an error', async () => {
Expand All @@ -165,7 +165,7 @@ describe('disable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -225,7 +225,7 @@ describe('disable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand All @@ -242,7 +242,7 @@ describe('disable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand All @@ -258,7 +258,7 @@ describe('disable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down
10 changes: 5 additions & 5 deletions x-pack/plugins/alerts/server/alerts_client/tests/enable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ describe('enable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt,
},
references: [],
Expand Down Expand Up @@ -239,7 +239,7 @@ describe('enable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt,
},
references: [],
Expand All @@ -252,7 +252,7 @@ describe('enable()', () => {
});
expect(
(unsecuredSavedObjectsClient.create.mock.calls[0][1] as InvalidatePendingApiKey).apiKeyId
).toBe('MTIz');
).toBe('123');
});

test(`doesn't enable already enabled alerts`, async () => {
Expand Down Expand Up @@ -345,7 +345,7 @@ describe('enable()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt,
},
references: [],
Expand All @@ -358,7 +358,7 @@ describe('enable()', () => {
expect(alertsClientParams.createAPIKey).toHaveBeenCalled();
expect(
(unsecuredSavedObjectsClient.create.mock.calls[0][1] as InvalidatePendingApiKey).apiKeyId
).toBe('MTIz');
).toBe('123');
expect(unsecuredSavedObjectsClient.update).toHaveBeenCalledTimes(1);
expect(taskManager.schedule).not.toHaveBeenCalled();
});
Expand Down
10 changes: 5 additions & 5 deletions x-pack/plugins/alerts/server/alerts_client/tests/update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ describe('update()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -388,7 +388,7 @@ describe('update()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand All @@ -397,7 +397,7 @@ describe('update()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -560,7 +560,7 @@ describe('update()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -1002,7 +1002,7 @@ describe('update()', () => {
).rejects.toThrowErrorMatchingInlineSnapshot(`"Fail"`);
expect(
(unsecuredSavedObjectsClient.create.mock.calls[1][1] as InvalidatePendingApiKey).apiKeyId
).toBe('MjM0');
).toBe('234');
});

describe('updating an alert schedule', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ describe('updateApiKey()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -141,7 +141,7 @@ describe('updateApiKey()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MTIz',
apiKeyId: '123',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand Down Expand Up @@ -199,7 +199,7 @@ describe('updateApiKey()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand All @@ -223,7 +223,7 @@ describe('updateApiKey()', () => {
id: '1',
type: 'api_key_pending_invalidation',
attributes: {
apiKeyId: 'MjM0',
apiKeyId: '234',
createdAt: '2019-02-12T21:01:22.479Z',
},
references: [],
Expand All @@ -234,7 +234,7 @@ describe('updateApiKey()', () => {
);
expect(
(unsecuredSavedObjectsClient.create.mock.calls[0][1] as InvalidatePendingApiKey).apiKeyId
).toBe('MjM0');
).toBe('234');
});

describe('authorization', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ describe('markApiKeyForInvalidation', () => {
},
references: [],
});
markApiKeyForInvalidation(
await markApiKeyForInvalidation(
{ apiKey: Buffer.from('123:abc').toString('base64') },
loggingSystemMock.create().get(),
unsecuredSavedObjectsClient
Expand All @@ -30,4 +30,18 @@ describe('markApiKeyForInvalidation', () => {
'api_key_pending_invalidation'
);
});

test('should log the proper error when savedObjectsClient create failed', async () => {
const logger = loggingSystemMock.create().get();
const unsecuredSavedObjectsClient = savedObjectsClientMock.create();
unsecuredSavedObjectsClient.create.mockRejectedValueOnce(new Error('Fail'));
await markApiKeyForInvalidation(
{ apiKey: Buffer.from('123').toString('base64') },
logger,
unsecuredSavedObjectsClient
);
expect(logger.error).toHaveBeenCalledWith(
'Failed to mark for API key [id="MTIz"] for invalidation: Fail'
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ export const markApiKeyForInvalidation = async (
return;
}
try {
const apiKeyId = Buffer.from(Buffer.from(apiKey, 'base64').toString().split(':')[0]).toString(
'base64'
);
const apiKeyId = Buffer.from(apiKey, 'base64').toString().split(':')[0];
await savedObjectsClient.create('api_key_pending_invalidation', {
apiKeyId,
createdAt: new Date().toISOString(),
Expand Down
15 changes: 11 additions & 4 deletions x-pack/plugins/alerts/server/invalidate_pending_api_keys/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
KibanaRequest,
SavedObjectsClientContract,
} from 'kibana/server';
import { EncryptedSavedObjectsClient } from '../../../encrypted_saved_objects/server';
import { InvalidateAPIKeyParams, SecurityPluginSetup } from '../../../security/server';
import {
RunContext,
Expand Down Expand Up @@ -129,15 +130,17 @@ function taskRunner(
let totalInvalidated = 0;
const configResult = await config;
try {
const [{ savedObjects, http }] = await coreStartServices;
const [{ savedObjects, http }, { encryptedSavedObjects }] = await coreStartServices;
const savedObjectsClient = savedObjects.getScopedClient(
getFakeKibanaRequest(http.basePath.serverBasePath),
{
includedHiddenTypes: ['api_key_pending_invalidation'],
excludedWrappers: ['security'],
}
);

const encryptedSavedObjectsClient = encryptedSavedObjects.getClient({
includedHiddenTypes: ['api_key_pending_invalidation'],
});
const configuredDelay = configResult.invalidateApiKeysTask.removalDelay;
const delay = timePeriodBeforeDate(new Date(), configuredDelay).toISOString();

Expand All @@ -156,6 +159,7 @@ function taskRunner(
logger,
savedObjectsClient,
apiKeysToInvalidate,
encryptedSavedObjectsClient,
securityPluginSetup
);

Expand Down Expand Up @@ -192,13 +196,16 @@ async function invalidateApiKeys(
logger: Logger,
savedObjectsClient: SavedObjectsClientContract,
apiKeysToInvalidate: SavedObjectsFindResponse<InvalidatePendingApiKey>,
encryptedSavedObjectsClient: EncryptedSavedObjectsClient,
securityPluginSetup?: SecurityPluginSetup
) {
let totalInvalidated = 0;
await Promise.all(
apiKeysToInvalidate.saved_objects.map(async (apiKeyObj) => {
const apiKeyId = Buffer.from(apiKeyObj.attributes.apiKeyId, 'base64').toString();

const decryptedApiKey = await encryptedSavedObjectsClient.getDecryptedAsInternalUser<
InvalidatePendingApiKey
>('api_key_pending_invalidation', apiKeyObj.id);
const apiKeyId = decryptedApiKey.attributes.apiKeyId;
const response = await invalidateAPIKey({ id: apiKeyId }, securityPluginSetup);
if (response.apiKeysEnabled === true && response.result.error_count > 0) {
logger.error(`Failed to invalidate API Key [id="${apiKeyObj.attributes.apiKeyId}"]`);
Expand Down
6 changes: 6 additions & 0 deletions x-pack/plugins/alerts/server/saved_objects/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,10 @@ export function setupSavedObjects(
attributesToEncrypt: new Set(['apiKey']),
attributesToExcludeFromAAD: new Set(AlertAttributesExcludedFromAAD),
});

// Encrypted attributes
encryptedSavedObjects.registerType({
type: 'api_key_pending_invalidation',
attributesToEncrypt: new Set(['apiKeyId']),
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,6 @@ export function defineRoutes(
const findResult = await savedObjectsWithTasksAndAlerts.find<InvalidatePendingApiKey>({
type: 'api_key_pending_invalidation',
});
// eslint-disable-next-line no-console
console.log(findResult);
return res.ok({
body: { apiKeysToInvalidate: findResult.saved_objects },
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,6 @@ export default function createUpdateTests({ getService }: FtrProviderContext) {
.then((response: SupertestResponse) => response.body);
}

function getAlertingApiKeysToInvalidate() {
return supertest
.get(`/api/alerts_fixture/api_keys_pending_invalidation`)
.expect(200)
.then((response: SupertestResponse) => response.body);
}

describe('update', () => {
const objectRemover = new ObjectRemover(supertest);

Expand Down Expand Up @@ -859,7 +852,6 @@ export default function createUpdateTests({ getService }: FtrProviderContext) {
})
.expect(200);
objectRemover.add(space.id, createdAlert.id, 'alert', 'alerts');

const updatedData = {
name: 'bcd',
tags: ['bar'],
Expand Down Expand Up @@ -910,9 +902,6 @@ export default function createUpdateTests({ getService }: FtrProviderContext) {
expect(alertTask.status).to.eql('idle');
// ensure the alert is rescheduled to a minute from now
ensureDatetimeIsWithinRange(Date.parse(alertTask.runAt), 60 * 1000);

const apiKeyIds = await getAlertingApiKeysToInvalidate();
expect(apiKeyIds.apiKeysToInvalidate.length).to.be(0);
});
break;
default:
Expand Down

0 comments on commit 1cc9d52

Please sign in to comment.