【问题标题】:PostgreSQL Row Level Security in Node JSNode JS 中的 PostgreSQL 行级安全性
【发布时间】:2023-01-12 06:21:43
【问题描述】:

我有一个在多个租户/用户之间共享的数据库。但是,我想添加行级安全保护,以便任何给定的租户只能看到属于他们的那些行。

因此,对于每个租户,我在 PostgreSQL 中都有一个用户,例如“client_1”和“client_2”。在每个表中,有一列“tenant_id”,其默认值为“session_user”。

然后,我有这样的行级安全性:

CREATE POLICY policy_warehouse_user ON warehouse FOR ALL
TO PUBLIC USING (tenant_id = current_user);
ALTER TABLE warehouse ENABLE ROW LEVEL SECURITY;
This works great, and if I set the user "SET ROLE client_1" I can only access those rows in which the tenant_id = "client_1".

但是,我正在为如何在 Node JS 后端进行最佳设置而苦苦挣扎。重要的是,对于每个租户,例如“client_1”,可以连接多个用户。所以我们系统上的几个用户,都在 X 公司工作,将以“client_1”的身份连接到数据库。

我目前正在做的是:

let config = {
        user: 'test_client2',
        host: process.env.PGHOST,
        database: process.env.PGDATABASE,
        max: 10, //default value
        password: 'test_client2',
        port: process.env.PGPORT,
    }

const pool = new Pool(config);
const client = await pool.connect()

await client.query('sql...')

client.release();

我觉得这可能是一个糟糕的解决方案,尤其是因为每次执行查询时我都会创建一个新的池。所以问题是,我如何才能最好地确保每个用户使用与其租户对应的 ROLE 在数据库中执行查询?

【问题讨论】:

    标签: node.js database postgresql node-postgres row-level-security


    【解决方案1】:

    也许你可以有一个 setupDatabase 方法来返回你的应用程序的池,这将在应用程序引导时调用一次:

    function setUpDatabase {
      let config = {
        user: 'test_client2',
        host: process.env.PGHOST,
        database: process.env.PGDATABASE,
        max: 10, //default value
        password: 'test_client2',
        port: process.env.PGPORT,
      }
    
      const pool = new Pool(config);
      return pool
    }
    

    然后当您在执行查询之前确定租户时,您设置了角色

    await client.query('set role $tenant', currentTenant);
    // my assumption is that next line will use the role you set before
    await client.query('select * from X where Y'); 
    

    这只是一个建议,我还没有测试过。

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2018-09-23
      • 2020-07-21
      • 2019-11-25
      相关资源
      最近更新 更多