Skip to content

Commit

Permalink
[Spaces] Rework privileges computation for customize selection (#195253)
Browse files Browse the repository at this point in the history
## Summary

This PR reworks how privileges get computed when a user selects the
customize option, and then opts to further customize each available
feature, and is particularly necessary because the previous
implementation for when bulk actions where applied for customization
applied the privilege value on the `base` property instead of on each
feature to further easier customization this in turn resulted in quite
the buggy experience. See visuals below;

## Visuals

### Before

https://github.com/user-attachments/assets/e0bf8c39-5aaf-4489-bfe4-efe4a79650a4

### After


https://github.com/user-attachments/assets/eacbd2db-b9c1-41c2-9c34-8ba21a3f230c
 

<!-- ### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials -->
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
<!--
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
-->

Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
eokoneyo and elasticmachine authored Oct 14, 2024
1 parent 41850b6 commit 87f3c49
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ import {

import { PrivilegesRolesForm } from './space_assign_role_privilege_form';
import type { Space } from '../../../../../common';
import { FEATURE_PRIVILEGES_ALL, FEATURE_PRIVILEGES_READ } from '../../../../../common/constants';
import {
FEATURE_PRIVILEGES_ALL,
FEATURE_PRIVILEGES_CUSTOM,
FEATURE_PRIVILEGES_READ,
} from '../../../../../common/constants';
import { spacesManagerMock } from '../../../../spaces_manager/spaces_manager.mock';
import {
createPrivilegeAPIClientMock,
Expand Down Expand Up @@ -316,6 +320,11 @@ describe('PrivilegesRolesForm', () => {

await userEvent.click(screen.getByTestId('custom-privilege-button'));

expect(screen.getByTestId(`${FEATURE_PRIVILEGES_CUSTOM}-privilege-button`)).toHaveAttribute(
'aria-pressed',
String(true)
);

expect(
screen.getByTestId('space-assign-role-privilege-customization-form')
).toBeInTheDocument();
Expand All @@ -330,5 +339,74 @@ describe('PrivilegesRolesForm', () => {
String(true)
);
});

it('allows modifying individual features after selecting a base privilege within the customize table', async () => {
const user = userEvent.setup();

getRolesSpy.mockResolvedValue([]);
getAllKibanaPrivilegeSpy.mockResolvedValue(createRawKibanaPrivileges(kibanaFeatures));

const featureIds: string[] = kibanaFeatures.map((kibanaFeature) => kibanaFeature.id);

const roles: Role[] = [
createRole('test_role_1', [
{ base: [FEATURE_PRIVILEGES_READ], feature: {}, spaces: [space.id] },
]),
];

renderPrivilegeRolesForm({
preSelectedRoles: roles,
});

await waitFor(() => null);

expect(screen.getByTestId(`${FEATURE_PRIVILEGES_READ}-privilege-button`)).toHaveAttribute(
'aria-pressed',
String(true)
);

await user.click(screen.getByTestId('custom-privilege-button'));

expect(screen.getByTestId(`${FEATURE_PRIVILEGES_CUSTOM}-privilege-button`)).toHaveAttribute(
'aria-pressed',
String(true)
);

expect(
screen.getByTestId('space-assign-role-privilege-customization-form')
).toBeInTheDocument();

// By default all features are set to the none privilege
expect(screen.queryByTestId(`${featureIds[0]}_read`)).not.toHaveAttribute(
'aria-pressed',
String(true)
);

await user.click(screen.getByTestId('changeAllPrivilegesButton'));

// change all privileges to read
await user.click(screen.getByTestId(`changeAllPrivileges-${FEATURE_PRIVILEGES_READ}`));

featureIds.forEach((_, idx) => {
// verify that all features are set to read
expect(screen.queryByTestId(`${featureIds[idx]}_read`)).toHaveAttribute(
'aria-pressed',
String(true)
);
});

// change a single feature to all
await user.click(screen.getByTestId(`${featureIds[0]}_all`));

expect(screen.queryByTestId(`${featureIds[0]}_read`)).not.toHaveAttribute(
'aria-pressed',
String(true)
);

expect(screen.getByTestId(`${featureIds[0]}_all`)).toHaveAttribute(
'aria-pressed',
String(true)
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import type { KibanaFeature, KibanaFeatureConfig } from '@kbn/features-plugin/co
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import { type RawKibanaPrivileges } from '@kbn/security-authorization-core';
import type { Role } from '@kbn/security-plugin-types-common';
import type { Role, RoleKibanaPrivilege } from '@kbn/security-plugin-types-common';
import type { BulkUpdateRoleResponse } from '@kbn/security-plugin-types-public/src/roles/roles_api_client';
import { KibanaPrivileges } from '@kbn/security-role-management-model';
import { KibanaPrivilegeTable, PrivilegeFormCalculator } from '@kbn/security-ui-components';
Expand Down Expand Up @@ -513,10 +513,48 @@ export const PrivilegesRolesForm: FC<PrivilegesRolesFormProps> = (props) => {
// apply selected changes only to the designated customization anchor, this way we delay reconciling the intending privileges
// to all of the selected roles till we decide to commit the changes chosen
setRoleCustomizationAnchor(({ value, privilegeIndex }) => {
let privilege;
let privilege: RoleKibanaPrivilege;

if ((privilege = value!.kibana?.[privilegeIndex!])) {
privilege.base = _privilege;
// empty out base to setup customizing all features
privilege.base = [];

const securedFeatures = new KibanaPrivileges(
kibanaPrivileges,
features
).getSecuredFeatures();

securedFeatures.forEach((feature) => {
const nextFeaturePrivilege = feature
.getPrimaryFeaturePrivileges({
includeMinimalFeaturePrivileges: true,
})
.find((pfp) => {
if (pfp?.disabled || pfp?.requireAllSpaces) {
return false;
}
return Array.isArray(_privilege) && _privilege.includes(pfp.id);
});

let newPrivileges: string[] = [];

if (nextFeaturePrivilege) {
newPrivileges = [nextFeaturePrivilege.id];
feature.getSubFeaturePrivileges().forEach((psf) => {
if (Array.isArray(_privilege) && _privilege.includes(psf.id)) {
if (!psf.requireAllSpaces) {
newPrivileges.push(psf.id);
}
}
});
}

if (newPrivileges.length === 0) {
delete privilege.feature[feature.id];
} else {
privilege.feature[feature.id] = newPrivileges;
}
});
}

return { value, privilegeIndex };
Expand Down

0 comments on commit 87f3c49

Please sign in to comment.