Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql 9.1 - access tables through functions

I have 3 roles: superuser, poweruser and user. I have table "data" and functions data_select and data_insert.

Now I would like to define, that only superuser can access table "data". Poweruser and user can not access table "data" directly, but only through the functions.

User can run only function data_select, poweruser can run both data_select and data_insert.

So then I can create users alice, bob, ... and inherits them privileges of user or poweuser.

Is this actually achievable? I am fighting with this for the second day and not getting anywhere.

Thank you for your time.

like image 907
Petr Cezar Avatar asked Feb 12 '12 11:02

Petr Cezar


People also ask

How do I access tables in PostgreSQL?

Use the \dt or \dt+ command in psql to show tables in a specific database. Use the SELECT statement to query table information from the pg_catalog.

Which of the following is correct function to access database using PostgreSQL?

With PostgreSQL, you can access data by Use function calls (APIs) to prepare and execute SQL statements, scan result sets and perform updates from a large variety of different programming languages.


1 Answers

Yes, this is doable.

"superuser" could be an actual superuser, postgres by default. I rename the role for plain users to usr, because user is a reserved word - don't use it as identifier.

CREATE ROLE usr;
CREATE ROLE poweruser;
GRANT usr TO poweruser;  -- poweruser can do everything usr can.

CREATE ROLE bob PASSWORD <password>;
GRANT poweruser TO bob;

CREATE ROLE alice PASSWORD <password>;
GRANT usr TO alice;

REVOKE ALL ON SCHEMA x FROM public;
GRANT USAGE ON SCHEMA x TO usr;

REVOKE ALL ON TABLE x FROM public;
REVOKE ALL ON TABLE y FROM public;

CREATE FUNCTION
  ...
SECURITY DEFINER;

REVOKE ALL ON FUNCTION ... FROM public;
GRANT EXECUTE ON FUNCTION a TO usr;
GRANT EXECUTE ON FUNCTION b TO poweruser;

Or you could create daemon roles with no login to own the functions and hold the respective rights on the table. That would be even more secure.

If you are going this route, you will love ALTER DEFAULT PRIVILEGES (introduced with PostgreSQL 9.0). More details in this related answer.

Read the chapter Writing SECURITY DEFINER Functions Safely in the manual.

like image 158
Erwin Brandstetter Avatar answered Oct 15 '22 14:10

Erwin Brandstetter