這很重要
新專案不再支援適用於 PostgreSQL 的 Azure Cosmos DB。 請勿將此服務用於新專案。 請改用下列兩項服務之一:
使用 Azure Cosmos DB for NoSQL 作為專為高規模應用場景設計的分散式資料庫解決方案,其特色包括99.999% 的可用性服務等級協定(SLA)、即時自動調整,以及跨多個區域的自動容錯移轉。
針對使用開放原始碼超大規模 (Citus) 延伸模組的分區化 PostgreSQL 使用適用於 PostgreSQL 的 Azure 資料庫的彈性叢集功能。
PostgreSQL 資料列層級安全性原則會限制哪些使用者可以修改或存取哪些資料表資料列。 資料列層級安全性在多租用戶叢集中特別有用。 其可讓個別租用戶擁有資料庫的完整 SQL 存取權,同時對其他租用戶隱藏每個租用戶的資訊。
針對多租用戶應用程式實作
我們可以針對繫結至資料表資料列層級安全性原則的資料庫角色,使用命名慣例來實作租用戶資料的分隔。 我們會以編號的序列為每個租用戶指派資料庫角色:tenant1、tenant2 等等。租用戶會使用這些個別角色連線到 Azure Cosmos DB for PostgreSQL。 資料列層級安全性原則可以將角色名稱與 tenant_id 散發資料行中的值進行比較,以決定是否允許存取。
以下說明如何在 tenant_id 所散發的簡化事件資料表上套用此方法。 首先建立角色tenant1 和 tenant2。 然後以 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;
現在角色 tenant1 和 tenant2 為其查詢取得不同的結果:
以 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"
*/
後續步驟
- 了解如何在叢集中建立角色。
- 查看 Azure Cosmos DB for PostgreSQL 中的安全性概念