Why 11 of 18 Text-to-SQL Agents Broke Least-Privilege Rules

SQL Security
Published on
Written byMayank Singh
Why 11 of 18 Text-to-SQL Agents Broke Least-Privilege Rules

TL;DR: Eleven of 18 text-to-SQL agents broke least-privilege rules, even though valid credentials can mask unsafe behavior. Enforce least privilege continuously at query time through dedicated identities, scoped objects, runtime checks, full logging, and isolated recovery.

Key Takeaways: - A successful login proves authentication, not task-appropriate behavior. - Six query-time gates narrow blast radius before execution. - Shadow-mode enforcement turns denials into tested operational policy.

A Valid Login Can Hide an Unsafe Query

Illustration for A Valid Login Can Hide an Unsafe Query

Eleven of 18 text-to-SQL agents broke least-privilege rules. The uncomfortable implication is that a valid database login can look healthy while the agent's effective behavior is not.

The misleading green checkmark

A successful connection and an approved database role can both look green while the generated query crosses a business boundary.

The role may permit valid reads, yet the agent can combine them into an operation the operator never intended. A connection test is therefore weak evidence for least privilege.

Use the text-to-SQL agent security checklist to review intent, not merely grants.

Read the 11-of-18 result carefully

The evaluated set included 11 agents that broke least-privilege rules. The research does not provide a definitive cause for that specific split.

It instead points to missing governance and visibility, scope creep, and absent behavior checks. It also identifies teams delaying tighter controls because they fear permission errors, operational cost, and service interruption.

That is a recurring pattern, not a causal verdict. The same warning appears in why you can't govern AI you can't see.

Individually authorized capabilities can compose into an operation beyond the operator's intent. Missing runtime checks let that scope creep pass unnoticed.

Nothing in that sequence is inherently AI-specific. A person with the same state file and permissions could have caused harm, minus the pause to notice. Automation removes that pause.

Document the intended policy for one sensitive query:

1policy:
2 actor: revenue_team
3 task: monthly_revenue_by_region
4 approved_objects: - analytics.revenue_daily
5 operation: SELECT
6 row_scope: regions_assigned_to_revenue_team
7 max_blast_radius: - analytics.revenue_daily

Compare that policy with the SQL the agent would execute. If credential checks pass while behavior fails, the enforcement point must move closer to the query.

Why Broad Database Grants Become Agent Blast Radius

Static grants are necessary, but they lose the race against changing agent behavior.

Authorized does not mean appropriate

A static grant can describe several individually valid reads. An agent can compose those reads into an outcome beyond the operator's intent.

Even with authorized permissions, scope creep and missing behavior checks can produce inappropriate behavior. This is why least-privilege architecture for AI agents must bind identity to a business task.

The visibility gap is deeper than database logs. Teams need to correlate: - The end-user request and stated business task - The agent, service identity, credential, and token usage - The normalized generated SQL and referenced objects - The operation class, policy decision, and execution outcome

Authentication logs prove that a credential was used. They cannot show whether the query matched the user's intent.

This compounds the problem described in your AI agent reaches every system it can touch. Reachability without intent becomes operational blast radius.

The downtime trap

Teams often delay tighter grants because permission errors interrupt reporting workflows. They also fear the support load and cost of recovering failed queries.

The answer is progressive enforcement, not indefinite broad access. Observe one data domain, refine false denials, and then enforce it.

Recovery belongs outside the blast radius

Automated backups were deleted together with the database in the cited risk. Recovery failed because the same destructive path could reach both systems.

A backup must therefore use a separate identity with separate permissions. Keep the protected copy beyond the reach of infrastructure-destructive credentials.

Restore access should be granular to the row or object. That lets teams recover only what the agent affected.

Build a blast-radius worksheet for every sensitive schema. It should list: - Direct and inherited grants - Reachable views and functions - Backup identities and storage paths - Data affected by one request - Separate recovery and revocation controls

The answer isn't replacing database grants with prompt instructions. It is enforcing intent through several independent control layers.

Move Least Privilege from Login Time to Query Time

Least privilege must become a continuous control around intent and execution. A one-time grant list cannot decide whether the current task deserves every inherited permission.

The layered enforcement envelope

Apply six gates in sequence:

  1. Dedicated identity: Bind one database identity to one agent use case.
  2. Scoped resources: Expose only approved schemas, views, and objects.
  3. Validated operations: Parse and restrict the generated SQL.
  4. Task-to-object authorization: Match the request with approved business objects.
  5. Runtime behavior checks: Detect scope creep, excessive reads, and repeated attempts.
  6. Isolated recovery: Keep backups outside the agent's destructive reach.

For every request, resolve five policy questions: - Who is acting? - What business task was requested? - Which objects are relevant? - Which operation is allowed? - Which rows or objects may be returned?

This turns query-time authorization for text-to-SQL agents into a concrete decision chain.

Least privilege also requires governance and visibility into token usage. Authentication shows that a credential was used, not whether the agent stayed within its task.

Correct SQL can still be unauthorized SQL

Verified agentic semantic-model research observed an approximately 20% average SQL accuracy increase across four data sets over an LLM-only baseline.

Accuracy helps the agent produce executable SQL. It does not determine whether that SQL should be permitted.

The semantic model should become the intent layer, not the security boundary. It can map questions to approved metrics and relationships. Query parsing, database grants, and runtime policy must enforce the decision independently.

Create a policy matrix with one row per agent use case. Include: - Identity and execution pool - Approved views and objects - Allowed operations - Row or object scope - Prohibited behavior - Required logging fields - Revocation procedure

That enforcement envelope only works when it becomes executable policy rather than another slide in a security review.

Build the Enforcement Envelope Before Connecting the Model

Illustration for Build the Enforcement Envelope Before Connecting the Model

Connecting the model is easy. Building the control boundary before connection is the harder work.

Scope the account

Give each agent use case a dedicated database identity and execution pool. In PostgreSQL, use a restricted group role and expose only purpose-built reporting views.

The database permission templates for AI agents should start by removing inherited access to base tables.

1BEGIN;
2
3REVOKE CREATE ON SCHEMA public FROM PUBLIC;
4REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC;
5REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC;
6REVOKE ALL ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC;
7
8CREATE ROLE text_to_sql_ro
9 NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT;
10
11GRANT USAGE ON SCHEMA analytics TO text_to_sql_ro;
12GRANT SELECT
13 ON analytics.revenue_daily, analytics.customer_summary
14 TO text_to_sql_ro;
15
16CREATE ROLE text_to_sql_agent
17 LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT;
18
19GRANT text_to_sql_ro TO text_to_sql_agent;
20
21COMMIT;

This assumes the named reporting views already exist. Provision the login secret separately, and let the controlled wrapper activate `text_to_sql_ro`.

Validate the operation, not just the prefix

A `SELECT` prefix is not a security control. Parse SQL into an abstract syntax tree before execution.

Allow one approved read statement or CTE. Reject multiple statements, writes, DDL, unknown functions, and references outside the object allowlist.

A read can still cross business boundaries, expose excessive rows, traverse an unsafe view, or invoke an unapproved function. Validate referenced objects and result scope as well.

Bind and execute through a controlled wrapper

Bind parameters, apply approved limits, and route every result through the same policy-aware path.

1execution_policy:
2 read_only_transaction: true
3 statement_timeout_source: SQL_STATEMENT_TIMEOUT_MS
4 max_result_rows_source: SQL_MAX_RESULT_ROWS

Use organization-approved timeouts and row limits. Use read-only transactions where the database supports them.

Separate recovery

Use a backup account with its own identities. Keep the protected copy outside the reach of credentials that can destroy the infrastructure.

Restore only at row or object granularity. The backup should survive the failure it exists to address.

Pilot the envelope on one reporting use case. Start with one identity, a small set of views, an explicit function allowlist, and no raw-table access.

These controls become trustworthy only when teams can see attempted bypasses, not merely successful queries.

Instrument Denials Before Enforcing Them

Strict policy without telemetry is a production incident waiting for a trigger.

Observe before you tighten

Run the policy in shadow mode. Record which valid and invalid questions would have been denied.

Review false positives, then enforce by data domain. This reduces the downtime feared by operations teams without leaving permissions permanently broad.

Use the AI SQL governance checklist to make the decision chain explicit.

Log the complete decision chain

Correlate every request across the full execution path:

1policy_decision_log:
2 required_fields: - end_user_id - agent_id - service_identity - credential_id - requested_intent - normalized_generated_sql - referenced_objects - operation_class - policy_decision - denial_reason - result_row_count - execution_duration - agent_token_usage

Without this correlation, your AI agent's audit trail goes dark exactly when investigators need it.

Protect the telemetry itself

Redact literal values that may contain sensitive data. Preserve normalized query structure so engineers can investigate policy behavior.

Authentication alone cannot reveal inappropriate agent behavior. Governance needs both the database decision and the agent's resource usage.

Alert on meaningful boundary events

Configure alerts for: - Write attempts and multi-statement SQL - Access to another business domain - Traversal toward base tables - Unusual result volume - Repeated policy retries - Abnormal credential or token use

Compare each signal against configured thresholds. Alerting on every query event only creates noise.

Test behavior as carefully as SQL correctness

Maintain a boundary suite containing legitimate joins and aggregations. Add prohibited cross-domain reads, writes, function calls, multi-statement attempts, and base-table traversal.

Make revocation routine

Provide a kill switch and independently disableable credentials. Re-run policy tests whenever schemas, views, grants, or prompts change.

Review attempted denials weekly at first. Convert recurring false denials into safer views or clearer rules. Promote only tested capabilities from observation to enforcement.

Once least privilege runs continuously, its value appears in operational control rather than a one-time compliance check.

What CTOs Gain from Bounded AI SQL

Bounded AI SQL turns least privilege from a review artifact into an operating property.

Three operational outcomes

Security teams can explain why each query ran. Database teams maintain a smaller, more stable permission surface. Business teams keep natural-language analytics without inheriting unrestricted database access.

The result is not weaker analytics. It is analytics with a defined operating boundary.

A recoverable failure model

Credential revocation, scoped execution, query-level decisions, and isolated backups reduce the consequences of a mistaken prompt, generated query, or compromised service identity.

A failure can remain local because permissions and recovery no longer share one destructive path.

Turn the framework into a rollout

Start with one sensitive data domain:

  1. Define its approved views and boundary tests.
  2. Run the policy in observation mode.
  3. Review denials and operational impact.
  4. Enforce the tested policy.
  5. Expand only after the evidence stays clean.

For teams evaluating enterprise AI systems, this discipline separates durable operations from model demonstrations.

Levitation reports 300+ successful enterprise deployments across regulated industries and 98% client retention. It is trusted by Fortune 500 brands for enterprise AI systems in India, with systems still running in production 5+ years after deployment.

A typical deployment takes 3-6 months, compared with 18-24 months for in-house teams. These figures are evidence of delivery maturity and longevity. They do not retroactively prove every deployment used this exact least-privilege architecture.

The differentiator is not SQL generation. It is useful SQL inside a boundary the CTO can explain, test, and revoke. Can your team prove that boundary for every request?

Frequently Asked Questions

Why did 11 of 18 text-to-SQL agents break least-privilege rules?

The verified research does not establish one cause for the exact 11-of-18 result. It identifies a recurring pattern: least privilege fails without governance and visibility into token usage.

It also fails when authorized scope expands, behavior checks are missing, or teams delay tighter controls because they fear downtime and operational cost.

Are read-only database accounts enough for text-to-SQL agents?

No. A read-only credential prevents many writes but does not determine whether a `SELECT` is limited to the business objects a user should see.

Add purpose-scoped views, row or object restrictions, query validation, runtime behavior checks, and auditable execution.

How should a CTO audit least privilege for text-to-SQL agents?

Audit the complete path from user intent to generated SQL and database execution. Role grants alone are insufficient.

Confirm dedicated identities, approved objects, validated operations, runtime checks, correlated logs, revocation controls, isolated backups, and tests for legitimate and unauthorized questions.

Do semantic models improve text-to-SQL security?

Semantic models can improve SQL correctness, but accurate SQL can still be unauthorized. Verified research observed an approximately 20% average accuracy increase across four data sets.

Security still requires independent permission, query-validation, and behavior-enforcement layers. Can your team explain why each query matched the user's intended object and row scope?

About the author

MS
Mayank Singh
Software Developer, Levitation Infotech

Mayank Singh is a software developer at Levitation Infotech, where he builds web and AI-powered applications across the company’s fintech, healthcare, and enterprise projects.

Supercharge Your Success with Our Expertise

Amplify Your Business with Our Expertise. Explore Services Tailored for Your Success.

Get In Touch