Contents
What it does not cover
Said here so nobody learns it the hard way:
- A function’s body is trusted to be what the function is marked. The gate
does not read a body. It judges each function where it starts (0.4.3): wherever
reached in an agent’s session, it stops
set_config(), a function that runs SQL from a text, a built-in that changes state outside counted rows, a function the agent can alter (its marking is then its own claim) and one whoseSETclause moves the context a policy reads. What remains is a DBA’s function markedSTABLEorIMMUTABLEthat writes: it runs, and only the row-count backstop of a write or a DDL sees what it changed. PostgreSQL grantsEXECUTEon every new function toPUBLIC, so not granting is not enough:REVOKE EXECUTE ... FROM PUBLICon any function an agent must not reach. - Built-ins reached from C code are not judged one by one. PostgreSQL looks a built-in up by a fast path that asks no hook. The executor’s hook still sees every built-in an expression calls; what C code calls through a cache (the type cache, an RI check, index support) is chosen by DDL only a superuser runs – operator classes, base types – or, for a range type’s support function, has a signature no built-in that changes state has.
- Code an
allow_ddlagent plants runs for whoever uses its objects. Its functions never start in its own (or any agent’s) session, but a human or an application that inserts into its table, casts to its domain or builds on its range type runs them as itself – PostgreSQL’s rule for any role that may create objects. Keep agents' schemas out of other roles' paths. That includes a DBA’s own DDL: anALTER TABLEthat rewrites an agent’s table runs the agent’sCHECKas the DBA (measured as a superuser, 19.0). A superuser who runs it as the agent instead (SET ROLE) gets the refusal below, and the agent’s code does not run. PostgreSQL also runs code as its owner:ANALYZE,VACUUM FULL,REINDEX,CLUSTER,REPACK,brin_summarize_new_values()and the autovacuum evaluate a table’s index expressions as the table’s owner, a view or a rule writes with its owner’s privileges, and aSECURITY DEFINERor trigger function runs as its owner. Where that owner is an agent, outside the agent’s session, the gate refuses (0.4.5): no function an agent owns starts, nor a built-in that changes state, runs SQL from a text or isset_config(), and nothing writes with the agent’s rights to a relation it does not own. What that costs: the maintenance of an agent’s table whose index or statistics call the agent’s code fails instead of running, and the autovacuum leaves it without statistics and logs the refusal on each pass; and a referential action that runs as the agent – anON DELETE SET DEFAULTinto an agent’s table whose default callsnextval()– fails, and with it theDELETEon the referenced table. Writes with an agent’s rights to its own relations outside its session (anON DELETE CASCADEinto its table) still pass, and no budget counts them. Logical replication applies as the table’s owner: into an agent’s table whose index calls the agent’s code, the apply is refused and the subscription stops there, retrying (measured on 19.0); withrun_as_owner = trueit applies as the subscription’s owner instead, and the agent’s code runs with that role’s rights, as in the DBA’s DDL above. In an agent’s own session, what its objects call is its code (third review of 0.4.3): aVOLATILEfunction of another role’s that an object of the agent’s calls – a domain’sCHECK, a default, an index, a trigger – is judged as the statement’s own call. Native code (C, an untrusted language) is refused in every statement, so a C trigger function from contrib on an agent’s table refuses its writes; SQL and PL/pgSQL are refused in reads and run in writes – but aDEFAULTof the agent’s own table that anINSERTrelies on is written into the statement by the rewriter, and is judged there as the statement’s own call:no_opaque_functionrefuses a volatile user function in it. Two more edges: the judgment is by function, not by call site, so once an agent’s object calls a DBA’s function every call of it in that agent’s sessions is judged so; and it knows what PostgreSQL records inpg_depend– a PL/pgSQL body records nothing, so a DBA’s function that an agent’s PL/pgSQL function calls is never reached that way (the agent’s function never starts), and a call the DBA’s own PL/pgSQL body makes stays the DBA’s. - A persistent object of the agent can still answer for a name a DBA’s code does not
qualify. An agent creates no temporary object (0.4.3), so
pg_tempanswers for nothing; but a schema the agent can create in, searched before the DBA’s –ALTER ROLE agent SET search_path = agent_schema, public, or a schema named after the agent’s role under the default"$user", public– puts the agent’s table or type ahead of the DBA’s in the agent’s own session, and a policy helper that namestenant_ofunqualified reads the agent’s. A function is not affected (one the agent can alter never starts). Name tables in policy helpers with their schema, or pinSET search_path = public, pg_tempon them, and put an agent’s schema after the DBA’s. - The built-ins are classified by PostgreSQL’s marking and one reviewed list. A
VOLATILEbuilt-in that a later PostgreSQL adds is refused until it is reviewed (closed); the list was derived on 18.6 and 19beta2 (verify.rs,state_change). A built-in that PostgreSQL marksSTABLEorIMMUTABLEis trusted not to change state. - The context is what the session started with. The placeholders and the named
parameters; a module’s own parameter is not part of it (a value the role gives one before
the module loads may be respelled when it does). The gate refuses rather than resets: a
session whose context moved is refused until it
RESETs or reconnects. pg_living_assertions 0.5.5’srun()left the assertion’ssearch_pathin the session (fixed in its 0.5.6), so under 0.5.5 a write with a bound assertion is refused. A module’s parameter in a DBA’s
SETclause passes once the module defines it, or when it is named after an installed extension (pg_trgm.*,plpgsql.*). One that is neither when the function is judged –hnsw.*before anything loadedvectorin that session – is refused as a placeholder would be (closed).Without the library loaded before the agent’s first statement, the gate fails open.
whoami()reportsenforced. Useshared_preload_libraries.- Existing connections of a role are not behind the gate until they reconnect.
- A dump of the database does not carry who is an agent.
register_agentmarks the role (ALTER ROLE ... SET agent_gate.agent), and roles belong to the cluster:pg_dumpleaves the mark out,pg_dumpall --globals-onlyhas it. Restored into a server without the globals, the record still says the role is an agent while the role is outside the gate. The record itself does survivepg_dump;tests/dump_restore.shchecks both halves. - An agent session may change only the session parameters on an allowlist:
client formatting and time limits, which is what a driver sets on its own
(
application_name,client_encoding,DateStyle,statement_timeout, the transaction characteristics, and a few more).SHOWand transaction control pass, and so doDISCARDandDEALLOCATE(a pool’s reset, which puts the session’s own state back); everything else is refused, includingrole,session_authorization, everyagent_gate.*setting even if someone grantedSET ON PARAMETERon it, and – the reason it is an allowlist and not a list of forbidden names – whatever the application decides with. A row-level policy overcurrent_setting('app.tenant_id')is the ordinary way to separate tenants, and no denylist can name the parameters an application invents: measured, an agent could point that policy at another tenant and the same read returned the other tenant’s row (tests/rls_isolation.sh). An agent’s context is set on its role (ALTER ROLE ... SET), and a DBA who needs one more parameter adds it toagent_gate.settable– which is saying, out loud, that no policy of theirs stands on it. - The allowlist also covers parameters set when the connection starts. A
startup parameter – libpq’s
PGOPTIONS, theoptionsproperty of pgjdbc and node-pg – is not a statement and reaches no hook, and a value the client sets at startup outranks the one on the role. Measured with pgjdbc 42.7.13, node-pg 8.23.0 and libpq before this was covered:options=-c app.tenant_id=2and the agent read the other tenant’s row (tests/drivers.sh). An agent session that started with a parameter outside the allowlist now fails closed: every statement it sends is refused. What the drivers send on their own (client_encoding,DateStyle,TimeZone,extra_float_digits,application_name, astatement_timeoutinoptions) is on the list and keeps working.TimeZone(andDateStyle,IntervalStyle) are inputs to a policy too: one that compares withcurrent_date, or casts todateortimestamp, reads the session’s zone, so an agent that setsTimeZonesees what a policy dates in another zone – measured, a row embargoed until tomorrow, of its own tenant. Write such a policy withtimestamptzand an explicit zone (now() AT TIME ZONE 'UTC', adatecolumn compared in that zone): the allowlist keepsTimeZone, because every driver sends it.search_pathis deliberately not on it, so a driver configured with a default schema will be refused: pgjdbc’s connection code sendscurrentSchemaas the startup parametersearch_path(read in the driver, not measured here). Set the agent’s schema on its role instead. - The fast-path function-call protocol (
PQfn) skips the parser. Since 0.2.12 an agent session answers it only for the verbs: any other function reached that way – large objects,pg_read_file– is refused by the object-access hook before it runs. - What dry_run showed is what commit keeps (0.2.14). The session settings that
decide how a statement reads its literals and writes its values –
DateStyle,IntervalStyle,TimeZone,standard_conforming_strings,extra_float_digits,bytea_output– are recorded atpropose, anddry_runandcommitrefuse if any changed since. Measured on 0.2.13:dry_runshowed March 4, the session setDateStyle = 'ISO, DMY', andcommitkept April 3. - A read changes nothing (0.2.14). A
readthat calls a built-in which changes state outside the rows it returns –nextval,setval, thepg_advisory_*locks, large objects,pg_notify,setseed, WAL and statistics functions – is refused; until 0.2.13 one advanced a sequence 100,000 times and the record saidread. In a write they are allowed (an INSERT’s default callsnextval). A user function that is STABLE but calls one of them is not seen: its body is not in the statement. - A reused agent name starts clean (0.2.14). A proposal made under an earlier
registration of the same name answers like another agent’s, and
acts()shows only the current registration’s. - The record takes bounded input (0.2.14):
agent_gate.max_proposal_bytes(1 MB, SQL plus parameters) andagent_gate.max_intent_bytes(64 kB), superuser-only. The record stays append-only with no retention helper: reclaiming space still means disabling its triggers by hand. - The verbs run only under READ COMMITTED (0.2.12). At a stricter level the
gate would read the proposal and the record from an old snapshot; measured on
0.2.11, four REPEATABLE READ sessions each kept the same proposal. A verb
called at another level is refused. Two-phase commit (
PREPARE TRANSACTION) is refused in an agent session. - With
attempt_durability = fast, a crash can lose records of attempts that changed nothing. Never of changes. lastval()names the gate’s own sequence in an agent’s session. Each verb draws from the record’s sequences after the agent’s statement, soSELECT lastval()(PHP PDO’slastInsertId()with no sequence name) is refused for lack of privilege on the gate’s sequence.INSERT ... RETURNINGandcurrval('the_sequence')give the agent’s own value.dry_runis a rollback, not a sandbox. Sequence values, session advisory locks, and anything outside the transaction (dblink, untrusted languages) are not undone.- A row-level policy that calls a
SECURITY DEFINERfunction refuses every proposal on its table. The common membership helper (USING (is_member(tenant)),SECURITY DEFINERso it can read the membership table) is in the analyzed tree – the rewriter adds the policy’s qual – sono_opaque_functionrefuses the statement, and since 0.2.7 the function-manager hook would stop it anyway. That is the price of the rule, not an accident: write such a policy over asecurity_invokerhelper or a plain subquery on a table the agent may read, or the table is out of the agent’s reach. - An opaque user function is refused (0.2.3). A statement that calls a user
function which is volatile or
SECURITY DEFINERis refused atpropose(no_opaque_function): its body is not in the analyzed tree, so it could write rows no one counts or run as its owner outside the agent’s tenant. Built-ins (pg_catalog, e.g.gen_random_uuid()) and non-volatile, non-SECURITY DEFINERuser functions pass. There is no allow-list for functions in 0.2.3, so a volatile helper that does not write should be markedSTABLEorIMMUTABLE. Measured (tests/hostile.sh): such a function inside a WRITE is refused and writes nothing. no_opaque_functionwalks the proposal’s query tree, not every place a function can hide – this is a class, not a fixed list. It follows direct calls, operators,= ANY/IN, aggregates and window functions in the statement itself. It does NOT follow a function reached any other way: through a row comparison (RowCompareExpr), an aggregate’s own transition or final functions, an I/O or user cast, or a function the catalog attaches rather than the statement – a columnDEFAULT, aCHECKor domain constraint, a generated column, an expression index, or the body of a view or another function the statement touches. (The rewriter does write a columnDEFAULTinto anINSERT, or anUPDATE’sSET c = DEFAULT; since the fourth review of 0.4.3 the walker sets it apart when it is exactly the catalog’sDEFAULTof a table the agent cannot alter and not something the agent wrote, so a DBA’sgen_random_bytes()or order-numberDEFAULTno longer refuses the agent’sINSERT. That is the owner’s code, judged by the floor when it runs, like aCHECK. ADEFAULTof the agent’s own table is still walked as its call.) For ordinary DML done this way the commit backstop still counts the rows againstmax_rows(bounded in COUNT, though not in tenant or privilege – like an allow-listed trigger, a row written this way is counted but not tenant-filtered). A nested UTILITY is worse than uncounted:pg_stat_xactignoresTRUNCATE, so the backstop could not bound aTRUNCATE,GRANT,ALTERorDROPa function fires. 0.2.4 refuses any utility a trigger, constraint or function reaches while the gate runs the verified statement (on the gate’s own execution flag, notcurrent_user– inside aSECURITY DEFINERfunction the agent is already the owner). Measured: aCHECKwhose functionTRUNCATEd a table ran on a plainINSERTthe agent proposed – before 0.2.4 the table was emptied and kept; now the same statement aborts and the table is intact. The window spans the gate’s ownSET CONSTRAINTS, so a utility fired by a DEFERRED constraint trigger is caught too; the one utility the gate runs on purpose (anallow_ddlagent’s own DDL, and theSET CONSTRAINTS) is exempted, so it still goes through. This refuses ALL nested utility, benign included – a trigger that doesNOTIFY,SET LOCAL,LOCK TABLE,CALLorCREATE TEMP TABLEmakes the statement abort (pg_notify()called as a function is fine). ASECURITY DEFINERfunction reached through any of these positions is stopped before it runs (0.2.7). EverySECURITY DEFINERcall goes through PostgreSQL’sfmgr_security_definer, which calls the function-manager hook before the body; while SQL the agent wrote is running (verification, the verified statement, its deferred constraints, an allowed DDL) the gate refuses there, however the call was reached – another function, aCHECKor domain constraint, a default, a generated column, an expression index, a trigger, or the planner folding anIMMUTABLEwrapper atpropose. Measured on 0.2.6: such a wrapper verified and ran itsSECURITY DEFINERcallee atproposeand again atcommit; now neither, and the write aCHECKreached that way is not kept (tests/plan_time.sh). There is no allow-list for it. What this does NOT stop, because it is not aSECURITY DEFINERcall: a non-SECURITY DEFINERfunction in those positions (it runs with the agent’s rights; if it writes, the commit backstop counts the rows), a referential action, which runs as the table owner by its own mechanism, and a view withoutsecurity_invoker(below).- A cascade, trigger or rule that amplifies a write is refused (0.2.2/0.2.3).
Its extra rows run as the table owner, outside the agent’s
max_rowsand – for a referential action – its tenant.agent_gate.allow_write(agent, table)re-permits one table, but only for what the gate can check: a trigger whose own function is notSECURITY DEFINER. A cascade and a rule are NOT allow-listable in 0.2.3 (making some cascades safe needs a recursive closure over the cascade edges, and lands in 0.2.4), and a SECURITY DEFINER trigger never is. The commit backstop still counts every amplified row againstmax_rows(it over-counts, the safe side). A row anUPDATEmoves to another partition is a delete and an insert in those counters. Since the fourth review of 0.4.3 it is counted once: no more rows than the statement can only have moved – what it named minus the updates, and no more than the inserts and deletes in its target’s leaves – are taken off. Before, anUPDATEof a partition key was refused above half ofmax_rows. AMERGEthat moves rows, and a tree with a foreign or non-heap leaf, are still counted twice. It readspg_stat_xact_user_tables, which counts USER TABLES only – not foreign tables, large objects, sequences, or effects outside the transaction; aTRUNCATEit does not count is instead refused as a nested utility (0.2.4). “What the gate can check” is the honest bound: a non-SECURITY DEFINER trigger can still fire a cascade of its own that runs as a table owner outside RLS – the gate does not see the body. (ASECURITY DEFINERfunction it calls is stopped since 0.2.7.) Its rows are counted (so the limit holds) but not tenant-filtered. Allow-listing a trigger is a risk the DBA accepts for that one table; the backstop is the floor under it, not RLS. - A view is checked with its owner’s privileges unless it was created with
security_invoker. An agent grantedSELECTon such a view reads the tables behind it, including ones it has no privilege on at all: measured, a secret came through that way. That is PostgreSQL, not the gate – the gate verifies the proposal, it does not re-decide what a view may show.discoverlists the view, because the agent was granted it, and not the table behind. EXPLAINfolds constant calls to immutable functions. A DBA’s function falsely markedIMMUTABLEruns atpropose(with the guards above in place: noset_config(), noSECURITY DEFINERunder it). Marking functions honestly is a prerequisite for the DBA’s functions; a function the agent can alter is refused whatever it is marked (0.4.2).- The write budget counts a write when its transaction commits (0.4.5). The library charges
agent_gate_internal.budget_spentat PRE_COMMIT, after the deferred triggers, so a verb that waited – on a lock, onpg_sleep(), behind the agent’s other sessions – and a write kept in a transaction left open are counted from that moment (tests/budget.sh, cases 9 to 11). Up to 0.4.4 the window counted from the verb’s start, and six sessions of one agent kept 18 rows in one burst against a budget of 3 (measured on 0.4.5 before the change). What is left between the charge and the commit is PostgreSQL’s own commit: the WAL flush, and the wait for a synchronous standby where the DBA configures one (an agent cannot setsynchronous_commitunless the DBA adds it toagent_gate.settable). A write becomes visible that much after it is charged, and the next write’s window is short by as much. How long an agent can make that last – a write whose WAL is large, for one – is not measured. - The record is transactional. Inside an explicit transaction that the
caller rolls back, the record rolls back too; so does a
propose_and_committhat is cancelled, or that fails outside the gate’s own subtransaction, wherepropose+commitwould have kept the proposal. Every verdict is also written to the server log, which does not roll back – the verdict (agent, proposal id, kind, outcome) – and since 0.2.10 so is every row a rollback takes, statement and intent included. The server log can hold what an agent wrote: the gate’s rollback lines, and PostgreSQL’s ownlog_statementorlog_min_duration_statementif configured, which log theagent_gate.propose(...)call verbatim. A value passed as a parameter shows as$1in the statement; a literal in the SQL shows as written. - Parameters travel as text. Cast them in the SQL (
$1::int). Avarchar[]– what pgjdbc binds for aString[]– is accepted as the parser coerces it (0.4.3). - The verbs do not run in a read-only transaction (0.4.3). Every proposal, a read too,
is written to the record first, so a
READ ONLYtransaction (pgjdbc’ssetReadOnly(true)) and a hot standby are refused, saying so. - A cast that runs a function around a verb’s argument is refused (0.2.15).
Only the implicit cast the parser inserts to coerce a constant to the verb’s own
parameter type, through a built-in function, passes. An explicit cast, an I/O
conversion cast, or a cast through a user function would run that function while
the executor evaluates the argument – before verification raises the proposal
flag, so the definer guard would not see it – and is refused at parse time. Pass
such values as parameters, or cast them inside the proposed SQL (
$1::int), where verification covers them. allow_ddlis schema power, not a biggermax_rows. An agent allowed DDL runs anyCREATE,ALTERorDROPits grants permit; the change is verified by running it in a rolled-back subtransaction and kept only if that succeeds, butmax_rowsdoes not bound what it does to the agent’s own tables: a grantedDROP TABLEis kept, and anALTER COLUMN ... TYPE ... USINGrewrites every row of one with 0 rows counted. The query of aCREATE TABLE AS,SELECT INTOorCREATE MATERIALIZED VIEWis checked like a read before it runs (0.4.2), so it cannot carry a writing CTE, and a function the agent creates never starts in an agent’s session. An expression a DDL evaluates – aDEFAULTfilled in byALTER TABLE, aCHECK, an index expression – runs under the same floor, and what it changes in tables that existed before the DDL counts againstmax_rowsand the budget (0.4.3). A sequence it advances at commit is not undone. What PostgreSQL drops or alters for it is judged by owner, not counted: an object of a role whose privileges the agent has is its own, and an object with no owner of its own that a type’s drop takes with it (a cast, a transform) is not judged. A DDL that creates a sequence may draw from it at propose; if it also draws from one that existed before (ADD COLUMN s serial, ADD COLUMN n bigint DEFAULT nextval('public.s')) it is refused after the trial, and the values it drew are gone, as any rolled-backnextval()leaves them – and so is the value a DBA’s DDL-audit event trigger draws for each trial. That judgment reads the sequences the transaction holds locked, so one locked earlier in the same transaction refuses aserial(closed). Grant DDL narrowly, and leaveallow_ddl => falseunless a specific agent needs it.