可以将 PostgreSQL 安全定义器函数限制为 RLS 使用吗?

Possible to restrict PostgreSQL security definer function to RLS use?

我将 RLS(行级安全性)与 supabase.io 一起用于“无服务器”应用程序。我必须为 RLS 策略使用各种安全定义器函数。这些仍然可以通过 supabase 的 rpc 库调用。无论如何,是否可以将这些函数的调用限制为管理员(我)或用作 RLS 策略的一部分?

例如:

CREATE OR REPLACE FUNCTION get_bases_editable_or_viewable_for_user(user_id uuid, allow_edit bool)
returns setof bigint as $$
  select base_id
  from access_controls
  where access_controls.user_id =  AND ( AND access_controls.access_level = 'editor') OR access_controls.access_level = 'viewer';
$$ stable language sql security definer;

CREATE policy "Users can read bases they are editors or viewers of"
on public.bases
for select using ( bases.id in (get_bases_editable_or_viewable_for_user(auth.uid(), true)) );

get_bases_editable_or_viewable_for_user 允许任何用户,一旦拥有另一个用户的 UID,就可以找出该用户作为编辑者或查看者有权访问的 UID:

supabase.rpc(
  "get_bases_editable_or_viewable_for_user",
  { user_id: "dddddde6-1111-4bdf-aaaa-33336ccc31ee", allow_edit: true }
)
.then(console.log) // => bad

尽量减少泄露信息的机会对于最大限度地提高应用程序的安全性和用户的隐私始终很重要。

您不能以这种方式限制函数的权限,因为运行查询的用户必须能够执行它。

我看到两种改进方法:

  • 省略函数的第一个参数,这样它只给出当前用户的结果。那么没有人可以看到其他用户的信息。

  • 除上述之外,您还可以将 bases.id 作为函数参数传递,并使函数 return 成为 boolean。然后你无法获得列表,但性能可能会受到影响,因为必须为每一行调用该函数。