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

Backport 1.2.1: support ui redirect #7253

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions ui/app/components/auth-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,20 @@ export default Component.extend(DEFAULTS, {

authenticate: task(function*(backendType, data) {
let clusterId = this.cluster.id;
let targetRoute = this.redirectTo || 'vault.cluster';
try {
let authResponse = yield this.auth.authenticate({ clusterId, backend: backendType, data });

let { isRoot, namespace } = authResponse;
let transition = this.router.transitionTo(targetRoute, { queryParams: { namespace } });
let transition;
let { redirectTo } = this;
if (redirectTo) {
// reset the value on the controller because it's bound here
this.set('redirectTo', '');
// here we don't need the namespace because it will be encoded in redirectTo
transition = this.router.transitionTo(redirectTo);
} else {
transition = this.router.transitionTo('vault.cluster', { queryParams: { namespace } });
}
// returning this w/then because if we keep it
// in the task, it will get cancelled when the component in un-rendered
yield transition.followRedirects().then(() => {
Expand Down
2 changes: 1 addition & 1 deletion ui/app/components/key-value-header.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default Component.extend({
const showCurrent = this.get('showCurrent');
const ancestors = utils.ancestorKeysForKey(baseKey);
const parts = utils.keyPartsForKey(baseKey);
if (!ancestors) {
if (ancestors.length === 0) {
crumbs.push({
label: baseKey,
text: this.stripTrailingSlash(baseKey),
Expand Down
3 changes: 2 additions & 1 deletion ui/app/components/namespace-picker.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ export default Component.extend({
// gets set as 'lastMenuLeaves' in the ember concurrency task above
menuLeaves: computed('namespacePath', 'namespaceTree', function() {
let ns = this.get('namespacePath');
let leaves = ancestorKeysForKey(ns) || [];
ns = ns.replace(/^\//, '');
let leaves = ancestorKeysForKey(ns);
leaves.push(ns);
leaves = this.maybeAddRoot(leaves);

Expand Down
2 changes: 2 additions & 0 deletions ui/app/controllers/vault.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ export default Controller.extend({
queryParams: [
{
wrappedToken: 'wrapped_token',
redirectTo: 'redirect_to',
},
],
wrappedToken: '',
redirectTo: '',
env: config.environment,
auth: service(),
store: service(),
Expand Down
2 changes: 1 addition & 1 deletion ui/app/controllers/vault/cluster/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default Controller.extend({
queryParams: [{ authMethod: 'with' }],
wrappedToken: alias('vaultController.wrappedToken'),
authMethod: '',
redirectTo: null,
redirectTo: alias('vaultController.redirectTo'),

updateNamespace: task(function*(value) {
// debounce
Expand Down
2 changes: 1 addition & 1 deletion ui/app/lib/key-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function ancestorKeysForKey(key) {
parentKey = parentKeyForKey(parentKey);
}

return ancestors.length ? ancestors : null;
return ancestors;
}

export default {
Expand Down
25 changes: 20 additions & 5 deletions ui/app/mixins/cluster-route.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,41 @@ const INIT = 'vault.cluster.init';
const UNSEAL = 'vault.cluster.unseal';
const AUTH = 'vault.cluster.auth';
const CLUSTER = 'vault.cluster';
const CLUSTER_INDEX = 'vault.cluster.index';
const OIDC_CALLBACK = 'vault.cluster.oidc-callback';
const DR_REPLICATION_SECONDARY = 'vault.cluster.replication-dr-promote';

export { INIT, UNSEAL, AUTH, CLUSTER, DR_REPLICATION_SECONDARY };
export { INIT, UNSEAL, AUTH, CLUSTER, CLUSTER_INDEX, DR_REPLICATION_SECONDARY };

export default Mixin.create({
auth: service(),
store: service(),
router: service(),

transitionToTargetRoute(transition) {
transitionToTargetRoute(transition = {}) {
const targetRoute = this.targetRouteName(transition);
if (targetRoute && targetRoute !== this.routeName) {

if (
targetRoute &&
targetRoute !== this.routeName &&
targetRoute !== transition.targetName &&
targetRoute !== this.router.currentRouteName
) {
if (
// only want to redirect if we're going to authenticate
targetRoute === AUTH &&
transition.targetName !== CLUSTER_INDEX
) {
return this.transitionTo(targetRoute, { queryParams: { redirect_to: this.router.currentURL } });
}
return this.transitionTo(targetRoute);
}

return RSVP.resolve();
},

beforeModel() {
return this.transitionToTargetRoute();
beforeModel(transition) {
return this.transitionToTargetRoute(transition);
},

clusterModel() {
Expand Down
2 changes: 1 addition & 1 deletion ui/app/mixins/with-nav-to-nearest-ancestor.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default Mixin.create({
navToNearestAncestor: task(function*(key) {
let ancestors = utils.ancestorKeysForKey(key);
let errored = false;
let nearest = ancestors && ancestors.pop();
let nearest = ancestors.pop();
while (nearest) {
try {
let transition = this.transitionToRoute('vault.cluster.secrets.backend.list', nearest);
Expand Down
16 changes: 9 additions & 7 deletions ui/app/routes/vault/cluster/logout.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,21 @@ export default Route.extend(ModelBoundaryRoute, {
flashMessages: service(),
console: service(),
permissions: service(),
namespaceService: service('namespace'),

modelTypes: computed(function() {
return ['secret', 'secret-engine'];
}),

beforeModel() {
this.get('auth').deleteCurrentToken();
this.get('controlGroup').deleteTokens();
this.get('console').set('isOpen', false);
this.get('console').clearLog(true);
this.auth.deleteCurrentToken();
this.controlGroup.deleteTokens();
this.namespaceService.reset();
this.console.set('isOpen', false);
this.console.clearLog(true);
this.clearModelCache();
this.replaceWith('vault.cluster');
this.get('flashMessages').clearMessages();
this.get('permissions').reset();
this.replaceWith('vault.cluster.auth', { queryParams: { redirect_to: '' } });
this.flashMessages.clearMessages();
this.permissions.reset();
},
});
7 changes: 6 additions & 1 deletion ui/app/services/namespace.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ export default Service.extend({
namespace: userRoot,
},
});
let keys = ns.data.keys || [];
this.set(
'accessibleNamespaces',
ns.data.keys.map(n => {
keys.map(n => {
let fullNS = n;
// if the user's root isn't '', then we need to construct
// the paths so they connect to the user root to the list
Expand All @@ -51,4 +52,8 @@ export default Service.extend({
//do nothing here
}
}).drop(),

reset() {
this.set('accessibleNamespaces', null);
},
});
12 changes: 7 additions & 5 deletions ui/app/templates/components/namespace-link.hbs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
{{#link-to "vault.cluster.secrets" (query-params namespace=normalizedNamespace)
class=(concat "is-block " class)
}}
<LinkTo
@params={{array "vault.cluster.secrets" (query-params namespace=this.normalizedNamespace)}}
class={{concat "is-block " class}}
data-test-namespace-link={{this.normalizedNamespace}}
>
{{#if (has-block)}}
{{yield}}
{{else}}
<div class="level is-mobile">
<span class="level-left">{{namespaceDisplay}}</span>
<span class="level-left">{{this.namespaceDisplay}}</span>
<span class="level-right">
<button type="button" class="button is-ghost icon">
<Chevron @isButton={{true}} class="has-text-grey" />
</button>
</span>
</div>
{{/if}}
{{/link-to}}
</LinkTo>
5 changes: 3 additions & 2 deletions ui/app/templates/components/namespace-picker.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<D.trigger
@tagName="button"
@class="button is-transparent namespace-picker-trigger has-current-color"
data-test-namespace-toggle
>
{{yield}}
{{#if namespaceDisplay}}
Expand Down Expand Up @@ -44,7 +45,7 @@
<header class="current-namespace">
<h5 class="list-header">Current namespace</h5>
<div class="level is-mobile namespace-link">
<span class="level-left">{{if namespacePath (concat namespacePath "/") "root"}}</span>
<span class="level-left" data-test-current-namespace>{{if namespacePath (concat namespacePath "/") "root"}}</span>
<span class="level-right">
<Icon @glyph="check-circle-outline" class="has-text-success" />
</span>
Expand All @@ -65,7 +66,7 @@
{{if (and isAdding (eq leaf changedLeaf)) "leaf-panel-adding"}}
{{if (and (not isAdding) (eq leaf changedLeaf)) "leaf-panel-exiting"}}
">{{~#each-in (get namespaceTree leaf) as |leafName|}}
<NamespaceLink @targetNamespace={{concat leaf "/" leafName}} @class="namespace-link" @showLastSegment={{true}} />
<NamespaceLink @targetNamespace={{concat leaf "/" leafName}} @class="namespace-link" @showLastSegment={{true}} />
{{/each-in~}}</div>
{{/each}}
</div>
Expand Down
63 changes: 63 additions & 0 deletions ui/tests/acceptance/enterprise-namespaces-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { click, currentRouteName, currentURL, visit } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { create } from 'ember-cli-page-object';

import consoleClass from 'vault/tests/pages/components/console/ui-panel';
import authPage from 'vault/tests/pages/auth';
import logout from 'vault/tests/pages/logout';

const shell = create(consoleClass);

const createNS = async name => {
await shell.runCommands(`write sys/namespaces/${name} -force`);
};

const switchToNS = async name => {
await click('[data-test-namespace-toggle]');
await click(`[data-test-namespace-link="${name}"]`);
await click('[data-test-namespace-toggle]');
};

module('Acceptance | Enterprise | namespaces', function(hooks) {
setupApplicationTest(hooks);

hooks.beforeEach(function() {
return authPage.login();
});

test('it clears namespaces when you log out', async function(assert) {
let ns = 'foo';
await createNS(ns);
await shell.runCommands(`write -field=client_token auth/token/create policies=default`);
let token = shell.lastLogOutput;
await logout.visit();
await authPage.login(token);
assert.dom('[data-test-namespace-toggle]').doesNotExist('does not show the namespace picker');
await logout.visit();
});

test('it shows nested namespaces if you log in with a namspace starting with a /', async function(assert) {
let nses = ['beep', 'boop', 'bop'];
for (let [i, ns] of nses.entries()) {
await createNS(ns);
// this is usually triggered when creating a ns in the form, here we'll trigger a reload of the
// namespaces manually
await this.owner.lookup('service:namespace').findNamespacesForUser.perform();
if (i === nses.length - 1) {
break;
}
// the namespace path will include all of the namespaces up to this point
let targetNamespace = nses.slice(0, i + 1).join('/');
await switchToNS(targetNamespace);
}
await logout.visit();
await authPage.visit({ with: 'token', namespace: '/beep/boop' });
await authPage.tokenInput('root').submit();
await click('[data-test-namespace-toggle]');
assert.dom('[data-test-current-namespace]').hasText('/beep/boop/', 'current namespace begins with a /');
assert
.dom('[data-test-namespace-link="beep/boop/bop"]')
.exists('renders the link to the nested namespace');
});
});
39 changes: 39 additions & 0 deletions ui/tests/acceptance/redirect-to-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { currentURL, visit } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import authPage from 'vault/tests/pages/auth';

module('Acceptance | redirect_to functionality', function(hooks) {
setupApplicationTest(hooks);

test('redirect to a route after authentication', async function(assert) {
let url = '/vault/secrets/secret/create';
await visit(url);
assert.equal(
currentURL(),
`/vault/auth?redirect_to=${encodeURIComponent(url)}&with=token`,
'encodes url for the query param'
);
// the login method on this page does another visit call that we don't want here
await authPage.tokenInput('root').submit();
assert.equal(currentURL(), url, 'navigates to the redirect_to url after auth');
});

test('redirect from root does not include redirect_to', async function(assert) {
let url = '/';
await visit(url);
assert.equal(currentURL(), `/vault/auth?with=token`, 'there is no redirect_to query param');
});

test('redirect to a route after authentication with a query param', async function(assert) {
let url = '/vault/secrets/secret/create?initialKey=hello';
await visit(url);
assert.equal(
currentURL(),
`/vault/auth?redirect_to=${encodeURIComponent(url)}&with=token`,
'encodes url for the query param'
);
await authPage.tokenInput('root').submit();
assert.equal(currentURL(), url, 'navigates to the redirect_to with the query param after auth');
});
});
43 changes: 41 additions & 2 deletions ui/tests/unit/mixins/cluster-route-test.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import { assign } from '@ember/polyfills';
import EmberObject from '@ember/object';
import ClusterRouteMixin from 'vault/mixins/cluster-route';
import { INIT, UNSEAL, AUTH, CLUSTER, DR_REPLICATION_SECONDARY } from 'vault/mixins/cluster-route';
import {
INIT,
UNSEAL,
AUTH,
CLUSTER,
CLUSTER_INDEX,
DR_REPLICATION_SECONDARY,
} from 'vault/mixins/cluster-route';
import { module, test } from 'qunit';
import sinon from 'sinon';

module('Unit | Mixin | cluster route', function() {
function createClusterRoute(
clusterModel = {},
methods = { hasKeyData: () => false, authToken: () => null }
methods = { router: {}, hasKeyData: () => false, authToken: () => null, transitionTo: () => {} }
) {
let ClusterRouteObject = EmberObject.extend(
ClusterRouteMixin,
Expand Down Expand Up @@ -80,4 +88,35 @@ module('Unit | Mixin | cluster route', function() {
'forwards when not a DR secondary and navigating to DR_REPLICATION_SECONDARY'
);
});

test('#transitionToTargetRoute', function(assert) {
let redirectRouteURL = '/vault/secrets/secret/create';
let subject = createClusterRoute({ needsInit: false, sealed: false });
subject.router.currentURL = redirectRouteURL;
let spy = sinon.spy(subject, 'transitionTo');
subject.transitionToTargetRoute();
assert.ok(
spy.calledWithExactly(AUTH, { queryParams: { redirect_to: redirectRouteURL } }),
'calls transitionTo with the expected args'
);

spy.restore();
});

test('#transitionToTargetRoute with auth as a target', function(assert) {
let subject = createClusterRoute({ needsInit: false, sealed: false });
let spy = sinon.spy(subject, 'transitionTo');
// in this case it's already transitioning to the AUTH route so we don't need to call transitionTo again
subject.transitionToTargetRoute({ targetName: AUTH });
assert.ok(spy.notCalled, 'transitionTo is not called');
spy.restore();
});

test('#transitionToTargetRoute with auth target, coming from cluster route', function(assert) {
let subject = createClusterRoute({ needsInit: false, sealed: false });
let spy = sinon.spy(subject, 'transitionTo');
subject.transitionToTargetRoute({ targetName: CLUSTER_INDEX });
assert.ok(spy.calledWithExactly(AUTH), 'calls transitionTo without redirect_to');
spy.restore();
});
});