Safe Database Access for AI Coding Agents
In this article
This guide explains how to give AI coding agents safe, controlled access to a production database. You'll learn a practical, step-by-step approach that minimizes risk of data corruption, leaks, or accidental damage, while still letting the agent work effectively. We'll cover the essential prerequisites, the exact steps to implement, common pitfalls, and troubleshooting strategies.
What You'll Need
- A production database (any major SQL or NoSQL database).
- Access to your database's user/role management and network configuration.
- An AI coding agent that supports custom API endpoints or database connections (e.g., GitHub Copilot, Cursor, or a custom agent).
- Basic familiarity with your database's query language and permission system.
- Optional but recommended: a separate staging environment for testing.
Step-by-Step
- Create a dedicated database user for the agent. Never use your admin or application credentials. In PostgreSQL, for example:
CREATE USER ai_agent WITH PASSWORD 'strong_random_password';For MySQL:CREATE USER 'ai_agent'@'%' IDENTIFIED BY 'strong_random_password';Use a strong, unique password that you store in a secret manager, not in the agent's prompt. - Grant only the minimum necessary privileges. The agent likely needs to read data and possibly write to a temporary schema. Start with SELECT on the tables it needs. If it must write, create a separate schema (e.g.,
ai_temp) and grant ALL on that schema only, plus SELECT on the production tables. In PostgreSQL:GRANT SELECT ON ALL TABLES IN SCHEMA public TO ai_agent;andGRANT ALL ON SCHEMA ai_temp TO ai_agent;For MySQL:GRANT SELECT ON prod.* TO 'ai_agent'@'%';andGRANT ALL ON ai_temp.* TO 'ai_agent'@'%'; - Restrict network access. If possible, allow connections only from the agent's IP address or via a VPN. In cloud databases (AWS RDS, GCP Cloud SQL), use security groups or firewall rules. For on-prem, use firewall rules. This prevents unauthorized access even if credentials leak.
- Set a statement timeout and row limits. Prevent runaway queries. In PostgreSQL, set
statement_timeoutin the agent's session or role:ALTER ROLE ai_agent SET statement_timeout = '30s';Also, encourage the agent to useLIMITin queries, but enforce a hard cap with a proxy if possible. - Use a read-only replica (if available). For pure read tasks, point the agent to a read replica instead of the primary. This eliminates the risk of accidental writes and reduces load on the primary. Most cloud providers offer read replicas with a single click.
- Implement a query proxy or middleware (advanced). Tools like
pgbouncerwith query filtering, or a custom proxy that inspects SQL, can block dangerous statements (e.g.,DROP TABLE,DELETEwithout WHERE). This is the most robust approach but requires development effort. - Enable audit logging. Turn on database audit logs to record all queries made by the agent. This helps you review what the agent did and detect issues early. In PostgreSQL, enable
log_statement = 'all'for that role, or use extensions likepgaudit. - Test in a staging environment first. Before granting production access, test the exact same setup in a staging environment with similar data. This verifies that the permissions are sufficient and that the agent can perform its tasks.
- Provide the agent with a detailed system prompt. Include the database schema, sample queries, and explicit instructions on what it is allowed to do (e.g., "You may only run SELECT queries and write to the ai_temp schema. Never attempt to drop tables or modify production data.")
- Monitor and review. After granting access, monitor the audit logs regularly and review the agent's queries. Set up alerts for suspicious activity, such as many failed attempts or queries that touch sensitive columns.
Common Mistakes
- Granting too many privileges. Giving the agent UPDATE or DELETE on production tables is the most common and dangerous error. Always start with SELECT only and add write access only if absolutely necessary, and then only to a dedicated temp schema.
- Using the same credentials for the agent and the application. This defeats the purpose of isolation. If the agent misbehaves, you can't revoke its access without affecting your app.
- Ignoring network restrictions. Leaving the database open to the internet with just a username/password is a huge risk. Always restrict by IP or VPN.
- No timeout or row limits. A single bad query can lock tables or consume all resources, bringing down the database. Always set timeouts and encourage LIMIT.
- Not testing in staging. You might grant too little or too much access. Testing in staging prevents surprises in production.
- Forgetting to revoke access when the agent is no longer needed. Regularly audit and remove unused accounts.
Tips
- Use a secret manager (like AWS Secrets Manager, HashiCorp Vault) to store the database credentials. Never hardcode them in the agent's prompt or configuration files.
- Consider using a read-only API endpoint that the agent can call instead of direct database access. This adds a layer of abstraction and allows you to enforce strict query patterns.
- Set up a rollback plan. If you must allow writes, ensure you have automated backups and know how to restore a specific table or schema.
- Educate the agent's users. Make sure the developers who use the agent understand the restrictions and why they exist.
- Use database views to expose only the columns the agent needs, even if the underlying table has more.
Troubleshooting
- Agent gets "permission denied" errors. Check the exact privileges granted. In PostgreSQL, you may need to also grant USAGE on the schema. For MySQL, check that the user has privileges on the specific database. Re-read the grant statements and adjust.
- Agent's queries are slow or time out. If you set a statement timeout, the agent might hit it on complex queries. Consider increasing the timeout slightly, or optimize the queries. Also, ensure the agent is using indexes properly.
- Agent cannot connect to the database. Check network rules, firewall, and whether the database is publicly accessible. Test the connection from the same network as the agent. Verify the host, port, and credentials.
- Agent accidentally writes to production. If you granted write access to a temp schema but the agent writes elsewhere, it means the privileges are too broad. Revoke and re-grant with more specific table-level permissions. Also, review audit logs to see what happened.
- Audit logs are too verbose. If you enabled logging for all statements, it can flood your logs. Filter to only log failed queries or queries that touch sensitive tables.
Frequently Asked Questions
Can I give the agent write access to a single table?
Yes, but it's risky. If you must, grant UPDATE and INSERT on that specific table only, and never DELETE. Also, consider using a view that restricts which columns can be updated.
What if my database doesn't support read replicas?
You can still use a separate schema for the agent's writes and rely on strict permissions. For reads, you can use a transaction with SET TRANSACTION READ ONLY to enforce read-only within the session.
How do I prevent the agent from seeing sensitive columns (e.g., passwords, PII)?
Create a view that excludes those columns and grant the agent access to the view, not the base table. Alternatively, use column-level security if your database supports it.
Should I use a separate database instance entirely?
If your budget allows, a separate instance (even a small one) is the safest. You can replicate data to it and let the agent work on a copy. This is ideal for heavy data exploration.
How often should I rotate the agent's credentials?
At minimum, rotate them every 90 days. If you suspect a leak, rotate immediately. Use automated rotation if your secret manager supports it.
Can I use a proxy like pgbouncer to restrict queries?
Yes, pgbouncer can be configured with query filtering, but it's not its primary purpose. A dedicated SQL proxy (like ProxySQL for MySQL) is more flexible. This adds complexity but gives you fine-grained control.