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

UI: add ACL-checking to turn off exec button #7919

Merged
merged 9 commits into from
May 11, 2020
Merged
71 changes: 71 additions & 0 deletions ui/app/abilities/abstract.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Ability } from 'ember-can';
import { inject as service } from '@ember/service';
import { computed, get } from '@ember/object';
import { equal, not } from '@ember/object/computed';

export default Ability.extend({
system: service(),
token: service(),

bypassAuthorization: not('token.aclEnabled'),
selfTokenIsManagement: equal('token.selfToken.type', 'management'),

activeNamespace: computed('system.activeNamespace.name', function() {
return this.get('system.activeNamespace.name') || 'default';
}),

rulesForActiveNamespace: computed('activeNamespace', 'token.selfTokenPolicies.[]', function() {
let activeNamespace = this.activeNamespace;

return (this.get('token.selfTokenPolicies') || []).toArray().reduce((rules, policy) => {
let policyNamespaces = get(policy, 'rulesJSON.Namespaces') || [];

let matchingNamespace = this._findMatchingNamespace(policyNamespaces, activeNamespace);

if (matchingNamespace) {
rules.push(policyNamespaces.find(namespace => namespace.Name === matchingNamespace));
}

return rules;
}, []);
}),

// Chooses the closest namespace as described at the bottom here:
// https://www.nomadproject.io/guides/security/acl.html#namespace-rules
_findMatchingNamespace(policyNamespaces, activeNamespace) {
let namespaceNames = policyNamespaces.mapBy('Name');

if (namespaceNames.includes(activeNamespace)) {
return activeNamespace;
}

let globNamespaceNames = namespaceNames.filter(namespaceName => namespaceName.includes('*'));

let matchingNamespaceName = globNamespaceNames.reduce(
(mostMatching, namespaceName) => {
// Convert * wildcards to .* for regex matching
let namespaceNameRegExp = new RegExp(namespaceName.replace(/\*/g, '.*'));
let characterDifference = activeNamespace.length - namespaceName.length;

if (
characterDifference < mostMatching.mostMatchingCharacterDifference &&
activeNamespace.match(namespaceNameRegExp)
) {
return {
mostMatchingNamespaceName: namespaceName,
mostMatchingCharacterDifference: characterDifference,
};
} else {
return mostMatching;
}
},
{ mostMatchingNamespaceName: null, mostMatchingCharacterDifference: Number.MAX_SAFE_INTEGER }
).mostMatchingNamespaceName;

if (matchingNamespaceName) {
return matchingNamespaceName;
} else if (namespaceNames.includes('default')) {
return 'default';
}
},
});
14 changes: 14 additions & 0 deletions ui/app/abilities/allocation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import AbstractAbility from './abstract';
import { computed, get } from '@ember/object';
import { or } from '@ember/object/computed';

export default AbstractAbility.extend({
canExec: or('bypassAuthorization', 'selfTokenIsManagement', 'policiesSupportExec'),

policiesSupportExec: computed('rulesForActiveNamespace.@each.capabilities', function() {
return this.rulesForActiveNamespace.some(rules => {
let capabilities = get(rules, 'Capabilities') || [];
return capabilities.includes('alloc-exec');
});
}),
});
12 changes: 3 additions & 9 deletions ui/app/abilities/client.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import { Ability } from 'ember-can';
import { inject as service } from '@ember/service';
import AbstractAbility from './abstract';
import { computed, get } from '@ember/object';
import { equal, or, not } from '@ember/object/computed';

export default Ability.extend({
token: service(),
import { or } from '@ember/object/computed';

export default AbstractAbility.extend({
// Map abilities to policy options (which are coarse for nodes)
// instead of specific behaviors.
canWrite: or('bypassAuthorization', 'selfTokenIsManagement', 'policiesIncludeNodeWrite'),

bypassAuthorization: not('token.aclEnabled'),
selfTokenIsManagement: equal('token.selfToken.type', 'management'),

policiesIncludeNodeWrite: computed('token.selfTokenPolicies.[]', function() {
// For each policy record, extract the Node policy
const policies = (this.get('token.selfTokenPolicies') || [])
Expand Down
72 changes: 3 additions & 69 deletions ui/app/abilities/job.js
Original file line number Diff line number Diff line change
@@ -1,80 +1,14 @@
import { Ability } from 'ember-can';
import { inject as service } from '@ember/service';
import AbstractAbility from './abstract';
import { computed, get } from '@ember/object';
import { equal, or, not } from '@ember/object/computed';

export default Ability.extend({
system: service(),
token: service(),
import { or } from '@ember/object/computed';

export default AbstractAbility.extend({
canRun: or('bypassAuthorization', 'selfTokenIsManagement', 'policiesSupportRunning'),

bypassAuthorization: not('token.aclEnabled'),
selfTokenIsManagement: equal('token.selfToken.type', 'management'),

activeNamespace: computed('system.activeNamespace.name', function() {
return this.get('system.activeNamespace.name') || 'default';
}),

rulesForActiveNamespace: computed('activeNamespace', 'token.selfTokenPolicies.[]', function() {
let activeNamespace = this.activeNamespace;

return (this.get('token.selfTokenPolicies') || []).toArray().reduce((rules, policy) => {
let policyNamespaces = get(policy, 'rulesJSON.Namespaces') || [];

let matchingNamespace = this._findMatchingNamespace(policyNamespaces, activeNamespace);

if (matchingNamespace) {
rules.push(policyNamespaces.find(namespace => namespace.Name === matchingNamespace));
}

return rules;
}, []);
}),

policiesSupportRunning: computed('rulesForActiveNamespace.@each.capabilities', function() {
return this.rulesForActiveNamespace.some(rules => {
let capabilities = get(rules, 'Capabilities') || [];
return capabilities.includes('submit-job');
});
}),

// Chooses the closest namespace as described at the bottom here:
// https://www.nomadproject.io/guides/security/acl.html#namespace-rules
_findMatchingNamespace(policyNamespaces, activeNamespace) {
let namespaceNames = policyNamespaces.mapBy('Name');

if (namespaceNames.includes(activeNamespace)) {
return activeNamespace;
}

let globNamespaceNames = namespaceNames.filter(namespaceName => namespaceName.includes('*'));

let matchingNamespaceName = globNamespaceNames.reduce(
(mostMatching, namespaceName) => {
// Convert * wildcards to .* for regex matching
let namespaceNameRegExp = new RegExp(namespaceName.replace(/\*/g, '.*'));
let characterDifference = activeNamespace.length - namespaceName.length;

if (
characterDifference < mostMatching.mostMatchingCharacterDifference &&
activeNamespace.match(namespaceNameRegExp)
) {
return {
mostMatchingNamespaceName: namespaceName,
mostMatchingCharacterDifference: characterDifference,
};
} else {
return mostMatching;
}
},
{ mostMatchingNamespaceName: null, mostMatchingCharacterDifference: Number.MAX_SAFE_INTEGER }
).mostMatchingNamespaceName;

if (matchingNamespaceName) {
return matchingNamespaceName;
} else if (namespaceNames.includes('default')) {
return 'default';
}
},
});
20 changes: 12 additions & 8 deletions ui/app/templates/components/exec/open-button.hbs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
<button
data-test-exec-button
type="button"
class="button exec-button is-outline is-small"
{{action "open"}}>
{{x-icon "console"}}
<span>Exec</span>
</button>
{{#let (cannot "exec allocation") as |cannotExec|}}
backspace marked this conversation as resolved.
Show resolved Hide resolved
<button
data-test-exec-button
type="button"
class="button exec-button is-outline is-small {{if cannotExec "tooltip"}}"
disabled={{if cannotExec 'disabled'}}
aria-label={{if cannotExec "You don’t have permission to exec"}}
{{action "open"}}>
{{x-icon "console"}}
<span>Exec</span>
</button>
{{/let}}
7 changes: 7 additions & 0 deletions ui/tests/acceptance/allocation-detail-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ module('Acceptance | allocation detail', function(hooks) {
node.id.split('-')[0],
'Node short id is in the subheading'
);
assert.ok(Allocation.execButton.isPresent);

assert.equal(document.title, `Allocation ${allocation.name} - Nomad`);

Expand Down Expand Up @@ -347,6 +348,12 @@ module('Acceptance | allocation detail (not running)', function(hooks) {
'Empty message is appropriate'
);
});

test('the exec and stop/restart buttons are absent', async function(assert) {
assert.notOk(Allocation.execButton.isPresent);
assert.notOk(Allocation.stop.isPresent);
assert.notOk(Allocation.restart.isPresent);
});
});

module('Acceptance | allocation detail (preemptions)', function(hooks) {
Expand Down
61 changes: 59 additions & 2 deletions ui/tests/acceptance/job-detail-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,16 @@ module('Acceptance | job detail (with namespaces)', function(hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);

let job;
let job, clientToken;

hooks.beforeEach(function() {
server.createList('namespace', 2);
server.create('node');
job = server.create('job', { type: 'service', namespaceId: server.db.namespaces[1].name });
job = server.create('job', { type: 'service', status: 'running', namespaceId: server.db.namespaces[1].name });
server.createList('job', 3, { namespaceId: server.db.namespaces[0].name });

server.create('token');
clientToken = server.create('token');
});

test('when there are namespaces, the job detail page states the namespace for the job', async function(assert) {
Expand Down Expand Up @@ -101,4 +104,58 @@ module('Acceptance | job detail (with namespaces)', function(hooks) {
assert.equal(jobRow.name, jobs[index].name, `Job ${index} is right`);
});
});

test('the exec button state can change between namespaces', async function(assert) {
const job1 = server.create('job', { status: 'running', namespaceId: server.db.namespaces[0].id });
const job2 = server.create('job', { status: 'running', namespaceId: server.db.namespaces[1].id });

window.localStorage.nomadTokenSecret = clientToken.secretId;

const policy = server.create('policy', {
id: 'something',
name: 'something',
rulesJSON: {
Namespaces: [
{
Name: job1.namespaceId,
Capabilities: ['list-jobs', 'alloc-exec'],
},
{
Name: job2.namespaceId,
Capabilities: ['list-jobs'],
},
],
},
});

clientToken.policyIds = [policy.id];
clientToken.save();

await JobDetail.visit({ id: job1.id });
assert.notOk(JobDetail.execButton.isDisabled);

const secondNamespace = server.db.namespaces[1];
await JobDetail.visit({ id: job2.id, namespace: secondNamespace.name });
assert.ok(JobDetail.execButton.isDisabled);
});

test('the anonymous policy is fetched to check whether to show the exec button', async function(assert) {
window.localStorage.removeItem('nomadTokenSecret');

server.create('policy', {
id: 'anonymous',
name: 'anonymous',
rulesJSON: {
Namespaces: [
{
Name: 'default',
Capabilities: ['list-jobs', 'alloc-exec'],
},
],
},
});

await JobDetail.visit({ id: job.id, namespace: server.db.namespaces[1].name });
assert.notOk(JobDetail.execButton.isDisabled);
});
});
12 changes: 12 additions & 0 deletions ui/tests/helpers/module-for-job.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ export default function moduleForJob(title, context, jobFactory, additionalTests
assert.equal(currentURL(), `/jobs/${job.id}/evaluations`);
});

test('the title buttons are dependent on job status', async function(assert) {
if (job.status === 'dead') {
assert.ok(JobDetail.start.isPresent);
assert.notOk(JobDetail.stop.isPresent);
assert.notOk(JobDetail.execButton.isPresent);
} else {
assert.notOk(JobDetail.start.isPresent);
assert.ok(JobDetail.stop.isPresent);
assert.ok(JobDetail.execButton.isPresent);
}
});

if (context === 'allocations') {
test('allocations for the job are shown in the overview', async function(assert) {
assert.ok(JobDetail.allocationsSummary, 'Allocations are shown in the summary section');
Expand Down
4 changes: 4 additions & 0 deletions ui/tests/pages/allocations/detail.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export default create({
stop: twoStepButton('[data-test-stop]'),
restart: twoStepButton('[data-test-restart]'),

execButton: {
scope: '[data-test-exec-button]',
},

details: {
scope: '[data-test-allocation-details]',

Expand Down
13 changes: 13 additions & 0 deletions ui/tests/pages/jobs/detail.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ import {
create,
collection,
clickable,
hasClass,
isPresent,
property,
text,
visitable,
} from 'ember-cli-page-object';

import allocations from 'nomad-ui/tests/pages/components/allocations';
import twoStepButton from 'nomad-ui/tests/pages/components/two-step-button';

export default create({
visit: visitable('/jobs/:id'),
Expand All @@ -22,6 +25,16 @@ export default create({
return this.tabs.toArray().findBy('id', id);
},

stop: twoStepButton('[data-test-stop]'),
start: twoStepButton('[data-test-start]'),

execButton: {
scope: '[data-test-exec-button]',
isDisabled: property('disabled'),
hasTooltip: hasClass('tooltip'),
tooltipText: attribute('aria-label'),
},

stats: collection('[data-test-job-stat]', {
id: attribute('data-test-job-stat'),
text: text(),
Expand Down
Loading