I'm trying to implement a simple ABAC system using row level security, with main policy defined as following:
CREATE policy resource_access ON resource
USING (
(
org_id::varchar = current_setting('scope.org.id', true)
)
AND
(
acl_read && regexp_split_to_array(current_setting('scope.acl'), ',')::varchar[]
)
)
Issuing queries akin to:
WITH
acl AS (SELECT set_config('scope.acl', 'ACL', true) "__acl"),
result AS ( ... )
SELECT * FROM acl, result
With the main reason to use WITH is to avoid multiple statements when queries are later PREPAREd and EXECUTEd by the Postgres driver I'm using.
The result in example above can contain any arbitrary queries required by the application. To ensure that set_config is executed in the query, it's also added to the final SELECT.
However, I still do consistently encounter the following error:
QueryFailedError: unrecognized configuration parameter "scope.acl"
Which appears to be caused by executing the subquery from WITH
in isolation from the result query.
So the main questions are:
- Is there any elegant way to ensure running
set_config
before the main query (the one inresult
) is executed? - Is there any better way to construct queries for the application side, to avoid using
WITH
, but keeping them as a single SQL statement?
Thank you!
Best Answer
We've ended up using the JOINs over CTEs, which implicitly applies the expected order, and queries looking like:
In which case,
acl
CTE runs before theresult
and ensures that RLS could pick up a correct configuration.Whilst it might very well be sub-optimal for a larger scale table, it worked perfectly for our scale (10k-100k rows) with no noticeable performance degradation compared to using CTEs without the resulting
FULL OUTER JOIN
. More importantly, our correctness tests haven't highlighted any deviations from the expected order, despite this behavior (ofresult
running afteracl
in CTEs block) is implicit.