PostgreSQL Rails:PG中是否有可能在PG中拥有仅写入数据库用户



我正在Ruby上的Ruby上构建JSON API。我想拥有应该将数据馈送到系统但不允许从中阅读的只有写入的用户帐户。

为了获得额外的安全性,我想在数据库级别执行此规则。

这个想法是拥有一种使用与数据库的单独连接的"作者"用户类型。该连接应允许插入/更新/删除,但不要选择。

我的所有设置都很好,但是不幸的是,铁轨在插入时生成了此查询:

INSERT INTO "default"."products" ("id", "name", "sku") VALUES ($1, $2, $3) RETURNING "id"

"返回的ID"部分正在使其失败,因为用户没有选择权限:

ActiveRecord::StatementInvalid: PG::InsufficientPrivilege: ERROR:  permission denied 
for relation products: 
INSERT INTO "default"."products" ("id", "name", "sku") VALUES ($1, $2, $3) RETURNING "id"

有什么办法可以在PG或Rails中解决这个问题?我看到的两个选项是:

  1. 授予PG中的作者用户的"有限"选择权,因此他们只能"查看"一些列。我不知道这是否可以。
  2. 让Rails在查询结束时不添加"返回ID",尽管这可能会产生副作用。

我找到了一个有相同问题的人的一篇文章,最终仅授予作者用户的某些权利:

https://til.hashrocket.com/posts/0c83645c03-postgres-permissions-to-insert-but-not-not-return

有任何实际解决方案可以使上述设置工作?

自PostgreSQL 9.5:

以来,使用行级别安全功能有一种方法
create table products(id serial primary key, name text not null, sku text not null);
grant select,insert on products to tometzky;
grant usage on sequence products_id_seq to tometzky;
alter table products enable row level security;
create policy products_tometzky on products to tometzky
  using (id=currval('products_id_seq'));
tometzky=> select * from products;
ERROR:  currval of sequence "products_id_seq" is not yet defined in this session
tometzky=> insert into products (name, sku) values ('a','a') returning id;
1
tometzky=> select * from products;
1|a|a
tometzky=> insert into products (name, sku) values ('b','b') returning id;
2
tometzky=> select * from products;
2|b|b

用户只看到他放入数据库的最后一行。他知道这是什么。

相关内容

最新更新