2017-07-30 64 views
2

在Postgres中,如何创建具有CREATEROLE特权的用户,但仅限于特定的DB/DB集合?Postgres CREATEROLE限制到特定分区

我试图做:

CREATE ROLE user WITH LOGIN PASSWORD 'password' NOCREATEDB CREATEROLE; 

这是正确的吗? +我如何将CREATEROLE授予多个分贝?

+1

“_小心使用CREATEROLE特权。对于CREATEROLE角色的权限没有继承的概念。这意味着即使角色没有特定的权限但允许创建其他角色,也可以使用不同于自己的特权轻松创建另一个角色(除了使用超级用户特权创建角色)。例如,如果角色“用户”具有CREATEROLE特权但不具有CREATEDB特权,但它可以使用CREATEDB特权创建新角色。因此,将具有CREATEROLE特权的角色视为几乎是超级用户角色。“ – Abelisto

回答

1

看来,这不是一个简单的方法来做到这一点。但是你可以创建功能与security definer选项,以实现所需的行为:

create or replace function fn_create_role(p_name text, p_password text, p_databases text[]) returns void 
    language plpgsql 
    security definer 
as $$ 
begin 
    execute format('create role %I with login password %L;', p_name, p_password); 
    execute format('grant connect on database %s to %I', array_to_string(p_databases, ','), p_name); 
    return; 
end $$; 

创建此功能的超级用户。

然后,您可以使用NOCREATEROLE选项创建角色,但授予此功能EXECUTE权限并使用它创建其他角色。

注意:您需要从public角色撤销connect选择特定的DB不允许角色连接到它们的默认,例如:

revoke connect on database db1, db2 from public; 

测试:


作为超级用户( nd在我的情况下谁也拥有架构同名)

postgres=# create database db1; create database db2; 
CREATE DATABASE 
CREATE DATABASE 
postgres=# revoke connect on database db1, db2 from public; 
REVOKE 
postgres=# create role foo with login password 'bar' nocreatedb nocreaterole; 
CREATE ROLE 
postgres=# set role foo; 
SET 
postgres=> create role win with login password 'amp' nocreatedb nocreaterole; 
ERROR: permission denied to create role 
postgres=> set role nd; 
SET 
postgres=# grant usage on schema nd to foo; 
GRANT 
postgres=# grant execute on function nd.fn_create_role(text, text, text[]) to foo; 
GRANT 
postgres=# set role foo; 
SET 
postgres=> select nd.fn_create_role('win', 'amp', '{db1}'); 
┌────────────────┐ 
│ fn_create_role │ 
╞════════════════╡ 
│    │ 
└────────────────┘ 
(1 row) 

并在终端:

 
$ psql -h localhost -d db1 -U win 
Password for user win: 
psql (9.6.3) 
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off) 
Type "help" for help. 

[email protected]=> \q 
$ psql -h localhost -d db2 -U win 
Password for user win: 
psql: FATAL: permission denied for database "db2" 
DETAIL: User does not have CONNECT privilege. 
2

根据数据库群集创建角色,按照doc而不是数据库创建角色。如果您将这种强大的权利授予用户,他将能够在集群的每个数据库中创建可用的角色。

由于您需要授予角色权限,因此您可以确保将来自单个数据库的内容分配给该角色。