【问题标题】:PostgreSQL + Rails: is it possible to have a write-only database user in PG?PostgreSQL + Rails:PG 中是否可以有只写数据库用户?
【发布时间】:2017-04-26 17:55:55
【问题描述】:

我正在 Ruby on Rails 中构建 JSON API。我希望拥有应该向系统提供数据但不应被允许从中读取数据的只写用户帐户。

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

这个想法是有一个“作家”类型的用户,它使用与数据库的单独连接。应该允许此连接插入/更新/删除,但不允许选择。

我已经把所有东西都设置好了,但不幸的是 Rails 在插入时会生成这个查询:

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

“返回 id”部分使其失败,因为用户没有 SELECT 权限:

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 中的写入用户授予“有限”SELECT 权限,因此他们只能“看到”某些列。我不知道这是否可能。
  2. 让 Rails 不在查询末尾添加“返回 id”,尽管这可能会产生副作用。

我发现了一篇有同样问题的人的文章,最后只是将 SELECT 权限授予作家用户:

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

是否有实际的解决方案可以使上述设置正常工作?

【问题讨论】:

    标签: ruby-on-rails postgresql select permissions sql-grant


    【解决方案1】:

    自 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
    

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

    【讨论】:

    • 非常感谢您的快速回复。您知道是否有一种方法可以将这种策略概括一下,而不必为每张桌子都设置它?可能包含在默认权限中的东西?我正在开发的应用程序还很年轻,我想确保在我们添加更多模型时不会忘记这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2019-06-25
    • 2021-05-22
    • 1970-01-01
    相关资源
    最近更新 更多