Skip to content

Commit

Permalink
EMT-248: fix PR comments, use kibana access
Browse files Browse the repository at this point in the history
  • Loading branch information
nnamdifrankie committed Mar 19, 2020
1 parent 982a518 commit b47d7a4
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,16 @@ describe('test actions handlers', () => {

it('should succeed on valid new agent action', async () => {
const mockRequest = httpServerMock.createKibanaRequest({
headers: {
authorization: 'ApiKey TmVqTDBIQUJsRkw1em52R1ZIUF86NS1NaTItdHFUTHFHbThmQW1Fb0ljUQ==',
},
body: {
action: {
type: 'CONFIG_CHANGE',
data: 'data',
sent_at: '2020-03-14T19:45:02.620Z',
},
},
params: {
agentId: 'id',
},
});

const agentAction = ({
Expand All @@ -70,7 +70,7 @@ describe('test actions handlers', () => {
} as unknown) as AgentAction;

const actionsService: ActionsService = {
getAgentByAccessAPIKeyId: jest.fn().mockReturnValueOnce({
getAgent: jest.fn().mockReturnValueOnce({
id: 'agent',
}),
getSavedObjectsClientContract: jest.fn().mockReturnValueOnce(mockSavedObjectsClient),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { RequestHandler } from 'kibana/server';
import { TypeOf } from '@kbn/config-schema';
import { PostNewAgentActionRequestSchema } from '../../types/rest_spec';
import { ActionsService } from '../../services/agents';
import * as APIKeyService from '../../services/api_keys';
import { NewAgentAction } from '../../../common/types/models';
import { PostNewAgentActionResponse } from '../../../common/types/rest_spec';

Expand All @@ -22,25 +21,37 @@ export const postNewAgentActionHandlerBuilder = function(
TypeOf<typeof PostNewAgentActionRequestSchema.body>
> {
return async (context, request, response) => {
const soClient = actionsService.getSavedObjectsClientContract(request);

const res = APIKeyService.parseApiKey(request.headers);

const agent = await actionsService.getAgentByAccessAPIKeyId(soClient, res.apiKeyId as string);

const newAgentAction = request.body.action as NewAgentAction;

const savedAgentAction = await actionsService.updateAgentActions(
soClient,
agent,
newAgentAction
);

const body: PostNewAgentActionResponse = {
success: true,
item: savedAgentAction,
};

return response.ok({ body });
try {
const soClient = actionsService.getSavedObjectsClientContract(request);

const agent = await actionsService.getAgent(soClient, request.params.agentId);

const newAgentAction = request.body.action as NewAgentAction;

const savedAgentAction = await actionsService.updateAgentActions(
soClient,
agent,
newAgentAction
);

const body: PostNewAgentActionResponse = {
success: true,
item: savedAgentAction,
};

return response.ok({ body });
} catch (e) {
if (e.isBoom) {
return response.customError({
statusCode: e.output.statusCode,
body: { message: e.message },
});
}

return response.customError({
statusCode: 500,
body: { message: e.message },
});
}
};
};
4 changes: 2 additions & 2 deletions x-pack/plugins/ingest_manager/server/routes/agent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ export const registerRoutes = (router: IRouter) => {
{
path: AGENT_API_ROUTES.ACTIONS_PATTERN,
validate: PostNewAgentActionRequestSchema,
options: { tags: [] },
options: { tags: [`access:${PLUGIN_ID}-all`] },
},
postNewAgentActionHandlerBuilder({
getAgentByAccessAPIKeyId: AgentService.getAgentByAccessAPIKeyId,
getAgent: AgentService.getAgent,
getSavedObjectsClientContract: getInternalUserSOClient,
updateAgentActions: AgentService.updateAgentActions,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ function keys<O extends object>(obj: O): Array<keyof O> {
}

export interface ActionsService {
getAgentByAccessAPIKeyId: (
soClient: SavedObjectsClientContract,
accessAPIKeyId: string
) => Promise<Agent>;
getAgent: (soClient: SavedObjectsClientContract, agentId: string) => Promise<Agent>;

getSavedObjectsClientContract: (kibanaRequest: KibanaRequest) => SavedObjectsClientContract;

Expand Down
67 changes: 16 additions & 51 deletions x-pack/test/api_integration/apis/fleet/agents/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,68 +5,26 @@
*/

import expect from '@kbn/expect';
import uuid from 'uuid';

import { FtrProviderContext } from '../../../ftr_provider_context';
import { getSupertestWithoutAuth } from './services';

export default function(providerContext: FtrProviderContext) {
const { getService } = providerContext;
const esArchiver = getService('esArchiver');
const esClient = getService('es');

const supertest = getSupertestWithoutAuth(providerContext);
let apiKey: { id: string; api_key: string };
const supertest = getService('supertest');

describe('fleet_agents_actions', () => {
before(async () => {
await esArchiver.loadIfNeeded('fleet/agents');

const { body: apiKeyBody } = await esClient.security.createApiKey({
body: {
name: `test access api key: ${uuid.v4()}`,
},
});
apiKey = apiKeyBody;
const {
body: { _source: agentDoc },
} = await esClient.get({
index: '.kibana',
id: 'agents:agent1',
});
agentDoc.agents.access_api_key_id = apiKey.id;
await esClient.update({
index: '.kibana',
id: 'agents:agent1',
refresh: 'true',
body: {
doc: agentDoc,
},
});
});
after(async () => {
await esArchiver.unload('fleet/agents');
});

it('should return a 401 if this a not a valid actions access', async () => {
await supertest
.post(`/api/ingest_manager/fleet/agents/agent1/actions`)
.set('kbn-xsrf', 'xx')
.set('Authorization', 'ApiKey NOT_A_VALID_TOKEN')
.send({
action_ids: [],
})
.expect(401);
});

it('should return a 200 if this a valid actions request', async () => {
const { body: apiResponse } = await supertest
.post(`/api/ingest_manager/fleet/agents/agent1/actions`)
.set('kbn-xsrf', 'xx')
.set(
'Authorization',
`ApiKey ${Buffer.from(`${apiKey.id}:${apiKey.api_key}`).toString('base64')}`
)
.send({
action: {
type: 'CONFIG_CHANGE',
Expand All @@ -83,10 +41,6 @@ export default function(providerContext: FtrProviderContext) {
const { body: agentResponse } = await supertest
.get(`/api/ingest_manager/fleet/agents/agent1`)
.set('kbn-xsrf', 'xx')
.set(
'Authorization',
`ApiKey ${Buffer.from(`${apiKey.id}:${apiKey.api_key}`).toString('base64')}`
)
.expect(200);

const updatedAction = agentResponse.item.actions.find(
Expand All @@ -102,10 +56,6 @@ export default function(providerContext: FtrProviderContext) {
const { body: apiResponse } = await supertest
.post(`/api/ingest_manager/fleet/agents/agent1/actions`)
.set('kbn-xsrf', 'xx')
.set(
'Authorization',
`ApiKey ${Buffer.from(`${apiKey.id}:${apiKey.api_key}`).toString('base64')}`
)
.send({
action: {
data: 'action_data',
Expand All @@ -117,5 +67,20 @@ export default function(providerContext: FtrProviderContext) {
'[request body.action.type]: expected at least one defined value but got [undefined]'
);
});

it('should return a 404 when agent does not exist', async () => {
const { body: apiResponse } = await supertest
.post(`/api/ingest_manager/fleet/agents/agent100/actions`)
.set('kbn-xsrf', 'xx')
.send({
action: {
type: 'CONFIG_CHANGE',
data: 'action_data',
sent_at: '2020-03-18T19:45:02.620Z',
},
})
.expect(404);
expect(apiResponse.message).to.eql('Saved object [agents/agent100] not found');
});
});
}

0 comments on commit b47d7a4

Please sign in to comment.