Postgresql

創建讀寫使用者和只讀使用者

  • September 27, 2019

我正在嘗試做我認為是 RDS 實例上 PostgreSQL 數據庫的常見設置。我希望有:

  • 無論是在public模式上,還是在我不特別關心的自定義模式上
  • 讀寫使用者
  • 只讀使用者
  • 讀寫使用者應該能夠在模式中創建表
  • 只讀使用者應該能夠自動從這個新表中讀取,即無需額外的GRANT

我試圖關注這篇AWS 部落格文章這個答案,但似乎我碰壁了。

我試過以下無濟於事,postgres使用者是RDS創建的具有角色的使用者rds_superuser

-- Making sure roles can't do anything on the database without explicit grant
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON DATABASE my_database FROM PUBLIC;
CREATE SCHEMA my_schema;

-- Read-write
CREATE ROLE read_write;

GRANT CONNECT ON DATABASE my_database TO read_write;
GRANT USAGE, CREATE ON SCHEMA my_schema TO read_write;

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA my_schema TO read_write;
ALTER DEFAULT PRIVILEGES IN SCHEMA my_schema GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO read_write;

GRANT USAGE ON ALL SEQUENCES IN SCHEMA my_schema TO read_write;
ALTER DEFAULT PRIVILEGES IN SCHEMA my_schema GRANT USAGE ON SEQUENCES TO read_write;

-- Read-only
CREATE ROLE read_only;

GRANT CONNECT ON DATABASE my_database TO read_only;
GRANT USAGE ON SCHEMA my_schema TO read_only;

GRANT SELECT ON ALL TABLES IN SCHEMA my_schema TO read_only;
ALTER DEFAULT PRIVILEGES IN SCHEMA my_schema GRANT SELECT ON TABLES TO read_only;

-- Users
CREATE USER read_write_user WITH PASSWORD 'password_1';
GRANT read_write TO my_database;

CREATE USER read_only_user WITH PASSWORD 'password_2';
GRANT read_only TO my_database_read_only;

當我使用 user 連接到數據庫時read_write_user,我可以創建一個新表my_table,但是如果我使用 user 連接read_only_user,我無法訪問它,我收到以下錯誤:permission denied for table my_table.

我與使用者重新連接postgres,發現我無權將此表的訪問權限授予read_only角色:

GRANT SELECT ON ALL TABLES IN SCHEMA my_schema TO read_only;

導致此錯誤:no privileges were granted for "my_table".

因此,如果我理解正確,postgres使用者沒有足夠的權限授予對由創建的對象的訪問權限,read_write_user並且ALTER DEFAULT PRIVILEGES沒有做我認為它會做的事情。

在撤銷/授予任何內容之前,我嘗試在新數據庫上添加以下查詢:

GRANT ALL ON DATABASE my_database TO postgres;
GRANT ALL ON SCHEMA my_schema TO postgres;

它沒有幫助。

我覺得這與事實有關,rds_superusersuperuser我不知道如何前進,有沒有辦法做我想做的事情?

ALTER DEFAULT PRIVILEGES僅影響執行該ALTER DEFAULT PRIVILEGES語句的使用者創建的表。

你必須這樣做:

ALTER DEFAULT PRIVILEGES FOR ROLE read_write IN SCHEMA my_schema
  GRANT SELECT ON TABLES TO read_only;

引用自:https://dba.stackexchange.com/questions/247417