Search code examples
postgresqldatabase-permissions

How can I make sure a function only SELECTs from one specific schema?


What do I need to do to make sure that sandbox.execute_any_query() only SELECTs from tables in schema sandbox?

create function sandbox.execute_any_query(_query text) returns json as 
$$
declare
    _result json;
begin
    execute format('select row_to_json(t) from (%s) t', _query) into _result;
    return _result;
end
$$
language plpgsql;

Solution

  • Mark the function as SECURITY DEFINER and make sure that the function owner does not have permissions on any schema other than sandbox.

    Then the function will run in the user context of the owner, and any attempt to access other schemas will cause an error.