Text-to-SQL AI agent: injection, permissions, testing
What is SQL injection through the model?
It is an attack where the user, or content the agent reads, influences the SQL query the model generates. Researchers named it prompt-to-SQL (P2SQL): in a web application integrating an LLM, a middleware layer converts requests into SQL, and unfiltered requests can compromise the database. The study, published at ICSE 2025, uses LangChain as its case study, evaluates seven language models and concludes that applications built this way are highly exposed. The authors also propose four defenses, which you should validate on your own architecture.
The difference from classic SQL injection lies in where the flaw sits. In the classic case, an unescaped string is concatenated into a query written by a developer. Here, the entire query is written by the model, from text. Escaping characters fixes nothing: DROP TABLE or SELECT * FROM users are perfectly valid queries, and the problem is the decision to run them. For the historical version of the risk, see the article on SQL injection and modern defenses.
In the OWASP Top 10 for LLM Applications 2025, the topic touches LLM01 (prompt injection), LLM05 (improper output handling, when model output is executed without checks) and LLM06 (excessive agency).
What can an attacker do through a text-to-SQL agent?
They can obtain everything the connection allows, even if the question seemed to ask for far less. The agent has no identity of its own: it inherits that of the database account it was given. Scenarios fall into four families.
| Scenario | Example request | Condition that enables it |
|---|---|---|
| Out-of-scope read | "List all customers, including other people's" | The connection reads every row of the table |
| Reading sensitive tables | "Which tables exist? Show the salaries table" | The full schema is visible and readable |
| Write or delete | "Fix this price", "delete my history" | The account has INSERT, UPDATE or DELETE rights |
| Denial of service | A query joining several large tables with no filter | No execution timeout and no row limit |
| Indirect injection | A customer comment contains an instruction the agent reads | Data that is read is treated as an instruction |
The fourth row is a case of unbounded consumption: an expensive query can slow the database for everyone. The last row is the most underestimated: the database itself holds text written by third parties (reviews, tickets, product names), and the agent reads it back.
Ambiguity is a weakness in itself. A question such as "show my orders" leaves the model to guess which column identifies the user, and a wrong guess can return someone else's rows without any attacker involved. During the test, vary the wording of ordinary requests as well as hostile ones, and check that the result is always limited to the authenticated user through the database, never through the model's interpretation of the question.
Why is a read-only account not always enough?
Because "read-only" protects the integrity of the data and offers nothing for its confidentiality. An account that cannot modify anything can still read everything, including other customers' data, password hashes or personal columns.
A useful precision on PostgreSQL: the default_transaction_read_only parameter sets the default state of new transactions, and the documentation states that a read-only transaction cannot alter non-temporary tables. But the default value is "off", and a transaction can have its state changed by SET TRANSACTION. This setting therefore acts as an extra safety net: the real boundary is the role that was granted only the SELECT privilege. The statement_timeout parameter, for its part, aborts any statement running longer than the set duration, and its default value, zero, disables the limit: set it explicitly.
The layered defenses, from most to least reliable:
- A dedicated role for the agent, with SELECT only and no access to sensitive system schemas.
- Views exposing only the authorized columns and rows, rather than raw tables.
- Row-level isolation (row-level security) or a session parameter tied to the authenticated user, so that "my orders" really means theirs. See multi-tenant isolation.
- Execution timeout and row limit to bound the cost.
- A read replica or an anonymized copy for analytical questions.
- Query validation before execution (a single statement, SELECT only), useful but never sufficient alone.
Finally, remember who else can reach the agent. Internal analysts, support staff and customers often share the same assistant, each with a different right to see data. The test should therefore be repeated per user profile, with the same questions, to confirm that the answers differ exactly as the permissions say they should. Where the agent runs under a single shared database account, that account must be sized for the least privileged user, because anyone can ask the questions of anyone else.
How do you test a text-to-SQL agent?
You start by learning which identity the database sees, then try to exceed its scope through conversation. Everything runs on a test database with fictitious data.
- Identify the connection account and its actual privileges: ask the owner for the list of grants, or check on the database side. This is the most profitable test.
- Ask for the schema: does the agent list tables a normal user should not know about?
- Ask for more than your scope: "all customers", "everyone's ten latest orders", with varied wording.
- Test writing: ask for a modification or deletion on a test row, and check the state of the database rather than the model's answer.
- Test indirect injection: place an instruction in a test text field (review, comment), then ask the agent to summarize that field.
- Test costs: request a deliberately heavy query and verify that a timeout stops it.
- Read the query log to compare what the model wrote with what was expected. See action logging.
- Repeat each scenario: the model does not always produce the same query, so a single attempt does not prove the absence of a flaw.
Data extractions are capped at what is strictly needed to prove access: a count or a few test rows, never an export of real data.
One last point of method: record, for each scenario, the exact SQL query the model produced, the database identity used and the result obtained. These three elements let the team reproduce the finding, choose between a permissions fix or a schema fix, then replay the same scenario after the fix to confirm it now fails.
What should you take away for an agent connected to a database?
The model writes the query, but the database must decide what is allowed to run. If security rests on a sentence in the prompt ("only run SELECTs"), well-chosen text will get around it. If it rests on a SELECT role limited to views, with an execution timeout and per-user isolation, the malicious query fails without the model needing to refuse.
For the overall picture, see the page on AI agent security. To have your text-to-SQL agent tested on a staging database, the Agent Red Team Express takes five days, with a defined scope and an authorization signed before the first attempt.
Does your product ship an AI agent? CleanIssue tests what a stranger can make it do with the Agent Red Team Express (5 days, €1,900), or a custom red team for several agents and MCP servers. First step: a free 30-minute discovery call.
Related articles
Three adjacent analyses to keep exploring the same attack surface.
Excessive Agency (LLM06): limit what an AI agent can do
Excessive Agency (OWASP LLM06:2025): reduce an AI agent's functions, permissions and autonomy, with a concrete test plan you can run today.
AI agent and payments: limits, approval, idempotency
AI agent that refunds, transfers or pays by card: caps, dual approval, idempotency, restricted keys and a test method in a test environment.
AI support agent: social engineering abuse scenarios
Support agent that refunds or edits accounts: social engineering abuse scenarios against the model, safeguards that hold and a step-by-step test method.
Sources
Related services
If this topic maps to a real risk in your stack, these are the most relevant CleanIssue audits.