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

Deriving application from Kibana index #20614

Merged
merged 3 commits into from
Jul 10, 2018
Merged
Show file tree
Hide file tree
Changes from 2 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
19 changes: 10 additions & 9 deletions x-pack/plugins/security/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,11 @@ export const security = (kibana) => new kibana.Plugin({
injectDefaultVars: function (server) {
const config = server.config();

const { authorization } = server.plugins.security;
return {
secureCookies: config.get('xpack.security.secureCookies'),
sessionTimeout: config.get('xpack.security.sessionTimeout'),
rbacApplication: config.get('xpack.security.rbac.application'),
rbacApplication: authorization.application,
};
}
},
Expand All @@ -97,12 +98,6 @@ export const security = (kibana) => new kibana.Plugin({
// to re-compute the license check results for this plugin
xpackInfoFeature.registerLicenseCheckResultsGenerator(checkLicense);

watchStatusAndLicenseToInitialize(xpackMainPlugin, plugin, async (license) => {
if (license.allowRbac) {
await registerPrivilegesWithCluster(server);
}
});

validateConfig(config, message => server.log(['security', 'warning'], message));

// Create a Hapi auth scheme that should be applied to each request.
Expand All @@ -112,11 +107,17 @@ export const security = (kibana) => new kibana.Plugin({
// automatically assigned to all routes that don't contain an auth config.
server.auth.strategy('session', 'login', 'required');

const auditLogger = new SecurityAuditLogger(server.config(), new AuditLogger(server, 'security'));

// exposes server.plugins.security.authorization
initAuthorizationService(server);

watchStatusAndLicenseToInitialize(xpackMainPlugin, plugin, async (license) => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved this because the registerPrivilegesWithCluster function is now dependent on the server.plugins.authorization that initAuthorizationService exposes.

if (license.allowRbac) {
await registerPrivilegesWithCluster(server);
}
});

const auditLogger = new SecurityAuditLogger(server.config(), new AuditLogger(server, 'security'));

const { savedObjects } = server;
savedObjects.setScopedSavedObjectsClientFactory(({
request,
Expand Down
16 changes: 0 additions & 16 deletions x-pack/plugins/security/server/lib/__tests__/validate_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,20 +75,4 @@ describe('Validate config', function () {
sinon.assert.calledWith(config.set, 'xpack.security.secureCookies', true);
sinon.assert.notCalled(log);
});

it('should throw error if xpack.security.rbac.application is the default when kibana.index is set', function () {
// other valid keys that we need
config.get.withArgs('server.ssl.key').returns('foo');
config.get.withArgs('server.ssl.certificate').returns('bar');
config.get.withArgs('xpack.security.encryptionKey').returns(validKey);

config.get.withArgs('kibana.index').returns('notDefaultIndex');
config.get.withArgs('xpack.security.rbac.application').returns('defaultApplication');
config.getDefault.withArgs('kibana.index').returns('defaultIndex');
config.getDefault.withArgs('xpack.security.rbac.application').returns('defaultApplication');

expect(() => validateConfig(config, log)).to.throwError();

sinon.assert.notCalled(log);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ exports[`deep freezes exposed service 1`] = `"Cannot delete property 'checkPrivi
exports[`deep freezes exposed service 2`] = `"Cannot add property foo, object is not extensible"`;

exports[`deep freezes exposed service 3`] = `"Cannot assign to read only property 'login' of object '#<Object>'"`;

exports[`deep freezes exposed service 4`] = `"Cannot assign to read only property 'application' of object '#<Object>'"`;
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ export const CHECK_PRIVILEGES_RESULT = {
LEGACY: Symbol('Legacy'),
};

export function checkPrivilegesWithRequestFactory(shieldClient, config, actions) {
export function checkPrivilegesWithRequestFactory(shieldClient, config, actions, application) {
const { callWithRequest } = shieldClient;

const application = config.get('xpack.security.rbac.application');
const kibanaIndex = config.get('kibana.index');

const hasIncompatibileVersion = (applicationPrivilegesResponse) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { checkPrivilegesWithRequestFactory, CHECK_PRIVILEGES_RESULT } from './ch

import { ALL_RESOURCE } from '../../../common/constants';

const application = 'kibana-our_application';
const defaultVersion = 'default-version';
const defaultApplication = 'default-application';
const defaultKibanaIndex = 'default-index';
const savedObjectTypes = ['foo-type', 'bar-type'];

Expand All @@ -26,7 +26,6 @@ const createMockConfig = ({ settings = {} } = {}) => {

const defaultSettings = {
'pkg.version': defaultVersion,
'xpack.security.rbac.application': defaultApplication,
'kibana.index': defaultKibanaIndex,
};

Expand Down Expand Up @@ -63,7 +62,7 @@ const checkPrivilegesTest = (
const mockShieldClient = createMockShieldClient({
username,
application: {
[defaultApplication]: {
[application]: {
[ALL_RESOURCE]: applicationPrivilegesResponse
}
},
Expand All @@ -72,7 +71,7 @@ const checkPrivilegesTest = (
},
});

const checkPrivilegesWithRequest = checkPrivilegesWithRequestFactory(mockShieldClient, mockConfig, mockActions);
const checkPrivilegesWithRequest = checkPrivilegesWithRequestFactory(mockShieldClient, mockConfig, mockActions, application);
const request = Symbol();
const checkPrivileges = checkPrivilegesWithRequest(request);

Expand All @@ -88,7 +87,7 @@ const checkPrivilegesTest = (
expect(mockShieldClient.callWithRequest).toHaveBeenCalledWith(request, 'shield.hasPrivileges', {
body: {
applications: [{
application: defaultApplication,
application: application,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

uber nit: can simplify to just application,

resources: [ALL_RESOURCE],
privileges: uniq([
mockActions.version, mockActions.login, ...privileges
Expand Down
6 changes: 4 additions & 2 deletions x-pack/plugins/security/server/lib/authorization/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ export function initAuthorizationService(server) {
const config = server.config();

const actions = actionsFactory(config);
const application = `kibana-${config.get('kibana.index')}`;

server.expose('authorization', deepFreeze({
checkPrivilegesWithRequest: checkPrivilegesWithRequestFactory(shieldClient, config, actions),
actions
actions,
application,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's the little things in life, but I like this abstraction 😎

checkPrivilegesWithRequest: checkPrivilegesWithRequestFactory(shieldClient, config, actions, application),
}));
}
27 changes: 23 additions & 4 deletions x-pack/plugins/security/server/lib/authorization/init.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,21 @@ jest.mock('./actions', () => ({
actionsFactory: jest.fn(),
}));

const createMockConfig = (settings = {}) => {
const mockConfig = {
get: jest.fn()
};

mockConfig.get.mockImplementation(key => settings[key]);

return mockConfig;
};

test(`calls server.expose with exposed services`, () => {
const mockConfig = Symbol();
const kibanaIndex = '.a-kibana-index';
const mockConfig = createMockConfig({
'kibana.index': kibanaIndex
});
const mockServer = {
expose: jest.fn(),
config: jest.fn().mockReturnValue(mockConfig)
Expand All @@ -33,20 +46,25 @@ test(`calls server.expose with exposed services`, () => {
checkPrivilegesWithRequestFactory.mockReturnValue(mockCheckPrivilegesWithRequest);
const mockActions = Symbol();
actionsFactory.mockReturnValue(mockActions);
mockConfig.get.mock;

initAuthorizationService(mockServer);

const application = `kibana-${kibanaIndex}`;
expect(getClient).toHaveBeenCalledWith(mockServer);
expect(actionsFactory).toHaveBeenCalledWith(mockConfig);
expect(checkPrivilegesWithRequestFactory).toHaveBeenCalledWith(mockShieldClient, mockConfig, mockActions);
expect(checkPrivilegesWithRequestFactory).toHaveBeenCalledWith(mockShieldClient, mockConfig, mockActions, application);
expect(mockServer.expose).toHaveBeenCalledWith('authorization', {
checkPrivilegesWithRequest: mockCheckPrivilegesWithRequest,
actions: mockActions,
application,
checkPrivilegesWithRequest: mockCheckPrivilegesWithRequest,
});
});

test(`deep freezes exposed service`, () => {
const mockConfig = Symbol();
const mockConfig = createMockConfig({
'kibana.index': ''
});
const mockServer = {
expose: jest.fn(),
config: jest.fn().mockReturnValue(mockConfig)
Expand All @@ -61,4 +79,5 @@ test(`deep freezes exposed service`, () => {
expect(() => delete exposed.checkPrivilegesWithRequest).toThrowErrorMatchingSnapshot();
expect(() => exposed.foo = 'bar').toThrowErrorMatchingSnapshot();
expect(() => exposed.actions.login = 'not-login').toThrowErrorMatchingSnapshot();
expect(() => exposed.application = 'changed').toThrowErrorMatchingSnapshot();
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,12 @@
import { difference, isEmpty, isEqual } from 'lodash';
import { buildPrivilegeMap } from './privileges';
import { getClient } from '../../../../../server/lib/get_client_shield';
import { actionsFactory } from './actions';



export async function registerPrivilegesWithCluster(server) {
const config = server.config();

const actions = actionsFactory(config);
const application = config.get('xpack.security.rbac.application');
const savedObjectTypes = server.savedObjects.types;
const { authorization } = server.plugins.security;
const { types: savedObjectTypes } = server.savedObjects;
const { actions, application } = authorization;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we could simplify the destructuring here by passing plugin as a second argument, then this just becomes const { actions, application } = plugin.authorization. Feel free to ignore me here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm gonna leave this alone for now... I really dislike having this dependent on the whole server, and would prefer that we pass in the explicit dependencies, and we can address it at this point.


const shouldRemovePrivileges = (existingPrivileges, expectedPrivileges) => {
if (isEmpty(existingPrivileges)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,16 @@
import { registerPrivilegesWithCluster } from './register_privileges_with_cluster';
import { getClient } from '../../../../../server/lib/get_client_shield';
import { buildPrivilegeMap } from './privileges';
import { actionsFactory } from './actions';
jest.mock('../../../../../server/lib/get_client_shield', () => ({
getClient: jest.fn(),
}));
jest.mock('./privileges', () => ({
buildPrivilegeMap: jest.fn(),
}));
jest.mock('./actions', () => ({
actionsFactory: jest.fn(),
}));

const registerPrivilegesWithClusterTest = (description, {
settings = {},
savedObjectTypes,
actions,
expectedPrivileges,
existingPrivileges,
throwErrorWhenGettingPrivileges,
Expand All @@ -37,19 +32,26 @@ const registerPrivilegesWithClusterTest = (description, {
};

const defaultVersion = 'default-version';
const defaultApplication = 'default-application';
const application = 'default-application';

const createMockServer = () => {
const mockServer = {
config: jest.fn().mockReturnValue({
get: jest.fn(),
}),
log: jest.fn(),
plugins: {
security: {
authorization: {
actions: Symbol(),
application
}
}
}
};

const defaultSettings = {
'pkg.version': defaultVersion,
'xpack.security.rbac.application': defaultApplication,
};

mockServer.config().get.mockImplementation(key => {
Expand All @@ -68,18 +70,17 @@ const registerPrivilegesWithClusterTest = (description, {
expect(error).toBeUndefined();
expect(mockCallWithInternalUser).toHaveBeenCalledTimes(2);
expect(mockCallWithInternalUser).toHaveBeenCalledWith('shield.getPrivilege', {
privilege: defaultApplication,
privilege: application,
});
expect(mockCallWithInternalUser).toHaveBeenCalledWith(
'shield.postPrivileges',
{
body: {
[defaultApplication]: privileges
[application]: privileges
},
}
);

const application = settings['xpack.security.rbac.application'] || defaultApplication;
expect(mockServer.log).toHaveBeenCalledWith(
['security', 'debug'],
`Registering Kibana Privileges with Elasticsearch for ${application}`
Expand All @@ -96,10 +97,9 @@ const registerPrivilegesWithClusterTest = (description, {
expect(error).toBeUndefined();
expect(mockCallWithInternalUser).toHaveBeenCalledTimes(1);
expect(mockCallWithInternalUser).toHaveBeenLastCalledWith('shield.getPrivilege', {
privilege: defaultApplication
privilege: application
});

const application = settings['xpack.security.rbac.application'] || defaultApplication;
expect(mockServer.log).toHaveBeenCalledWith(
['security', 'debug'],
`Registering Kibana Privileges with Elasticsearch for ${application}`
Expand All @@ -117,7 +117,6 @@ const registerPrivilegesWithClusterTest = (description, {
expect(actualError).toBeInstanceOf(Error);
expect(actualError.message).toEqual(expectedErrorMessage);

const application = settings['xpack.security.rbac.application'] || defaultApplication;
expect(mockServer.log).toHaveBeenCalledWith(
['security', 'error'],
`Error registering Kibana Privileges with Elasticsearch for ${application}: ${expectedErrorMessage}`
Expand All @@ -139,7 +138,7 @@ const registerPrivilegesWithClusterTest = (description, {
}

return {
[defaultApplication]: existingPrivileges
[application]: existingPrivileges
};
})
.mockImplementationOnce(async () => {
Expand All @@ -148,7 +147,6 @@ const registerPrivilegesWithClusterTest = (description, {
}
});

actionsFactory.mockReturnValue(actions);
buildPrivilegeMap.mockReturnValue(expectedPrivileges);

let error;
Expand All @@ -163,30 +161,27 @@ const registerPrivilegesWithClusterTest = (description, {
expectDidntUpdatePrivileges: createExpectDidntUpdatePrivileges(mockServer, mockCallWithInternalUser, error),
expectErrorThrown: createExpectErrorThrown(mockServer, error),
mocks: {
buildPrivilegeMap
buildPrivilegeMap,
server: mockServer,
}
});
});
};

registerPrivilegesWithClusterTest(`passes saved object types, application and actions to buildPrivilegeMap`, {
settings: {
'pkg.version': 'foo-version',
'xpack.security.rbac.application': 'foo-application',
'pkg.version': 'foo-version'
},
savedObjectTypes: [
'foo-type',
'bar-type',
],
actions: {
login: 'mock-action:login',
version: 'mock-action:version',
},
assert: ({ mocks }) => {
expect(mocks.buildPrivilegeMap).toHaveBeenCalledWith(['foo-type', 'bar-type'], 'foo-application', {
login: 'mock-action:login',
version: 'mock-action:version',
});
expect(mocks.buildPrivilegeMap).toHaveBeenCalledWith(
['foo-type', 'bar-type'],
mocks.server.plugins.security.authorization.application,
mocks.server.plugins.security.authorization.actions,
);
},
});

Expand Down
8 changes: 0 additions & 8 deletions x-pack/plugins/security/server/lib/validate_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@

const crypto = require('crypto');

const isDefault = (config, key) => {
return config.getDefault(key) === config.get(key);
};

export function validateConfig(config, log) {
if (config.get('xpack.security.encryptionKey') == null) {
log('Generating a random key for xpack.security.encryptionKey. To prevent sessions from being invalidated on ' +
Expand All @@ -31,8 +27,4 @@ export function validateConfig(config, log) {
} else {
config.set('xpack.security.secureCookies', true);
}

if (!isDefault(config, 'kibana.index') && isDefault(config, 'xpack.security.rbac.application')) {
throw new Error('When setting kibana.index, xpack.security.rbac.application must be set as well.');
}
}
Loading