← 中文资源

简体中文版本

安全屏障视图阻止不安全谓词下推

为 PostgreSQL 视图启用 security_barrier,阻止外层非防泄漏谓词越过视图 WHERE 过滤提前执行,避免旁路探测隐藏行。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE / EXPLAIN 语句,涉及 employee_pay、v_non_exec_open、v_non_exec_safe。 employee_pay 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。 逐子句看,这些语句使用了:WHERE 只放行满足条件的行进入这条语句;ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这个脚本里出现了哪些表?

employee_pay、v_non_exec_open、v_non_exec_safe。

核心语句

CREATE TEMP VIEW v_non_exec_safe
WITH (security_barrier = true) AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';
CREATE TEMP VIEW v_non_exec_open AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';
SELECT emp_id, department, salary
FROM v_non_exec_safe
WHERE pg_temp.low_cost_ratio(salary)
ORDER BY emp_id;

代码示例

CREATE TEMP TABLE employee_pay (
    emp_id     integer PRIMARY KEY,
    department text NOT NULL,
    salary     integer NOT NULL
);

INSERT INTO employee_pay VALUES
    (1, 'eng',   180000),
    (2, 'sales', 120000),
    (3, 'exec',  450000);

-- Plain view lets the planner pull up the subquery and reorder predicates by cost
CREATE TEMP VIEW v_non_exec_open AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';

-- security_barrier enforces the view filter before any non-leakproof outer predicate
CREATE TEMP VIEW v_non_exec_safe
WITH (security_barrier = true) AS
SELECT emp_id, department, salary
FROM employee_pay
WHERE department <> 'exec';

-- Non-LEAKPROOF helper: dividing by (450000 - amt) raises division_by_zero on exec rows
CREATE OR REPLACE FUNCTION pg_temp.low_cost_ratio(amt integer)
RETURNS boolean
LANGUAGE plpgsql
IMMUTABLE
COST 0.0001 AS $$
BEGIN
    RETURN (1000000 / (450000 - amt)) > 0;
END;
$$;

-- Compare plans: v_non_exec_open pulls up into one scan; v_non_exec_safe keeps a barrier
EXPLAIN (COSTS OFF)
SELECT emp_id, salary FROM v_non_exec_open WHERE pg_temp.low_cost_ratio(salary);

EXPLAIN (COSTS OFF)
SELECT emp_id, salary FROM v_non_exec_safe WHERE pg_temp.low_cost_ratio(salary);

-- Safe view filters department <> 'exec' first so row 3 never hits division by zero
SELECT emp_id, department, salary
FROM v_non_exec_safe
WHERE pg_temp.low_cost_ratio(salary)
ORDER BY emp_id;