PostgreSQL Database Roles

I want to read more about PostgreSQL database roles. When you let AI write sql queries to intelligently fulfill a user request, you want to give the AI a constrained role so that it does not mess up the db. I want to read more about this here.

Date Created:
2 471

References



Notes


PostgreSQL manages database access permissions using the concept of roles. A role can be thought of as either a database user, a group of database users, depending on how the role is set up. Roles can own database objects (for example, tables and functions) can assign privileges on those objects to other roles to control who has access to which objects. Furthermore, it is possible to grant membership in a role to another role, thus allowing the membership role to use privileges assigned to another role.

The concept of roles subsumes the concepts of users and groups. [...] users and groups [used to be] distinct kinds of entities, but now there are only roles. Any role can act as a user, group, or both.

Database Roles

Database roles are conceptually completely separate from operating systems users. Database roles are global across a database cluster installation. Create a role:

CREATE ROLE name;

To remove an existing role:

DROP ROLE name;

The programs createuser and dropuser are provided as wrappers around these SQL commands that can be called from the Shell command line.

To determine the set of existing roles, examine the pg_roles system catalog:

SELECT rolname FROM pg_roles;

To see those capable of logging in:

SELECT rolname FROM pg_roles WHERE rolcanlogin;

The psql program's \du meta-command is also useful for listing existing roles. In order to bootstrap the database system, a freshly initialized system always contains one predefined login-capable rile. This role is always a superuser, and it will have the same name as the operating system user that initialized the database cluster with initdb unless a different name is specified. This role is always a superuser, and it will have the same name as the operating system user that initialized the database cluster with initdb unless a different name is specified.

Every connection made to the database server is made using the name of some particular role, and this role determines the initial access privileges for commands issued in that connection.

Role Attributes

A database role can have a number of attributes that define its privileges and interact with the client authentication system.

login privelege

  • Only roles that have the LOGIN attribute can be used as the initial role name for a database connection.
CREATE ROLE name LOGIN;
CREATE USER name;

Note: CREATE USER is equivalent to CREATE ROLE except that CREATE USER includes LOGIN by default.

superuser status

  • A database superuser bypasses all permission checks, except the right to login. This is a dangerous privilege, and should be used carefully.

database creation

  • A role must be explicitly given permission to create databases (except for superusers, since those bypass all permission checks). To create such a role, use CREATE ROLE name CREATEDB

role creation

  • A role must be explicitly given permission to create more roles. To create such a role, use CREATE ROLE name CREATEROLE. A role with CREATEROLE privilege can alter and drop roles which have been granted to the CREATEROLE user with the ADMIN option.

initating replication

  • A role must be explicitly given permission to initiate streaming replication (except for superusers, since those bypass all permission checks). A role used for streaming replication must have LOGIN permission as well. To create such as role, use CREATE ROLE name REPLICATION LOGIN

password

  • A password is only significant if the client authentication method requires the user to supply a password when connecting to the database. Specify a password upon role creation with CREATE ROLE name PASSWORD 'string'

inheritence of priveleges

  • A role inherits the privileges of roles it is a member of, by default. However, to create a role which does not inherit privileges by default, use CREATE ROLE name NOINHERIT. Inheritance can be overwritten for individual grants by using WITH INHERIT TRUE or WITH INHERIT FALSE

bypassing row-level security

  • A role must be explicitly given permission to bypass every row-level security (RLS) policy (except for superusers). To create such a role, use CREATE ROLE name BYPASSRLS as a superuser.

connection limit

  • Connection limit can specify how many concurrent connections a role can make. -1 (the default) means no limit. Specify connection limit upon role creation with CREATE ROLE name CONNECTION LIMIT 'integer'.

A role's attribute can be modified with ALTER ROLE. When a non-superuser creates a role using the CREATEROLE privilege, the created role is automatically granted back to the creating user, just as if the bootstrap superuser has executed the command GRANT created_user TO creating_user WITH ADMIN TRUE, SET FALSE, INHERIT FALSE.

Role Membership

It is frequently convenient to group users together to ease management of privileges: that way, privileges can be granted to, or revoked from, a group as a whole. In PostgreSQL this is done by creating a role that represents the group, and then granting membership n the group role to individual user roles.

Create Group Role

CREATE ROLE name; -- create the role, typically role being used as group would not have LOGIN attribute
-- Once a group role exists, you can add and remove members using the GRANT and REVOKE commands
GRANT group_role TO role1, ...;
REVOKE group_role FROM role1, ...;

The members of a group role can use the privileges of the role in two ways:

  1. Member roles that have been granted membership with the SET option can do SET ROLE to temporarily become the group role.
  2. Member roles that have been granted membership with the INHERIT option automatically have use of the privileges of those directly or indirectly a member of, though the chain stops at memberships lacking the inherit option.

The role attributes LOGINSUPERUSERCREATEDB, and CREATEROLE can be thought of as special privileges, but they are never inherited as ordinary privileges on database objects are. You must actually SET ROLE to a specific role having one of these attributes in order to make use of the attribute. 

Dropping Roles

Because roles can own database objects and can hold privileges to access other objects, dropping a role is often not just a matter of a quick DROP ROLE. Any objects owned by the role must first be dropped or reassigned to other owners; and any permissions granted to the role must be revoked. Ownership of objects can be transferred one at a time using ALTER commands:

ALTER TABLE bobs_table OWNER TO alice;

Alternatively, the REASSIGNED OWNED command can be used to reassign ownership of all objects owned by the role-to-be-dropped to a single other role.

Predefined Roles

PostgreSQL provides a set or predefined roles that provide access to certain, commonly needed, privileged capabilities and information. Administrators can GRANT these roles to users and/or other roles in their environment, providing those users with access to the specified capabilities and information.

Role

Allowed Access

pg_read_all_data

Read all data (tables, views, sequences), as if having SELECT rights on those objects, and USAGE rights on all schemas, even without having it explicitly. This role does not have the role attribute BYPASSRLS set. If RLS is being used, an administrator may wish to set BYPASSRLS on roles which this role is GRANTed to.

pg_write_all_data

Write all data (tables, views, sequences), as if having INSERTUPDATE, and DELETE rights on those objects, and USAGE rights on all schemas, even without having it explicitly. This role does not have the role attribute BYPASSRLS set. If RLS is being used, an administrator may wish to set BYPASSRLS on roles which this role is GRANTed to.

pg_read_all_settings

Read all configuration variables, even those normally visible only to superusers.

pg_read_all_stats

Read all pg_stat_* views and use various statistics related extensions, even those normally visible only to superusers.

pg_stat_scan_tables

Execute monitoring functions that may take ACCESS SHARE locks on tables, potentially for a long time.

pg_monitor

Read/execute various monitoring views and functions. This role is a member of pg_read_all_settingspg_read_all_stats and pg_stat_scan_tables.

pg_database_owner

None. Membership consists, implicitly, of the current database owner.

pg_signal_backend

Signal another backend to cancel a query or terminate its session.

pg_read_server_files

Allow reading files from any location the database can access on the server with COPY and other file-access functions.

pg_write_server_files

Allow writing to files in any location the database can access on the server with COPY and other file-access functions.

pg_execute_server_program

Allow executing programs on the database server as the user the database runs as with COPY and other functions which allow executing a server-side program.

pg_checkpoint

Allow executing the CHECKPOINT command.

pg_maintain

Allow executing VACUUMANALYZECLUSTERREFRESH MATERIALIZED VIEWREINDEX, and LOCK TABLE on all relations, as if having MAINTAIN rights on those objects, even without having it explicitly.

pg_use_reserved_connections

Allow use of connection slots reserved via reserved_connections.

pg_create_subscription

Allow users with CREATE permission on the database to issue CREATE SUBSCRIPTION.

Function Security

Functions, triggers, and row-level security policies allow users to insert code into the backend server that other users might execute unintentionally. Functions run inside the backend server process with the operating system permissions of the database server daemon. If the programming language used for the function allows unchecked memory accesses, it is possible to change the server's internal data structures.

Comments

You have to be logged in to add a comment

User Comments

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC