· AI dev tools

PostgreSQL, AI Agents, temporary read-only access via roles and expiring credentials

An AI agent needing to check an order's current status to determine why shipment is delayed illustrates the need for data access, even when the agent has the relevant order processing code.


Instead of manually running SQL commands and feeding the results back to the AI, we can permit it to query the database directly. Developers looking to grant AI agents access to PostgreSQL should explore several methods to safely control what they can see and do.

PostgreSQL offers two distinct mechanisms for limiting modification capabilities: enforcing read-only transactions or setting specific database role permissions. One way to enforce read-only behavior is by initiating a transaction in that mode: BEGIN READ ONLY; SELECT id, status FROM public.orders WHERE id = 1042; COMMIT;. Alternatively, you might configure a specific database user to default to read-only transactions using ALTER ROLE agent SET default_transaction_read_only = on;. However, a crucial warning is that an AI agent possessing write permissions can bypass this safeguard by executing SET default_transaction_read_only = off;.

While read-only transactions offer an extra layer of caution, restricting the underlying database permissions themselves presents a superior method. This involves crafting a PostgreSQL role with a precise set of allowed actions. Rather than granting sweeping access across every table, you grant permission only to those tables the agents actually require. The process begins with CREATE ROLE agent_readonly NOLOGIN; followed by granting the necessary rights: GRANT CONNECT ON DATABASE production TO agent_readonly; GRANT USAGE ON SCHEMA public TO agent_readonly; and GRANT SELECT ON public.orders TO agent_readonly;. Subsequently, a distinct database user can be established that inherits these privileges: CREATE ROLE agent_142 LOGIN PASSWORD '<generated-password>' IN ROLE agent_readonly;.

This permission-based approach ensures that PostgreSQL strictly upholds these access boundaries, irrespective of the current transaction setting. Should this specific database user attempt to alter an order record, the system will issue a permission error. The agent role inherently possesses SELECT privileges, yet a cautionary note must be heeded: PostgreSQL permissions accumulate, meaning careful configuration is necessary. For instance, if the PUBLIC group has been granted UPDATE authority on public.orders, the read-only user will still retain the ability to change orders.

A PostgreSQL read replica mirrors changes from the primary server. When running in standby mode, this replica actively denies write operations to its tables, even if the agent's role includes write privileges. Nevertheless, the agent's designated role still dictates the scope of tables and rows it can view. Furthermore, executing the agent's queries against a replica diverts the computational load, including memory and CPU usage, away from the main primary server. Another caveat to consider is that replicas may fall behind the primary; an agent investigating a payment delay might incorrectly see the order as unpaid if the transaction just cleared on the primary.

Limiting write operations alone does not mitigate every risk associated with allowing an AI agent to run arbitrary SQL commands. The VALID UNTIL clause permits setting an expiration date for a PostgreSQL role's password. Once this time elapses, PostgreSQL refuses any new connections attempting to use that expired credential. This is implemented via ALTER ROLE agent_142 VALID UNTIL '2026-12-01 12:15:00+00'; a related warning is that any established connections remain active even after the password expires, allowing an agent to continue running queries over an already open link. To demonstrate this persistence, one should connect to a test database with the credentials before they expire and execute SELECT now(), pg_backend_pid(); then, keep that database connection open and run the same command after the expiration time; the query will still succeed.

To effectively revoke database access, you must block new connections and explicitly close existing ones: ALTER ROLE agent_142 NOLOGIN; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'agent_142'; followed by DROP ROLE agent_142; to completely remove the temporary database role. When implementing this strategy in a live environment, automation is vital for provisioning credentials, scheduling the necessary cleanup, handling failures during cleanup retries, and confirming that all extant connections have been closed.

A privileged database administrator can enable PostgreSQL query logging for the agent's login role using ALTER ROLE agent_142 SET log_statement = 'all'; this setting must be applied before the agent initiates its connection. If a unique login role is created for every investigation, the role specified in the logs reveals which specific investigation a given query pertains to. However, a limitation exists with log_statement = 'all', as the query log might still omit statements containing syntax errors or expose sensitive data.

Constructing a thorough audit trail requires additional steps beyond simple role management. Instead of directly administering temporary database users, a PostgreSQL-compatible proxy situated before the database offers a more robust solution for access control. This proxy can generate temporary virtual PostgreSQL credentials, tie them to a specific session, forward queries using a restricted upstream database user, log every executed query, and automatically terminate the session after a set duration.

Using PgStack Access, which functions as a managed PostgreSQL proxy placed in front of the database, a single command yields a temporary connection URL for a read-only session: pgstack access start --env production --duration 15m --read-only. It must be noted that the agent can connect using a standard client like psql without ever gaining access to the actual database credentials. For the scenario of an unshipped order, the agent can retrieve its current status and cross-reference what that status implies within the order processing code. After the fifteen-minute window concludes, PgStack Access automatically terminates the session and invalidates the associated credentials. The session log meticulously records every SQL statement executed during the investigation. Ultimately, the appropriate method for granting AI agents access to a PostgreSQL database hinges entirely on the specific use case; PgStack Access facilitates this workflow without forcing development teams to manage their own proxy infrastructure.

Why it matters

As AI coding agents become integrated into production workflows, securing database access is critical to prevent data breaches or accidental modifications. Developers need robust tooling to grant just-in-time, least-privilege access for investigations.

Earlier coverage

Related coverage

Also worth reading

  1. next.js 16.6.0-canary.4 released, adding Go syntax highlighting and Node.js 24 unit tests
  2. TypeScript 7.1-rc released for developers to download on npm
  3. next.js 16.6.0-canary.2 released, adds file uploads, updates docs, and more
  4. next.js 16.6.0-canary.1 released with 405 for forbidden Route Handler methods
  5. Angular 21.2.27 released, fixes component template capture during compile