

# Managing roles for data groups

Database roles belong to the whole DB cluster, not to one data group. When a data group moves, Aurora must determine, for each role that owns its objects or has privileges on them, whether to create the role on the target DB cluster or to use an existing role with the same name. You provide this information by mapping each of those roles to the data group.

At the start of prepare, Aurora checks every role that owns or has privileges on objects in the data group. If any of these roles isn't mapped to the data group, the prepare fails. For this reason, map roles before you move a data group. We recommend that you map them before you create objects in the data group.

When you map roles, consider the following:
+ You need role mappings only to move a data group. If you don't plan to move it, you don't need to map any roles.
+ Map the cluster admin user to every data group that you plan to move. For more information, see [Mapping the cluster admin user](aurora-data-groups-prereqs.md#dg-prereq-admin).
+ You map roles to each data group separately. To map several roles that use the same mapping type, pass all of them in one `aurora_datagroup_add_role_access` function call.
+ You can't use wildcard characters or patterns in role names. Aurora doesn't map new roles or new data groups automatically.

**Topics**
+ [Mapping types](#dg-users-types)
+ [Choosing which roles to map](#dg-users-which)
+ [Mapping, listing, and removing role mappings](#dg-users-map)
+ [What happens to roles during a move](#dg-users-move)

## Mapping types
<a name="dg-users-types"></a>

Each role mapping has one of the following types.

**`DATAGROUP_CONSTRAINED`**  
A role that belongs to one data group and moves with it. Use this type for an application role that works only with that data group.  
+ You can map the role to only one data group.
+ A role with the same name can't already exist on the target DB cluster. Prepare creates the role there with its privileges, attributes, password, and role memberships.
+ After the move, Aurora removes the mapping and drops the role on the source DB cluster.

**`EXPECT_NAME_MATCH`**  
A role that's used across the DB cluster, such as the cluster admin user or a shared reporting role. The role isn't limited to the data group.  
+ You can map the role to more than one data group.
+ A role with the same name must already exist on the target DB cluster before you prepare the move. Only the role's privileges on, and ownership of, the objects in the data group move with it.
+ The role on the target DB cluster must have at least the attributes that the source role has (such as `LOGIN`, `CREATEROLE`, and `BYPASSRLS`), a connection limit at least as high as the source role's (no limit, `-1`, counts as highest), and at least the roles granted to the source role. Prepare checks this and doesn't change the role on the target DB cluster. If the target role is missing any of these, prepare is refused. Role memberships don't move, so grant them on the target DB cluster before you prepare.
+ After the move, Aurora removes the mapping on the source DB cluster and keeps the role there. The role's grants on the moved objects also stay on the source DB cluster. If the role doesn't need these grants on the source DB cluster, revoke them.

Role mappings move with the data group. Prepare creates them on the target DB cluster, so you don't need to map the roles again to move the data group back.

A `DATAGROUP_CONSTRAINED` role is limited to its data group:
+ The role can't connect to databases outside its data group or own objects outside it. It can't be granted `rds_superuser`, and it can't be granted to a role that isn't mapped to a data group.
+ Roles in one chain of grants must all have the same mapping type. For example, you can't grant a `DATAGROUP_CONSTRAINED` role to an `EXPECT_NAME_MATCH` role. To give an `EXPECT_NAME_MATCH` role the same privileges, grant them to a separate `EXPECT_NAME_MATCH` role, and then grant that role to it.

## Choosing which roles to map
<a name="dg-users-which"></a>

Map every role or user that owns objects in the data group or has privileges on them, as follows:
+ Map the cluster admin user with `EXPECT_NAME_MATCH`. A move is refused without this mapping. The cluster admin user owns the objects that it creates, so most data groups need this mapping. The mapping matches roles by name, so the move works only if the target DB cluster has a cluster admin user with the same name. To have the data group's objects owned by a role that moves with them, use a `DATAGROUP_CONSTRAINED` role as their owner. You still map the cluster admin user.

  To make a `DATAGROUP_CONSTRAINED` role the owner, create the database in the data group as the cluster admin user, and then use one of the following ways:
  + Make the `DATAGROUP_CONSTRAINED` role the database owner with `ALTER DATABASE {{orders}} OWNER TO {{tenant42_app}}`. The database owner can create objects in the `public` schema.
  + Grant the `DATAGROUP_CONSTRAINED` role `USAGE` and `CREATE` on the schema. Connect to the database first, for example `GRANT USAGE, CREATE ON SCHEMA public TO {{tenant42_app}};`

  Then connect as the role and create the tables. The role owns the objects that it creates. The following methods don't work: `CREATE DATABASE ... OWNER` with the role fails with `must be able to SET ROLE`, and granting the role to the cluster admin user fails with `cannot grant role to non-datagroup role`.
+ Map the roles that belong to one data group with `DATAGROUP_CONSTRAINED`, so that they move with the data group. These roles own objects or have privileges only in the data group's databases.
+ Map shared roles with `EXPECT_NAME_MATCH`, and create them on the target DB cluster before you prepare a move. A shared role also owns objects or has privileges in databases outside the data group.
+ You don't need to map the system roles `rdsadmin`, `rds_superuser`, and the `pg_*` roles. You can map them as `EXPECT_NAME_MATCH`. If a mapped role is a member of a system role on the source DB cluster, prepare checks that the same membership exists on the target DB cluster.

To find the roles to map, list the databases where each role owns objects or has privileges. The following query reads two PostgreSQL system catalogs: `pg_shdepend`, which records the owner of each object and the privileges granted on it in every database, and `pg_database`, which records the owner of each database. Run it on the writer DB instance as the cluster admin user.

```SQL
SELECT r.rolname AS role, d.datname AS database
  FROM pg_shdepend s
  JOIN pg_roles r ON r.oid = s.refobjid
  JOIN pg_database d ON d.oid = s.dbid
 WHERE s.refclassid = 'pg_authid'::regclass
UNION
SELECT r.rolname, d.datname
  FROM pg_database d
  JOIN pg_roles r ON r.oid = d.datdba
 ORDER BY 1, 2;
```

The output has one row for each role and database pair. A role that appears only in the data group's databases is a candidate for `DATAGROUP_CONSTRAINED`. A role that also appears in other databases is a shared role, so map it as `EXPECT_NAME_MATCH`. The query includes schemas and default privileges (`ALTER DEFAULT PRIVILEGES`). It doesn't show privileges on a database itself, such as `CONNECT`, or role memberships, so check those separately.

The following example output is for a cluster where the `tenant42` data group holds the `orders42` database:

```
      role       |  database
-----------------+-----------
 postgres        | orders42
 postgres        | postgres
 reporting       | orders42
 reporting       | orders17
 tenant42_app    | orders42
 tenant42_reader | orders42
```

In this example, `tenant42_app` and `tenant42_reader` appear only in `orders42`, so map them as `DATAGROUP_CONSTRAINED`. `postgres` is the cluster admin user, and `reporting` also has privileges in `orders17`, so map both as `EXPECT_NAME_MATCH`. Also check role memberships. If a role is granted to a mapped role, map it with the same mapping type.

Before you prepare a move, check that each `EXPECT_NAME_MATCH` role on the target DB cluster meets the requirements in [Mapping types](#dg-users-types). Run the following query on the writer DB instance of each DB cluster, and compare the output. If the target role is missing an attribute or a role membership, add it on the target DB cluster. If its connection limit is lower, raise it with `ALTER ROLE ... CONNECTION LIMIT`.

```SQL
SELECT r.rolname, r.rolcanlogin, r.rolcreaterole, r.rolcreatedb, r.rolbypassrls, r.rolconnlimit,
       ARRAY(SELECT g.rolname
               FROM pg_auth_members m
               JOIN pg_roles g ON g.oid = m.roleid
              WHERE m.member = r.oid
              ORDER BY 1) AS member_of
  FROM pg_roles r
 WHERE r.rolname IN ('{{postgres}}', '{{reporting}}');
```

The output resembles the following example. Here, both roles have the same attributes and memberships on the source and target DB clusters, so they pass the check.

```
  rolname  | rolcanlogin | rolcreaterole | rolcreatedb | rolbypassrls | rolconnlimit |    member_of
-----------+-------------+---------------+-------------+--------------+--------------+-----------------
 postgres  | t           | t             | t           | f            |           -1 | {rds_superuser}
 reporting | f           | f             | f           | f            |           -1 | {}
(2 rows)
```

## Mapping, listing, and removing role mappings
<a name="dg-users-map"></a>

Run the following statements on the writer DB instance, as the cluster admin user.
+ The mapping functions require superuser privileges. If a role without these privileges calls a mapping function, the call fails with the error `must be superuser to map resources to datagroup`.

------
#### [ Aurora PostgreSQL ]

To map roles, use `aurora_datagroup_add_role_access`. Pass the data group name, the mapping type, and one or more roles. The function returns `success` and `message` columns.

```SQL
SELECT * FROM aurora_datagroup_add_role_access('tenant42', 'EXPECT_NAME_MATCH', 'postgres');
SELECT * FROM aurora_datagroup_add_role_access('tenant42', 'DATAGROUP_CONSTRAINED', 'tenant42_app', 'tenant42_reader');
```

To list mappings, use `aurora_datagroup_list_role_access`. Any user can run it.

```SQL
SELECT * FROM aurora_datagroup_list_role_access();
```

The output resembles the following:

```
     resource_type     |  resource_name  | datagroup_name
-----------------------+-----------------+----------------
 EXPECT_NAME_MATCH     | postgres        | tenant42
 DATAGROUP_CONSTRAINED | tenant42_app    | tenant42
 DATAGROUP_CONSTRAINED | tenant42_reader | tenant42
(3 rows)
```

To remove mappings, use `aurora_datagroup_remove_role_access`.

```SQL
SELECT * FROM aurora_datagroup_remove_role_access('tenant42', 'tenant42_reader');
```

The `resource_type` column shows the mapping type.

------

## What happens to roles during a move
<a name="dg-users-move"></a>

The following describes what happens to roles at each step of a move:
+ Prepare – Aurora checks the mappings on the source DB cluster. On the target DB cluster, it creates the `DATAGROUP_CONSTRAINED` roles and checks that the `EXPECT_NAME_MATCH` roles exist and match the source roles.
+ Cancel – Aurora removes the items that prepare created on the target DB cluster: the data group's databases, the role mappings, and the `DATAGROUP_CONSTRAINED` roles. Roles that already existed on the target DB cluster remain.
+ Execute – The roles' privileges on, and ownership of, the moved objects take effect on the target DB cluster. On the source DB cluster, Aurora drops the `DATAGROUP_CONSTRAINED` roles and removes all mappings for the data group.

From the start of prepare until the move finishes or you cancel it, you can't change the data group's role mappings, or run `ALTER ROLE`, `GRANT`, or `REVOKE` on a mapped role. The cluster admin user also can't create roles on the source or target DB cluster. These statements fail with `cannot execute {{statement}} on role "{{name}}" while an operation on datagroup "{{name}}" is in progress`. Make role changes before you prepare the move.

If prepare is refused because of a role, the error message names the role. The following table lists these errors and how to resolve them.


**Role errors that refuse a prepare**  

| Error message | Cause | Action | 
| --- | --- | --- | 
| `datagroup move blocked: role "{{name}}" referenced by this datagroup is outside the allowed roles` | A role that owns objects or has privileges in the data group isn't mapped to it. | Map the role, or remove its privileges and ownership in the data group. | 
| `datagroup move blocked: role "{{name}}" referenced by this datagroup doesn't exist on the destination cluster` | An `EXPECT_NAME_MATCH` role doesn't exist on the target DB cluster. | Create the role on the target DB cluster. | 
| `datagroup: role {{name}} on the destination cluster lacks an attribute it has on the source: {{attributes}}` | An `EXPECT_NAME_MATCH` role on the target DB cluster is missing an attribute that it has on the source DB cluster. | Add the listed attributes to the role on the target DB cluster. | 
| The same message, with `CONNECTION LIMIT {{n}}, {{m}} on the source` in the attributes | An `EXPECT_NAME_MATCH` role on the target DB cluster has a lower connection limit than on the source DB cluster. | Raise the limit on the target DB cluster with `ALTER ROLE {{name}} CONNECTION LIMIT {{m}}`, or set it to `-1` for no limit. | 
| `datagroup: the destination cluster is missing a grant of a role this datagroup uses: role {{name}} lacks {{role}}` | An `EXPECT_NAME_MATCH` role on the target DB cluster is missing a role membership that it has on the source DB cluster. | Grant the missing role to it on the target DB cluster. | 
| The error names the role. | A role with the same name as a `DATAGROUP_CONSTRAINED` role already exists on the target DB cluster. | Drop or rename that role on the target DB cluster, or choose a different target DB cluster. | 

When Aurora refuses a prepare, it sends a data group event with the error message, and the data group returns to the `active` status on the source DB cluster. For more information, see [What happens when a move fails](aurora-data-groups-moving.md#dg-move-failures).