refactor: 💡 role grants tab to use code block (#3261)

* refactor: 💡 grants tab to use code block

* refactor: 💡 update getter comment

* test: 💍 fix tests

* refactor: 💡 remove language arg for codeblock

✅ Closes: https://hashicorp.atlassian.net/browse/ICU-18757
This commit is contained in:
Lisbet Alvarez authored and Zhihe Li committed 2026-05-14 15:21:29 -04:00
1 parent 990146fa34
commit 1a8c895ea9
12 files changed
+76 -480

No files matched your search

+13 -4
View File
@@ -64,12 +64,21 @@ export class RolesPage extends BaseResourcePage {
*/
async addGrantsToRole(grants) {
await this.page.getByRole('link', { name: 'Grants', exact: true }).click();
await this.page.getByRole('textbox', { name: 'New Grant' }).fill(grants);
await this.page.getByRole('button', { name: 'Add', exact: true }).click();
await this.page
.getByRole('link', { name: 'Edit Grants', exact: true })
.click();
await this.page.locator('.hds-code-editor').getByRole('textbox').click();
await expect(
this.page.locator('.hds-code-editor').getByRole('textbox'),
).toBeFocused();
await this.page
.locator('.hds-code-editor')
.getByRole('textbox')
.fill(grants);
await this.page.getByRole('button', { name: 'Save', exact: true }).click();
await this.dismissSuccessAlert();
await expect(
this.page.getByRole('textbox', { name: 'Grant', exact: true }),
).toHaveValue(grants);
this.page.locator('.grant-codeblock .hds-code-block__code'),
).toHaveText(grants);
}
}
@@ -3,91 +3,27 @@
SPDX-License-Identifier: BUSL-1.1
}}
{{#if (can 'setGrants role' @model)}}
<Rose::Form
@onSubmit={{fn this.createGrant @addGrant}}
@cancel={{@cancel}}
@disabled={{@model.isSaving}}
>
<Rose::List::KeyValue as |list|>
{{! Add grant field (only one per form) }}
<list.item as |item|>
<item.key>
<Hds::Form::Label @controlId='add-grant'>
{{t 'resources.role.grant.actions.create'}}
</Hds::Form::Label>
</item.key>
<item.cell>
<Hds::Form::TextInput::Field
{{on 'input' (set-from-event this 'newGrantString')}}
name='grant'
title={{t 'form.grant.help'}}
@id='add-grant'
@type='text'
@value={{this.newGrantString}}
/>
</item.cell>
<item.cell>
<Hds::Button
disabled={{this.cannotSave}}
type='submit'
@color='secondary'
@text={{t 'actions.add'}}
/>
</item.cell>
</list.item>
</Rose::List::KeyValue>
</Rose::Form>
{{/if}}
<Rose::Form
@onSubmit={{fn @submit this.grantStrings}}
@cancel={{@cancel}}
@disabled={{@model.isSaving}}
as |form|
>
<Rose::List::KeyValue as |list|>
{{#each this.grants as |grant index|}}
<list.item as |item|>
<item.key>
<Hds::Form::Label @controlId='update-grant-{{index}}'>
{{t 'form.grant.label'}}
</Hds::Form::Label>
</item.key>
<item.cell>
<Hds::Form::TextInput::Field
{{on 'input' (set-from-event grant 'value')}}
name='grant'
title={{t 'form.grant.help'}}
disabled={{if (can 'setGrants role' @model) false true}}
@id='update-grant-{{index}}'
@type='text'
@value={{grant.value}}
@error={{@model.errors.grant_strings}}
/>
</item.cell>
<item.cell>
{{#if (can 'setGrants role' @model)}}
<Hds::Button
{{on 'click' (fn @removeGrant grant.value)}}
type='button'
@color='secondary'
@icon='trash'
@isIconOnly={{true}}
@text={{t 'actions.remove'}}
/>
{{/if}}
</item.cell>
</list.item>
{{/each}}
</Rose::List::KeyValue>
{{#if (can 'setGrants role' @model)}}
<form.actions
@submitText={{t 'actions.save'}}
@cancelText={{t 'actions.cancel'}}
<Hds::Layout::Flex as |F|>
<F.Item @basis='66%'>
<Hds::CodeBlock
class='grant-codeblock'
@ariaLabel={{t 'resources.role.grant-templates.titles.grant-strings'}}
@value={{this.grants}}
/>
{{/if}}
</F.Item>
</Hds::Layout::Flex>
</Rose::Form>
{{#if (can 'setGrants role' @model)}}
<Hds::ButtonSet class='margin-top-l' data-test-grants-btns>
<Hds::Button
@text={{t 'resources.role.edit-grants.title'}}
@color='secondary'
@route='scopes.scope.roles.role.edit-grants'
/>
<Hds::Button
@text={{t 'resources.role.grant-templates.actions.add-grant-templates'}}
@color='secondary'
@route='scopes.scope.roles.role.add-grant-templates'
/>
</Hds::ButtonSet>
{{/if}}
@@ -4,58 +4,15 @@
*/
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { computed, action } from '@ember/object';
export default class FormRoleGrantsComponent extends Component {
// =attributes
/**
* @type {string}
* Returns grants currently saved on a role
* @return {string}
*/
@tracked newGrantString = '';
/**
* Returns grants currently on model, in addition to
* grants added (or deleted) interactively by user -
* before form submission
* @return {[string]}
*/
@computed('args.model.grant_strings.[]')
get grants() {
return this.args.model.grant_strings.map((value) => ({ value }));
}
/**
* Returns grants after form submission
* @return {[object]}
*/
@computed('grants.@each.value')
get grantStrings() {
return this.grants.map((obj) => obj.value);
}
/**
* True if the grant string field is empty, false otherwise. This is used
* to disable the submit button.
* @return {boolean}
*/
@computed('newGrantString')
get cannotSave() {
return !this.newGrantString;
}
// =actions
/**
* Calls the passed function with the grant string as an argument and then
* clears the value of the grant string field.
* `@addGrant` should be passed by the context calling this component.
* @param {Function} addGrantFn
*/
@action
createGrant(addGrantFn) {
addGrantFn(this.newGrantString);
this.newGrantString = '';
return this.args.model.grant_strings.join('\n');
}
}
@@ -33,7 +33,7 @@ export default class ScopesScopeRolesRoleAddGrantTemplatesController extends Con
async addGrantTemplates(role, grantTemplates) {
// Add the grant templates to the role's grant_strings without saving yet
// Note that we transition first to avoid a discard changes confirmation
this.router.replaceWith('scopes.scope.roles.role.grants');
this.router.replaceWith('scopes.scope.roles.role.edit-grants');
role.grant_strings = [...role.grant_strings, ...grantTemplates];
}
@@ -4,65 +4,7 @@
*/
import Controller, { inject as controller } from '@ember/controller';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { loading } from 'ember-loading';
import { notifySuccess, notifyError } from 'core/decorators/notify';
export default class ScopesScopeRolesRoleGrantsController extends Controller {
@controller('scopes/scope/roles/index') roles;
// =services
@service router;
// =actions
/**
* Adds a new grant to the role at the beginning of the grants list.
* Grant creation is not immediately permanent; users may rollback the change
* via "cancel" or commit it via "save".
* @param {RoleModel} role
* @param {string} grantString
*/
@action
addGrant(role, grantString) {
role.grant_strings = [grantString].concat(role.grant_strings);
}
/**
* Removes a grant from the role. Grant removal is not immediately permanent;
* users may rollback the change via "cancel" or commit it via "save".
* @param {RoleModel} role
* @param {string} grantString
*/
@action
removeGrant(role, grantString) {
role.grant_strings = role.grant_strings.filter(
(str) => str !== grantString,
);
}
/**
* Save a role.
* @param {RoleModel} role
* @param {[string]} grantStrings
*/
@action
@loading
@notifyError(({ message }) => message, { catch: true })
@notifySuccess('notifications.save-success')
async save(role, grantStrings) {
await role.saveGrantStrings(grantStrings);
}
/**
* Rollback changes on a role.
* @param {RoleModel} role
*/
@action
async cancel(role) {
role.rollbackAttributes();
await this.router.refresh('scopes.scope.roles.role');
}
}
+6
View File
@@ -1002,3 +1002,9 @@
height: 200px;
}
}
.grant-codeblock {
.hds-code-block__code {
height: 200px;
}
}
@@ -37,13 +37,7 @@
</page.navigation>
<page.body>
<Form::Role::Grants
@model={{@model}}
@submit={{fn this.save @model}}
@cancel={{fn this.cancel @model}}
@addGrant={{fn this.addGrant @model}}
@removeGrant={{fn this.removeGrant @model}}
/>
<Form::Role::Grants @model={{@model}} />
</page.body>
</Rose::Layout::Page>
@@ -11,6 +11,7 @@ import {
fillIn,
findAll,
waitUntil,
waitFor,
} from '@ember/test-helpers';
import { setupApplicationTest } from 'admin/tests/helpers';
import * as commonSelectors from 'admin/tests/helpers/selectors';
@@ -46,6 +47,7 @@ module('Acceptance | roles | add-grant-templates', function (hooks) {
urls.role = `${urls.roles}/${instances.role.id}`;
urls.addGrantTemplates = `${urls.role}/add-grant-templates`;
urls.grants = `${urls.role}/grants`;
urls.editGrants = `${urls.role}/edit-grants`;
});
test('visiting add-grant-templates route', async function (assert) {
@@ -107,11 +109,15 @@ module('Acceptance | roles | add-grant-templates', function (hooks) {
await click(commonSelectors.TABLE_ROW_CHECKBOX);
await click(commonSelectors.SAVE_BTN);
assert.strictEqual(currentURL(), urls.grants);
assert.strictEqual(initialGrantCount, 0);
assert.dom(selectors.FIELD_GRANT).isVisible({ count: 1 });
assert.dom(selectors.FIELD_GRANT).hasValue('ids=*;type=*;actions=*');
assert.strictEqual(currentURL(), urls.editGrants);
await waitFor(commonSelectors.CODE_EDITOR_CM);
assert.dom(commonSelectors.CODE_EDITOR_CODE).isVisible();
assert
.dom(commonSelectors.CODE_EDITOR_CONTENT)
.hasText('ids=*;type=*;actions=*');
});
test('cancel navigates back to grants without changes', async function (assert) {
@@ -122,6 +128,7 @@ module('Acceptance | roles | add-grant-templates', function (hooks) {
await click(commonSelectors.CANCEL_BTN);
assert.strictEqual(initialGrantCount, 0);
assert.dom(selectors.FIELD_GRANT).isVisible({ count: 0 });
assert.strictEqual(currentURL(), urls.grants);
assert.dom(selectors.GRANT_CODE_BLOCK).hasText('');
});
});
+10 -178
View File
@@ -4,19 +4,17 @@
*/
import { module, test } from 'qunit';
import { visit, currentURL, click, fillIn } from '@ember/test-helpers';
import { visit, currentURL } from '@ember/test-helpers';
import { setupApplicationTest } from 'admin/tests/helpers';
import { Response } from 'miragejs';
import * as selectors from './selectors';
import * as commonSelectors from 'admin/tests/helpers/selectors';
module('Acceptance | roles | grants', function (hooks) {
setupApplicationTest(hooks);
// This is unique to permissions tests and only used once here
const FIELD_GRANT_DISABLED = 'input[disabled]';
let grantsCount;
const GRANT_STRINGS = [
'ids=hc_123;actions=read',
'type=credential-store;ids=;actions=read',
];
const instances = {
scopes: {
@@ -27,7 +25,6 @@ module('Acceptance | roles | grants', function (hooks) {
const urls = {
roles: null,
role: null,
newRole: null,
};
hooks.beforeEach(async function () {
@@ -37,19 +34,19 @@ module('Acceptance | roles | grants', function (hooks) {
});
instances.role = this.server.create('role', {
scope: instances.scopes.org,
grant_strings: GRANT_STRINGS,
});
urls.roles = `/scopes/${instances.scopes.org.id}/roles`;
urls.role = `${urls.roles}/${instances.role.id}`;
urls.grants = `${urls.role}/grants`;
grantsCount = () =>
this.server.schema.roles.all().models[0].grant_strings.length;
});
test('visiting role grants', async function (assert) {
await visit(urls.grants);
assert.strictEqual(currentURL(), urls.grants);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
assert.dom(selectors.GRANT_CODE_BLOCK).hasText(GRANT_STRINGS.join('\n'));
assert.dom(selectors.GRANTS_BTNS).isVisible();
});
test('cannot set grants without proper authorization', async function (assert) {
@@ -59,172 +56,7 @@ module('Acceptance | roles | grants', function (hooks) {
instances.role.update({ authorized_actions });
await visit(urls.grants);
// This checks that only the form for existing grants is displayed
assert.dom(commonSelectors.FORM).exists({ count: 1 });
assert.dom(selectors.FIELD_NEW_GRANT_ADD_BTN).doesNotExist();
assert.dom(FIELD_GRANT_DISABLED).exists({ count: grantsCount() });
assert.dom(selectors.SAVE_BTN).doesNotExist();
assert.dom(commonSelectors.CANCEL_BTN).doesNotExist();
});
test('update a grant', async function (assert) {
assert.expect(1);
this.server.post(
'/roles/:idMethod',
(_, { params: { idMethod }, requestBody }) => {
const attrs = JSON.parse(requestBody);
assert.strictEqual(
attrs.grant_strings[0],
selectors.FIELD_GRANT_VALUE,
'A grant is updated',
);
const id = idMethod.split(':')[0];
return { id };
},
);
await visit(urls.grants);
await fillIn(selectors.FIELD_GRANT, selectors.FIELD_GRANT_VALUE);
await click(selectors.SAVE_BTN);
});
test('cancel a grant update', async function (assert) {
await visit(urls.grants);
await fillIn(selectors.FIELD_GRANT, selectors.FIELD_GRANT_VALUE);
await click(commonSelectors.CANCEL_BTN);
assert
.dom(selectors.FIELD_GRANT)
.doesNotIncludeText(selectors.FIELD_GRANT_VALUE);
});
test('shows error message on grant update', async function (assert) {
this.server.post('/roles/:idMethod', () => {
return new Response(
400,
{},
{
status: 400,
code: 'invalid_argument',
message: 'The request was invalid.',
details: {},
},
);
});
await visit(urls.grants);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
await fillIn(selectors.FIELD_GRANT, selectors.FIELD_GRANT_VALUE);
await click(selectors.SAVE_BTN);
assert
.dom(commonSelectors.ALERT_TOAST_BODY)
.hasText('The request was invalid.');
});
test('create a grant', async function (assert) {
assert.expect(1);
this.server.post(
'/roles/:idMethod',
(_, { params: { idMethod }, requestBody }) => {
const attrs = JSON.parse(requestBody);
assert.strictEqual(
attrs.grant_strings.length,
grantsCount() + 1,
'A grant is created',
);
const id = idMethod.split(':')[0];
return { id };
},
);
await visit(urls.grants);
await fillIn(selectors.FIELD_NEW_GRANT, selectors.FIELD_GRANT_VALUE);
await click(selectors.FIELD_NEW_GRANT_ADD_BTN);
await click(selectors.SAVE_BTN);
});
test('cancel a grant creation', async function (assert) {
await visit(urls.grants);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
await fillIn(selectors.FIELD_NEW_GRANT, selectors.FIELD_GRANT_VALUE);
await click(selectors.FIELD_NEW_GRANT_ADD_BTN);
await click(commonSelectors.CANCEL_BTN);
assert.dom(selectors.FIELD_NEW_GRANT).hasNoText();
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
});
test('shows error message on grant create', async function (assert) {
this.server.post('/roles/:idMethod', () => {
return new Response(
400,
{},
{
status: 400,
code: 'invalid_argument',
message: 'The request was invalid.',
details: {},
},
);
});
await visit(urls.grants);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
await fillIn(selectors.FIELD_NEW_GRANT, selectors.FIELD_GRANT_VALUE);
await click(selectors.FIELD_NEW_GRANT_ADD_BTN);
await click(selectors.SAVE_BTN);
assert
.dom(commonSelectors.ALERT_TOAST_BODY)
.hasText('The request was invalid.');
});
test('delete a grant', async function (assert) {
await visit(urls.grants);
await click(selectors.FIELD_GRANT_REMOVE_BTN);
await click(selectors.SAVE_BTN);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() - 1 });
});
test('cancel a grant remove', async function (assert) {
await visit(urls.grants);
await click(selectors.FIELD_GRANT_REMOVE_BTN);
await click(commonSelectors.CANCEL_BTN);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
});
test('shows error message on grant remove', async function (assert) {
this.server.post('/roles/:idMethod', () => {
return new Response(
400,
{},
{
status: 400,
code: 'invalid_argument',
message: 'The request was invalid.',
details: {},
},
);
});
await visit(urls.grants);
assert.dom(selectors.FIELD_GRANT).exists({ count: grantsCount() });
await click(selectors.FIELD_GRANT_REMOVE_BTN);
await click(selectors.SAVE_BTN);
assert
.dom(commonSelectors.ALERT_TOAST_BODY)
.hasText('The request was invalid.');
assert.dom(selectors.GRANTS_BTNS).doesNotExist();
assert.dom(selectors.GRANT_CODE_BLOCK).hasText(GRANT_STRINGS.join('\n'));
});
});
+2 -9
View File
@@ -54,18 +54,11 @@ export const REMOVE_ORG_PROJECTS_BTN = (name) =>
`[data-test-manage-scopes-remove-${name}-modal] div:nth-child(3) button`;
// Role grants
export const FIELD_NEW_GRANT = 'form:nth-child(1) [name="grant"]';
export const FIELD_NEW_GRANT_ADD_BTN = 'form:nth-child(1) [type="submit"]';
export const FIELD_GRANT = 'form:nth-child(2) [name="grant"]';
export const FIELD_GRANT_VALUE = 'ids=123,action=delete';
export const FIELD_GRANT_REMOVE_BTN = 'form:nth-child(2) button[type="button"]';
export const GRANTS_FORM = 'form:nth-child(2)';
export const GRANT_CODE_BLOCK = '.grant-codeblock .hds-code-block__code';
export const EXPORT_OPTIONS_FLYOUT = '[data-test-export-options-flyout]';
export const EXPORT_FORMAT_SELECT =
'[data-test-export-options-flyout] [name="export-format"]';
export const FORMATTED_EXPORT_CODE_BLOCK =
'[data-test-export-options-flyout] .hds-code-block code';
// We need to use a different selector for the grants form because the
// grants form has multiple submit buttons
export const SAVE_BTN = '.rose-form-actions [type=submit]';
export const EXPORT_GRANTS_BTN = '[data-test-export-grants-btn]';
export const GRANTS_BTNS = '[data-test-grants-btns]';
@@ -66,7 +66,9 @@ module(
await controller.addGrantTemplates(role, newGrantTemplates);
assert.ok(routerStub.calledOnceWith('scopes.scope.roles.role.grants'));
assert.ok(
routerStub.calledOnceWith('scopes.scope.roles.role.edit-grants'),
);
assert.deepEqual(role.grant_strings, [
'ids=*;type=user;actions=read',
'ids=*;type=*;actions=*',
@@ -5,96 +5,14 @@
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { visit } from '@ember/test-helpers';
import { setupMirage } from 'admin/tests/helpers/mirage';
import { authenticateSession } from 'ember-simple-auth/test-support';
module('Unit | Controller | scopes/scope/roles/role/grants', function (hooks) {
setupTest(hooks);
setupMirage(hooks);
let store;
let controller;
const instances = {
scopes: {
global: null,
},
role: null,
};
const urls = {
grants: null,
};
hooks.beforeEach(async function () {
store = this.owner.lookup('service:store');
controller = this.owner.lookup('controller:scopes/scope/roles/role/grants');
instances.scopes.global = this.server.create(
'scope',
{ id: 'global' },
'withGlobalAuth',
);
await authenticateSession({
isGlobal: true,
account_id: this.server.schema.accounts.first().id,
});
instances.role = this.server.create('role', {
scope: instances.scopes.global,
});
urls.grants = `/scopes/global/roles/${instances.role.id}/grants`;
});
test('it exists', function (assert) {
const controller = this.owner.lookup(
'controller:scopes/scope/roles/role/grants',
);
assert.ok(controller);
assert.ok(controller.roles);
});
// TODO: Will be removed once this view becomes read only
test('cancel action rolls-back changes on the specified model', async function (assert) {
await visit(urls.grants);
const role = await store.findRecord('role', instances.role.id);
const grantStrings = role.grant_strings;
role.grant_strings = ['ids=*;type=*;actions=read'];
assert.deepEqual(role.grant_strings, ['ids=*;type=*;actions=read']);
await controller.cancel(role);
assert.deepEqual(role.grant_strings, grantStrings);
});
test('save action saves grantStrings to specified model', async function (assert) {
await visit(urls.grants);
const role = await store.findRecord('role', instances.role.id);
const grantStrings = role.grant_strings;
const newGrantStrings = [...grantStrings, 'ids=*;type=*;actions=read'];
await controller.save(role, newGrantStrings);
assert.deepEqual(role.grant_strings, newGrantStrings);
});
test('removeGrant action removes a grant string from a role', async function (assert) {
await visit(urls.grants);
const role = await store.findRecord('role', instances.role.id);
const grantStrings = role.grant_strings;
await controller.removeGrant(role, grantStrings[0]);
assert.deepEqual(role.grant_strings, grantStrings.slice(1));
});
test('addGrant action adds a grant string from a role', async function (assert) {
await visit(urls.grants);
const role = await store.findRecord('role', instances.role.id);
const grantStrings = role.grant_strings;
const grantString = 'ids=*;type=*;actions=read';
await controller.addGrant(role, grantString);
assert.deepEqual(role.grant_strings, [grantString, ...grantStrings]);
});
});