AI Agents Shouldn't Have Permanent Database Credentials

AI Agents Shouldn't Have Permanent Database Credentials

Evgeny Li · · 9 min read

TL;DR

  • Read-only access. A restricted PostgreSQL role can limit the agent to the data it needs.
  • Temporary credentials. Password expiration blocks new connections that use the expired password, but existing connections can stay open.
  • Query recording. An SQL log tied to an investigation can show what the agent ran.
  • Session-based access. A PostgreSQL proxy can provide read-only sessions that expire automatically and record the SQL queries run in each session.

AI coding agents like Claude Code and Codex can help troubleshoot production issues. But understanding the codebase isn't always enough. They often need access to the data.

Suppose a customer reports that an order hasn't shipped. An AI agent can find the order processing code and check which statuses can block shipment. It still needs the order's current status to see which case applies.

We can run SQL queries manually and pass the results back to the AI agent or let it query the database directly. Let's explore a few approaches to granting AI agents access to PostgreSQL.

Read-only access in PostgreSQL

PostgreSQL provides two ways to restrict write operations: read-only transactions and database role permissions.

Read-only transactions

PostgreSQL allows starting a transaction in read-only mode:

BEGIN READ ONLY;
SELECT id, status FROM public.orders WHERE id = 1042;
COMMIT;

We can also make read-only transactions the default for a particular database user:

ALTER ROLE agent SET default_transaction_read_only = on;

Caveat: An AI agent with write permissions can override this setting and start a writable transaction.

SET default_transaction_read_only = off;

Read-only transactions are useful as an additional precaution, but we also need to restrict the database permissions themselves.

Read-only roles

A better approach is to create a PostgreSQL role with a specific set of permissions. Instead of granting access to all tables, we can grant access only to the tables AI agents need.

CREATE ROLE agent_readonly NOLOGIN;

GRANT CONNECT ON DATABASE production TO agent_readonly;
GRANT USAGE ON SCHEMA public TO agent_readonly;
GRANT SELECT ON public.orders TO agent_readonly;

We can then create a separate database user that inherits these permissions:

CREATE ROLE agent_142 LOGIN PASSWORD '<generated-password>'
IN ROLE agent_readonly;
Creating a login role for investigating a particular issue

With this approach, PostgreSQL enforces these permissions regardless of the transaction mode. If this database user tries to update an order, PostgreSQL returns a permission error.

The agent_readonly NOLOGIN role grants permissions inherited by the agent_142 login. The agent can SELECT from orders but cannot UPDATE it.

The agent role inherits SELECT permissions

Caveat: PostgreSQL permissions are additive, so we need to configure access carefully. For example, if UPDATE on public.orders is granted to PUBLIC (all database roles), our read-only user will still be able to modify orders.

Read replicas

A read replica follows changes from the primary. A PostgreSQL read replica in standby mode rejects writes to its tables even if the agent's role has write permissions. Note that the agent's role still determines which tables and rows it can see.

Running the agent's queries on a replica also moves their CPU and memory load off the primary.

Caveat: A replica can lag behind the primary. An agent investigating a delayed order might see it as unpaid even though the payment just went through.

Limitations of read-only access

Restricting write operations doesn't address all the risks of letting an AI agent execute arbitrary SQL queries:

  • Data exposure. A read-only database user might be able to read personally identifiable information (PII), authentication tokens, or data belonging to other customers. We can further restrict access by specifying individual columns, creating views that expose only a subset of the data, or using row-level security (RLS).
  • Performance. A SELECT query can scan large tables, consume significant CPU and memory resources, or hold locks for a long time. Complex RLS policies can also add query execution overhead.
  • Credential exposure. An AI agent needs access to its own restricted credentials, and privileged credentials elsewhere in its environment need to stay out of its reach. Even temporary credentials should be treated as secrets.

Temporary credentials in PostgreSQL

The VALID UNTIL clause sets an expiration time for a PostgreSQL role's password. After that time, PostgreSQL rejects new connections that use the expired password.

ALTER ROLE agent_142 VALID UNTIL '2026-12-01 12:15:00+00';

Caveat: Existing connections stay open after the password expires, so an agent can keep running queries over a connection it already opened.

To demonstrate the difference, connect to a test database with these credentials before they expire and run this query:

SELECT now(), pg_backend_pid();

Keep the database connection open and run the same query after the expiration time. The query should still succeed.

An existing connection stays open past the VALID UNTIL cutoff. New connections using the same password can authenticate before the cutoff and are rejected afterward.

Existing connections survive password expiration

To expire database access, we need to prevent new connections and explicitly terminate existing ones:

ALTER ROLE agent_142 NOLOGIN;

SELECT pg_terminate_backend(pid)
FROM pg_stat_activity WHERE usename = 'agent_142';

DROP ROLE agent_142;
Clean up the temporary database role

To use this approach in production, we need to automate credential provisioning, schedule cleanup, retry failed cleanup operations, and verify that existing connections have been terminated.

Recording SQL queries

A privileged database user can enable PostgreSQL query logging for the agent's login role:

ALTER ROLE agent_142 SET log_statement = 'all';

Set this before the agent connects. If each investigation gets its own login role, the role in the logs tells you which investigation a query belongs to.

Caveat: With log_statement = 'all', the query log can still omit statements with syntax errors and include sensitive values.

Building a comprehensive audit trail takes a few more steps:

  • Collecting and storing logs somewhere outside the database.
  • Recording why each temporary database user was granted access.
  • Making it easy to search and review executed SQL queries.
  • Managing retention and access to the logs themselves.

Session-based database access

Instead of managing temporary database users directly, we can use a PostgreSQL-compatible proxy in front of our database to manage access.

The proxy can generate virtual PostgreSQL credentials, associate them with a session, forward queries using a restricted upstream database user, record the queries, and terminate the session at a specified time.

An AI agent connects through a PostgreSQL proxy to a restricted upstream role. The proxy expires sessions and records SQL queries.

Temporary recorded access using a PostgreSQL proxy

With PgStack Access as a managed PostgreSQL proxy in front of our database, one CLI command can return a temporary connection URL for a read-only session:

pgstack access start --env production --duration 15m --read-only

Full disclosure: I work on PgStack.

The agent can connect with a standard client like psql without having access to the underlying database credentials. For an order that hasn't shipped, the agent can read its current status and check what that status means in the order processing code.

After 15 minutes, PgStack Access automatically ends the session and invalidates its credentials. The session record shows which SQL statements ran during the investigation.

Limitations of a session-aware PostgreSQL proxy

  • Additional infrastructure. Using a proxy adds a service that sits between AI agents and the database. If we implement it ourselves, we need to handle availability, connection management, and support for PostgreSQL-specific protocol features.
  • Data security. A proxy handles database traffic, so we need to use encrypted connections, encrypt stored credentials and query recordings, and restrict access to the recordings.
  • The underlying permissions still matter. Temporary access and query recording don't replace the need to restrict which data an agent can read or to isolate expensive workloads.

Conclusion

The right way to give AI agents access to a PostgreSQL database depends on the use case:

  • No live data required: A development database or a sanitized copy of production can be enough.
  • Occasional production access: A restricted PostgreSQL role with an expiring password and query logging can cover a single investigation. Active connections still need to be terminated when access ends.
  • Team-wide production access: Centralized access and query recording can tie each session to an AI agent and an investigation. That gives the team a record of why access was granted and which SQL statements ran.

PgStack Access provides this workflow without requiring teams to run their own proxy.

Subscribe for more like this

PgStack Logo
© 2026 Bemi Technologies, Inc.
SOC 2 Type II CertifiedSOC 2 Type II Certified
HIPAA CompliantHIPAA Compliant