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

Register privileges in Kibana Platform Security plugin and remove legacy getUser API. #65472

Merged
merged 13 commits into from
Jun 5, 2020
Merged
Show file tree
Hide file tree
Changes from 10 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
2 changes: 1 addition & 1 deletion .sass-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ files:
- 'src/legacy/core_plugins/timelion/**/*.s+(a|c)ss'
- 'src/plugins/vis_type_vislib/**/*.s+(a|c)ss'
- 'src/plugins/vis_type_xy/**/*.s+(a|c)ss'
- 'x-pack/legacy/plugins/security/**/*.s+(a|c)ss'
- 'x-pack/plugins/canvas/**/*.s+(a|c)ss'
- 'x-pack/plugins/triggers_actions_ui/**/*.s+(a|c)ss'
- 'x-pack/plugins/lens/**/*.s+(a|c)ss'
- 'x-pack/plugins/cross_cluster_replication/**/*.s+(a|c)ss'
- 'x-pack/legacy/plugins/maps/**/*.s+(a|c)ss'
- 'x-pack/plugins/maps/**/*.s+(a|c)ss'
- 'x-pack/plugins/spaces/**/*.s+(a|c)ss'
- 'x-pack/plugins/security/**/*.s+(a|c)ss'
ignore:
- 'x-pack/plugins/canvas/shareable_runtime/**/*.s+(a|c)ss'
rules:
Expand Down
2 changes: 1 addition & 1 deletion x-pack/.i18nrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"xpack.reporting": ["plugins/reporting"],
"xpack.rollupJobs": ["legacy/plugins/rollup", "plugins/rollup"],
"xpack.searchProfiler": "plugins/searchprofiler",
"xpack.security": ["legacy/plugins/security", "plugins/security"],
"xpack.security": "plugins/security",
"xpack.server": "legacy/server",
"xpack.siem": "plugins/siem",
"xpack.snapshotRestore": "plugins/snapshot_restore",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { Lifecycle, ResponseToolkit } from 'hapi';
import * as t from 'io-ts';
import { SecurityPluginSetup } from '../../../../../../../plugins/security/server';
import { LicenseType } from '../../../../common/constants/security';

export const internalAuthData = Symbol('internalAuthData');
Expand Down Expand Up @@ -39,6 +40,11 @@ export interface BackendFrameworkAdapter {
}

export interface KibanaLegacyServer {
newPlatform: {
setup: {
plugins: { security: SecurityPluginSetup };
};
};
plugins: {
xpack_main: {
status: {
Expand All @@ -53,9 +59,6 @@ export interface KibanaLegacyServer {
};
};
};
security: {
getUser: (request: KibanaServerRequest) => any;
};
elasticsearch: {
status: {
on: (status: 'green' | 'yellow' | 'red', callback: () => void) => void;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ResponseToolkit } from 'hapi';
import { PathReporter } from 'io-ts/lib/PathReporter';
import { get } from 'lodash';
import { isLeft } from 'fp-ts/lib/Either';
import { KibanaRequest, LegacyRequest } from '../../../../../../../../src/core/server';
// @ts-ignore
import { mirrorPluginStatus } from '../../../../../../server/lib/mirror_plugin_status';
import {
Expand Down Expand Up @@ -128,13 +129,10 @@ export class KibanaBackendFrameworkAdapter implements BackendFrameworkAdapter {
}

private async getUser(request: KibanaServerRequest): Promise<KibanaUser | null> {
let user;
try {
user = await this.server.plugins.security.getUser(request);
} catch (e) {
return null;
}
if (user === null) {
const user = this.server.newPlatform.setup.plugins.security?.authc.getCurrentUser(
KibanaRequest.from((request as unknown) as LegacyRequest)
);
if (!user) {
return null;
}
const assertKibanaUser = RuntimeKibanaUser.decode(user);
Expand Down
59 changes: 6 additions & 53 deletions x-pack/legacy/plugins/security/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,64 +6,17 @@

import { Root } from 'joi';
import { resolve } from 'path';
import { Server } from 'src/legacy/server/kbn_server';
import { KibanaRequest, LegacyRequest } from '../../../../src/core/server';
// @ts-ignore
import { watchStatusAndLicenseToInitialize } from '../../server/lib/watch_status_and_license_to_initialize';
import { AuthenticatedUser, SecurityPluginSetup } from '../../../plugins/security/server';

/**
* Public interface of the security plugin.
*/
export interface SecurityPlugin {
getUser: (request: LegacyRequest) => Promise<AuthenticatedUser>;
}

function getSecurityPluginSetup(server: Server) {
const securityPlugin = server.newPlatform.setup.plugins.security as SecurityPluginSetup;
if (!securityPlugin) {
throw new Error('Kibana Platform Security plugin is not available.');
}

return securityPlugin;
}

export const security = (kibana: Record<string, any>) =>
new kibana.Plugin({
id: 'security',
publicDir: resolve(__dirname, 'public'),
require: ['kibana', 'xpack_main'],
require: ['kibana'],
configPrefix: 'xpack.security',
uiExports: {
hacks: ['plugins/security/hacks/legacy'],
injectDefaultVars: (server: Server) => {
return { enableSpaceAwarePrivileges: server.config().get('xpack.spaces.enabled') };
},
},

config(Joi: Root) {
return Joi.object({
enabled: Joi.boolean().default(true),
})
uiExports: { hacks: ['plugins/security/hacks/legacy'] },
config: (Joi: Root) =>
Joi.object({ enabled: Joi.boolean().default(true) })
.unknown()
.default();
},

async postInit(server: Server) {
watchStatusAndLicenseToInitialize(server.plugins.xpack_main, this, async () => {
const xpackInfo = server.plugins.xpack_main.info;
if (xpackInfo.isAvailable() && xpackInfo.feature('security').isEnabled()) {
await getSecurityPluginSetup(server).__legacyCompat.registerPrivilegesWithCluster();
}
});
},

async init(server: Server) {
const securityPlugin = getSecurityPluginSetup(server);

server.expose({
getUser: async (request: LegacyRequest) =>
securityPlugin.authc.getCurrentUser(KibanaRequest.from(request)),
});
},
.default(),
init() {},
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
*/

import { i18n } from '@kbn/i18n';
import { StartServicesAccessor, ApplicationSetup, AppMountParameters } from 'src/core/public';
import {
ApplicationSetup,
AppMountParameters,
AppNavLinkStatus,
StartServicesAccessor,
} from '../../../../../src/core/public';
import { AuthenticationServiceSetup } from '../authentication';

interface CreateDeps {
Expand All @@ -23,8 +28,7 @@ export const accountManagementApp = Object.freeze({
application.register({
id: this.id,
title,
// TODO: switch to proper enum once https://github.com/elastic/kibana/issues/58327 is resolved.
navLinkStatus: 3,
navLinkStatus: AppNavLinkStatus.hidden,
appRoute: '/security/account',
async mount({ element }: AppMountParameters) {
const [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@
}

&:focus {
@include euiFocusRing;

border-color: transparent;
border-radius: $euiBorderRadius;
@include euiFocusRing;

.secLoginCard__title {
text-decoration: underline;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import { Feature } from '../../../../../features/public';
import { KibanaPrivileges } from '../model';
import { SecurityLicenseFeatures } from '../../..';

// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { featuresPluginMock } from '../../../../../features/server/mocks';

export const createRawKibanaPrivileges = (
features: Feature[],
{ allowSubFeaturePrivileges = true } = {}
) => {
const featuresService = {
getFeatures: () => features,
};
const featuresService = featuresPluginMock.createSetup();
featuresService.getFeatures.mockReturnValue(features);

const licensingService = {
getFeatures: () => ({ allowSubFeaturePrivileges } as SecurityLicenseFeatures),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,12 @@ function getProps({
const { http, docLinks, notifications } = coreMock.createStart();
http.get.mockImplementation(async (path: any) => {
if (path === '/api/spaces/space') {
return buildSpaces();
if (spacesEnabled) {
return buildSpaces();
}

const notFoundError = { response: { status: 404 } };
throw notFoundError;
}
});

Expand All @@ -181,7 +186,6 @@ function getProps({
notifications,
docLinks: new DocumentationLinksService(docLinks),
fatalErrors,
spacesEnabled,
uiCapabilities: buildUICapabilities(canManageSpaces),
history: (scopedHistoryMock.create() as unknown) as ScopedHistory,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ interface Props {
docLinks: DocumentationLinksService;
http: HttpStart;
license: SecurityLicense;
spacesEnabled: boolean;
uiCapabilities: Capabilities;
notifications: NotificationsStart;
fatalErrors: FatalErrorsSetup;
Expand Down Expand Up @@ -225,14 +224,21 @@ function useRole(
return [role, setRole] as [Role | null, typeof setRole];
}

function useSpaces(http: HttpStart, fatalErrors: FatalErrorsSetup, spacesEnabled: boolean) {
const [spaces, setSpaces] = useState<Space[] | null>(null);
function useSpaces(http: HttpStart, fatalErrors: FatalErrorsSetup) {
const [spaces, setSpaces] = useState<{ enabled: boolean; list: Space[] } | null>(null);
useEffect(() => {
(spacesEnabled ? http.get('/api/spaces/space') : Promise.resolve([])).then(
(fetchedSpaces) => setSpaces(fetchedSpaces),
(err) => fatalErrors.add(err)
http.get('/api/spaces/space').then(
(fetchedSpaces) => setSpaces({ enabled: true, list: fetchedSpaces }),
(err: IHttpFetchError) => {
// Spaces plugin can be disabled and hence this endpoint can be unavailable.
if (err.response?.status === 404) {
Copy link
Member Author

Choose a reason for hiding this comment

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

note: I moved this change to a separate commit as I want to hear your thoughts. It's "the least evil" solution I could come up with. Alternatively we can introduce an endpoint that will return isSpacesEnabled only based on the "Spaces Service" that Spaces registers with Security during setup.

Copy link
Member

Choose a reason for hiding this comment

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

I think this is tolerable. I think it'd make sense (in a followup) for us to export a useSpaces hook from the Spaces plugin itself, so that we could at least have the Spaces plugin own this determination.

The disabled check aside, I could see other plugins benefiting from this hook too.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, I agree

setSpaces({ enabled: false, list: [] });
} else {
fatalErrors.add(err);
}
}
);
}, [http, fatalErrors, spacesEnabled]);
}, [http, fatalErrors]);

return spaces;
}
Expand Down Expand Up @@ -278,7 +284,6 @@ export const EditRolePage: FunctionComponent<Props> = ({
roleName,
action,
fatalErrors,
spacesEnabled,
license,
docLinks,
uiCapabilities,
Expand All @@ -295,7 +300,7 @@ export const EditRolePage: FunctionComponent<Props> = ({
const runAsUsers = useRunAsUsers(userAPIClient, fatalErrors);
const indexPatternsTitles = useIndexPatternsTitles(indexPatterns, fatalErrors, notifications);
const privileges = usePrivileges(privilegesAPIClient, fatalErrors);
const spaces = useSpaces(http, fatalErrors, spacesEnabled);
const spaces = useSpaces(http, fatalErrors);
const features = useFeatures(getFeatures, fatalErrors);
const [role, setRole] = useRole(
rolesAPIClient,
Expand Down Expand Up @@ -434,8 +439,8 @@ export const EditRolePage: FunctionComponent<Props> = ({
<EuiSpacer />
<KibanaPrivilegesRegion
kibanaPrivileges={new KibanaPrivileges(kibanaPrivileges, features)}
spaces={spaces}
spacesEnabled={spacesEnabled}
spaces={spaces.list}
spacesEnabled={spaces.enabled}
uiCapabilities={uiCapabilities}
canCustomizeSubFeaturePrivileges={license.getFeatures().allowSubFeaturePrivileges}
editable={!isRoleReadOnly}
Expand Down Expand Up @@ -519,7 +524,7 @@ export const EditRolePage: FunctionComponent<Props> = ({
setFormError(null);

try {
await rolesAPIClient.saveRole({ role, spacesEnabled });
await rolesAPIClient.saveRole({ role, spacesEnabled: spaces.enabled });
} catch (error) {
notifications.toasts.addDanger(get(error, 'data.message'));
return;
Expand Down Expand Up @@ -554,7 +559,7 @@ export const EditRolePage: FunctionComponent<Props> = ({
backToRoleList();
};

const description = spacesEnabled ? (
const description = spaces.enabled ? (
<FormattedMessage
id="xpack.security.management.editRole.setPrivilegesToKibanaSpacesDescription"
defaultMessage="Set privileges on your Elasticsearch data and control access to your Kibana spaces."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ export const rolesManagementApp = Object.freeze({
];

const [
[
{ application, docLinks, http, i18n: i18nStart, injectedMetadata, notifications },
{ data, features },
],
[{ application, docLinks, http, i18n: i18nStart, notifications }, { data, features }],
{ RolesGridPage },
{ EditRolePage },
{ RolesAPIClient },
Expand Down Expand Up @@ -86,9 +83,6 @@ export const rolesManagementApp = Object.freeze({
<EditRolePage
action={action}
roleName={roleName}
spacesEnabled={
injectedMetadata.getInjectedVar('enableSpaceAwarePrivileges') as boolean
}
rolesAPIClient={rolesAPIClient}
userAPIClient={new UserAPIClient(http)}
indicesAPIClient={new IndicesAPIClient(http)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { CoreSetup, Logger } from '../../../../../src/core/server';
import { Authorization } from '.';
import { HttpServiceSetup, Logger } from '../../../../../src/core/server';
import { AuthorizationServiceSetup } from '.';

export function initAPIAuthorization(
http: CoreSetup['http'],
{ actions, checkPrivilegesDynamicallyWithRequest, mode }: Authorization,
http: HttpServiceSetup,
{ actions, checkPrivilegesDynamicallyWithRequest, mode }: AuthorizationServiceSetup,
logger: Logger
) {
http.registerOnPostAuth(async (request, response, toolkit) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { CoreSetup, Logger } from '../../../../../src/core/server';
import { FeaturesService } from '../plugin';
import { Authorization } from '.';
import { HttpServiceSetup, Logger } from '../../../../../src/core/server';
import { PluginSetupContract as FeaturesPluginSetup } from '../../../features/server';
import { AuthorizationServiceSetup } from '.';

class ProtectedApplications {
private applications: Set<string> | null = null;
constructor(private readonly featuresService: FeaturesService) {}
constructor(private readonly featuresService: FeaturesPluginSetup) {}

public shouldProtect(appId: string) {
// Currently, once we get the list of features we essentially "lock" additional
Expand All @@ -30,14 +30,14 @@ class ProtectedApplications {
}

export function initAppAuthorization(
http: CoreSetup['http'],
http: HttpServiceSetup,
{
actions,
checkPrivilegesDynamicallyWithRequest,
mode,
}: Pick<Authorization, 'actions' | 'checkPrivilegesDynamicallyWithRequest' | 'mode'>,
}: Pick<AuthorizationServiceSetup, 'actions' | 'checkPrivilegesDynamicallyWithRequest' | 'mode'>,
logger: Logger,
featuresService: FeaturesService
featuresService: FeaturesPluginSetup
) {
const protectedApplications = new ProtectedApplications(featuresService);

Expand Down
Loading