Merge pull request #688 from hashicorp/poc-ui-capabilities

API support for UI capabilities
This commit is contained in:
Randall Morey authored and GitHub committed 2021-08-11 10:40:04 -04:00
commit 0c9ba7e7a7
22 files changed
+1916 -1700

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
import { Ability } from 'ember-can';
/**
* Generic ability provides abilities common to all models in the API.
*/
export default class ModelAbility extends Ability {
// =permissions
/**
* @type {boolean}
*/
get canRead() {
return this.hasAuthorizedAction('read');
}
/**
* @type {boolean}
*/
get canUpdate() {
return this.hasAuthorizedAction('update');
}
/**
* @type {boolean}
*/
get canDelete() {
return this.hasAuthorizedAction('delete');
}
/**
* To save an existing model (already persisted to the API), it must contain
* the the `update` authorized action.
*
* For now, new models _always_ have this ability. The reason is because the
* `create` action is authorized on collections, not individual records. So
* this function can't actually tell from a model instance if create
* is allowed.
*
* @type {boolean}
*/
get canSave() {
if (this.model.isNew || (!this.model.isNew && this.canUpdate)) {
return true;
}
return false;
}
// =methods
/**
* Returns true if the given action is contained in the ability model's
* `authorized_actions` array.
* @param {string} action
* @return {boolean}
*/
hasAuthorizedAction(action) {
return this.model.authorized_actions?.includes(action);
}
}
+7
View File
@@ -1,4 +1,5 @@
import Model from '@ember-data/model';
import { attr } from '@ember-data/model';
import { fragment } from 'ember-data-model-fragments/attributes';
import { computed } from '@ember/object';
@@ -35,6 +36,12 @@ export default class BaseModel extends Model {
// =attributes
@attr({
readOnly: true,
emptyArrayIfMissing: true,
})
authorized_actions;
set scopeModel(model) {
if (model) {
const json = model.serialize();
+1
View File
@@ -0,0 +1 @@
export { default } from 'api/abilities/model';
+8
View File
@@ -1,7 +1,15 @@
import factory from '../generated/factories/account';
import { random, internet } from 'faker';
import permissions from '../helpers/permissions';
export default factory.extend({
authorized_actions: () =>
permissions.authorizedActionsFor('account') || [
'no-op',
'read',
'update',
'delete',
],
attributes() {
switch (this.type) {
case 'password':
+58
View File
@@ -0,0 +1,58 @@
import { copy } from 'ember-copy';
/**
* Allows development-time toggling of resource permissions via the window
* querystring. Pass a JSON object into the query to toggle permissions.
* Note that the value must be a valid JSON object in order to be parsed.
*
* @example
* ?authorized_actions={"account": ["read"]}
*
* Within a Mirage factory, pass the actions into the mock:
*
* @example
* import { Factory } from 'ember-cli-mirage';
* import permissions from '../helpers/permissions';
*
* export default Factory.extend({
* authorized_actions: () =>
* permissions.authorizedActionsFor('account') ||
* ['no-op', 'read', 'update', 'delete']
* });
*/
class ToggledCapabilities {
// =attributes
// Get the query string and drop the leading '?'
#rawQuery = window.location.search.substring(1);
// Split the querystring into key/value pairs
#queryPairs = this.#rawQuery.split('&').map((item) => item.split('='));
// Find the value of a pair with key `authorized_actions`
// Safe-ish when the item is not present
#rawAuthorizedActions = (this.#queryPairs.find(
(item) => item[0] === 'authorized_actions'
) || [])[1];
// Safe-ish when the value is not present
#authorizedActions =
JSON.parse(
decodeURIComponent(this.#rawAuthorizedActions || '') || 'null'
) || {};
// =methods
/**
* Returns authorized actions for the specified field, if any are defined
* in the `authorized_actions` query. Returns undefined otherwise.
* @return {?string[]}
*/
authorizedActionsFor(field) {
if (this.#authorizedActions[field]) {
return copy(this.#authorizedActions[field], true);
}
}
}
export default new ToggledCapabilities();
+1
View File
@@ -24,6 +24,7 @@
"doc:toc": "doctoc README.md"
},
"dependencies": {
"ember-can": "^3.1.0",
"ember-cli-babel": "^7.23.0",
"ember-cli-htmlbars": "^5.3.1",
"ember-cli-mirage": "^1.1.8",
@@ -0,0 +1,68 @@
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Abilities | Model', function (hooks) {
setupTest(hooks);
test('it reflects when a given model may be read based on authorized_actions', function (assert) {
assert.expect(2);
const service = this.owner.lookup('service:can');
const model = {
authorized_actions: ['read'],
};
assert.ok(service.can('read model', model));
model.authorized_actions = [];
assert.notOk(service.can('read model', model));
});
test('it reflects when a given model may be updated based on authorized_actions', function (assert) {
assert.expect(2);
const service = this.owner.lookup('service:can');
const model = {
authorized_actions: ['update'],
};
assert.ok(service.can('update model', model));
model.authorized_actions = [];
assert.notOk(service.can('update model', model));
});
test('it reflects when a given model may be saved based on isNew and authorized_actions', function (assert) {
assert.expect(4);
const service = this.owner.lookup('service:can');
let model = {
isNew: false,
authorized_actions: ['update'],
};
assert.ok(service.can('save model', model));
model = {
isNew: false,
authorized_actions: [],
};
assert.notOk(service.can('save model', model));
// Model instances are always saveable at this level when isNew is true.
// In practice, the ability to _create_ a resource depends not on instance
// authorization, but on collection authorization, which is
// tested separately.
model = {
isNew: true,
authorized_actions: ['update'],
};
assert.ok(service.can('save model', model));
model = {
isNew: true,
authorized_actions: [],
};
assert.ok(service.can('save model', model));
});
test('it reflects when a given model may be deleted based on authorized_actions', function (assert) {
assert.expect(2);
const service = this.owner.lookup('service:can');
const model = {
authorized_actions: ['delete'],
};
assert.ok(service.can('delete model', model));
model.authorized_actions = [];
assert.notOk(service.can('delete model', model));
});
});
@@ -170,6 +170,7 @@ module('Unit | Serializer | application', function (hooks) {
id: '1',
type: 'user',
attributes: {
authorized_actions: [],
name: 'User 1',
account_ids: [],
scope: { scope_id: 'o_123' },
@@ -200,6 +201,7 @@ module('Unit | Serializer | application', function (hooks) {
id: '1',
type: 'target',
attributes: {
authorized_actions: [],
name: 'Target 1',
scope: { scope_id: 'o_123' },
host_sets: [],
@@ -66,6 +66,7 @@ module('Unit | Serializer | group', function (hooks) {
id: '1',
type: 'group',
attributes: {
authorized_actions: [],
name: 'Group 1',
scope: { scope_id: 'o_123' },
member_ids: [],
@@ -67,6 +67,7 @@ module('Unit | Serializer | host set', function (hooks) {
id: '1',
type: 'host-set',
attributes: {
authorized_actions: [],
name: 'Host Set 1',
host_ids: [{ value: '1' }, { value: '2' }, { value: '3' }],
},
@@ -96,6 +97,7 @@ module('Unit | Serializer | host set', function (hooks) {
id: '1',
type: 'host-set',
attributes: {
authorized_actions: [],
name: 'Host Set 1',
scope: { scope_id: 'o_123' },
host_ids: [],
@@ -67,6 +67,7 @@ module('Unit | Serializer | role', function (hooks) {
id: '1',
type: 'role',
attributes: {
authorized_actions: [],
name: 'Role 1',
grant_strings: ['*', '*'],
principals: [],
@@ -93,6 +94,7 @@ module('Unit | Serializer | role', function (hooks) {
id: '1',
type: 'role',
attributes: {
authorized_actions: [],
name: 'Role 1',
scope: { scope_id: 'o_123' },
principals: [],
@@ -110,6 +110,7 @@ module('Unit | Serializer | target', function (hooks) {
id: '1',
type: 'target',
attributes: {
authorized_actions: [],
name: 'Target 1',
host_sets: [
{ host_set_id: '1', host_catalog_id: '2' },
@@ -143,6 +144,7 @@ module('Unit | Serializer | target', function (hooks) {
id: '1',
type: 'target',
attributes: {
authorized_actions: [],
name: 'Target 1',
scope: { scope_id: 'o_123' },
host_sets: [],
@@ -62,6 +62,7 @@ module('Unit | Serializer | user', function (hooks) {
id: '1',
type: 'user',
attributes: {
authorized_actions: [],
name: 'user 1',
scope: { scope_id: 'o_123' },
account_ids: [],
@@ -117,11 +117,13 @@
</form.input>
{{/if}}
<form.actions
@disabled={{if @model.cannotSave @model.cannotSave}}
@enableEditText={{t 'actions.edit-form'}}
@submitText={{t 'actions.save'}}
@cancelText={{t 'actions.cancel'}}
/>
{{#if (can 'save model' @model)}}
<form.actions
@disabled={{if @model.cannotSave @model.cannotSave}}
@enableEditText={{t 'actions.edit-form'}}
@submitText={{t 'actions.save'}}
@cancelText={{t 'actions.cancel'}}
/>
{{/if}}
</Rose::Form>
@@ -91,11 +91,13 @@
</form.input>
{{/if}}
<form.actions
@disabled={{if @model.cannotSave @model.cannotSave}}
@enableEditText={{t 'actions.edit-form'}}
@submitText={{t 'actions.save'}}
@cancelText={{t 'actions.cancel'}}
/>
{{#if (can 'save model' @model)}}
<form.actions
@disabled={{if @model.cannotSave @model.cannotSave}}
@enableEditText={{t 'actions.edit-form'}}
@submitText={{t 'actions.save'}}
@cancelText={{t 'actions.cancel'}}
/>
{{/if}}
</Rose::Form>
@@ -1,13 +1,15 @@
<Rose::Dropdown
@text='{{t 'actions.manage'}}'
@dropdownRight={{true}}
as |dropdown|
>
<dropdown.button
@style='danger'
@disabled={{@model.canSave}}
{{on 'click' (route-action 'deleteAccount' @model)}}
{{#if (can 'delete model' @model)}}
<Rose::Dropdown
@text='{{t 'actions.manage'}}'
@dropdownRight={{true}}
as |dropdown|
>
{{t 'resources.account.actions.delete'}}
</dropdown.button>
</Rose::Dropdown>
<dropdown.button
@style='danger'
@disabled={{@model.canSave}}
{{on 'click' (route-action 'deleteAccount' @model)}}
>
{{t 'resources.account.actions.delete'}}
</dropdown.button>
</Rose::Dropdown>
{{/if}}
@@ -18,13 +18,17 @@
{{#each @model as |account|}}
<body.row as |row|>
<row.headerCell scope='row'>
<LinkTo
@route='scopes.scope.auth-methods.auth-method.accounts.account'
@model={{account.id}}
>
{{#if (can 'read model' account)}}
<LinkTo
@route='scopes.scope.auth-methods.auth-method.accounts.account'
@model={{account.id}}
>
{{account.accountName}}
</LinkTo>
{{else}}
{{account.accountName}}
<p>{{account.description}}</p>
</LinkTo>
{{/if}}
<p>{{account.description}}</p>
</row.headerCell>
<row.cell>
<code>{{account.attributes.issuer}}</code>
@@ -68,13 +72,17 @@
{{#each @model as |account|}}
<body.row as |row|>
<row.headerCell>
<LinkTo
@route='scopes.scope.auth-methods.auth-method.accounts.account'
@model={{account.id}}
>
{{#if (can 'read model' account)}}
<LinkTo
@route='scopes.scope.auth-methods.auth-method.accounts.account'
@model={{account.id}}
>
{{account.accountName}}
</LinkTo>
{{else}}
{{account.accountName}}
<p>{{account.description}}</p>
</LinkTo>
{{/if}}
<p>{{account.description}}</p>
</row.headerCell>
<row.cell>
{{account.attributes.login_name}}
-120
View File
@@ -68,32 +68,6 @@ module('Acceptance | accounts', function (hooks) {
assert.equal(currentURL(), urls.accounts);
});
test('can navigate to an account form', async function (assert) {
assert.expect(1);
await visit(urls.accounts);
await click('main tbody .rose-table-header-cell:nth-child(1) a');
await a11yAudit();
assert.equal(currentURL(), urls.account);
});
test('can update an account and save changes', async function (assert) {
assert.expect(1);
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'update name');
await click('form [type="submit"]:not(:disabled)');
assert.equal(this.server.db.accounts[0].name, 'update name');
});
test('can update an account and cancel changes', async function (assert) {
assert.expect(1);
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'update name');
await click('form button:not([type="submit"])');
assert.notEqual(this.server.db.accounts[0].name, 'update name');
});
test('can create a new account', async function (assert) {
assert.expect(1);
const accountsCount = this.server.db.accounts.length;
@@ -116,14 +90,6 @@ module('Acceptance | accounts', function (hooks) {
assert.equal(currentURL(), urls.accounts);
});
test('can delete an account', async function (assert) {
assert.expect(1);
const accountsCount = this.server.db.accounts.length;
await visit(urls.account);
await click('.rose-layout-page-actions .rose-dropdown-button-danger');
assert.equal(this.server.db.accounts.length, accountsCount - 1);
});
test('saving a new account with invalid fields displays error messages', async function (assert) {
assert.expect(2);
this.server.post('/accounts', () => {
@@ -160,90 +126,4 @@ module('Acceptance | accounts', function (hooks) {
'Displays field-level errors.'
);
});
test('errors are displayed when save on account fails', async function (assert) {
assert.expect(1);
this.server.patch('/accounts/:id', () => {
return new Response(
490,
{},
{
status: 490,
code: 'error',
message: 'Oops.',
}
);
});
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'save account');
await click('form [type="submit"]');
await a11yAudit();
assert.ok(
find('[role="alert"]').textContent.trim(),
'Oops.',
'Displays primary error message.'
);
});
test('errors are displayed when delete on account fails', async function (assert) {
assert.expect(1);
this.server.del('/accounts/:id', () => {
return new Response(
490,
{},
{
status: 490,
code: 'error',
message: 'Oops.',
}
);
});
await visit(urls.account);
await click('.rose-layout-page-actions .rose-dropdown-button-danger');
await a11yAudit();
assert.ok(
find('[role="alert"]').textContent.trim(),
'Oops.',
'Displays primary error message.'
);
});
test('saving an existing account with invalid fields displays error messages', async function (assert) {
assert.expect(2);
this.server.patch('/accounts/:id', () => {
return new Response(
400,
{},
{
status: 400,
code: 'invalid_argument',
message: 'The request was invalid.',
details: {
request_fields: [
{
name: 'name',
description: 'Name is required.',
},
],
},
}
);
});
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'existing account');
await click('form [type="submit"]');
await a11yAudit();
assert.ok(
find('[role="alert"]').textContent.trim(),
'The request was invalid.',
'Displays primary error message.'
);
assert.ok(
find('.rose-form-error-message').textContent.trim(),
'Name is required.',
'Displays field-level errors.'
);
});
});
@@ -0,0 +1,102 @@
import { module, test } from 'qunit';
import { visit, click, find } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import a11yAudit from 'ember-a11y-testing/test-support/audit';
import { Response } from 'miragejs';
import {
authenticateSession,
// These are left here intentionally for future reference.
//currentSession,
//invalidateSession,
} from 'ember-simple-auth/test-support';
module('Acceptance | accounts | delete', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
const instances = {
scopes: {
global: null,
org: null,
},
authMethods: null,
account: null,
};
const urls = {
orgScope: null,
authMethods: null,
accounts: null,
account: null,
};
hooks.beforeEach(function () {
authenticateSession({});
instances.scopes.global = this.server.create('scope', { id: 'global' });
instances.scopes.org = this.server.create('scope', {
type: 'org',
scope: { id: 'global', type: 'global' },
});
instances.authMethod = this.server.create('auth-method', {
scope: instances.scopes.org,
});
instances.account = this.server.create('account', {
scope: instances.scopes.org,
authMethod: instances.authMethod,
});
// Generate route URLs for resources
urls.orgScope = `/scopes/${instances.scopes.org.id}`;
urls.authMethods = `${urls.orgScope}/auth-methods`;
urls.authMethod = `${urls.authMethods}/${instances.authMethod.id}`;
urls.accounts = `${urls.authMethod}/accounts`;
urls.account = `${urls.accounts}/${instances.account.id}`;
});
hooks.afterEach(async function () {
const notification = find('.rose-notification');
if (notification) {
await click('.rose-notification-dismiss');
}
});
test('can delete an account', async function (assert) {
assert.expect(1);
const accountsCount = this.server.db.accounts.length;
await visit(urls.account);
await click('.rose-layout-page-actions .rose-dropdown-button-danger');
assert.equal(this.server.db.accounts.length, accountsCount - 1);
});
test('cannot delete an account without proper authorization', async function (assert) {
assert.expect(1);
instances.account.authorized_actions =
instances.account.authorized_actions.filter((item) => item !== 'delete');
await visit(urls.account);
assert.notOk(
find('.rose-layout-page-actions .rose-dropdown-button-danger')
);
});
test('errors are displayed when delete on account fails', async function (assert) {
assert.expect(1);
this.server.del('/accounts/:id', () => {
return new Response(
490,
{},
{
status: 490,
code: 'error',
message: 'Oops.',
}
);
});
await visit(urls.account);
await click('.rose-layout-page-actions .rose-dropdown-button-danger');
await a11yAudit();
assert.ok(
find('[role="alert"]').textContent.trim(),
'Oops.',
'Displays primary error message.'
);
});
});
@@ -0,0 +1,76 @@
import { module, test } from 'qunit';
import { visit, currentURL, click, find } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import a11yAudit from 'ember-a11y-testing/test-support/audit';
import {
authenticateSession,
// These are left here intentionally for future reference.
//currentSession,
//invalidateSession,
} from 'ember-simple-auth/test-support';
module('Acceptance | accounts | read', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
const instances = {
scopes: {
global: null,
org: null,
},
authMethods: null,
account: null,
};
const urls = {
orgScope: null,
authMethods: null,
accounts: null,
account: null,
};
hooks.beforeEach(function () {
authenticateSession({});
instances.scopes.global = this.server.create('scope', { id: 'global' });
instances.scopes.org = this.server.create('scope', {
type: 'org',
scope: { id: 'global', type: 'global' },
});
instances.authMethod = this.server.create('auth-method', {
scope: instances.scopes.org,
});
instances.account = this.server.create('account', {
scope: instances.scopes.org,
authMethod: instances.authMethod,
});
// Generate route URLs for resources
urls.orgScope = `/scopes/${instances.scopes.org.id}`;
urls.authMethods = `${urls.orgScope}/auth-methods`;
urls.authMethod = `${urls.authMethods}/${instances.authMethod.id}`;
urls.accounts = `${urls.authMethod}/accounts`;
urls.account = `${urls.accounts}/${instances.account.id}`;
});
hooks.afterEach(async function () {
const notification = find('.rose-notification');
if (notification) {
await click('.rose-notification-dismiss');
}
});
test('can navigate to an account form', async function (assert) {
assert.expect(1);
await visit(urls.accounts);
await click('main tbody .rose-table-header-cell:nth-child(1) a');
await a11yAudit();
assert.equal(currentURL(), urls.account);
});
test('cannot navigate to an account form without proper authorization', async function (assert) {
assert.expect(1);
instances.account.authorized_actions =
instances.account.authorized_actions.filter((item) => item !== 'read');
await visit(urls.accounts);
assert.notOk(find('main tbody .rose-table-header-cell:nth-child(1) a'));
});
});
@@ -0,0 +1,142 @@
import { module, test } from 'qunit';
import { visit, click, find, fillIn } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import a11yAudit from 'ember-a11y-testing/test-support/audit';
import { Response } from 'miragejs';
import {
authenticateSession,
// These are left here intentionally for future reference.
//currentSession,
//invalidateSession,
} from 'ember-simple-auth/test-support';
module('Acceptance | accounts | update', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
const instances = {
scopes: {
global: null,
org: null,
},
authMethods: null,
account: null,
};
const urls = {
orgScope: null,
authMethods: null,
accounts: null,
account: null,
};
hooks.beforeEach(function () {
authenticateSession({});
instances.scopes.global = this.server.create('scope', { id: 'global' });
instances.scopes.org = this.server.create('scope', {
type: 'org',
scope: { id: 'global', type: 'global' },
});
instances.authMethod = this.server.create('auth-method', {
scope: instances.scopes.org,
});
instances.account = this.server.create('account', {
scope: instances.scopes.org,
authMethod: instances.authMethod,
});
// Generate route URLs for resources
urls.orgScope = `/scopes/${instances.scopes.org.id}`;
urls.authMethods = `${urls.orgScope}/auth-methods`;
urls.authMethod = `${urls.authMethods}/${instances.authMethod.id}`;
urls.accounts = `${urls.authMethod}/accounts`;
urls.account = `${urls.accounts}/${instances.account.id}`;
});
hooks.afterEach(async function () {
const notification = find('.rose-notification');
if (notification) {
await click('.rose-notification-dismiss');
}
});
test('can update an account and save changes', async function (assert) {
assert.expect(1);
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'update name');
await click('form [type="submit"]:not(:disabled)');
assert.equal(this.server.db.accounts[0].name, 'update name');
});
test('can update an account and cancel changes', async function (assert) {
assert.expect(1);
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'update name');
await click('form button:not([type="submit"])');
assert.notEqual(this.server.db.accounts[0].name, 'update name');
});
test('errors are displayed when save on account fails', async function (assert) {
assert.expect(1);
this.server.patch('/accounts/:id', () => {
return new Response(
490,
{},
{
status: 490,
code: 'error',
message: 'Oops.',
}
);
});
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'save account');
await click('form [type="submit"]');
await a11yAudit();
assert.ok(
find('[role="alert"]').textContent.trim(),
'Oops.',
'Displays primary error message.'
);
});
test('saving an existing account with invalid fields displays error messages', async function (assert) {
assert.expect(2);
this.server.patch('/accounts/:id', () => {
return new Response(
400,
{},
{
status: 400,
code: 'invalid_argument',
message: 'The request was invalid.',
details: {
request_fields: [
{
name: 'name',
description: 'Name is required.',
},
],
},
}
);
});
await visit(urls.account);
await click('form [type="button"]', 'Activate edit mode');
await fillIn('[name="name"]', 'existing account');
await click('form [type="submit"]');
await a11yAudit();
assert.ok(
find('[role="alert"]').textContent.trim(),
'The request was invalid.',
'Displays primary error message.'
);
assert.ok(
find('.rose-form-error-message').textContent.trim(),
'Name is required.',
'Displays field-level errors.'
);
});
});
+1334 -1544
View File
File diff suppressed because it is too large. Load diff