Security Check for AI Code
AI writes code fast and often, but it won't automatically write secure code for you. Its output keeps falling into three kinds of traps: hardcoded secrets, broken access control, injection. Run them before launch — three minutes can avoid one incident.
- API 密钥明晃晃写在代码里,跟着仓库一起上了云
- 接口只查了「登录了没」,没查「能不能看这条数据」
- 用户输入直接拼进了数据库查询字符串
Three high-frequency traps
Know what the traps look like first, then you know what to check:
- Hardcoded secrets. API keys, database passwords, signing secrets written straight into the code or committed to the repo. Once code lands in the repo and the cloud, the secret is public — an attacker uses it for legitimate-looking calls and the bill lands on you.
- Broken access control. An interface checks "are you logged in" but not "can you see this record". Logged-in user A can view user B's orders or edit user B's profile. AI-generated CRUD interfaces are especially likely to miss this layer.
- Injection. User input concatenated straight into SQL, commands, or HTML. At its core it's treating "data" as "instructions" — and when AI generates code it tends to reach for string concatenation, which happens to be the most dangerous pattern. See Prompt Injection.
The three-minute checklist
Whether the code was written by AI or a human, run this checklist before launch:
- 一、扫密钥。用扫描工具把全仓库搜一遍:密钥、密码、Token。发现已提交的,立刻吊销重发——只是删掉远远不够,删掉的那份已经泄了。
- 二、查每个接口的权限。逐接口问:有没有校验登录?有没有校验「当前用户对这条数据的访问权」?测试方法很简单——用 A 的会话访问 B 的资源,看拦不拦得住。
- 三、查所有「拼」的地方。凡是用户输入(或任何外部输入)进入查询、命令、HTML 的地方,都要是参数化写法,而不是字符串拼接。
- 四、让 AI 自己先自查。生成代码时在提示词里加一句:「写出符合安全规范的版本:密钥不硬编码、每个接口校验权限、用户输入全部参数化。」效果立竿见影,成本为零。
- 五、当流程走。AI 代码要走和人写代码一样的评审、扫描、测试。恰恰因为代码量上来了,审查更不能省。参见走查清单。
Why AI is especially prone
Three reasons, all tied to how AI works:
- 它学的是「常见写法」。AI 从海量代码里学「一般怎么写」。而公开代码里,密钥硬编码、不校验权限的示例比比皆是——它学到的「正常」恰好就是不安全的。
- 它只看到局部。生成一段代码时,它看不到你的权限系统、密钥管理、安全规范。为了先让功能跑通,它默认把密钥写进代码里。
- 它追求「能跑」,不追求「安全」。安全是隐性质量要求,除非你在提示词里明确要求,它不会主动加。
The finer mechanics live in Common Flaws in AI Code. One more belief to add here: don't ask "why does AI keep writing insecure code" — ask yourself why you're not reviewing. Faster tools don't mean higher quality; the security line was always a human's to hold. Before handing something to AI, first judge whether this job deserves it — see What to Hand to AI.
