GRANT statements with bound parameters - postgresql

I'm using a client library that only accepts SQL strings that are compile-time constant, in order to prevent SQL injection attacks. And I wanted to execute some GRANT statements for a set of tables and a user.
I tried
GRANT SELECT ON $1 TO $2
and passing the table and user names as bound parameters. But that fails with
syntax error at or near "$1"
Not being able to pass in a tablename as a bound parameter is understandable (you can't use SELECT columns FROM $1 for instance), and with a bit of work, I can make the tablenames compile-time constants. But changing the command to
GRANT SELECT ON MyTable to $1
and passing just the username as a bound parameter also fails. Which is more of an issue: whereas the tablenames can be hard-coded with a bit of work, the username is only known at runtime.
Is there a way to pass the username as a bound parameter, or do I need to bypass my client library in order to GRANT permissions to a run-time-defined username?

CREATE OR REPLACE FUNCTION test_grant (_role text)
RETURNS void
AS $$
DECLARE
_sql text := '';
BEGIN
_sql := 'GRANT SELECT ON a to ' || quote_ident(_role) || ' GRANTED BY current_user ';
RAISE NOTICE '%', _sql;
EXECUTE _sql;
RAISE NOTICE '% granted table a to %', CURRENT_USER, _role;
END
$$
LANGUAGE plpgsql
STRICT.
You can also make the table as function input argument. quote_ident is used for identifiers quoting. In GRANT SELECT ON MyTable to $1 you hope to make sure $1 is a identifiers rather than some string. Because if $1 string then the whole command can be:
GRANT SELECT ON MyTable to public;
GRANT SELECT ON MyTable to role_a WITH GRANT OPTION;
So the above function can solve these problem.

The only statements that can use parameters are INSERT, UPDATE, DELETE and SELECT. GRANT cannot use parameters; you will have to build a statement dynamically.

Related

Postgres: GRANT to user based on sub-query

This is a symptom of database and user names being different between my dev/staging/live environments, but is there a way to GRANT permissions to a user, determined by some kind of sub-query?
Something like this (not valid syntax):
GRANT UPDATE (my_column) ON my_table TO (SELECT CASE current_database()
WHEN 'account-dev' THEN 'c-app'
WHEN 'account-staging' THEN 'x-app'
WHEN 'account-live' THEN 'a-app'
END);
Use psql and its wonderful \gexec:
SELECT format(
'GRANT UPDATE (my_column) ON my_table TO %I;',
CASE current_database()
WHEN 'account-dev' THEN 'c-app'
WHEN 'account-staging' THEN 'x-app'
WHEN 'account-live' THEN 'a-app'
END
) \gexec
Alternatively, you can write a DO statement that uses EXECUTE to execute a dynamic statement constructed as above.

Postgres: how to declare user type variable?

I want to write a small script to grant permissions. The script works if I type in the user directly into each query but it's more efficient to use a variable but I cannot find what type to declare it as.
DO $$
DECLARE
usr ??? := myuser;
BEGIN
GRANT SELECT, INSERT, UPDATE, DELETE
ON ALL TABLES IN SCHEMA public
TO usr;
GRANT ALL PRIVILEGES ON SCHEMA public to usr;
END $$
You need dynamic SQL for that:
DO
$$DECLARE
usr text := 'myuser' ;
BEGIN
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE '
'ON ALL TABLES IN SCHEMA public '
'TO %I',
usr);
END;$$;
The second statement works similarly.

Dynamic SELECT INTO in PL/pgSQL function

How can I write a dynamic SELECT INTO query inside a PL/pgSQL function in Postgres?
Say I have a variable called tb_name which is filled in a FOR loop from information_schema.tables. Now I have a variable called tc which will be taking the row count for each table. I want something like the following:
FOR tb_name in select table_name from information_schema.tables where table_schema='some_schema' and table_name like '%1%'
LOOP
EXECUTE FORMAT('select count(*) into' || tc 'from' || tb_name);
END LOOP
What should be the data type of tb_name and tc in this case?
CREATE OR REPLACE FUNCTION myfunc(_tbl_pattern text, _schema text = 'public')
RETURNS void AS -- or whatever you want to return
$func$
DECLARE
_tb_name information_schema.tables.table_name%TYPE; -- currently varchar
_tc bigint; -- count() returns bigint
BEGIN
FOR _tb_name IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = _schema
AND table_name ~ _tbl_pattern -- see below!
LOOP
EXECUTE format('SELECT count(*) FROM %I.%I', _schema, _tb_name)
INTO _tc;
-- do something with _tc
END LOOP;
END
$func$ LANGUAGE plpgsql;
Notes
I prepended all parameters and variables with an underscore (_) to avoid naming collisions with table columns. Just a useful convention.
_tc should be bigint, since that's what the aggregate function count() returns.
The data type of _tb_name is derived from its parent column dynamically: information_schema.tables.table_name%TYPE. See the chapter Copying Types in the manual.
Are you sure you only want tables listed in information_schema.tables? Makes sense, but be aware of implications. See:
How to check if a table exists in a given schema
a_horse already pointed to the manual and Andy provided a code example. This is how you assign a single row or value returned from a dynamic query with EXECUTE to a (row) variable. A single column (like count in the example) is decomposed from the row type automatically, so we can assign to the scalar variable tc directly - in the same way we would assign a whole row to a record or row variable. Related:
How to get the value of a dynamically generated field name in PL/pgSQL
Schema-qualify the table name in the dynamic query. There may be other tables of the same name in the current search_path, which would result in completely wrong (and very confusing!) results without schema-qualification. Sneaky bug! Or this schema is not in the search_path at all, which would make the function raise an exception immediately.
How does the search_path influence identifier resolution and the "current schema"
Always quote identifiers properly to defend against SQL injection and random errors. Schema and table have to be quoted separately! See:
Table name as a PostgreSQL function parameter
Truncating all tables in a Postgres database
I use the regular expression operator ~ in table_name ~ _tbl_pattern instead of table_name LIKE ('%' || _tbl_pattern || '%'), that's simpler. Be wary of special characters in the pattern parameter either way! See:
PostgreSQL Reverse LIKE
Escape function for regular expression or LIKE patterns
Pattern matching with LIKE, SIMILAR TO or regular expressions in PostgreSQL
I set a default for the schema name in the function call: _schema text = 'public'. Just for convenience, you may or may not want that. See:
Assigning default value for type
Addressing your comment: to pass values, use the USING clause like:
EXECUTE format('SELECT count(*) FROM %I.%I
WHERE some_column = $1', _schema, _tb_name,column_name)
USING user_def_variable;
Related:
INSERT with dynamic table name in trigger function
It looks like you want the %I placeholder for FORMAT so that it treats your variable as an identifier. Also, the INTO clause should go outside the prepared statement.
FOR tb_name in select table_name from information_schema.tables where table_schema='some_schema' and table_name like '%1%'
LOOP
EXECUTE FORMAT('select count(*) from %I', tb_name) INTO tc;
END LOOP

Give a user permission to ALTER a function

I try to ALTER a function with a new user and I get the error:
ERROR: must be owner of function ACases
********** Error **********
ERROR: must be owner of function ACases
SQL state: 42501
What permission do I have to give to a user so he can ALTER that function?
The only way I found was to make the user the OWNER of the function.
But if that is the case, only one user (owner) can ALTER the function. So how would I change the OWNER for all functions?
CREATE OR REPLACE FUNCTION public."ACases"(caseid integer)
RETURNS boolean AS
$BODY$
DECLARE
BEGIN
RETURN FALSE;
END;
$BODY$
LANGUAGE plpgsql;
ALTER FUNCTION public."ACases"(integer) OWNER TO postgres;
GRANT ALL PRIVILEGES ON FUNCTION public."ACases"(integer) TO user_name;
The manual on ALTER FUNCTION is clear on that:
You must own the function to use ALTER FUNCTION. To change a function's
schema, you must also have CREATE privilege on the new schema.
To alter the owner, you must also be a direct or indirect
member of the new owning role, and that role must have CREATE
privilege on the function's schema. (These restrictions enforce that
altering the owner doesn't do anything you couldn't do by dropping and
recreating the function. However, a superuser can alter ownership of
any function anyway.)
Bold emphasis mine.
You also need a couple of basic privileges to create functions. Per documentation:
To be able to define a function, the user must have the USAGEprivilege on the language.
...
To be able to create a function, you must have USAGE privilege on the argument types and the return type.
The simple solution would be make changes to functions as superuser. (Default superuser is postgres, but any user can be made superuser.)
If you really need to change ownership on all functions, this would do the trick:
SELECT string_agg('ALTER FUNCTION '
|| quote_ident(n.nspname) || '.'
|| quote_ident(p.proname) || '('
|| pg_catalog.pg_get_function_identity_arguments(p.oid)
|| ') OWNER TO foo;'
, E'\n') AS _sql
FROM pg_catalog.pg_proc p
JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public';
-- AND p.relowner <> (SELECT oid FROM pg_roles WHERE rolname = 'foo')
-- AND p.proname ~~ 'f_%'
Restricted to the public schema.
For more details and explanation refer to this more complete answer on dba.SE.
Also closely related:
DROP FUNCTION without knowing the number/type of parameters?

PL/pgSQL anonymous code block

In PostgreSQL 9.0 I have this PLPGSQL anonymous code block:
DO $$
DECLARE
bigobject integer;
BEGIN
SELECT lo_creat(-1) INTO bigobject;
ALTER LARGE OBJECT bigobject OWNER TO postgres;
INSERT INTO files (id, "mountPoint", data, comment) VALUES (15, '/images/image.png', bigobject, 'image data');
SET search_path = pg_catalog;
SELECT pg_catalog.lo_open(bigobject, 131072);
SELECT pg_catalog.lowrite(0, '\\x000001000100101010000000000028010000160000002800000010000000200000000100040');
SELECT pg_catalog.lo_close(0);
REVOKE ALL ON LARGE OBJECT bigobject FROM PUBLIC;
REVOKE ALL ON LARGE OBJECT bigobject FROM postgres;
GRANT ALL ON LARGE OBJECT bigobject TO postgres;
GRANT ALL ON LARGE OBJECT bigobject TO "com.ektyn.eshops.myuser";
END
$$;
but it fails:
ERROR: syntax error at or near "bigobject"
LINE 6: ALTER LARGE OBJECT bigobject OWNER TO postgres;
^
********** Error **********
ERROR: syntax error at or near "bigobject"
SQL state: 42601
Character: 103
and I can't find mistake in code.
There must be an oid constant in ALTER LARGE OBJECT oid .... Try this workaround:
DO $$
DECLARE
bigobject integer;
BEGIN
SELECT lo_creat(-1) INTO bigobject;
EXECUTE 'ALTER LARGE OBJECT ' || bigobject::text || ' OWNER TO postgres';
...
The same also applies to GRANT and REVOKE, of course.
In addition to what #klin already cleared up, you cannot use SELECT without a target in PL/pgSQL code. Replace it with PERFORM in those calls.
Aside: Using "com.ektyn.eshops.myuser" as name for a role is a terrible idea. Use legal, lower case identifiers that don't have to be double-quoted.
This is an artifact of the fact that PostgreSQL has two completely different kinds of SQL statements internally - plannable (SELECT, INSERT, UPDATE, and DELETE) and unplannable (everything else) statements.
Only plannable statements support query parameters.
PL/pgSQL implements variable substitutions into statements, like your bigobject, using query parameters.
Because they aren't supported for non-plannable statements, no substitution is performed. So PL/pgSQL tries to execute the statement literally, as if you'd typed:
ALTER LARGE OBJECT bigobject OWNER TO postgres;
directly at the psql prompt. It does not detect this as an error.
To work around this, use EXECUTE ... FORMAT, e.g.
EXECUTE format('ALTER LARGE OBJECT %s OWNER TO postgres', bigobject);
See this related answer about COPY.