Share via


Azure Cosmos DB for PostgreSQL 中的資料列層級安全性

適用於: Azure Cosmos DB for PostgreSQL (由 PostgreSQL 的超大規模 (Citus) 資料庫延伸模組提供)

PostgreSQL 資料列層級安全性原則會限制哪些使用者可以修改或存取哪些資料表資料列。 資料列層級安全性在多租用戶叢集中特別有用。 其可讓個別租用戶擁有資料庫的完整 SQL 存取權,同時對其他租用戶隱藏每個租用戶的資訊。

針對多租用戶應用程式實作

我們可以針對繫結至資料表資料列層級安全性原則的資料庫角色,使用命名慣例來實作租用戶資料的分隔。 我們會依 tenant1tenant2 等編號順序為每個租用戶指派資料庫角色。租用戶會使用這些個別角色連線到 Azure Cosmos DB for PostgreSQL。 資料列層級安全性原則可以將角色名稱與 tenant_id 散發資料行中的值進行比較,以決定是否允許存取。

以下說明如何在 tenant_id 所散發的簡化事件資料表上套用此方法。 首先建立角色tenant1tenant2。 然後以 citus 系統管理員使用者身分執行下列 SQL 命令:

CREATE TABLE events(
  tenant_id int,
  id int,
  type text
);

SELECT create_distributed_table('events','tenant_id');

INSERT INTO events VALUES (1,1,'foo'), (2,2,'bar');

-- assumes that roles tenant1 and tenant2 exist
GRANT select, update, insert, delete
  ON events TO tenant1, tenant2;

如其所示,具有此資料表選取權限的任何人都可以查看這兩個資料列。 來自任一租用戶的使用者可以看到並更新另一個租用戶的資料列。 我們可以使用資料列層級資料表安全性原則來解決資料外洩問題。

每個原則都包含兩個子句:USING 和 WITH CHECK。 當使用者嘗試讀取或寫入資料列時,資料庫會針對這些子句評估每個資料列。 PostgreSQL 會根據 USING 子句中指定的運算式檢查現有的資料表資料列,以及根據 WITH CHECK 子句檢查透過 INSERT 或 UPDATE 建立的資料列。

-- first a policy for the system admin "citus" user
CREATE POLICY admin_all ON events
  TO citus           -- apply to this role
  USING (true)       -- read any existing row
  WITH CHECK (true); -- insert or update any row

-- next a policy which allows role "tenant<n>" to
-- access rows where tenant_id = <n>
CREATE POLICY user_mod ON events
  USING (current_user = 'tenant' || tenant_id::text);
  -- lack of CHECK means same condition as USING

-- enforce the policies
ALTER TABLE events ENABLE ROW LEVEL SECURITY;

現在角色 tenant1tenant2 為其查詢取得不同的結果:

以 tenant1 身分連線:

SELECT * FROM events;
┌───────────┬────┬──────┐
│ tenant_id │ id │ type │
├───────────┼────┼──────┤
│         1 │  1 │ foo  │
└───────────┴────┴──────┘

以 tenant2 身分連線:

SELECT * FROM events;
┌───────────┬────┬──────┐
│ tenant_id │ id │ type │
├───────────┼────┼──────┤
│         2 │  2 │ bar  │
└───────────┴────┴──────┘
INSERT INTO events VALUES (3,3,'surprise');
/*
ERROR:  new row violates row-level security policy for table "events_102055"
*/

下一步