-
Notifications
You must be signed in to change notification settings - Fork 8.6k
[Beats Management] APIs: Create enrollment tokens #19018
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
Merged
ycombinator
merged 20 commits into
elastic:feature/x-pack/management/beats
from
ycombinator:x-pack/management/beats/apis/create-enrollment-tokens
May 15, 2018
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
b9e0211
WIP checkin
ycombinator 1e489dd
Register API routes
ycombinator e599bab
Fixing typo in index name
ycombinator 3db7008
Adding TODOs
ycombinator 6346181
Removing commented out license checking code that isn't yet implemented
ycombinator 08176b4
Remove unnecessary async/await
ycombinator c684373
Don't return until indices have been refreshed
ycombinator a6dc656
Add API integration test
ycombinator 5e9bc08
Converting to Jest test
ycombinator d8d9845
Fixing API for default case + adding test for it
ycombinator eed5bc5
Fixing copy pasta typos
ycombinator 0a7b85d
Adding TODO
ycombinator b8d029b
Fixing variable name
ycombinator a395c6d
Using a single index
ycombinator 4fb7357
Adding expiration date field
ycombinator 62ae9b3
Adding test for expiration date field
ycombinator a335fea
Ignore non-existent index
ycombinator 75796f2
Fixing logic in test
ycombinator bbf8c11
Creating constant for default enrollment tokens TTL value
ycombinator 0df549b
Updating test
ycombinator File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,3 +5,4 @@ | |
| */ | ||
|
|
||
| export { PLUGIN } from './plugin'; | ||
| export { INDEX_NAMES } from './index_names'; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| export const INDEX_NAMES = { | ||
| BEATS: '.management-beats' | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
x-pack/plugins/beats/server/lib/call_with_request_factory/call_with_request_factory.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| import { once } from 'lodash'; | ||
|
|
||
| const callWithRequest = once((server) => { | ||
| const config = server.config().get('elasticsearch'); | ||
| const cluster = server.plugins.elasticsearch.createCluster('beats', config); | ||
| return cluster.callWithRequest; | ||
| }); | ||
|
|
||
| export const callWithRequestFactory = (server, request) => { | ||
| return (...args) => { | ||
| return callWithRequest(server)(request, ...args); | ||
| }; | ||
| }; |
7 changes: 7 additions & 0 deletions
7
x-pack/plugins/beats/server/lib/call_with_request_factory/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| export { callWithRequestFactory } from './call_with_request_factory'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| export { wrapEsError } from './wrap_es_error'; |
22 changes: 22 additions & 0 deletions
22
x-pack/plugins/beats/server/lib/error_wrappers/wrap_es_error.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| import Boom from 'boom'; | ||
|
|
||
| /** | ||
| * Wraps ES errors into a Boom error response and returns it | ||
| * This also handles the permissions issue gracefully | ||
| * | ||
| * @param err Object ES error | ||
| * @return Object Boom error response | ||
| */ | ||
| export function wrapEsError(err) { | ||
| const statusCode = err.statusCode; | ||
| if (statusCode === 403) { | ||
| return Boom.forbidden('Insufficient user permissions for managing Beats configuration'); | ||
| } | ||
| return Boom.wrap(err, err.statusCode); | ||
| } |
40 changes: 40 additions & 0 deletions
40
x-pack/plugins/beats/server/lib/error_wrappers/wrap_es_error.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| import { wrapEsError } from './wrap_es_error'; | ||
|
|
||
| describe('wrap_es_error', () => { | ||
| describe('#wrapEsError', () => { | ||
|
|
||
| let originalError; | ||
| beforeEach(() => { | ||
| originalError = new Error('I am an error'); | ||
| originalError.statusCode = 404; | ||
| }); | ||
|
|
||
| it('should return a Boom object', () => { | ||
| const wrappedError = wrapEsError(originalError); | ||
|
|
||
| expect(wrappedError.isBoom).to.be(true); | ||
| }); | ||
|
|
||
| it('should return the correct Boom object', () => { | ||
| const wrappedError = wrapEsError(originalError); | ||
|
|
||
| expect(wrappedError.output.statusCode).to.be(originalError.statusCode); | ||
| expect(wrappedError.output.payload.message).to.be(originalError.message); | ||
| }); | ||
|
|
||
| it('should return invalid permissions message for 403 errors', () => { | ||
| const securityError = new Error('I am an error'); | ||
| securityError.statusCode = 403; | ||
| const wrappedError = wrapEsError(securityError); | ||
|
|
||
| expect(wrappedError.isBoom).to.be(true); | ||
| expect(wrappedError.message).to.be('Insufficient user permissions for managing Logstash pipelines'); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| import { registerCreateEnrollmentTokensRoute } from './register_create_enrollment_tokens_route'; | ||
|
|
||
| export function registerApiRoutes(server) { | ||
| registerCreateEnrollmentTokensRoute(server); | ||
| } |
70 changes: 70 additions & 0 deletions
70
x-pack/plugins/beats/server/routes/api/register_create_enrollment_tokens_route.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| import Joi from 'joi'; | ||
| import uuid from 'uuid'; | ||
| import moment from 'moment'; | ||
| import { | ||
| get, | ||
| flatten | ||
| } from 'lodash'; | ||
| import { INDEX_NAMES } from '../../../common/constants'; | ||
| import { callWithRequestFactory } from '../../lib/call_with_request_factory'; | ||
| import { wrapEsError } from '../../lib/error_wrappers'; | ||
|
|
||
| function persistTokens(callWithRequest, tokens, enrollmentTokensTtlInSeconds) { | ||
| const enrollmentTokenExpiration = moment().add(enrollmentTokensTtlInSeconds, 'seconds').toJSON(); | ||
| const body = flatten(tokens.map(token => [ | ||
| { index: { _id: `enrollment_token:${token}` } }, | ||
| { type: 'enrollment_token', enrollment_token: { token, expires_on: enrollmentTokenExpiration } } | ||
| ])); | ||
|
|
||
| const params = { | ||
| index: INDEX_NAMES.BEATS, | ||
| type: '_doc', | ||
| body, | ||
| refresh: 'wait_for' | ||
| }; | ||
|
|
||
| return callWithRequest('bulk', params); | ||
| } | ||
|
|
||
| // TODO: add license check pre-hook | ||
| // TODO: write to Kibana audit log file | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I plan to add audit log functionality across all APIs that need it in a follow up PR. |
||
| export function registerCreateEnrollmentTokensRoute(server) { | ||
| const DEFAULT_NUM_TOKENS = 1; | ||
| const enrollmentTokensTtlInSeconds = server.config().get('xpack.beats.enrollmentTokensTtlInSeconds'); | ||
|
|
||
| server.route({ | ||
| method: 'POST', | ||
| path: '/api/beats/enrollment_tokens', | ||
| config: { | ||
| validate: { | ||
| payload: Joi.object({ | ||
| num_tokens: Joi.number().optional().default(DEFAULT_NUM_TOKENS).min(1) | ||
| }).allow(null) | ||
| } | ||
| }, | ||
| handler: async (request, reply) => { | ||
| const callWithRequest = callWithRequestFactory(server, request); | ||
| const numTokens = get(request, 'payload.num_tokens', DEFAULT_NUM_TOKENS); | ||
|
|
||
| const tokens = []; | ||
| while (tokens.length < numTokens) { | ||
| tokens.push(uuid.v4().replace(/-/g, "")); | ||
| } | ||
|
|
||
| try { | ||
| await persistTokens(callWithRequest, tokens, enrollmentTokensTtlInSeconds); | ||
| } catch (err) { | ||
| return reply(wrapEsError(err)); | ||
| } | ||
|
|
||
| const response = { tokens }; | ||
| reply(response); | ||
| } | ||
| }); | ||
| } | ||
109 changes: 109 additions & 0 deletions
109
x-pack/test/api_integration/apis/beats/create_enrollment_token.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| import expect from 'expect.js'; | ||
| import moment from 'moment'; | ||
|
|
||
| export default function ({ getService }) { | ||
| const supertest = getService('supertest'); | ||
| const chance = getService('chance'); | ||
| const es = getService('es'); | ||
|
|
||
| const ES_INDEX_NAME = '.management-beats'; | ||
| const ES_TYPE_NAME = '_doc'; | ||
|
|
||
| describe('create_enrollment_token', () => { | ||
| const cleanup = () => { | ||
| return es.indices.delete({ | ||
| index: ES_INDEX_NAME, | ||
| ignore: [ 404 ] | ||
| }); | ||
| }; | ||
|
|
||
| beforeEach(cleanup); | ||
| afterEach(cleanup); | ||
|
|
||
| it('should create one token by default', async () => { | ||
| const { body: apiResponse } = await supertest | ||
| .post( | ||
| '/api/beats/enrollment_tokens' | ||
| ) | ||
| .set('kbn-xsrf', 'xxx') | ||
| .send() | ||
| .expect(200); | ||
|
|
||
| const tokensFromApi = apiResponse.tokens; | ||
|
|
||
| const esResponse = await es.search({ | ||
| index: ES_INDEX_NAME, | ||
| type: ES_TYPE_NAME, | ||
| q: 'type:enrollment_token' | ||
| }); | ||
|
|
||
| const tokensInEs = esResponse.hits.hits | ||
| .map(hit => hit._source.enrollment_token.token); | ||
|
|
||
| expect(tokensFromApi.length).to.eql(1); | ||
| expect(tokensFromApi).to.eql(tokensInEs); | ||
| }); | ||
|
|
||
| it('should create the specified number of tokens', async () => { | ||
| const numTokens = chance.integer({ min: 1, max: 2000 }); | ||
|
|
||
| const { body: apiResponse } = await supertest | ||
| .post( | ||
| '/api/beats/enrollment_tokens' | ||
| ) | ||
| .set('kbn-xsrf', 'xxx') | ||
| .send({ | ||
| num_tokens: numTokens | ||
| }) | ||
| .expect(200); | ||
|
|
||
| const tokensFromApi = apiResponse.tokens; | ||
|
|
||
| const esResponse = await es.search({ | ||
| index: ES_INDEX_NAME, | ||
| type: ES_TYPE_NAME, | ||
| q: 'type:enrollment_token', | ||
| size: numTokens | ||
| }); | ||
|
|
||
| const tokensInEs = esResponse.hits.hits | ||
| .map(hit => hit._source.enrollment_token.token); | ||
|
|
||
| expect(tokensFromApi.length).to.eql(numTokens); | ||
| expect(tokensFromApi).to.eql(tokensInEs); | ||
| }); | ||
|
|
||
| it('should set token expiration to 10 minutes from now by default', async () => { | ||
| await supertest | ||
| .post( | ||
| '/api/beats/enrollment_tokens' | ||
| ) | ||
| .set('kbn-xsrf', 'xxx') | ||
| .send() | ||
| .expect(200); | ||
|
|
||
| const esResponse = await es.search({ | ||
| index: ES_INDEX_NAME, | ||
| type: ES_TYPE_NAME, | ||
| q: 'type:enrollment_token' | ||
| }); | ||
|
|
||
| const tokenInEs = esResponse.hits.hits[0]._source.enrollment_token; | ||
|
|
||
| // We do a fuzzy check to see if the token expires between 9 and 10 minutes | ||
| // from now because a bit of time has elapsed been the creation of the | ||
| // tokens and this check. | ||
| const tokenExpiresOn = moment(tokenInEs.expires_on).valueOf(); | ||
| const tenMinutesFromNow = moment().add('10', 'minutes').valueOf(); | ||
| const almostTenMinutesFromNow = moment(tenMinutesFromNow).subtract('2', 'seconds').valueOf(); | ||
| expect(tokenExpiresOn).to.be.lessThan(tenMinutesFromNow); | ||
| expect(tokenExpiresOn).to.be.greaterThan(almostTenMinutesFromNow); | ||
| }); | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License; | ||
| * you may not use this file except in compliance with the Elastic License. | ||
| */ | ||
|
|
||
| export default function ({ loadTestFile }) { | ||
| describe('beats', () => { | ||
| loadTestFile(require.resolve('./create_enrollment_token')); | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I plan to add license checking functionality across all APIs in a follow up PR.