2

I have the following setup:

create role test_user noinherit nologin;

create table test_me ( attr text );
create view v_test_me as select * from test_me;

create function fn() returns trigger language plpgsql as $$
begin
    insert into test_me(attr) values (NEW.attr);
    return NEW;
end; $$;
create trigger tg instead of insert on v_test_me 
for each row execute procedure fn();

grant insert on v_test_me to test_user;

set role test_user;
insert into v_test_me(attr) values ('hello?');

Here I have a table and a view on top of it. The view has an instead-of-trigger. I am allowing test_user to insert into the view. But i get the following error:

ERROR:  permission denied for table test_me
CONTEXT:  SQL statement "insert into test_me(attr) values (NEW.attr)"

It looks like I do not have permission to execute an insert statement on the test_me table, which is expected. Is there any way I can allow user to insert into test_me table without directly granting them such permission?

1 Answer 1

3

In this case a SECURITY DEFINER modifier on the trigger function fn() will solve the issue. As per CREATE FUNCTION documentation:

SECURITY DEFINER specifies that the function is to be executed with the privileges of the user that created it

This will allow inserting into test_me table, provided the owner of the function has such permission.

Sign up to request clarification or add additional context in comments.

1 Comment

Heed the warning in the documentation and set search_path on all SECURITY DEFINER functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.