Skip to content
mentoor

Topic 1 of 5 · 5 min read

Scoped database roles for agents

Goal: Write the grants and settings for an agent role that can answer reporting questions but cannot write or run unbounded scans.

Give every agent or AI feature its own database role that can only do what its job needs, and let the database enforce the limits rather than the prompt. A system prompt that says "only run SELECT" is a request. A grant is a rule.

Check yourself · 1 of 3

A text-to-SQL feature only needs to answer sales questions. Which setup is safest?

Choose one answer

Why it matters

A coding agent or text-to-SQL feature that connects with the application's owner login can do everything the app can: write, drop, read every tenant's rows. Models guess, misread a question and follow instructions hidden in data. When the role cannot do the harmful thing, a wrong guess costs one failed query instead of an incident.

How to build the role

  1. Create a separate login role. One per agent or feature, so its queries are identifiable and its access can be revoked alone.
  2. Grant the least. USAGE on one schema, SELECT on named tables or, better, on views that already hide sensitive columns. Nothing on public by default.
  3. Add row-level security when one table holds several tenants or users. A policy filters rows for that role no matter what query it writes.
  4. Cap time and sessions. statement_timeout kills runaway scans, idle_in_transaction_session_timeout frees stuck sessions, and CONNECTION LIMIT stops an agent loop from exhausting connections.
  5. Cap rows in the tool layer. PostgreSQL has no per-role row limit, so the code that runs the agent's SQL should add a LIMIT or fetch through a cursor and stop.

Before and after

Before, the agent gets the app's DATABASE_URL. After:

CREATE ROLE agent_reports LOGIN CONNECTION LIMIT 3;
REVOKE ALL ON SCHEMA public FROM agent_reports;
GRANT USAGE ON SCHEMA reporting TO agent_reports;
GRANT SELECT ON reporting.orders_summary TO agent_reports;

ALTER ROLE agent_reports SET statement_timeout = '5s';
ALTER ROLE agent_reports SET idle_in_transaction_session_timeout = '10s';
ALTER ROLE agent_reports SET default_transaction_read_only = on;

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY agent_tenant ON orders FOR SELECT TO agent_reports
  USING (tenant_id = current_setting('app.tenant_id')::int);

Note which line is the real barrier. default_transaction_read_only is only a default: a session can run SET default_transaction_read_only = off and then write. The missing INSERT, UPDATE and DELETE grants are what stop it.

What goes wrong

  • Table owners skip row security. The role that owns a table bypasses its policies unless you run ALTER TABLE ... FORCE ROW LEVEL SECURITY. Never let the agent role own anything.
  • Grants on the whole schema. GRANT SELECT ON ALL TABLES also exposes the users table with emails and hashes. Name the tables.
  • Timeouts set in the client only. A setting in the agent's connection string can be changed by the agent. Set it on the role.
  • Shared passwords. One credential for three agents makes the audit log useless and revocation impossible.

Examples

Expose a view, not the table

The customers table has email, phone and password_hash. Instead of granting SELECT on it, create reporting.customer_counts with only region and signup_month, and grant that view. The agent can answer "signups per region" and has no path to the sensitive columns.

A runaway query

A text-to-SQL feature writes SELECT * FROM events e JOIN sessions s ON true, a cross join. With statement_timeout = '5s' set on its role, the database cancels it with an error and the agent can retry with a fix. Without it, the query holds a connection and CPU until someone notices.

Key points

  • Create one login role per agent or feature so access and audit trails are separate.
  • Grants are the real barrier: missing INSERT, UPDATE and DELETE privileges stop writes, while a read-only default setting can be switched back by the session.
  • Row-level security filters rows for the role whatever query the agent writes, but table owners bypass it unless FORCE is set.
  • Set statement_timeout and idle_in_transaction_session_timeout on the role, not in the client connection string.
  • Row limits belong in the tool layer, because PostgreSQL has no per-role row cap.

Common mistakes

  • Connecting the agent with the application's owner or admin login for convenience.
  • Trusting a prompt instruction such as "read only" instead of withholding write grants.
  • Granting SELECT on all tables in a schema, which exposes sensitive tables added later.
  • Putting timeouts in the connection string, where the agent can override them.

Check yourself · 2 of 3

An agent role has default_transaction_read_only = on, yet the role also holds UPDATE on orders. What is true?

Choose one answer

Check yourself · 3 of 3

Row-level security is enabled on orders with a tenant policy, but the agent still sees every tenant's rows. What is the most likely cause?

Choose one answer

Practice items, not counted towards your mastery.

Start here