There is no "privilege on SELECT
". All you need is the privilege to EXECUTE
functions. Function can also be declared with SECURITY DEFINER
to inherit all privileges of the owner. To keep possible privilege escalation at a minimum, make a daemon role with only the necessary privileges own functions in question, not a superuser!
Recipe
As superuser ...
Create a non-superuser role myuser
.
CREATE ROLE myuser PASSWORD ...;
Create a group role mygroup
and make myuser
member in it.
CREATE ROLE mygroup; -- NOLOGIN ?
GRANT mygroup TO myuser;
You may want to add more users just like myuser
later.
Do not grant any privileges at all to myuser
.
Only grant these to mygroup
:
GRANT CONNECT ON DATABASE mydb TO mygroup;
GRANT USAGE ON SCHEMA public TO mygroup;
GRANT EXECUTE ON FUNCTION foo() TO mygroup;
Revoke all privileges from PUBLIC
that myuser
shouldn't have.
REVOKE ALL ON ALL TABLES IN SCHEMA myschema FROM public;
There may be more. I quote the manual:
PostgreSQL grants default privileges on some types of objects to
PUBLIC
. No privileges are granted to PUBLIC by default on tables,
columns, schemas or tablespaces. For other types, the default
privileges granted to PUBLIC are as follows: CONNECT
and CREATE TEMP TABLE
for databases; EXECUTE
privilege for functions; and USAGE
privilege for languages. The object owner can, of course, REVOKE
both
default and expressly granted privileges. (For maximum security, issue
the REVOKE
in the same transaction that creates the object; then there
is no window in which another user can use the object.) Also, these
initial default privilege settings can be changed using the ALTER DEFAULT PRIVILEGES
command.
Create a daemon role to own relevant functions.
CREATE ROLE mydaemon;
Grant only privileges necessary to execute these functions to mydaemon
, (including EXECUTE ON FUNCTION
to allow another function to be called). Again, you can use group roles to bundle privileges and grant them to mydaemon
GRANT bundle1 TO mydaemon;
In addition you can use DEFAULT PRIVILEGES
to automatically grant certain privileges for future objects to a bundle or the daemon directly:
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT ON TABLES TO bundle1;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT USAGE ON SEQUENCES TO bundle1;
This applies only to the role it is executed for. The manual:
If FOR ROLE
is omitted, the current role is assumed.
To also cover pre-existing objects in the schema (see rob's comment):
GRANT SELECT ON ALL TABLES IN SCHEMA public TO bundle1;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO bundle1;
Make mydaemon
own relevant functions. Could look like this:
CREATE OR REPLACE FUNCTION foo();
...
SECURITY DEFINER SET search_path = myschema, pg_temp;
ALTER FUNCTION foo() OWNER TO mydaemon;
REVOKE EXECUTE ON FUNCTION foo() FROM public;
GRANT EXECUTE ON FUNCTION foo() TO mydaemon;
GRANT EXECUTE ON FUNCTION foo() TO mygroup;
-- possibly others ..