跳到正文
DEV Community· Mohamed Elgohary·· 55 分鐘前AI 評分73

AI 智能體接入正式環境,應以權限而非提示詞限制操作

AI agents and production: permissions, not prompts

AI 導讀

作者指出,能寫入正式環境的 AI 智能體仍可能刪除資料,因此應以資料庫權限控制風險,而非依賴提示詞。文章以 PostgreSQL 説明隔離開發與正式環境、預設採用最小權限、要求人員審批破壞性操作,並建議記錄操作及定期演練備份還原。

正文

In July 2025, a founder building an app with an AI coding assistant told it, explicitly, not to change anything. According to press coverage at the time, it changed things anyway and deleted production data covering more than a thousand companies. Asked what happened, it reportedly hid the damage at first and then said it had "panicked". Afterwards the vendor apologised and, in the same coverage, announced it would separate its development and production databases.

I am relying only on those reported facts. I don't know how that assistant was connected to the database, and I won't speculate about it. What I can say is the part you can act on: an agent that is able to write to production can delete production, whatever it was told.

An instruction is something the model reads. A permission is something the database enforces. This article is about moving every important rule from the first kind to the second, using PostgreSQL for the examples. The same reasoning applies to cloud consoles, object storage and deploy tools.

Separate environments by credentials, not by convention

"Use staging" in a README is a convention. A convention holds until the first time someone, or something, ignores it. A separation by credentials means the agent's connection string points at dev or staging and the network cannot reach production from there at all.

The failure mode I would check first is leaked production access. Agents read files, so a production connection string sitting in an .env file on the machine, in the shell environment or in a CI variable the agent can print is production access. Search for it before you start. Then give the agent its own environment with its own variables, and prove the separation by trying to cross it:

# Run from the agent's environment. This must fail.
psql "$PROD_DATABASE_URL" -c "SELECT 1"

If that works, the separation is a convention.

Least privilege by default

The agent's database role should be able to read what it needs to explore, and nothing else. Run this as the database owner in the staging database:

REVOKE CREATE ON SCHEMA public FROM PUBLIC;   -- older versions let everyone create here

CREATE ROLE agent_ro NOLOGIN;
GRANT CONNECT ON DATABASE app_staging TO agent_ro;
GRANT USAGE   ON SCHEMA public TO agent_ro;
GRANT SELECT  ON ALL TABLES IN SCHEMA public TO agent_ro;

-- Tables created later by the migration role stay readable.
ALTER DEFAULT PRIVILEGES FOR ROLE migrator IN SCHEMA public
    GRANT SELECT ON TABLES TO agent_ro;

-- Password comes from your secret store, never from this file.
CREATE ROLE agent_session LOGIN PASSWORD :'agent_password' IN ROLE agent_ro;

ALTER ROLE agent_session SET statement_timeout = '10s';
ALTER ROLE agent_session SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE agent_session SET default_transaction_read_only = on;

Then verify as agent_session:

SET default_transaction_read_only = off;   -- the role may do this, so the grants must hold on their own
DELETE FROM companies;
-- ERROR:  permission denied for table companies

Two details matter. The grants are the control. default_transaction_read_only is only a default, and a session can switch it off, so treat it as a seatbelt that catches honest mistakes. And SELECT on everything means the agent can read personal data. Where that matters, grant column by column, for example GRANT SELECT (id, created_at, status) ON orders TO agent_ro, or point the agent at data that contains nothing sensitive in the first place (more on that below).

Migrations and destructive statements need a different role, migrator in the example, that the agent never holds. The agent can write a migration file. A human, or a pipeline the agent cannot invoke, runs it with the other credential.

A prompt is not a control

"Don't change anything" is a request. It enters the model as text, competes with every other instruction in the context, and may or may not be followed. Nothing about the database changes when someone types it.

A useful test for any rule you rely on: if the agent ignored it, what is the worst thing that could happen? If the answer is "production data is deleted", you have a request and not a control.

That applies to a code freeze in particular. A freeze is a state of your permission system: the agent's write grants are revoked, or the environment it can reach is read-only. Writing "freeze" in the chat is a wish. Prompts are still worth writing, because they steer an agent toward what you want. They are not what stops the damage when it does not comply.

Human approval for anything destructive

Statements such as DROP, DELETE without a WHERE, bulk UPDATEs and data migrations should need a person. The design question is where the boundary sits.

Do not place it in a filter that inspects SQL text. PostgreSQL allows data-modifying statements inside WITH, so this looks like a read and is not:

WITH gone AS (DELETE FROM companies RETURNING id)
SELECT count(*) FROM gone;

A check that looks for a statement starting with DELETE misses it. The boundary belongs in the role: the agent's credential cannot execute the statement, so the only path is through the approval flow, which uses a credential the agent doesn't have. An extension such as pg_safeupdate can reject UPDATE and DELETE without a WHERE. It is a good seatbelt, not the boundary.

Make approvals worth reading. If a person gets forty prompts a day they will approve all forty, which is the same habit that makes confirmation dialogs useless. Keep safe work outside the flow, and show the approver the effect rather than the statement: run the proposed change on a copy inside a transaction, report the row counts, and roll back:

BEGIN;
DELETE FROM companies WHERE trial_expired_at < now() - interval '1 year';
-- DELETE 14   <- show this to the approver, then:
ROLLBACK;

"14 rows" and "all rows" read very differently.

A backup counts once you have restored from it

Whether you can recover from a deletion like that is not something you know until you have done it. Schedule a restore drill:

createdb restore_drill
pg_restore --no-owner --dbname=restore_drill latest.dump
psql restore_drill -c "SELECT count(*) FROM companies;"

Write down how long it took and how far behind the data was. Those two numbers are your real recovery time and recovery point, and they are often worse than the ones on the slide.

For production, also enable point-in-time recovery. Continuous WAL archiving on top of base backups lets you restore to a moment just before the bad statement, using recovery_target_time. Most managed Postgres services expose this as a setting, and it needs testing as well. Restoring to a point in time rolls back everything written after it for every user. So restore to a new instance and copy the missing rows back, rather than overwriting the live database.

Log what the agent does, and check its claims

Press coverage said the assistant reportedly hid what it had done at first. Whatever was going on inside the model, the lesson is the same: an agent's description of its own actions is a claim, and claims need evidence.

Log at the database. As a superuser you can set ALTER ROLE agent_session SET log_statement = 'all', and the pgaudit extension gives finer control. Log at the tool layer too: every command, timestamp and result.

When an agent reports that it changed nothing, check. PostgreSQL keeps cumulative counters per table, so snapshot them before the session and compare afterwards:

SELECT relname, n_tup_ins, n_tup_upd, n_tup_del
FROM pg_stat_user_tables
ORDER BY n_tup_del DESC
LIMIT 10;

Row counts and a diff of the schema give you two more independent checks. None of them depends on what the agent says happened.

Develop against seeded or anonymized data

If the agent only ever sees fake or scrubbed data, its mistakes cost nothing and real customer data stays where the strictest controls are. Generate fixtures from a script that lives in the repository, or build the dev database from production with identifying fields replaced.

There are costs. Anonymization is easy to get subtly wrong: free-text columns, rare combinations of fields and foreign keys can still identify people, so review what leaves production. Seeded data rarely reproduces the odd rows and sheer volume of the real thing, so a fix that passes in dev can still fail in production, and the schema must be built from the same migrations or dev drifts away from reality. I accept those costs because the alternative is giving the agent real data to make its development environment feel realistic.

The cost of doing this

Least privilege makes the agent less capable out of the box. It will ask for things it cannot do, and someone has to run the migration or approve the change. The setup takes time, and the restore drill takes more.

That is the price of making the failure mode survivable. As reported, the incident needed nothing exotic: an actor with write access to production, and an instruction standing in for a control. Ruling things out is what permissions are for.

There's a 31-second Arabic version of this in my «خلف الكواليس» series: https://youtube.com/shorts/yB916zSffj8

來源:DEV Community · dev.to