vault/ui/app/components/database-role-edit.js
Rémi Lapeyre 3aee6ec464
Fix UI when editing database roles (#24660)
* Fix UI when editing database roles

When using a database role the UI will try to update the database connection
associated to the role. This is to make sure that the role is allowed to
use this connection:

    async _updateAllowedRoles(store, { role, backend, db, type = 'add' }) {
      const connection = await store.queryRecord('database/connection', { backend, id: db });
      const roles = [...connection.allowed_roles];
      const allowedRoles = type === 'add' ? addToArray([roles, role]) : removeFromArray([roles, role]);
      connection.allowed_roles = allowedRoles;
      return connection.save();
    },

    async createRecord(store, type, snapshot) {
      const serializer = store.serializerFor(type.modelName);
      const data = serializer.serialize(snapshot);
      const roleType = snapshot.attr('type');
      const backend = snapshot.attr('backend');
      const id = snapshot.attr('name');
      const db = snapshot.attr('database');
      try {
        await this._updateAllowedRoles(store, {
          role: id,
          backend,
          db: db[0],
        });
      } catch (e) {
        throw new Error('Could not update allowed roles for selected database. Check Vault logs for details');
      }

      return this.ajax(this.urlFor(backend, id, roleType), 'POST', { data }).then(() => {
        // ember data doesn't like 204s if it's not a DELETE
        return {
          data: assign({}, data, { id }),
        };
      });
    },

This is intended to help the administrator as the role will only work if
it is allowed by the database connection.

This is however an issue if the person doing the update does not have
the permission to update the connection: they will not be able to use
the UI to update the role even though they have the appropriate permissions
to do so (using the CLI or the API will work for example).

This is often the case when the database connections are created by a
centralized system but a human operator needs to create the roles.

You can try this with the following test case:

    $ cat main.tf
    resource "vault_auth_backend" "userpass" {
      type = "userpass"
    }

    resource "vault_generic_endpoint" "alice" {
      depends_on           = [vault_auth_backend.userpass]
      path                 = "auth/userpass/users/alice"
      ignore_absent_fields = true

      data_json = jsonencode({
        "policies" : ["root"],
        "password" : "alice"
      })
    }

    data "vault_policy_document" "db_admin" {
      rule {
        path         = "database/roles/*"
        capabilities = ["create", "read", "update", "delete", "list"]
      }
    }

    resource "vault_policy" "db_admin" {
      name   = "db-admin"
      policy = data.vault_policy_document.db_admin.hcl
    }

    resource "vault_generic_endpoint" "bob" {
      depends_on           = [vault_auth_backend.userpass]
      path                 = "auth/userpass/users/bob"
      ignore_absent_fields = true

      data_json = jsonencode({
        "policies" : [vault_policy.db_admin.name],
        "password" : "bob"
      })
    }

    resource "vault_mount" "db" {
      path = "database"
      type = "database"
    }

    resource "vault_database_secret_backend_connection" "postgres" {
      backend           = vault_mount.db.path
      name              = "postgres"
      allowed_roles     = ["*"]
      verify_connection = false

      postgresql {
        connection_url = "postgres://username:password@localhost/database"
      }
    }
    $ terraform apply --auto-approve

then using bob to create a role associated to the `postgres` connection.

This patch changes the way the UI does the update: it still tries to
update the database connection but if it fails to do so because it does not
have the permission it just silently skip this part and updates the role.

This also update the error message returned to the user in case of issues
to include the actual errors.

* Add changelog

* Also ignore error when deleting a role

* Address code review comments

---------

Co-authored-by: Chelsea Shaw <82459713+hashishaw@users.noreply.github.com>
2024-01-05 11:11:33 -08:00

120 lines
3.2 KiB
JavaScript

/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
const LIST_ROOT_ROUTE = 'vault.cluster.secrets.backend.list-root';
const SHOW_ROUTE = 'vault.cluster.secrets.backend.show';
export default class DatabaseRoleEdit extends Component {
@service router;
@service flashMessages;
@service store;
constructor() {
super(...arguments);
if (this.args.initialKey) {
this.args.model.database = [this.args.initialKey];
}
}
@tracked loading = false;
get warningMessages() {
const warnings = {};
if (
(this.args.model.type === 'dynamic' && this.args.model.canCreateDynamic === false) ||
(this.args.model.type === 'static' && this.args.model.canCreateStatic === false)
) {
warnings.type = `You don't have permissions to create this type of role.`;
}
return warnings;
}
get databaseType() {
const backend = this.args.model?.backend;
const dbs = this.args.model?.database || [];
if (!backend || dbs.length === 0) {
return null;
}
return this.store
.queryRecord('database/connection', { id: dbs[0], backend })
.then((record) => record.plugin_name)
.catch(() => null);
}
@action
generateCreds(roleId, roleType = '') {
this.router.transitionTo('vault.cluster.secrets.backend.credentials', roleId, {
queryParams: { roleType },
});
}
@action
delete() {
const secret = this.args.model;
const backend = secret.backend;
return secret
.destroyRecord()
.then(() => {
try {
this.router.transitionTo(LIST_ROOT_ROUTE, backend, { queryParams: { tab: 'role' } });
} catch (e) {
console.debug(e); // eslint-disable-line
}
})
.catch((e) => {
this.flashMessages.danger(e.errors?.join('. '));
});
}
@action
handleCreateEditRole(evt) {
evt.preventDefault();
this.loading = true;
const mode = this.args.mode;
const roleSecret = this.args.model;
const secretId = roleSecret.name;
if (mode === 'create') {
roleSecret.set('id', secretId);
const path = roleSecret.type === 'static' ? 'static-roles' : 'roles';
roleSecret.set('path', path);
}
return roleSecret
.save()
.then(() => {
try {
this.router.transitionTo(SHOW_ROUTE, `role/${secretId}`);
} catch (e) {
console.debug(e); // eslint-disable-line
}
})
.catch((e) => {
const errorMessage = e.errors?.join('. ') || e.message;
this.flashMessages.danger(
errorMessage || 'Could not save the role. Please check Vault logs for more information.'
);
this.loading = false;
});
}
@action
rotateRoleCred(id) {
const backend = this.args.model?.backend;
const adapter = this.store.adapterFor('database/credential');
return adapter
.rotateRoleCredentials(backend, id)
.then(() => {
this.flashMessages.success(`Success: Credentials for ${id} role were rotated`);
})
.catch((e) => {
this.flashMessages.danger(e.errors);
});
}
}