0% found this document useful (0 votes)
7 views17 pages

Ceng301 Dbms Session 11

Uploaded by

grupsakli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views17 pages

Ceng301 Dbms Session 11

Uploaded by

grupsakli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CENG301 Database Management Systems

Session-11
Asst. Prof. Mustafa YENIAD
[email protected]
PostgreSQL Schemas
• In PostgreSQL, a schema is a namespace that contains named database objects
such as:
tables, views, indexes, data types, functions, stored procedures and operators.
• A schema is a named collection of tables (as well as functions, data types, and
operators).
• The schema name must be unique within a database.
• A database can contain one or multiple schemas and each schema belongs to only one
database. Two schemas can have different objects that share the same name.
• To access an object in a schema, you need to qualify the object by using the following
DBMS

syntax:
schema_name.object_name
• There are some scenarios that you want to use schemas:
• Schemas allow you to organize database objects e.g., tables into logical groups to make them more manageable.
• Schemas enable multiple users to use one database without interfering with each other.
• PostgreSQL automatically creates a schema called public for every new database. Whatever object you create without specifying
the schema name, PostgreSQL will place it into this public schema. Therefore, the following statements are equivalent:
CREATE TABLE table_name( CREATE TABLE public.table_name(
... ...
); );

postgres=# SELECT current_schema(); #returns the current schema:


PostgreSQL Roles
• PostgreSQL uses various mechanisms to implement authentication, authorization, and object ownership
within database clusters. Core among these is the concept of roles.
• PostgreSQL lets you grant permissions directly to the database users. However, as a good practice, it is
recommended that you create multiple roles with specific sets of permissions based on application and
access requirements. Then assign the appropriate role to each user.
• Roles are at the core of most practical database operations. Their flexibility allows them to act both as user
identifiers and user classes.
• Every action within the database cluster is checked against the role's privileges and the success of each
DBMS

connection to the database cluster is determined by the role one authenticates to.
• It is important to get a good handle on role management because of its importance within core operations!

• PostgreSQL doesn’t use the user concept like other database systems:
• It uses roles to represent user accounts (roles are equivalent to users).
• A role is a grouping of a specific set of capabilities, permissions, and "owned" entities.
• Instead of having distinct concepts of "users" and "groups",
PostgreSQL uses roles to represent both of these ideas.
• A role can correspond to an individual person in the real world,
or it can operate as a group with certain access that
other roles can become members of.
PostgreSQL Roles
• With PostgreSQL, you can create users and roles with granular access permissions.
• The new user or role must be selectively granted the required permissions for each
database object. This gives a lot of power to the end user, but at the same time, it makes the process of
creating users and roles with the correct permissions potentially complicated.

• PostgreSQL lets you grant permissions directly to the database users. However, as a good
practice, it is recommended that you create multiple roles with specific sets of permissions based on
DBMS

application and access requirements. Then assign the appropriate role to each user.

• The roles should be used to enforce a least privilege model for accessing database objects.

• Always keep in mind: The master user should never be used by the application!
• Instead, most of the time, users should use accounts dedicated to the specific functions or data objects they are
working with, only using the superuser accounts when more powerful access is required.

• The master user that is created during PostgreSQL installation (postgres) should be used
only for database administration tasks like creating other users, roles, and databases.
PostgreSQL Roles
• The recommended approach for setting up fine-grained access control in PostgreSQL is as follows:
• Use the master user to create roles per application or use case, like readonly and readwrite.
• Add permissions to allow these roles to access various database objects. For example, the readonly role can only run
SELECT queries.
• Grant the roles the least possible permissions required for the functionality.
• Create new users for each application or distinct functionality, like app_user and reporting_user.
• Assign the applicable roles to these users to quickly grant them the same permissions as the role. For example, grant
the readwrite role to app_user and grant the readonly role to reporting_user.
DBMS

• At any time, you can remove the role from the user in order to revoke the permissions.
• The following diagram summarizes these recommendations:
PostgreSQL Roles
Role attributes:
• Role attributes are flags on the role itself that determine some of the core privileges it has on the database cluster level.
These can be set when the role is initially created, or changed at any time by any role with the appropriate attributes
(SUPERUSER or CREATEROLE in this case). Attributes that can be applied to a role include:

Role Explanation
LOGIN Allows users to initially connect to the database cluster using this role.
The CREATE USER command automatically adds this attribute, while CREATE ROLE command does not!
DBMS

SUPERUSER Allows the role to bypass all permission checks except the right to log in.
Only other SUPERUSER roles can create roles with this attribute.
CREATEDB Allows the role to create new databases.
CREATEROLE Allows the role to create, alter, and delete other roles.
This attribute also allows the role to assign or alter role membership. An exception is that a role with the CREATEROLE
attribute cannot alter SUPERUSER roles without also having the SUPERUSER attribute.
REPLICATION Allows the role to initiate streaming replication. Roles with this attribute must also have the LOGIN attribute.
PASSWORD Assigns a password to the role that will be used with password or md5 authentication mechanisms.
This attribute takes a password in quotations as an argument directly after the attribute keyword.
INHERIT Determines whether the role inherits the privileges of roles it is a member of.
Without the INHERIT, members must use SET ROLE to change into the other role in order to access those exclusive privileges.
This attribute is set for new roles by default.

For more about role attributes, check out: https://www.postgresql.org/docs/current/role-attributes.html


PostgreSQL Roles
• As mentioned briefly at the beginning of course sessions, a special privilege called superuser allows
unrestricted administrative access to the database cluster (this is similar to the root account in Linux and Unix-
like operating systems, but at the database level).
• There must always be at least one role with superuser privileges in each database cluster.
• The initial superuser account is created during the installation process:
• The name of the initial superuser account (=master user)can vary depending on the installation process,
but most often, this account is called postgres.
DBMS

• Remember:
• PostgreSQL's authentication system has a number of different components, each of which are tied to roles. In order
to be used for the initial connection to the database, roles must first have the LOGIN attribute set. The
authentication rules are defined in the host-based configuration file called pg_hba.conf. Each rule defines methods
of authentication that may be scoped to the individual role. Upon installation, PostgreSQL is set up to use peer
authentication, meaning that it associates PostgreSQL roles with a matching Unix/Linux system account. It means
that, if a role exists within PostgreSQL, a Unix/Linux username with the same name is able to sign in as that role (in
this case, the postgres role is the default role with superuser privileges):
$ sudo --login -u postgres # switch to the postgres account
postgres@[hostname]:~ $ psql # then access the PostgreSQL prompt immediately
postgres=# \du # this meta-command lists the roles attributes in your Postgres instance
PostgreSQL Roles

• Additional info: The equivalent SQL statement to list roles:


SELECT r.rolname, r.rolsuper, r.rolinherit,
r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,
DBMS

r.rolconnlimit, r.rolvaliduntil,
ARRAY(SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
WHERE m.member = r.oid) AS memberof
, r.rolreplication
, r.rolbypassrls
FROM pg_catalog.pg_roles r
WHERE r.rolname !~ '^pg_'
ORDER BY 1;
The "ORDER BY 1" statement above sorts the results based on the first column in the SELECT list.
PostgreSQL Roles
• If you are only interested in seeing which roles have the superuser attribute, you can ask for a list explicitly:
postgres=# SELECT rolname FROM pg_roles WHERE rolsuper;
DBMS

• Alternatively, you can list all users and their superuser status for a more complete picture (if multiple users created):
postgres=# SELECT usename, usesuper FROM pg_user;

• If you want to find the attributes of the role you are currently using:
postgres=# \du :USER
PostgreSQL Roles
Users, groups and roles:
• Users, groups, and roles are the same thing in PostgreSQL, with the only difference being that users have permission to
log in by default.
• The CREATE USER and CREATE GROUP statements are actually aliases for the CREATE ROLE statement.

LOGIN
CREATE USER = CREATE ROLE + PERMISSION
DBMS

• Additional info: In other relational database management systems (RDBMS) like Oracle, users and roles are two different entities.
In Oracle, a role cannot be used to log in to the database. The roles are used only to group grants and other roles. This role can then be
assigned to one or more users to grant them all the permissions.

• To create roles the general syntax is:

CREATE ROLE role_name


CREATE ROLE role_name; OR
WITH options;
PostgreSQL Roles
Role OPTIONS:
• Role OPTIONS can be:
Role OPTION Explanation
SUPERUSER | NOSUPERUSER determine if the role is a superuser or not
CREATEDB | NOCREATEDB allow the role to create new databases or not
CREATEROLE | NOCREATEROLE allow the role to create or change roles
INHERIT | NOINHERIT determine if the role to inherit privileges of roles of which it is a member
DBMS

LOGIN | NOLOGIN allow the role to log in or not


REPLICATION | NOREPLICATION determine if the role is a replication roles
CONNECTION LIMIT limit specify the number of concurrent connection a role can made, -1 means unlimited
PASSWORD 'password' | PASSWORD NULL change the role’s password
VALID UNTIL 'timestamp' set the date and time after which the role’s password is no long valid.
BYPASSRLS | NOBYPASSRLS set Row-level Security (as an additional filter; when a user tries to perform an operation on a
table, this filter is applied before any query condition or filtering, and data is shrunk down or
access is denied based on the specific policy).
• The following rules are applied:
• Superusers can change any of those attributes for any role.
• Roles that have the CREATEROLE attribute can change any of these attributes
for only non-superusers and no-replication roles.
• Ordinal roles can only change their own passwords.
PostgreSQL Roles
• To create a PostgreSQL role, use the following SQL statement:
postgres=# CREATE ROLE user1;
• OR you can also create a user with the following SQL statement:
postgres=# CREATE USER user1;
Both of these statements create the exact same user.
• To get all roles in the current PostgreSQL database server, you can query them from the pg_roles system catalog as follows:
DBMS

(Noice that the roles that start with with pg_ are system roles)
postgres=# SELECT rolname FROM pg_roles;
postgres=# \du # to list all existing roles

• As you can see clearly from the output, the role user1 cannot login. To allow to log in to the PostgreSQL database server, you need to
ALTER the LOGIN attribute to it (this enables the ability to login, the authentication methods are still controlled by the pg_hba.conf file).

postgres=# ALTER ROLE user1 WITH LOGIN;


PostgreSQL Roles
• To set or update the password for a role, you can type the following statement:
postgres=# ALTER ROLE user1 WITH LOGIN PASSWORD 'secret';
postgres=# du\
• You can also use the ALTER ROLE command to rename a role:
postgres=# ALTER ROLE user1 RENAME TO user2;
postgres=# du\
DBMS

• If you want user2 to be able to create roles, and create databases, you can specify those two attributes, separated
by spaces:
postgres=# ALTER ROLE user2 WITH CREATEROLE CREATEDB;
postgres=# du\

• To revoke CREATEROLE status from user2, just type:


postgres=# ALTER USER user2 WITH NOCREATEDB;
postgres=# du\

• To set password expire for user2 until the end of 2024:


postgres=# ALTER ROLE user2 WITH VALID UNTIL '2025-01-01';
postgres=# du\ user2
PostgreSQL Roles - Public Schema and Public Role
• As mentioned at the previous slides, to create a PostgreSQL role, use the following SQL statement:
postgres=# CREATE ROLE user3;
• You can also create a user with the following SQL statement:
postgres=# CREATE USER user3;
• Both of these statements create the exact same user.
This new user does not have any permissions other than the default permissions available to the public role.
DBMS

All new users and roles inherit permissions from the public role.
The following section provides more details about the public role.
Public schema and public role:
• When a new database is created, PostgreSQL by default creates a schema named public and grants access on this
schema to a backend role named public. All new users and roles are by default granted this public role, and therefore can
create objects in the public schema.
• PostgreSQL uses a concept of a search_path.
The search_path is a list of schema names that PostgreSQL checks when you don’t use a qualified name of the database object.
For example, when you select from a table named “mytable”, PostgreSQL looks for this table in the schemas listed in the search path. It
chooses the first match it finds.

• By default, the search path contains the following schemas:


postgres=# show search_path;
For more about search path, check out: https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH
PostgreSQL Roles - Public Schema and Public Role

• The first name "$user" resolves to the name of the currently logged in user.
• By default, no schema with the same name as the user name exists. So the public schema becomes the default schema whenever
an unqualified object name is used. Because of this, when a user tries to create a new table without specifying the schema name,
the table gets created in the public schema.
DBMS

• As mentioned earlier, by default, all users have access to create objects in the public schema, and therefore the table is created
successfully. This becomes a problem if you are trying to create a read-only user. Even if you restrict all privileges, the permissions
inherited via the public role allow the user to create objects in the public schema. To fix this, you should revoke the default create
permission on the public schema from the public role using the following SQL statement (make sure that you are the owner of the
public schema or are part of a role that allows you to run this SQL statement):

postgres=# REVOKE CREATE ON SCHEMA public FROM PUBLIC;


• To revoke the public role’s ability to connect to the database:
(This makes sure that users can’t connect to the database by default unless this permission is explicitly granted)
postgres=# REVOKE ALL ON DATABASE mydatabase FROM PUBLIC;
• Revoking permissions from the public role impacts all existing users and roles. Any users and roles that should be able to connect
to the database or create objects in the public schema should be granted the permissions explicitly before revoking any
permissions from the public role in the production environment.
PostgreSQL Roles - Public Schema and Public Role
• The following sections document the process of creating new roles
and granting them permissions to access various database objects.
• Permissions must be granted at the database, schema, and schema
object level.
For example, if you need to grant access to a table, you must also make sure that
the role has access to the database and schema in which the table exists. If any of
the permissions are missing, the role cannot access the table.
DBMS

• Read-only Role:
The first step is to create a new role named readonly using the following
SQL statement:
postgres=# CREATE ROLE readonly;
• This is a base role with no permissions and no password. It cannot be used to log in to the database.
Grant this role permission to connect to your target created previously database named "mydatabase":
postgres=# GRANT CONNECT ON DATABASE mydatabase TO readonly;
• The next step is to grant this role usage access to your schema. Let’s assume the schema is named "myschema":
postgres=# GRANT CONNECT ON SCHEMA myschema TO readonly;
• This step grants the readonly role permission to perform some activity inside the schema. Without this step, the readonly
role cannot perform any action on the objects in this schema, even if the permissions were granted for those objects!
PostgreSQL Roles - Public Schema and Public Role
• The next step is to grant the readonly role access to run select on the required tables.
postgres=# GRANT SELECT TABLE mytable1, mytable2 TO readonly;
• If the requirement is to grant access on all the tables and views in the schema, then you can use the following SQL:
postgres=# GRANT SELECT ALL TABLES IN SCHEMA myschema TO readonly;

• The preceding SQL statement grants SELECT access to the readonly role on all the existing tables and views in the schema
myschema. Note that any new tables that get added in the future will not be accessible by the readonly user. To help
DBMS

ensure that new tables and views are also accessible, run the following statement to grant permissions automatically:
postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT ON TABLES TO readonly;
• With the roles in place, the process of creating users is simplified. Just create the user and grant it one of the existing
roles. Here are the SQL statements for this process:
postgres=# CREATE USER user4 WITH PASSWORD 'secret';
postgres=# GRANT readonly TO user4;

• Using the method documented previously, it becomes very easy to revoke privileges from a user. For example, you can
remove the readonly permission from user4 using the following SQL statement:
postgres=# REVOKE readonly FROM user4;

You might also like