#!/usr/bin/env bash
# The review of 0.4.4 (2026-11-29): an allow_ddl agent's rights used outside its session, closed in
# 0.4.5, each path with its tooth and its control. Every verdict is read from the effect -- the
# DBA's table `orders`, the sequence `s` -- and not from the gate's answer alone.
#
# The root they share: PostgreSQL runs code as an object's OWNER in sessions that are not the
# owner's. When the owner is an agent, that code ran with the agent's rights and no proposal behind
# it: the gate's floor stood only in the agent's own sessions. 0.4.5 refuses, wherever the current
# user is a registered agent and the session is not an agent's, the start of an agent's function,
# the start of a built-in the floor stops, and a write with the agent's rights to a relation the
# agent does not own.
#
#   P1. ANALYZE of a table whose range type's subtype_diff is the agent's;
#   P2. ANALYZE, VACUUM FULL, REINDEX, CLUSTER and REPACK (19) of a table with an index expression
#       over the agent's function;
#   P3. ANALYZE of a table with an expression statistics object over it;
#   P4. brin_summarize_new_values() of a BRIN index over it;
#   P5. the autovacuum on its own;
#   P6. a rule of the agent's that writes the DBA's table, fired by a human;
#   P7. a view of the agent's, written through by a human;
#   P8. a SECURITY DEFINER function of the agent's, called by a human;
#   P9. a trigger of the agent's fired by an ON DELETE CASCADE; its foreign keys keep working;
#   P10. a DBA's index function that calls nextval(), on the agent's table, under ANALYZE;
#   P11. a DBA's table given to the agent with ALTER TABLE ... OWNER TO, under ANALYZE.
#   P12. an installation of 0.4.4 with the agent and its objects already in place, upgraded.
# Each control is the same object owned by a role that is not an agent: it runs, and its code
# advances the sequence `cs`.
#
#   PG_CONFIG=/path/to/pg_config tests/cluster.sh init && tests/cluster.sh start
#   PG_CONFIG=/path/to/pg_config tests/audit10.sh
set -euo pipefail

ROOT=$(cd "$(dirname "$0")/.." && pwd)
PG_CONFIG=${PG_CONFIG:-pg_config}
BIN=$("$PG_CONFIG" --bindir)
export PGHOST=${PGHOST:-$ROOT/.testcluster}
export PGPORT=${PGPORT:-5499}
SUPERUSER=${SUPERUSER:-$(id -un)}
DB=agent_gate_audit10
OLD=agent_gate_audit10_old  # P12: a database that runs 0.4.4 until it is upgraded
D=agent_gate_audit10_d      # an allow_ddl agent, max_rows 2
N=agent_gate_audit10_n      # an ordinary role with a schema of its own: the control
H=agent_gate_audit10_h      # a human who uses the objects
O=agent_gate_audit10_o      # P12: the allow_ddl agent of the 0.4.4 database (roles are global)
L=agent_gate_audit10_l      # P13: a role registered while a DBA's session is open
K=agent_gate_audit10_k      # P13b: the same, the DBA's session acting as that role

as_super() { "$BIN/psql" -X -U "$SUPERUSER" -d "$DB" -tA "$@" 2>&1 || true; }
as() { local r=$1; shift; "$BIN/psql" -X -U "$r" -d "$DB" -tA "$@" 2>&1 || true; }
pc() { as "$D" -c "$(printf "select agent_gate.propose_and_commit(\$q\$%s\$q\$, 'audit10')" "$1")"; }
first_error() { grep -m1 -E '^(ERROR|WARNING)' <<<"$1" || echo "no error"; }
naptime_back() { as_super -c "alter system reset autovacuum_naptime" >/dev/null; as_super -c "select pg_reload_conf()" >/dev/null; }

source "$(dirname "${BASH_SOURCE[0]}")/guard.sh"
trap 'naptime_back; release_claimed' EXIT
require_throwaway_cluster
for r in "$D" "$N" "$H" "$O" "$L" "$K"; do claim_role "$r"; done
claim_database "$DB"
claim_database "$OLD"
"$BIN/psql" -X -U "$SUPERUSER" -d "$DB" -v ON_ERROR_STOP=1 -q -v d="$D" -v n="$N" -v h="$H" >/dev/null <<SQL
CREATE EXTENSION pg_agent_gate;
CREATE TABLE public.orders (id int PRIMARY KEY);
INSERT INTO public.orders SELECT generate_series(1, 20);
CREATE SEQUENCE public.s;
CREATE SEQUENCE public.cs;
CREATE SCHEMA ddl AUTHORIZATION :"d";
CREATE SCHEMA ndl AUTHORIZATION :"n";
GRANT USAGE ON SCHEMA public TO :"d", :"n", :"h";
GRANT USAGE ON SCHEMA ddl, ndl TO :"h";
GRANT SELECT, DELETE ON public.orders TO :"d";
GRANT USAGE, SELECT, UPDATE ON SEQUENCE public.s TO :"d";
GRANT USAGE, SELECT, UPDATE ON SEQUENCE public.cs TO :"n", :"h";
SELECT agent_gate.register_agent('audit10_d', :'d', 'schema power in its own schema',
                                 p_max_rows => 2, p_allow_ddl => true, p_max_rows_per_window => 1000);
SQL

failures=0
check() {
    local what=$1 expected=$2 got=$3
    if [[ "$got" == *"$expected"* ]]; then echo "  ok   $what"; else
        echo "  FAIL $what"; echo "       expected to contain: $expected"; echo "       got: ${got//$'\n'/ }" | cut -c1-${CUT:-400}; failures=$((failures + 1)); fi
}
equals() {
    local what=$1 expected=$2 got=$3
    if [[ "$got" == "$expected" ]]; then echo "  ok   $what"; else
        echo "  FAIL $what"; echo "       expected exactly: $expected"; echo "       got: ${got//$'\n'/ }" | cut -c1-${CUT:-400}; failures=$((failures + 1)); fi
}
REFUSED="would run with an agent's rights outside the agent's session"
# What the agent's code does with its rights, and what the control's does with its own.
body() {
    printf 'begin if current_user = %s then delete from public.orders; perform nextval(%s); elsif current_user = %s then perform nextval(%s); end if; return %s; end' \
        "'$D'" "'public.s'" "'$N'" "'public.cs'" "$1"
}
# $1 schema, $2 name: an int -> int function. An index or a range type needs it IMMUTABLE, and an
# IMMUTABLE PL/pgSQL function cannot DELETE: so the functions are IMMUTABLE while they are planted
# and VOLATILE when the code is fired (marking), or the attack would have no teeth.
fn_sql() { echo "create function $1.$2(x int) returns int language plpgsql immutable as \$f\$ $(body x) \$f\$"; }
marking() {
    as_super -c "do \$m\$ declare r regprocedure; begin
        for r in select p.oid::regprocedure from pg_proc p
                  where p.pronamespace::regnamespace::text in ('ddl', 'ndl', 'public')
                    and p.proname in ('f', 'diff', 'fo') loop
            execute format('alter function %s $1', r);
        end loop; end \$m\$" >/dev/null
}
# Read the effect, then put it back, so that a path that fails does not fail the next ones too.
untouched() {
    equals "$1: orders untouched" "20" "$(as_super -c 'select count(*) from public.orders')"
    equals "$1: s untouched" "f" "$(as_super -c 'select is_called from public.s')"
    as_super -c "insert into public.orders select g from generate_series(1, 20) g on conflict do nothing" >/dev/null
    as_super -c "select setval('public.s', 1, false)" >/dev/null
}
cs_now() { as_super -c "select case when is_called then last_value else 0 end from public.cs"; }
ran() {
    if [ "$(cs_now)" -gt "$2" ]; then echo "  ok   $1: the control's code ran"; else
        echo "  FAIL $1: the control's code did not run"; failures=$((failures + 1)); fi
}
# The agent's table with 2000 rows and an index over ddl.f, and the control's, the same in ndl.
plant_pair() {
    local t=$1 idx=$2
    marking immutable
    pc "create table ddl.$t (x int)" >/dev/null
    pc "create index ${t}_i on ddl.$t $idx" >/dev/null
    as_super -c "insert into ddl.$t select generate_series(1, 2000)" >/dev/null
    as "$N" -c "create table ndl.$t (x int); create index ${t}_i on ndl.$t ${idx//ddl./ndl.}; insert into ndl.$t select generate_series(1, 2000)" >/dev/null
    marking volatile
}

pc "$(fn_sql ddl f)" >/dev/null
as "$N" -c "$(fn_sql ndl f)" >/dev/null
equals "setup: the agent's function is the agent's" "$D" "$(as_super -c "select proowner::regrole from pg_proc where oid = 'ddl.f(int)'::regprocedure")"
equals "setup: register_agent gave the agent the mark" "t" "$(as_super -c "select pg_has_role('$D', 'agent_gate_agents', 'MEMBER')")"

echo "P1. ANALYZE, a range type's subtype_diff"
pc "create function ddl.diff(a float8, b float8) returns float8 language plpgsql immutable as \$f\$ $(body 'a - b') \$f\$" >/dev/null
marking immutable
pc "create type ddl.fr as range (subtype = float8, subtype_diff = ddl.diff)" >/dev/null
pc "create table ddl.rt (r ddl.fr)" >/dev/null
marking volatile
as_super -c "insert into ddl.rt select ('[' || g || ',' || (g + 1) || ')')::ddl.fr from generate_series(1, 3000) g" >/dev/null
check "a DBA's ANALYZE is refused" "ddl.diff() $REFUSED" "$(first_error "$(as_super -c 'analyze ddl.rt')")"
untouched P1
marking immutable
as "$N" -c "create function ndl.diff(a float8, b float8) returns float8 language plpgsql immutable as \$f\$ $(body 'a - b') \$f\$; create type ndl.fr as range (subtype = float8, subtype_diff = ndl.diff); create table ndl.rt (r ndl.fr); insert into ndl.rt select ('[' || g || ',' || (g + 1) || ')')::ndl.fr from generate_series(1, 3000) g" >/dev/null
marking volatile
c=$(cs_now); check "control: ANALYZE of the same, not an agent's" "no error" "$(first_error "$(as_super -c 'analyze ndl.rt')")"; ran "P1 control" "$c"

echo "P2. maintenance over an index expression"
plant_pair t2 "((ddl.f(x)))"
for cmd in "analyze %s" "vacuum full %s" "reindex table %s" "cluster %s using t2_i" "repack %s"; do
    what=${cmd%% %s*}
    if [ "$what" = repack ] && [ "$(as_super -c 'show server_version_num')" -lt 190000 ]; then
        echo "  --   repack: not in this PostgreSQL"; continue; fi
    check "$what: refused" "ddl.f() $REFUSED" "$(first_error "$(as_super -c "$(printf "$cmd" ddl.t2)")")"
    untouched "P2 $what"
    c=$(cs_now); check "control: $what" "no error" "$(first_error "$(as_super -c "$(printf "$cmd" ndl.t2)")")"; ran "P2 $what control" "$c"
done

echo "P3. ANALYZE, an expression statistics object"
pc "create table ddl.t3 (x int)" >/dev/null
marking immutable
pc "create statistics ddl.st3 on (ddl.f(x)), (x + 1) from ddl.t3" >/dev/null
marking volatile
as_super -c "insert into ddl.t3 select generate_series(1, 2000)" >/dev/null
check "a DBA's ANALYZE is refused" "ddl.f() $REFUSED" "$(first_error "$(as_super -c 'analyze ddl.t3')")"
untouched P3
as "$N" -c "create table ndl.t3 (x int); create statistics ndl.st3 on (ndl.f(x)), (x + 1) from ndl.t3" >/dev/null
marking volatile
as_super -c "insert into ndl.t3 select generate_series(1, 2000)" >/dev/null
c=$(cs_now); check "control" "no error" "$(first_error "$(as_super -c 'analyze ndl.t3')")"; ran "P3 control" "$c"

echo "P4. brin_summarize_new_values()"
plant_pair t4 "using brin ((ddl.f(x))) with (pages_per_range = 1)"
check "refused" "ddl.f() $REFUSED" "$(first_error "$(as_super -c "select brin_summarize_new_values('ddl.t4_i')")")"
untouched P4
c=$(cs_now); check "control" "no error" "$(first_error "$(as_super -c "select brin_summarize_new_values('ndl.t4_i')")")"; ran "P4 control" "$c"

echo "P5. the autovacuum on its own"
plant_pair t5 "((ddl.f(x)))"
as_super -c "alter system set autovacuum_naptime = 1" >/dev/null; as_super -c "select pg_reload_conf()" >/dev/null
av() { as_super -c "select coalesce(autoanalyze_count, 0) from pg_stat_all_tables where relid = '$1'::regclass"; }
for i in $(seq 1 40); do [ "$(av ndl.t5)" -gt 0 ] && break; sleep 1; done
check "control: the autovacuum analyzed the same table, not an agent's" "1" "$(av ndl.t5)"
equals "  ...and not the agent's" "0" "$(av ddl.t5)"
untouched P5
naptime_back

echo "P6. a rule, fired by a human"
pc "create table ddl.r (x int)" >/dev/null
pc "create rule rr as on insert to ddl.r do also delete from public.orders" >/dev/null
as_super -c "grant insert on ddl.r to \"$H\"" >/dev/null
check "the human's INSERT is refused" "a write to orders $REFUSED" "$(first_error "$(as "$H" -c 'insert into ddl.r values (1)')")"
untouched P6
as_super -c "grant insert on public.orders to \"$N\"" >/dev/null
as "$N" -c "create table ndl.r (x int); create rule rr as on insert to ndl.r do also insert into public.orders values (21); grant insert on ndl.r to \"$H\"" >/dev/null
check "control: the same rule of another role's writes with that role's rights" "INSERT 0 1" "$(as "$H" -c 'insert into ndl.r values (1)')"
equals "  ...and its row is there" "1" "$(as_super -c 'select count(*) from public.orders where id = 21')"
as_super -c "delete from public.orders where id = 21" >/dev/null
as_super -c "revoke insert on public.orders from \"$N\"" >/dev/null

echo "P7. a view, written through by a human"
pc "create view ddl.v as select id from public.orders" >/dev/null
as_super -c "grant select, delete on ddl.v to \"$H\"" >/dev/null
check "the human's DELETE is refused" "a write to orders $REFUSED" "$(first_error "$(as "$H" -c 'delete from ddl.v')")"
untouched P7

echo "P8. a SECURITY DEFINER function, called by a human"
pc "create function ddl.sd() returns int language sql security definer as \$f\$ delete from public.orders returning 1 \$f\$" >/dev/null
check "the human's call is refused" "ddl.sd() $REFUSED" "$(first_error "$(as "$H" -c 'select ddl.sd()')")"
untouched P8
as "$N" -c "create function ndl.sd() returns bigint language sql security definer as \$f\$ select nextval('public.cs') \$f\$" >/dev/null
c=$(cs_now); check "control" "no error" "$(first_error "$(as "$H" -c 'select ndl.sd()')")"; ran "P8 control" "$c"

echo "P9. a trigger fired by an ON DELETE CASCADE; the agent's foreign keys"
pc "create function ddl.trg() returns trigger language plpgsql as \$f\$ $(body old) \$f\$" >/dev/null
pc "create table ddl.p (id int primary key)" >/dev/null
pc "create table ddl.ch (id int references ddl.p on delete cascade)" >/dev/null
pc "create trigger tr after delete on ddl.ch for each row execute function ddl.trg()" >/dev/null
as_super -c "grant select, insert, delete on ddl.p, ddl.ch to \"$H\"" >/dev/null
as "$H" -c 'insert into ddl.p values (1)' >/dev/null
check "a human's insert through the agent's foreign key works" "INSERT 0 1" "$(as "$H" -c 'insert into ddl.ch values (1)')"
equals "  ...both rows are there" "1,1" "$(as_super -c "select (select count(*) from ddl.p) || ',' || (select count(*) from ddl.ch)")"
check "the cascade that fires the agent's trigger is refused" "ddl.trg() $REFUSED" "$(first_error "$(as "$H" -c 'delete from ddl.p')")"
untouched P9

echo "P10. a DBA's index function that calls nextval(), on the agent's table"
as_super -c "create function public.dn(x int) returns int language plpgsql immutable as \$f\$ begin if current_user = '$D' then perform nextval('public.s'); perform nextval('ddl.sq'); elsif current_user = '$N' then perform nextval('public.cs'); end if; return x; end \$f\$" >/dev/null
pc "create sequence ddl.sq" >/dev/null
pc "create table ddl.t10 (x int)" >/dev/null
pc "create index t10_i on ddl.t10 ((public.dn(x)))" >/dev/null
as_super -c "insert into ddl.t10 select generate_series(1, 2000)" >/dev/null
check "a DBA's ANALYZE is refused" "pg_catalog.nextval() $REFUSED" "$(first_error "$(as_super -c 'analyze ddl.t10')")"
untouched P10
equals "  ...and the agent's own sequence did not move either" "f" "$(as_super -c 'select is_called from ddl.sq')"
as "$N" -c "create table ndl.t10 (x int); create index t10_i on ndl.t10 ((public.dn(x))); insert into ndl.t10 select generate_series(1, 2000)" >/dev/null
c=$(cs_now); check "control" "no error" "$(first_error "$(as_super -c 'analyze ndl.t10')")"; ran "P10 control" "$c"

echo "P11. a DBA's table given to the agent with ALTER TABLE ... OWNER TO"
as_super -c "$(fn_sql public fo)" >/dev/null
as_super -c "create table public.t11 (x int)" >/dev/null
as_super -c "create index t11_i on public.t11 ((public.fo(x)))" >/dev/null
marking volatile
as_super -c "insert into public.t11 select generate_series(1, 2000)" >/dev/null
as_super -c "alter table public.t11 owner to \"$D\"" >/dev/null
check "a DBA's ANALYZE is refused" "a write to orders $REFUSED" "$(first_error "$(as_super -c 'analyze public.t11')")"
untouched P11
as_super -c "alter table public.t11 owner to \"$N\"" >/dev/null
c=$(cs_now); check "control: given to a role that is not an agent" "no error" "$(first_error "$(as_super -c 'analyze public.t11')")"; ran "P11 control" "$c"

echo "the mark comes and goes with the registration"
as_super -c "select agent_gate.unregister_agent('audit10_d')" >/dev/null
equals "unregister_agent takes the mark away" "f" "$(as_super -c "select pg_has_role('$D', 'agent_gate_agents', 'MEMBER')")"
check "  ...and the role's table is maintained again" "no error" "$(first_error "$(as_super -c 'analyze ddl.t3')")"

echo "P12. 0.4.4 installed with the agent's objects in place, then ALTER EXTENSION UPDATE"
# The old schema, where PostgreSQL looks for it (as upgrade.sh does): 0.1.0, and the upgrade
# scripts that the package ships take it to 0.4.4.
EXTDIR=${EXTDIR:-$ROOT/target/release/pg_agent_gate-pg$("$PG_CONFIG" --version | sed -E 's/^PostgreSQL ([0-9]+).*/\1/')$("$PG_CONFIG" --sharedir)/extension}
cp "$ROOT/tests/fixtures/pg_agent_gate--0.1.0.sql" "$EXTDIR/"
old() { "$BIN/psql" -X -U "$SUPERUSER" -d "$OLD" -tA "$@" 2>&1 || true; }
oldpc() { as_old_agent -c "$(printf "select agent_gate.propose_and_commit(\$q\$%s\$q\$, 'audit10')" "$1")"; }
as_old_agent() { "$BIN/psql" -X -U "$O" -d "$OLD" -tA "$@" 2>&1 || true; }
old -c "create extension pg_agent_gate version '0.1.0'" >/dev/null
old -c "alter extension pg_agent_gate update to '0.4.4'" >/dev/null
equals "the old database runs 0.4.4" "0.4.4" "$(old -c "select extversion from pg_extension where extname = 'pg_agent_gate'")"
old -v ON_ERROR_STOP=1 -q >/dev/null <<SQL
CREATE TABLE public.orders (id int PRIMARY KEY);
INSERT INTO public.orders SELECT generate_series(1, 20);
CREATE SCHEMA ddl AUTHORIZATION "$O";
GRANT USAGE ON SCHEMA public TO "$O";
GRANT SELECT, DELETE ON public.orders TO "$O";
SELECT agent_gate.register_agent('audit10_old', '$O', 'schema power in its own schema',
                                 p_max_rows => 2, p_allow_ddl => true, p_max_rows_per_window => 1000);
SQL
old_body='begin if current_user = '"'$O'"' then delete from public.orders; end if; return a - b; end'
oldpc "create function ddl.diff(a float8, b float8) returns float8 language plpgsql immutable as \$f\$ $old_body \$f\$" >/dev/null
oldpc "create type ddl.fr as range (subtype = float8, subtype_diff = ddl.diff)" >/dev/null
oldpc "create table ddl.rt (r ddl.fr)" >/dev/null
old -c "alter function ddl.diff(float8, float8) volatile" >/dev/null
old -c "alter table ddl.rt set (autovacuum_enabled = false)" >/dev/null
old -c "insert into ddl.rt select ('[' || g || ',' || (g + 1) || ')')::ddl.fr from generate_series(1, 3000) g" >/dev/null
equals "  setup: 0.4.4's register_agent gave no mark" "f" "$(old -c "select pg_has_role('$O', 'agent_gate_agents', 'MEMBER')")"
old -c "analyze ddl.rt" >/dev/null
equals "under 0.4.4, a DBA's ANALYZE ran the agent's code with its rights (the hole)" "0" "$(old -c 'select count(*) from public.orders')"
old -c "insert into public.orders select generate_series(1, 20)" >/dev/null
old -c "alter extension pg_agent_gate update" >/dev/null
check "ALTER EXTENSION UPDATE reaches 0.4.5 or later" "0.4." "$(old -c "select extversion from pg_extension where extname = 'pg_agent_gate'")"
equals "  ...and gives the agent registered before it the mark" "t" "$(old -c "select pg_has_role('$O', 'agent_gate_agents', 'MEMBER')")"
check "after the upgrade, the same ANALYZE is refused" "ddl.diff() $REFUSED" "$(first_error "$(old -c 'analyze ddl.rt')")"
old -c "alter table ddl.rt reset (autovacuum_enabled)" >/dev/null
old -c "insert into ddl.rt select ('[' || g || ',' || (g + 1) || ')')::ddl.fr from generate_series(1, 3000) g" >/dev/null
as_super -c "alter system set autovacuum_naptime = 1" >/dev/null; as_super -c "select pg_reload_conf()" >/dev/null
old -c "create table public.ctl (x int); insert into public.ctl select generate_series(1, 3000)" >/dev/null
for i in $(seq 1 40); do [ "$(old -c "select coalesce(autoanalyze_count, 0) from pg_stat_all_tables where relid = 'public.ctl'::regclass")" -gt 0 ] && break; sleep 1; done
equals "  control: the autovacuum did go through that database" "1" "$(old -c "select least(coalesce(autoanalyze_count, 0), 1) from pg_stat_all_tables where relid = 'public.ctl'::regclass")"
equals "  ...and the autovacuum, left alone, deletes nothing" "20" "$(old -c 'select count(*) from public.orders')"
equals "  ...nor gets to analyze the agent's table" "0" "$(old -c "select coalesce(autoanalyze_count, 0) from pg_stat_all_tables where relid = 'ddl.rt'::regclass")"
naptime_back

echo "P13. a role registered while a DBA's session is open: that session sees it as an agent at once"
# A GRANT of the mark must reach a session that is already open, whatever it kept from earlier
# calls. L owns a table whose index calls its function, which writes when it runs as L; L is not an
# agent yet, so the first ANALYZE runs it, as it would any role's.
as_super -q -c "create schema l13 authorization $L; create table public.hits13 (n int); grant insert on public.hits13 to $L" >/dev/null
as "$L" -c "create function l13.f(x int) returns int language plpgsql immutable as \$f\$ begin return x; end \$f\$" >/dev/null
as "$L" -c "create table l13.t (x int); insert into l13.t select generate_series(1, 50); create index on l13.t (l13.f(x))" >/dev/null
as "$L" -c "create or replace function l13.f(x int) returns int language plpgsql volatile as \$f\$ begin if current_user = '$L' then insert into public.hits13 values (1); end if; return x; end \$f\$" >/dev/null
out13=$({ echo "analyze l13.t;"; echo "select 'hits ' || count(*) from public.hits13;"
          echo "\\! \"$BIN/psql\" -X -q -U \"$SUPERUSER\" -d \"$DB\" -c \"select agent_gate.register_agent('audit10_l', '$L', 'registered while a DBA session is open', p_max_rows => 2, p_allow_ddl => true)\" >/dev/null"
          echo "analyze l13.t;"; echo "select 'hits ' || count(*) from public.hits13;"; } \
        | "$BIN/psql" -X -U "$SUPERUSER" -d "$DB" -tA 2>&1 || true)
hits=($(grep -o '^hits [0-9]*' <<<"$out13" | awk '{print $2}'))
check "  control: before the registration that session's ANALYZE runs L's code" "x" "$([ "${hits[0]:-0}" -gt 0 ] && echo x)"
check "after it, the same session's ANALYZE is refused" "l13.f() $REFUSED" "$(first_error "$out13")"
equals "  ...and L's code wrote nothing more" "${hits[0]:-?}" "${hits[1]:-?}"

echo "P13b. the same with nothing in between: the DBA's session has switched to the role"
# Between the two calls the session asks about no other role: nothing but the GRANT can tell it that
# K became an agent.
as_super -q -c "create sequence public.s13; grant usage on sequence public.s13 to $K" >/dev/null
out13b=$({ echo "set role $K;"; echo "select 'nv ' || nextval('public.s13');"
           echo "\\! \"$BIN/psql\" -X -q -U \"$SUPERUSER\" -d \"$DB\" -c \"select agent_gate.register_agent('audit10_k', '$K', 'registered while a session acts as it', p_max_rows => 2)\" >/dev/null"
           echo "select 'nv ' || nextval('public.s13');"; } \
         | "$BIN/psql" -X -U "$SUPERUSER" -d "$DB" -tA 2>&1 || true)
check "  control: before the registration the session, as K, draws from the sequence" "nv 1" "$out13b"
check "after it, the same session, still K, is refused" "nextval() $REFUSED" "$(first_error "$out13b")"
equals "  ...and the sequence did not move" "1" "$(as_super -c 'select last_value from public.s13')"

if [ "$failures" -ne 0 ]; then
    echo "$failures check(s) failed"
    exit 1
fi
echo "the review of 0.4.4 is closed, each path against its control"
