An AI agent should never hold your application’s database credential—per-user identity, a narrow PostgreSQL role, and Row-Level Security make the database engine the enforcement point rather than the prompt.

TL;DR

  • Problem: Giving an MCP server or diagnostic agent the primary application role turns every prompt injection into a confused-deputy breach across all tenants and tables, with zero per-caller attribution in audit logs.
  • Answer: Eliminate static shared passwords; propagate caller identity via AWS RDS (rds_iam) or Google Cloud SQL (cloudsqliamuser) IAM authentication, enforce NOBYPASSRLS with FORCE ROW LEVEL SECURITY, and lock agent roles with default_transaction_read_only = on and statement_timeout.
  • Watch out: Session-level SET leaks tenant context across PgBouncer transaction pooling, table owners silently bypass RLS unless FORCE ROW LEVEL SECURITY is set, and RDS IAM tokens expire after 15 minutes for new pool connections.

Shared credentials turn agents into confused deputies; enforce in SQL

Situation

When engineering teams wire an AI agent or MCP server to PostgreSQL, the fastest path to a working prototype is copying the application’s DATABASE_URL into the agent’s environment. That single string usually carries a long-lived password for an application role that owns tables, reads and writes across every tenant, and bypasses Row-Level Security (RLS).

That shortcut collapses three distinct identities into one: the human caller (or upstream job), the agent runtime, and the application service. In Post 1 and Post 3, we saw how indirect prompt injection in retrieved text or poisoned MCP tool metadata can steer an LLM’s next tool call. When the agent connects to PostgreSQL using a broad application role, the database cannot tell whether a SELECT for tenant_id = 42 came from Tenant 42’s engineer or from a prompt injection inside Tenant 9’s support ticket.

PostgreSQL already provides deterministic primitives to solve this: granular ROLE privileges, predefined monitoring roles such as pg_read_all_stats, default_transaction_read_only, statement_timeout, and Row-Level Security. Both AWS RDS and Google Cloud SQL pair those engine primitives with short-lived IAM database authentication so neither the agent nor the MCP gateway needs static database passwords.

The Problem

Placing authorization in the agent’s prompt or MCP tool wrapper while connecting to PostgreSQL as a privileged shared user fails across four concrete database boundaries.

Identity propagation crosses three boundaries into PostgreSQL

  1. Shared application roles create an un-auditable confused deputy (TB-2 to TB-3). When every agent request hits PostgreSQL as app_user, session_user and current_user in pg_stat_activity and pgAudit both record app_user. If an indirect injection exfiltrates rows or runs an expensive cross-join, incident responders cannot attribute the query to the originating human caller or OIDC principal.
  2. Table ownership and BYPASSRLS silently disable Row-Level Security (TB-3). Enabling RLS on a table (ALTER TABLE ... ENABLE ROW LEVEL SECURITY) does not apply to the table owner or any role with the BYPASSRLS attribute. If the agent reuses the migration or application-owner role, every CREATE POLICY filter is skipped without a warning.
  3. Connection pooling breaks naive SET session isolation (TB-2 to TB-3). If a gateway uses PgBouncer or RDS Proxy in transaction-pooling mode and executes SET app.tenant_id = '...' without transaction scoping, that variable persists on the backend PostgreSQL process after the transaction commits—silently leaking Tenant A’s RLS context to Tenant B’s next request on the same pooled connection.
  4. IAM token lifetimes diverge from physical connection lifetimes (TB-2). In AWS RDS PostgreSQL, IAM authentication tokens generated for an rds_iam role have a strict, hardcoded 15-minute lifetime that cannot be extended. The token is checked only during the initial connection handshake—existing connections stay open past 15 minutes—but if a pool scales out or replaces a physical connection using a stale cached token, the handshake fails with an authentication error.

How do you let an agent run diagnostics or tenant-scoped queries on PostgreSQL without handing it static credentials or letting one poisoned prompt cross tenant and schema boundaries?

Options Considered

Teams typically evaluate three identity models for PostgreSQL agents.

Static roles fail; combine IAM DB auth with transaction-scoped RLS

How the Options Compare

OptionIdentity MechanismWhat It Gets RightWhere It BreaksVerdict
Static shared app_userSingle password in envZero pool changes; works out of the boxConfused deputy across all tenants; table owner skips RLS; no per-caller auditRejected
Pooled role + txn-local GUC (set_config)Gateway authenticates via IAM, sets set_config('app.tenant_id', ..., true) inside BEGINScales to 10,000+ SaaS tenants without creating thousands of DB roles; safe with PgBouncer transaction poolingRequires strict BEGIN + set_config(..., true) wrapper on every query; session_user reflects the gateway role unless application_name or audit headers are attachedChosen for multi-tenant SaaS data
Per-user Cloud IAM DB AuthEach human or service identity maps to a distinct DB user (rds_iam or cloudsqliamuser)Zero static passwords; native session_user attribution in pg_stat_activity and pgAudit; ideal for pg_read_all_stats diagnosticsCreating individual PostgreSQL roles does not scale to tens of thousands of external end-users; requires token refresh on new physical connectionsChosen for internal ops, engineers, and service identities

Using per-user Cloud IAM DB authentication for internal engineers and diagnostic agents, and transaction-scoped set_config + RLS for high-cardinality multi-tenant end-user queries, covers both workloads without ever placing a static password inside the agent runtime. In both models, the MCP Policy Gateway acts as the sole identity broker: it validates the caller’s OIDC token, rejects any tenant or role identifier supplied inside the LLM’s tool arguments, and binds the database session before any SQL executes. That separation guarantees that even if an indirect prompt injection alters the model’s SQL generation, PostgreSQL still enforces the caller’s exact row and schema boundary.

Target PostgreSQL Identity Architecture (RDS vs. Cloud SQL)

The target architecture enforces identity at the MCP Policy Gateway (TB-1), authenticates to PostgreSQL using short-lived cloud IAM tokens (TB-2), and delegates row, schema, and resource limits to the PostgreSQL engine (TB-3).

Enforce per-user identity and RLS across RDS and Cloud SQL

Comparing AWS RDS and Google Cloud SQL IAM Authentication

Both managed PostgreSQL platforms eliminate static passwords, but they differ in how roles are provisioned, how tokens are refreshed, and how connection proxies behave.

DimensionAWS RDS for PostgreSQLGoogle Cloud SQL for PostgreSQL
Instance enablementEnable IAM DB Authentication on the RDS instance/cluster (iam_database_authentication_enabled = true)Set instance flag cloudsql.iam_authentication=on
PostgreSQL plugin roleGrant rds_iam to the database user (GRANT rds_iam TO ...)Provision user via Cloud SQL API/CLI as CLOUD_IAM_USER or CLOUD_IAM_SERVICE_ACCOUNT (backed by cloudsqliamuser / cloudsqliamserviceaccount)
Username conventionStandard PostgreSQL identifier (e.g., agent_diag_ro or oncall_ops)Full IAM email or SA name (e.g., "[email protected]"—requires double quotes in SQL grants)
Token mechanism & TTLAWS SigV4 generate-db-auth-token; hardcoded 15-minute lifetime; IAM policy scopes rds-db:connect to DbUser ARNGoogle OAuth2 access token (gcloud auth print-access-token or ADC); short-lived token managed by Cloud IAM
Proxy / automatic refreshApplication or RDS Proxy refreshes token on new physical connections; IAM auth takes precedence over password for rds_iam usersCloud SQL Auth Proxy with --auto-iam-authn transparently injects and refreshes IAM tokens
Cloud authorization layerIAM policy condition on rds-db:connect (arn:aws:rds-db:region:acct:dbuser:dbi-.../username)Project IAM roles roles/cloudsql.instanceUser + roles/cloudsql.client (for Auth Proxy)

Production SQL: Narrow Roles, Timeouts, and Forced RLS

For PostgreSQL 15+ (compatible with PostgreSQL 14–17), separate diagnostic telemetry access from tenant data access. An agent diagnosing slow queries needs pg_read_all_stats—which lets a role view pg_stat_activity and pg_stat_statements statistics without granting SELECT on any application table (but note it also exposes other sessions’ raw query text in pg_stat_activity.query, literals included, so put it behind a SECURITY DEFINER view that projects only normalized pg_stat_statements columns)—plus default_transaction_read_only and statement_timeout baked directly into the role:

-- 1. Narrow diagnostic role (no table SELECT, read-only, 15s cap).
-- Caution: pg_read_all_stats also lets a role read other sessions' raw query text; see the wrapper-view note.
CREATE ROLE agent_diag_ro WITH LOGIN NOBYPASSRLS NOINHERIT;
GRANT rds_iam TO agent_diag_ro; -- On Cloud SQL, create as CLOUD_IAM_SERVICE_ACCOUNT instead
GRANT pg_read_all_stats TO agent_diag_ro;

ALTER ROLE agent_diag_ro SET default_transaction_read_only = on;
ALTER ROLE agent_diag_ro SET statement_timeout = '15s';
ALTER ROLE agent_diag_ro SET lock_timeout = '2s';

-- 2. Multi-tenant data role with forced RLS (cannot bypass even if owner)
CREATE ROLE agent_tenant_reader WITH LOGIN NOBYPASSRLS;
GRANT USAGE ON SCHEMA app TO agent_tenant_reader;
GRANT SELECT ON app.tickets TO agent_tenant_reader;
ALTER ROLE agent_tenant_reader SET default_transaction_read_only = on;
ALTER ROLE agent_tenant_reader SET statement_timeout = '10s';

ALTER TABLE app.tickets ENABLE ROW LEVEL SECURITY;
ALTER TABLE app.tickets FORCE ROW LEVEL SECURITY;

CREATE POLICY tickets_tenant_isolation ON app.tickets
  FOR SELECT
  TO agent_tenant_reader
  USING (
    tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
  );

Notice two critical details in that SQL:

  • NULLIF(current_setting('app.current_tenant_id', true), '')::uuid returns NULL instead of throwing an error or matching rows if the GUC is unset—failing closed (zero rows returned) if a caller forgets to initialize the transaction context.
  • The setting is only trustworthy if the agent cannot run arbitrary SQL: any session that can call set_config can choose its own tenant, so the gateway must be the only SQL path and the agent gets typed tools, not a SQL console.
  • FORCE ROW LEVEL SECURITY guarantees that even if a table’s ownership changes or a role inherits elevated table rights, PostgreSQL still evaluates tickets_tenant_isolation on every query.

When your gateway uses SET ROLE for internal engineering sessions rather than distinct physical connections, PostgreSQL maintains a strict distinction between session_user (the original authenticated IAM principal that opened the connection) and current_user (the active role after SET ROLE). Audit columns and pgAudit should always capture session_user alongside application_name so role switching never obscures who initiated the session. In addition, run REVOKE CREATE ON SCHEMA public FROM PUBLIC and ensure any helper views are created with security_invoker = true (available in PostgreSQL 15+) so views execute with the querying agent’s RLS and table permissions rather than the view owner’s privileges.

For connection pooling, AWS RDS Proxy supports IAM authentication directly between the gateway and the proxy, while the proxy maintains a warm pool to the RDS instance—preventing 15-minute token-expiry storms during sudden concurrency spikes, though RDS Proxy pins connections if session-level SET statements are issued instead of set_config(..., true). On Google Cloud SQL, running cloud-sql-proxy --auto-iam-authn as a sidecar next to the MCP Policy Gateway handles OAuth2 token acquisition and automatic TLS tunneling without embedding Google credential logic inside your MCP tool code.

Attacker and Defender Threat Matrix

Threat VectorTrust Boundary CrossedAttacker Objective (OWASP / ATLAS)Defender Control (Deterministic)Verification Signal
Cross-tenant ID injectionTB-2 → TB-3 (Agent → PostgreSQL)Read Tenant B rows by passing tenant_id = B in SQL/tool args (LLM01 / Collection)Ignore prompt tenant_id; derive from OIDC at gateway and bind via set_config(..., true) + RLSQuery for Tenant B under Tenant A’s OIDC token returns 0 rows
Table owner / BYPASSRLS escalationTB-3 (Role → Table)Skip RLS policies by connecting as migration or owner role (Privilege Escalation)Dedicated NOBYPASSRLS agent role + ALTER TABLE ... FORCE ROW LEVEL SECURITYSELECT * FROM app.tickets without GUC returns 0 rows
PgBouncer session variable leakTB-2 → TB-3 (Pool → Backend)Inherit previous tenant’s app.current_tenant_id on a reused pooled connectionAlways execute SELECT set_config('app.current_tenant_id', $1, true) inside BEGIN...COMMITSequential pooled requests for Tenant A then unset return 0 rows on request 2
Diagnostic role reads raw query textTB-2 → TB-3 (Telemetry → Model)pg_read_all_stats exposes other sessions’ pg_stat_activity.query with literalsExpose normalized pg_stat_statements through a SECURITY DEFINER view; do not hand the agent raw pg_stat_activityAgent role cannot read another user’s query text
Diagnostic agent reads PII tablesTB-3 (Telemetry → Data)Use EXPLAIN or SELECT on customer tables during latency triageGrant pg_read_all_stats only; revoke SELECT on app.* schemasDiagnostic role receives permission denied for table on app.tickets
Write or DDL injection via SQL toolTB-2 → TB-3 (Tool → Engine)Execute UPDATE, DELETE, or COPY TO PROGRAM via crafted prompt (LLM06)ALTER ROLE ... SET default_transaction_read_only = on + read replica routingAny DML/DDL statement fails with cannot execute in a read-only transaction
Static credential theft from agent envTB-1 → TB-2 (Sandbox → DB)Exfiltrate DATABASE_URL from agent environment or logs (Credential Access)Zero DB passwords in agent env; gateway uses 15-min RDS IAM or Cloud SQL Auth ProxyAgent runtime environment dump contains zero DB host passwords
Runaway sequential scan DoSTB-3 (Query → Primary CPU)Trigger full table scan or lock wait on primary database (Impact)statement_timeout = '15s', lock_timeout = '2s', and read-replica routingLong-running test query cancels automatically at 15s

How It Rolls Out

Combining Cloud IAM authentication with transaction-local RLS ensures every query is authenticated, bounded, and attributable.

Isolate pooled agent queries with IAM auth and transaction-local RLS

Runtime Execution Flow

  1. 01 OIDC to Role: The MCP Policy Gateway validates the caller’s OIDC token and extracts either the internal engineer’s IAM identity (for diagnostics) or the authenticated tenant_id (for SaaS data access). Prompt-supplied tenant IDs are discarded.
  2. 02 IAM Handshake: The gateway connects to PostgreSQL over TLS using a freshly minted IAM token—either an AWS SigV4 token (rds_iam, valid for 15 minutes at handshake) or via the Google Cloud SQL Auth Proxy (--auto-iam-authn for cloudsqliamuser / cloudsqliamserviceaccount).
  3. 03 Transaction-Local GUC: For multi-tenant queries, the gateway opens a transaction (BEGIN) and executes SELECT set_config('app.current_tenant_id', $1, true) alongside SET LOCAL application_name = '<trace_id>'. Passing true scopes the setting strictly to the current transaction so PgBouncer transaction pooling never leaks context.
  4. 04 Enforce and Audit: PostgreSQL evaluates RLS policies, default_transaction_read_only, and statement_timeout inside the engine. pgAudit and PostgreSQL logs record session_user (immutable original login) and application_name while redacting bind values.

Phased Rollout and Rollback Gates

  1. Phase 1 — Provision Narrow Roles and Enable IAM Auth: Enable iam_database_authentication_enabled (RDS) or cloudsql.iam_authentication=on (Cloud SQL). Create agent_diag_ro (pg_read_all_stats) and agent_tenant_reader (NOBYPASSRLS) with default_transaction_read_only = on and statement_timeout. Gate: New roles connect via IAM token and fail on INSERT/UPDATE. Rollback: Drop the new IAM roles; existing application traffic is untouched.
  2. Phase 2 — Enable and Force RLS on Multi-Tenant Tables: Apply ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY, and fail-closed NULLIF(current_setting(...), '') policies on target tables. Gate: Unset GUC returns 0 rows; Tenant A GUC returns only Tenant A rows. Rollback: Temporarily disable RLS on a specific table only if an un-migrated legacy batch job breaks, while keeping agent_tenant_reader blocked from that table via REVOKE.
  3. Phase 3 — Migrate MCP Tools to Gateway Identity Exchange: Move database credentials out of the agent runtime into the MCP Policy Gateway. Configure RDS token refresh per new physical connection or deploy Cloud SQL Auth Proxy with --auto-iam-authn. Gate: 100% of agent queries execute under IAM-authenticated roles with zero static passwords in agent env. Rollback: Temporarily route a specific tool through a scoped read-only password in Secrets Manager if IAM token generation hits cloud API rate limits.
  4. Phase 4 — Replica Pinning and pgAudit Verification: Point all agent read tools to read replicas and verify pgAudit captures session_user and application_name trace IDs. Gate: Zero agent queries hit the primary writer; audit logs correlate every tool call to a caller principal. Rollback: Fail over read tool DNS to another healthy replica.

In Practice

I have not benchmarked every RDS Proxy and Cloud SQL Auth Proxy concurrency limit across all instance sizes personally, so the mechanisms above are grounded in official PostgreSQL, AWS, and Google Cloud documentation:

  • PostgreSQL role and RLS mechanics (Pattern A — Official Docs): Per the PostgreSQL documentation, session_user records the immutable original login user while current_user reflects SET ROLE, FORCE ROW LEVEL SECURITY is required to subject table owners to RLS, and set_config(name, value, true) scopes GUCs to the current transaction for safe connection pooling. pg_read_all_stats grants read access to statistics views (pg_stat_activity, pg_stat_statements) without granting SELECT on user tables.
  • AWS RDS IAM token lifecycle (Pattern A — AWS Docs): Per AWS RDS IAM Database Authentication documentation, rds_iam tokens have a fixed 15-minute lifetime checked at connection establishment; active connections remain open past 15 minutes, but connection pools must generate fresh tokens for new physical connections.
  • Google Cloud SQL IAM authentication (Pattern A — Google Cloud Docs): Per Cloud SQL IAM Database Authentication documentation, enabling cloudsql.iam_authentication=on maps CLOUD_IAM_USER and CLOUD_IAM_SERVICE_ACCOUNT principals to cloudsqliamuser / cloudsqliamserviceaccount, requires roles/cloudsql.instanceUser plus explicit SQL GRANTs, and supports automatic token injection via cloud-sql-proxy --auto-iam-authn.

Where It Breaks

PostgreSQL identity fails via credential reuse, pool leaks, and RLS gaps

ConditionBreaks HowDetectMitigate
RDS IAM token cached >15 minutesPooler or gateway caches token at startup; after 15 minutes, scale-out connections fail authSpike in FATAL: PAM authentication failed or password authentication failed logsGenerate a fresh SigV4 token inside the pool’s connect hook for every new physical connection
Cloud SQL IAM user created without SQL GRANTsgcloud sql users create succeeds, but queries fail because cloudsqliamuser has no default schema/table rightsERROR: permission denied for schema/table on first agent callAutomate GRANT USAGE / GRANT SELECT in Terraform or migration scripts for every quoted IAM email
RLS policy references non-indexed columnWHERE tenant_id = current_setting(...) triggers sequential scans under RLS evaluationEXPLAIN (ANALYZE, BUFFERS) shows Seq Scan instead of Index Scan on tenant tablesIndex tenant_id on every RLS-protected table and verify query plans under agent_tenant_reader
Agent calls SECURITY DEFINER functionA SECURITY DEFINER function runs with the creator’s privileges, bypassing the caller’s RLS and read_only expectationsAudit pg_proc for prosecdef = true callable by PUBLIC or agent rolesREVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA app FROM PUBLIC; allowlist only SECURITY INVOKER functions
Multi-role SET ROLE inside rds_iam without NOINHERITOver-broad role inheritance grants unintended write or admin privileges to the diagnostic roleSELECT * FROM information_schema.applicable_roles shows unexpected parent rolesCreate agent roles with NOINHERIT and audit role memberships in CI

Key Takeaways

  • Never put the application’s DATABASE_URL in an agent runtime: Static shared credentials turn prompt injection into a cross-tenant confused-deputy breach with no caller attribution.
  • Use Cloud IAM DB auth for zero-password connections: Map internal callers and services via AWS RDS rds_iam (refreshing 15-minute tokens on new connections) or Cloud SQL cloudsqliamuser with --auto-iam-authn.
  • Enforce FORCE ROW LEVEL SECURITY and NOBYPASSRLS: Never rely on application WHERE clauses or table-owner defaults; fail closed with NULLIF(current_setting('app.current_tenant_id', true), '')::uuid.
  • Scope pool state to the transaction: Always pass true to set_config() inside BEGIN...COMMIT so PgBouncer transaction pooling never leaks tenant state across requests.
  • Lock diagnostic roles in SQL: Combine pg_read_all_stats (for telemetry without table SELECT), default_transaction_read_only = on, and statement_timeout directly on the PostgreSQL role.

What to Do Next

  • Problem: Agents connecting to PostgreSQL with shared application credentials bypass tenant isolation and leave no per-caller audit trail.
  • Solution: Replace static passwords with AWS RDS or Cloud SQL IAM authentication, enforce FORCE ROW LEVEL SECURITY with transaction-local set_config, and give diagnostic roles stats access through curated views (pg_read_all_stats alone also exposes other sessions’ raw query text) plus statement_timeout.
  • Proof: Connect as agent_tenant_reader without setting app.current_tenant_id, run SELECT count(*) FROM app.tickets, and verify PostgreSQL returns 0 rows while an INSERT fails with cannot execute in a read-only transaction.
  • Action: Audit your PostgreSQL agent roles this week, strip BYPASSRLS and table ownership from any role used by an MCP server, and enable IAM database authentication on your staging replica.