【发布时间】:2020-07-16 17:27:38
【问题描述】:
我目前有一个包含两个架构 app_private 和 app_public 的数据库(除了默认的公共架构)。我还有一个角色,该角色已被授予在 app_public 架构上使用的权限,但在 app_private 架构上却没有。我还在表上使用了两个函数(一个触发函数和一个检查约束函数)。
代码见下:
(1) 创建模式(和授权)
CREATE SCHEMA app_public;
CREATE SCHEMA app_private;
grant usage on schema public, app_public to "grant_test_role";
(2) 撤销 PUBLIC 用户的授权
然后我有这个特殊的 DDL 语句。它应该从公共用户角色(所有其他角色继承自)中REVOKE任何新添加的功能的权限。
alter default privileges revoke all on functions from public;
(3) 函数定义(触发器和约束)
-- Trigger Function
create OR replace function app_private.tg__timestamps() returns trigger as $$
begin
NEW.created_at = (case when TG_OP = 'INSERT' then NOW() else OLD.created_at end);
NEW.updated_at = (case when TG_OP = 'UPDATE' and OLD.updated_at >= NOW() then OLD.updated_at + interval '1 millisecond' else NOW() end);
return NEW;
end;
$$ language plpgsql volatile set search_path to pg_catalog, app_private, public, pg_temp;
-- Constraint Function
CREATE OR REPLACE FUNCTION app_private.constraint_max_length(
value text,
maxLength integer,
error_message text default 'The value "$1" is too long. It must be maximum $2 characters long.',
error_code text default 'MXLEN'
) RETURNS boolean
AS $$
begin
if length(value) > maxLength then
error_text = replace(replace(error_message, '$1', value), '$2', maxLength);
raise exception '%', error_text using errcode = error_code;
end if;
return true;
end;
$$ LANGUAGE plpgsql set search_path to pg_catalog, app_private, public, pg_temp;
(4) 表定义(使用上面的Trigger & Constraint函数)
create table app_public.test_tab (
id INT not null primary key,
name text not null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint name_length_check check (app_private.constraint_max_length(name, 5));
);
create trigger _100_timestamps
before insert or update on app_public.test_tab
for each row
execute procedure app_private.tg__timestamps();
-- Setting some restrictions on the test_tab for the "grant_test_role"
REVOKE ALL ON TABLE app_public.test_tab FROM "grant_test_role";
GRANT SELECT, DELETE ON app_public.test_tab TO "grant_test_role";
GRANT
INSERT(id, name),
UPDATE(id, name) ON app_public.test_tab TO "grant_test_role";
(5) 代码(作为 grant_test_role 运行)
begin;
set local role to grant_test_role;
insert into app_public.test_tab (id, name) values (1, 'Very Long Name');
commit;
我每次都尝试在新的数据库中执行此操作,以了解 PostgreSQL 权限如何在不同的调用上下文中工作(即触发函数、自动调用函数的约束检查等)
当我没有从 PUBLIC 用户撤销函数权限的代码块 (2) 时,代码块 (5) 将执行而不会出现任何错误。尽管用户角色没有授予触发函数和约束函数存在的 app_private 架构的事件。但是在代码块 (2) 存在的情况下,代码可以很好地执行触发器,但给了我一个 "permission denied for function constraint_max_length" 用于检查约束。
所以我试图理解,
- 存在于用户角色没有使用授权的架构中的触发器函数如何始终成功执行?
- 如果触发函数执行,为什么CHECK约束函数给我上面的permission denied错误?
- 代码块 (2) 的真正作用是什么?
我很难找到有关权限如何应用于这种“自动执行”场景(触发器/约束)的文档,因为用户不是“显式”调用这些函数,而是由D B。所以我不确定哪个 ROLE 正在执行它们。
【问题讨论】:
标签: postgresql triggers permissions constraints roles