KMSE Capabilities & Phase 1 Cleanup (#15143)

* fixes issues in key-edit component

* adds capabilities checks for keys and providers

* adds distribute component to key and provider edit
This commit is contained in:
Jordan Reimer 2022-04-26 08:23:31 -06:00 committed by GitHub
parent cc531c793d
commit d6933e9ef4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 531 additions and 388 deletions

View File

@ -149,4 +149,11 @@ export default class KeymgmtKeyAdapter extends ApplicationAdapter {
// TODO: re-fetch record data after
return this.ajax(this.url(backend, id, 'ROTATE'), 'PUT');
}
removeFromProvider(model) {
const url = `${this.buildURL()}/${model.backend}/kms/${model.provider.name}/key/${model.name}`;
return this.ajax(url, 'DELETE').then(() => {
model.provider = null;
});
}
}

View File

@ -181,7 +181,7 @@ export default class KeymgmtDistribute extends Component {
.distribute(backend, kms, key, data)
.then(() => {
this.flashMessages.success(`Successfully distributed key ${key} to ${kms}`);
this.router.transitionTo('vault.cluster.secrets.backend.show', key);
this.args.onClose();
})
.catch((e) => {
this.flashMessages.danger(`Error distributing key: ${e.errors}`);

View File

@ -2,6 +2,8 @@ import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
import { task } from 'ember-concurrency';
import { waitFor } from '@ember/test-waiters';
/**
* @module KeymgmtKeyEdit
@ -32,50 +34,50 @@ export default class KeymgmtKeyEdit extends Component {
return this.store.adapterFor('keymgmt/key');
}
get isMutable() {
return ['create', 'edit'].includes(this.args.mode);
}
get isCreating() {
return this.args.mode === 'create';
}
@action
toggleModal(bool) {
this.isDeleteModalOpen = bool;
}
@action
createKey(evt) {
@task
@waitFor
*saveKey(evt) {
evt.preventDefault();
this.args.model.save();
const { model } = this.args;
try {
yield model.save();
this.router.transitionTo(SHOW_ROUTE, model.name);
} catch (error) {
this.flashMessages.danger(error.errors.join('. '));
}
}
@action
updateKey(evt) {
evt.preventDefault();
const name = this.args.model.name;
this.args.model
.save()
.then(() => {
this.router.transitionTo(SHOW_ROUTE, name);
})
.catch((e) => {
this.flashMessages.danger(e.errors.join('. '));
});
async removeKey() {
try {
await this.keyAdapter.removeFromProvider(this.args.model);
this.flashMessages.success('Key has been successfully removed from provider');
} catch (error) {
this.flashMessages.danger(error.errors?.join('. '));
}
@action
removeKey(id) {
// TODO: remove action
console.log('remove', id);
}
@action
deleteKey() {
const secret = this.args.model;
const backend = secret.backend;
console.log({ secret });
secret
.destroyRecord()
.then(() => {
try {
this.router.transitionTo(LIST_ROOT_ROUTE, backend, { queryParams: { tab: 'key' } });
} catch (e) {
console.debug(e);
}
this.router.transitionTo(LIST_ROOT_ROUTE, backend);
})
.catch((e) => {
this.flashMessages.danger(e.errors?.join('. '));

View File

@ -1,5 +1,6 @@
import Model, { attr } from '@ember-data/model';
import { expandAttributeMeta } from 'vault/utils/field-to-attrs';
import lazyCapabilities, { apiPath } from 'vault/macros/lazy-capabilities';
export const KEY_TYPES = [
'aes256-gcm96',
@ -11,15 +12,23 @@ export const KEY_TYPES = [
'ecdsa-p521',
];
export default class KeymgmtKeyModel extends Model {
@attr('string') name;
@attr('string') backend;
@attr('string', {
label: 'Key name',
subText: 'This is the name of the key that shows in Vault.',
})
name;
@attr('string')
backend;
@attr('string', {
subText: 'The type of cryptographic key that will be created.',
possibleValues: KEY_TYPES,
})
type;
@attr('boolean', {
label: 'Allow deletion',
defaultValue: false,
})
deletionAllowed;
@ -93,4 +102,27 @@ export default class KeymgmtKeyModel extends Model {
{ name: 'protection', type: 'string', subText: 'Where cryptographic operations are performed.' },
];
}
@lazyCapabilities(apiPath`${'backend'}/key/${'id'}`, 'backend', 'id') keyPath;
@lazyCapabilities(apiPath`${'backend'}/key`, 'backend') keysPath;
@lazyCapabilities(apiPath`${'backend'}/key/${'id'}/kms`, 'backend', 'id') keyProvidersPath;
get canCreate() {
return this.keyPath.get('canCreate');
}
get canDelete() {
return this.keyPath.get('canDelete');
}
get canEdit() {
return this.keyPath.get('canUpdate');
}
get canRead() {
return this.keyPath.get('canRead');
}
get canList() {
return this.keysPath.get('canList');
}
get canListProviders() {
return this.keyProvidersPath.get('canList');
}
}

View File

@ -2,6 +2,7 @@ import Model, { attr } from '@ember-data/model';
import { tracked } from '@glimmer/tracking';
import { expandAttributeMeta } from 'vault/utils/field-to-attrs';
import { withModelValidations } from 'vault/decorators/model-validations';
import lazyCapabilities, { apiPath } from 'vault/macros/lazy-capabilities';
const CRED_PROPS = {
azurekeyvault: ['client_id', 'client_secret', 'tenant_id'],
@ -80,7 +81,11 @@ export default class KeymgmtProviderModel extends Model {
const attrs = expandAttributeMeta(this, ['name', 'created', 'keyCollection']);
attrs.splice(1, 0, { hasBlock: true, label: 'Type', value: this.typeName, icon: this.icon });
const l = this.keys.length;
const value = l ? `${l} ${l > 1 ? 'keys' : 'key'}` : 'None';
const value = l
? `${l} ${l > 1 ? 'keys' : 'key'}`
: this.canListKeys
? 'None'
: 'You do not have permission to list keys';
attrs.push({ hasBlock: true, isLink: l, label: 'Keys', value });
return attrs;
}
@ -104,6 +109,7 @@ export default class KeymgmtProviderModel extends Model {
}
async fetchKeys(page) {
if (this.canListKeys) {
try {
this.keys = await this.store.lazyPaginatedQuery('keymgmt/key', {
backend: 'keymgmt',
@ -117,5 +123,34 @@ export default class KeymgmtProviderModel extends Model {
throw error;
}
}
} else {
this.keys = [];
}
}
@lazyCapabilities(apiPath`${'backend'}/kms/${'id'}`, 'backend', 'id') providerPath;
@lazyCapabilities(apiPath`${'backend'}/kms`, 'backend') providersPath;
@lazyCapabilities(apiPath`${'backend'}/kms/${'id'}/key`, 'backend', 'id') providerKeysPath;
get canCreate() {
return this.providerPath.get('canCreate');
}
get canDelete() {
return this.providerPath.get('canDelete');
}
get canEdit() {
return this.providerPath.get('canUpdate');
}
get canRead() {
return this.providerPath.get('canRead');
}
get canList() {
return this.providersPath.get('canList');
}
get canListKeys() {
return this.providerKeysPath.get('canList');
}
get canCreateKeys() {
return this.providerKeysPath.get('canCreate');
}
}

View File

@ -147,7 +147,12 @@
class="button is-primary"
data-test-secret-save={{true}}
>
Save
{{if (or (not @key) this.isNewKey) "Add key" "Distribute key"}}
</button>
</div>
<div class="control">
<button type="button" class="button" {{on "click" @onClose}}>
Cancel
</button>
</div>
</div>

View File

@ -4,7 +4,9 @@
</p.top>
<p.levelLeft>
<h1 class="title is-3" data-test-secret-header="true">
{{#if (eq @mode "create")}}
{{#if this.isDistributing}}
Distribute key
{{else if (eq @mode "create")}}
Create key
{{else if (eq @mode "edit")}}
Edit key
@ -15,6 +17,9 @@
</p.levelLeft>
</PageHeader>
{{#if this.isDistributing}}
<Keymgmt::Distribute @backend={{@model.backend}} @key={{@model}} @onClose={{fn (mut this.isDistributing) false}} />
{{else}}
{{#if (eq this.mode "show")}}
<div class="tabs-container box is-sideless is-fullwidth is-paddingless is-marginless" data-test-keymgmt-key-toolbar>
<nav class="tabs">
@ -44,6 +49,7 @@
</div>
<Toolbar>
<ToolbarActions>
{{#if @model.canDelete}}
<button
type="button"
class="toolbar-link"
@ -53,9 +59,11 @@
>
Destroy key
</button>
{{/if}}
{{#if @model.provider}}
<ConfirmAction
@buttonClasses="toolbar-link"
@onConfirmAction={{fn this.removeKey @model.id}}
@onConfirmAction={{this.removeKey}}
@confirmTitle="Remove this key?"
@confirmMessage="This will remove all versions of the key from the KMS provider. The key will stay in Vault."
@confirmButtonText="Remove"
@ -63,7 +71,10 @@
>
Remove key
</ConfirmAction>
{{/if}}
{{#if (or @model.canDelete @model.provider)}}
<div class="toolbar-separator"></div>
{{/if}}
<ConfirmAction
@buttonClasses="toolbar-link"
@onConfirmAction={{fn this.rotateKey @model.id}}
@ -74,6 +85,7 @@
>
Rotate key
</ConfirmAction>
{{#if @model.canEdit}}
<ToolbarSecretLink
@secret={{@model.id}}
@mode="edit"
@ -83,23 +95,44 @@
>
Edit key
</ToolbarSecretLink>
{{/if}}
</ToolbarActions>
</Toolbar>
{{/if}}
{{#if (eq this.mode "create")}}
<form {{on "submit" this.createKey}}>
{{#each @model.createFields as |attr|}}
<FormField @attr={{attr}} @model={{@model}} />
{{/each}}
<input type="submit" value="Create key" />
</form>
{{else if (eq this.mode "edit")}}
<form {{on "submit" this.updateKey}}>
{{#each @model.updateFields as |attr|}}
{{#if this.isMutable}}
<form {{on "submit" (perform this.saveKey)}}>
<div class="box is-sideless is-fullwidth is-marginless">
{{#let (if (eq @mode "create") "createFields" "updateFields") as |fieldsKey|}}
{{#each (get @model fieldsKey) as |attr|}}
<FormField data-test-field={{true}} @attr={{attr}} @model={{@model}} />
{{/each}}
<input type="submit" value="Update" />
<div class="field is-grouped box is-fullwidth is-bottomless">
<div class="control">
<button
type="submit"
disabled={{this.saveTask.isRunning}}
class="button is-primary {{if this.saveTask.isRunning 'is-loading'}}"
data-test-keymgmt-key-submit
>
{{if this.isCreating "Create key" "Update"}}
</button>
</div>
<div class="control">
<LinkTo
@route={{if this.isCreating @root.path "vault.cluster.secrets.backend.show"}}
@model={{if this.isCreating @root.model @model.id}}
@query={{unless this.isCreating (hash itemType="key")}}
@disabled={{this.savekey.isRunning}}
class="button"
data-test-keymgmt-key-cancel
>
Cancel
</LinkTo>
</div>
</div>
{{/let}}
</div>
</form>
{{else if (eq @tab "versions")}}
{{#each @model.versions as |version|}}
@ -135,11 +168,23 @@
{{/each}}
</div>
<div class="has-top-margin-xl has-bottom-margin-s">
<h2 class="title has-border-bottom-light is-5 {{if @model.provider.permissionsError 'is-borderless is-marginless'}}">
<h2 class="title has-border-bottom-light is-5 {{unless @model.provider.canListKeys 'is-borderless is-marginless'}}">
Distribution Details
</h2>
{{! TODO: Use capabilities to tell if it's not distributed vs no permissions }}
{{#if @model.provider.permissionsError}}
{{#if (not @model.provider)}}
<EmptyState
@title="Key not distributed"
@message="When this key is distributed to a destination, those details will appear here."
data-test-keymgmt-dist-empty-state
>
{{#if @model.canListProviders}}
<button type="button" class="link" {{on "click" (fn (mut this.isDistributing) true)}}>
Distribute key
<Icon @name="chevron-right" />
</button>
{{/if}}
</EmptyState>
{{else if (not @model.provider.canListKeys)}}
<EmptyState
@title="You are not authorized"
@subTitle="Error 403"
@ -152,7 +197,7 @@
}}
@icon="minus-circle"
/>
{{else if @model.provider}}
{{else}}
<InfoTableRow @label="Distributed" @value={{@model.provider}}>
<LinkTo @route="vault.cluster.secrets.backend.show" @model={{concat "kms/" @model.provider}}>
<Icon @name="check-circle-fill" class="has-text-success" />{{@model.provider}}
@ -181,20 +226,10 @@
@icon="minus-circle"
/>
{{/if}}
{{else}}
<EmptyState
@title="Key not distributed"
@message="When this key is distributed to a destination, those details will appear here."
data-test-keymgmt-dist-empty-state
>
{{! TODO: Distribute link
<LinkTo @route="vault.cluster.secrets.backend.distribute">
Distribute
</LinkTo> }}
</EmptyState>
{{/if}}
</div>
{{/if}}
{{/if}}
<ConfirmationModal
@title="Destroy key?"

View File

@ -4,7 +4,9 @@
</p.top>
<p.levelLeft>
<h1 class="title is-3" data-test-kms-provider-header>
{{#if this.isShowing}}
{{#if this.isDistributing}}
Destribute key to provider
{{else if this.isShowing}}
Provider
<span class="has-font-weight-normal">{{@model.id}}</span>
{{else}}
@ -14,6 +16,9 @@
</p.levelLeft>
</PageHeader>
{{#if this.isDistributing}}
<Keymgmt::Distribute @backend={{@model.backend}} @provider={{@model}} @onClose={{fn (mut this.isDistributing) false}} />
{{else}}
{{#if this.isShowing}}
<div class="tabs-container box is-sideless is-fullwidth is-paddingless is-marginless">
<nav class="tabs">
@ -23,17 +28,20 @@
Details
</LinkTo>
</li>
{{#if @model.canListKeys}}
<li class={{if this.viewingKeys "is-active"}} data-test-kms-provider-tab="keys">
<LinkTo @route="vault.cluster.secrets.backend.show" @model={{@model.id}} @query={{hash tab="keys"}}>
Keys
</LinkTo>
</li>
{{/if}}
</ul>
</nav>
</div>
{{#unless this.viewingKeys}}
<Toolbar data-test-kms-provider-details-actions>
<ToolbarActions>
{{#if @model.canDelete}}
<ToolTip @verticalPosition="above" @horizontalPosition="center" as |T|>
<T.Trigger data-test-tooltip-trigger>
<ConfirmAction
@ -48,26 +56,34 @@
{{#if @model.keys.length}}
<T.Content class="tool-tip">
<div class="box" data-test-kms-provider-delete-tooltip>
This provider cannot be deleted until all 20 keys distributed to it are revoked. This can be done from the
Keys tab.
This provider cannot be deleted until all
{{@model.keys.length}}
key(s) distributed to it are revoked. This can be done from the Keys tab.
</div>
</T.Content>
{{/if}}
</ToolTip>
{{/if}}
{{#if (and @model.canDelete (or @model.canListKeys @model.canEdit))}}
<div class="toolbar-separator"></div>
{{! Update once distribute route has been created }}
{{! <LinkTo @route="vault.cluster.secrets.backend.kms-distribute">
{{/if}}
{{#if (or @model.canListKeys @model.canCreateKeys)}}
<button type="button" class="toolbar-link" {{on "click" (fn (mut this.isDistributing) true)}}>
Distribute key
<Icon @name="chevron-right" />
</LinkTo> }}
</button>
{{/if}}
{{#if @model.canEdit}}
<ToolbarSecretLink
@secret={{@model.id}}
@mode="edit"
@replace={{true}}
@queryParams={{query-params itemType="provider"}}
disabled={{(not @model.canEdit)}}
>
Update credentials
</ToolbarSecretLink>
{{/if}}
</ToolbarActions>
</Toolbar>
{{/unless}}
@ -188,3 +204,4 @@
{{/if}}
</div>
{{/if}}
{{/if}}

View File

@ -85,13 +85,10 @@ module('Integration | Component | keymgmt/distribute', function (hooks) {
this.server.shutdown();
});
test('it does not render without @backend attr', async function (assert) {
await render(hbs`<Keymgmt::Distribute />`);
assert.dom(SELECTORS.form).doesNotExist('Form does not exist');
});
test('it does not allow operation selection until valid key and provider selected', async function (assert) {
await render(hbs`<Keymgmt::Distribute @backend="keymgmt" @providers={{providers}} />`);
await render(
hbs`<Keymgmt::Distribute @backend="keymgmt" @providers={{providers}} @onClose={{fn (mut this.onClose)}} />`
);
assert.dom(SELECTORS.operationsSection).hasAttribute('disabled');
await clickTrigger();
await settled();
@ -108,7 +105,9 @@ module('Integration | Component | keymgmt/distribute', function (hooks) {
assert.dom(SELECTORS.errorProvider).exists('Shows key/provider match error on provider');
});
test('it shows key type select field if new key created', async function (assert) {
await render(hbs`<Keymgmt::Distribute @backend="keymgmt" @providers={{providers}} />`);
await render(
hbs`<Keymgmt::Distribute @backend="keymgmt" @providers={{providers}} @onClose={{fn (mut this.onClose)}} />`
);
assert.dom(SELECTORS.keyTypeSection).doesNotExist('Key Type section is not rendered by default');
// Add new item on search-select
await clickTrigger();
@ -118,7 +117,9 @@ module('Integration | Component | keymgmt/distribute', function (hooks) {
assert.dom(SELECTORS.keyTypeSection).exists('Key Type selector is shown');
});
test('it hides the provider field if passed from the parent', async function (assert) {
await render(hbs`<Keymgmt::Distribute @backend="keymgmt" @provider="provider-azure" />`);
await render(
hbs`<Keymgmt::Distribute @backend="keymgmt" @provider="provider-azure" @onClose={{fn (mut this.onClose)}} />`
);
assert.dom(SELECTORS.providerInput).doesNotExist('Provider input is hidden');
// Select existing key
await clickTrigger();
@ -140,7 +141,9 @@ module('Integration | Component | keymgmt/distribute', function (hooks) {
assert.dom(SELECTORS.errorNewKey).exists('Shows error on key type');
});
test('it hides the key field if passed from the parent', async function (assert) {
await render(hbs`<Keymgmt::Distribute @backend="keymgmt" @providers={{providers}} @key="example-1" />`);
await render(
hbs`<Keymgmt::Distribute @backend="keymgmt" @providers={{providers}} @key="example-1" @onClose={{fn (mut this.onClose)}} />`
);
assert.dom(SELECTORS.providerInput).exists('Provider input shown');
assert.dom(SELECTORS.keySection).doesNotExist('Key input not shown');
await select(SELECTORS.providerInput, 'provider-azure');

View File

@ -23,6 +23,7 @@ module('Integration | Component | keymgmt/key-edit', function (hooks) {
creation_time: now,
},
],
canDelete: true,
});
this.model = model;
this.tab = '';

View File

@ -47,6 +47,12 @@ module('Integration | Component | keymgmt/provider-edit', function (hooks) {
test('it should render show view', async function (assert) {
assert.expect(13);
// override capability getters
Object.defineProperties(this.model, {
canDelete: { value: true },
canListKeys: { value: true },
});
this.server.get('/keymgmt/kms/foo-bar/key', () => {
return {
data: {