ROLLBACK;
SET SESSION AUTHORIZATION default;

DROP SCHEMA t CASCADE;
CREATE SCHEMA t;
set search_path = 't';

CREATE TABLE t1 (col1 serial PRIMARY KEY, col2 text, flag boolean NOT NULL DEFAULT TRUE);
CREATE TABLE t2 (col1 int4 NOT NULL REFERENCES t1, col3 text);

DROP USER IF EXISTS u;


GRANT USAGE ON SCHEMA t TO u;
GRANT USAGE ON SEQUENCE t1_col1_seq TO u;
GRANT SELECT, INSERT ON TABLE t1 TO u;
GRANT SELECT, INSERT ON TABLE t2 TO u;


-- Indirect security check
CREATE OR REPLACE FUNCTION col1_value_access(col1 int4) RETURNS boolean AS $$
  SELECT EXISTS(SELECT *
                  FROM t1
                 WHERE t1.col1 = col1_value_access.col1
               );
$$ LANGUAGE sql SECURITY DEFINER STABLE SET search_path = 't';
GRANT EXECUTE ON FUNCTION col1_value_access(int4) TO PUBLIC;


ALTER TABLE t2 ENABLE ROW LEVEL SECURITY;
CREATE POLICY policy ON t2 TO u
      USING (col1_value_access(col1))
   WITH CHECK (col1_value_access(col1));

SET SESSION AUTHORIZATION u;
set search_path = 't';

-- Passes security check
INSERT INTO t1 (col2) VALUES ('text success');
INSERT INTO t2 (col1, col3) VALUES (currval('t1_col1_seq'), 'success');

-- Fails security check
-- Missing command counter increment?
WITH tins AS (
	INSERT INTO t1 (col2) VALUES ('text fail') RETURNING col1
)
INSERT INTO t2 (col1, col3) SELECT col1, 'fail' FROM tins;



SELECT * FROM t1 NATURAL JOIN t2;

