1

我已将 RLS 策略应用于“用户”表,并希望仅tenant_id=2检索记录:

CREATE TABLE "users" ("name" text UNIQUE NOT NULL, "tenant_id" int NOT NULL DEFAULT current_setting('app.current_tenant')::int);

--Enable Row Security Policies
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE users FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON users USING (tenant_id = current_setting('app.current_tenant')::int);

--Set "111" as the current tenant.
SET app.current_tenant TO 1;
INSERT INTO users VALUES ('admin');
INSERT INTO users VALUES ('bob');

--Set "222" as the current tenant.
SET app.current_tenant TO 2;
INSERT INTO users VALUES ('alice');

--Data output
SELECT * FROM users;

但我得到了结果中的所有用户:

name    tenant_id
admin   1
bob     1
alice   2

为什么会这样?

这是我所坚持的 dbFiddle: https ://www.db-fiddle.com/f/iFktvVsDNYKggUNT2oDJBV/0

4

1 回答 1

1

可以绕过行级安全性有四个原因:

  • 用户是表的所有者。

    您可以使表所有者受到行级安全性

    ALTER TABLE users FORCE ROW LEVEL SECURITY;
    
  • 用户是超级用户。

  • 用户是用BYPASSRLS.

  • 数据库参数row_security设置为off

请注意,使用带有占位符参数的行级安全性本质上是不安全的:如果攻击者可以发出 SQL 语句(例如,通过 SQL 注入),他们可以将值更改为他们喜欢的值。

于 2021-04-09T11:05:36.160 回答