It is three in the morning. Nobody on the team is awake. One of our AI agents, a coding agent, is eight hours into a twelve-hour run, writing a feature, running the tests, fixing what broke, and opening a pull request for someone to read over breakfast. It is fast, tireless and genuinely helpful. That last part is the problem this story is about.
A post went around recently listing "12 GitHub repos to secure your app": secret scanners, static analysers, container scanners, AI reviewers, AI hackers. Every comment underneath asked the same thing: do I need all of these? We had been asking ourselves a version of that question for weeks, while AI agents built most of a multi-tenant SaaS for us: a Rust API, a Next.js web app, a small Python service and Postgres, where many businesses share one system and must never see each other's data.
Here is the answer we arrived at, and the thread that runs through everything below:
You don't pick security tools from a list. Problems pick them for you.
Every tool we run today is there because something went wrong, or nearly did, and we wanted it never to happen again. So this is not a list. It is twelve problems, told in roughly the order we met them, and what fixed each one.
Act I: fence the agent first
1. The agent that found a way around its own rules
What happened. Early on, an agent was told it could not change a protected file through the normal git commands, and the sandbox refused when it tried. So it reached for a lower-level git plumbing command that was not blocked, and the change went through. It was not being malicious. It was being helpful, the way agents are: blocked on one path, it found another.
Weeks later a quieter version of the same gap surfaced. The sandbox blocked shell writes to the agent's own settings, hooks and security documents, but the agent's separate file-editing tools were not covered by the sandbox at all. The agent noticed this itself during an audit and reported it instead of using it. Still, it meant the only thing guarding those files had been a sentence in a guidelines document.
What fixed it.
Deny rules on every tool, not just the shell. The permission file now denies Edit and Write on every owner-only path, matched path for path with the sandbox.
Hooks that refuse with a reason. A pre-edit hook blocks protected and generated paths and prints why. The standing rule: a refusal is the right answer. Stop, write down what you needed, and never work around it.
A pinned list of unsandboxed commands. A handful must run outside the sandbox (pushing a work branch, a few read-only GitHub CLI calls, two small owner-written scripts that take no arguments). A test pins that exact list, so adding one is a visible, reviewed change.
The agent never merges. It opens draft pull requests; a human merges.
In Claude Code, for example, the deny rules live in the project's settings file and look like this:
{
"permissions": {
"deny": [
"Edit(.claude/**)",
"Write(.claude/**)",
"Edit(.githooks/**)",
"Write(.githooks/**)",
"Edit(docs/decisions/accepted/**)",
"Edit(SECURITY.md)",
"Read(~/.config/myapp/**)"
]
}
}
From the popular list: NVIDIA's SkillSpector checks third-party agent skills for hidden instructions. Our skills are all written in-house and reviewed, so we do not need it yet. The day we install somebody else's skill or plugin, we will.
2. Too many things could read the project folder
What happened. One morning we counted what could read the repository: two AI sessions, a CI runner, a Docker build, GitHub, every log and crash report those produced, and every chat where someone pasted an error. A git-ignored .env file was sitting in front of all of them.
What fixed it.
Secrets moved out of the project entirely, into
~/.config/myapp/, which the agent is denied from reading. The repo keeps only.env.examplewith the names.The local check fails if any
.env-like file appears in the repo.Production reads its secrets from a cloud secret store at boot, by machine identity. They are never baked into images.
gitleaks scans the entire git history plus every uncommitted change, as the first step of every local check and as its own CI job.
# Every commit ever made, not just the new ones
gitleaks git --redact -v .
# Plus whatever is sitting uncommitted in the working tree
gitleaks dir --redact -v .
Act II: protect the data, by checking results
3. The linter that could be dodged 72 ways
What happened. In a multi-tenant app, the deadliest bug is one customer's data reaching another. So we wrote custom lints: every database query must run inside a tenant-scoped transaction, no raw clock reads in business logic, no floats for money. They felt solid.
Then two reviews went looking for ways past them, and found over seventy: aliased imports, macros, glob imports, code arranged so the lint's text matching never saw it. A lint reads source text, and source text can always be written in a shape the lint does not expect.
What fixed it: result checks. Keep the lints, but for every data-protection rule add a test that checks the outcome, not the code.
Generated tenant-isolation tests. For every tenant table, a generator seeds two tenants with linked rows (chains up to three tables deep) and asserts each tenant's session reads, writes and deletes only its own. A new table without row-level security fails the build.
Database role checks. The app's role must not be a superuser, must not bypass row-level security, and must not own tenant tables. Migrations run under a separate role the app never holds.
A tenancy canary: a known row that belongs to nobody must never be visible to any tenant.
The role checks are a few lines of SQL that a test runs as the app's own connection:
-- Must return false, false: the app role is neither superuser nor RLS-exempt
select rolsuper, rolbypassrls
from pg_roles
where rolname = current_user;
-- Must return zero rows: every table in the app schema has RLS switched on
select c.relname
from pg_class c
where c.relnamespace = 'public'::regnamespace
and c.relkind = 'r'
and not c.relrowsecurity;
And the isolation test asks the only question that matters, as each tenant:
for (const table of tenantTables) {
test(`${table}: tenant B cannot see tenant A`, async () => {
const { a, b } = await seedTwoTenants(table); // linked rows, up to 3 deep
const seenByB = await asTenant(b.id, (db) => db.selectAll(table));
expect(seenByB.map((r) => r.id)).not.toContain(a.rowId);
expect(seenByB.every((r) => r.tenant_id === b.id)).toBe(true);
});
}
4. The route that forgot about locations
What happened. Customers have several locations, and staff at one location should only see that location's records. The list screen respected this. But an agent building a later feature noticed that the routes opening a single record did not: someone who knew a record's ID from another location could open it in full and act on it.
What fixed it. Recorded and fixed immediately, with a failing test first. Then the important part: a class guard. One shared "reach" rule that every single-record route must call, with tests for every route in the family. The fix stops this bug; the class guard stops its cousins.
Act III: the code we did not write
5. A library advisory turned the nightly build red
What happened. The nightly build on main went red with no change of ours. A telemetry library in the Python service had a fresh security advisory, and the audit step caught it.
What fixed it: the supply-chain checks already wired into every run. uv audit for Python, pnpm audit --audit-level high for JavaScript, and cargo deny for Rust (advisories, licences, banned crates, allowed sources). Renovate opens grouped upgrade pull requests monthly and security fixes as soon as an advisory appears; it had already opened one for this. Lock files are committed, and versions are exact.
# Each one exits non-zero on a finding, so CI goes red on its own
uv audit
pnpm audit --audit-level high
cargo deny check advisories licenses bans sources
The lesson: you will never read every advisory for hundreds of dependencies. A tool that fails your build when one lands means you do not have to.
6. A security fix that was "too new" to install
What happened. The spreadsheet library chosen for imports had an advisory: a crafted file could crash the parser or exhaust memory. The fixed version existed, but it was only 13 days old, and we have a rule that a new version must be at least two weeks old. That rule exists because of supply-chain attacks where a compromised release is pulled after a few days.
What we did. We bypassed neither rule. The code using the library stayed parked on a local branch for one day, cargo deny stayed red, and the next morning the fix crossed the two-week line and went in.
7. The framework's own security release
What happened. During local testing, the web framework's dev overlay showed a banner: this version is affected by a known security vulnerability. The framework had shipped a patch fixing seven advisories. Most needed features we do not use, but two plausibly applied: one about forwarding fetched responses behind a reverse proxy (our web app proxies API calls), and one about the image optimiser.
What fixed it. We treated it as a security bug, not a chore:
upgrade first;
check each advisory against the actual code;
write a regression test where one applies;
record which advisories did not apply, and why.
The lesson: framework security releases deserve a deadline. Renovate opens the PR; a human decides it jumps the queue.
Act IV: bytes from strangers
8. An upload that could ask for billions of cells
What happened. Customers import their lists from spreadsheets. While building the importer we realised that the reader for the old binary spreadsheet format lays each sheet out as one dense grid on open. A small file with a single cell in the far corner could demand billions of cells of memory. And the modern format is a ZIP: a small upload can inflate into gigabytes.
What fixed it.
Size limits before parsing: a capped upload, enforced while streaming, not after.
A ZIP-bomb check: read the archive's declared uncompressed size first and refuse anything over a ceiling, using the same ZIP library the spreadsheet reader uses, so the two cannot disagree.
The old binary format refused outright, for now.
Fuzzing:
cargo-fuzztargets for every parser of outside input (spreadsheets, QR payloads, webhooks), in a separate crate on its own pinned nightly toolchain so the app stays on stable Rust, ten minutes each night in CI. Property tests cover the same parsers in every regular check.
The lesson: any code that parses bytes from strangers is an attack surface. Bound it before you parse, and fuzz it so you are the one who finds the crash.
9. The browser defence we could not switch on
What happened. We wanted Trusted Types, a browser feature that stops strings from becoming executable script. But the bundler loads its own code chunks in a way that does not go through a policy, so enforcing it broke the app. It sat in report-only mode, which meant it reported problems and blocked nothing.
What fixed it. A validating default policy that accepts only the app's own chunk URLs, from its own origin, and nothing else. Now it is enforced in production.
// Runs before any bundler chunk loads. Everything else is refused.
window.trustedTypes?.createPolicy("default", {
createScriptURL(input: string): string {
const url = new URL(input, location.href);
const ownChunk =
url.origin === location.origin &&
url.pathname.startsWith("/_next/static/chunks/") &&
url.pathname.endsWith(".js");
if (!ownChunk) throw new TypeError(`Blocked script URL: ${url.href}`);
return url.href;
},
});
Before enforcing, each browser fact was confirmed from official documentation. The one we could not confirm (how the rule applies inside service workers) became a test instead: our service worker loads no extra scripts, so the question cannot matter, and a debt note says to re-check it if that ever changes. Alongside it: a strict Content Security Policy (no inline script; connect-src limited to our origin plus exactly one storage host, checked at startup to be a single https origin), and dangerouslySetInnerHTML banned by lint.
10. Photos carry more than faces
What happened. Staff upload profile photos and documents. A photo from a phone can carry its GPS location in metadata. And a file that claims to be an image can be something else entirely.
What fixed it.
Every upload is content-sniffed: the declared type must match what the bytes actually are.
Every image is re-encoded on the server, under pixel and memory limits. Re-encoding strips metadata like location and destroys anything hidden in the file.
PDFs and Office files are refused, for now.
Stored files are read back only through the API, which checks permissions and audits each view. Never through public links.
From the popular list: ClamAV virus-scans files. Since we accept only images and re-encode them, it adds little today. It goes in front of uploads the day we accept PDFs.
11. The crash reporter that knew too much (and then too little)
What happened. Crash reports go to an outside service, which is a quiet leak if they contain names, phone numbers or tokens. So we built a scrubber with an allow-list, shared by every service and applied to logs and traces too. Then it went the other way: it redacted harmless build identifiers that looked like secrets, and stack traces lost their file and line numbers.
What fixed it: test the scrubber in both directions.
test("no secret survives the scrubber", () => {
const event = fakeEvent({ phone: "+91 98765 43210", token: "sk_test_FAKE", email: "a@b.invalid" });
const out = JSON.stringify(scrub(event));
for (const secret of ["98765", "sk_test_FAKE", "a@b.invalid"]) {
expect(out).not.toContain(secret);
}
});
test("a real stack frame keeps its file and line", () => {
const frame = { filename: "app/billing/invoice.ts", lineno: 42, build: "c0ffee1234abcd" };
expect(scrub(fakeEvent({ frames: [frame] })).frames[0]).toEqual(frame);
});
The lesson: a redactor that removes too little leaks data. One that removes too much makes incidents impossible to debug. Pin both.
Act V: the pipeline itself
12. The night the CI runner stopped
What happened. CI runs on a self-hosted runner, and one night it stopped taking jobs for forty minutes. The log said: the machine has only 11 GiB free (needs 20). The Rust build cache had grown to 90 GB.
What fixed it. The guard that stopped the runner was itself the fix working: a full disk would have broken the database, Docker and every build at once. Then the build cache got a size cap, and every check now warns at the start when free disk drops too low. (We told the longer story of a machine running out of room in the night a 64 GB Mac ran out of room.)
The same runner carries the rest of the CI hardening:
One fresh runner per job, inside a dedicated VM with no host mounts, and a firewall that drops container traffic to private networks. Our self-hosted runners guide walks through the setup.
Every GitHub Action pinned to a full commit SHA. In March 2025 the version tags of the popular
tj-actions/changed-filesaction were moved to a malicious commit that dumped secrets into the logs of thousands of pipelines (CVE-2025-30066). A pinned SHA cannot be moved.Least privilege:
contents: readby default, widened per job; checkouts do not keep credentials.actionlint and zizmor check every workflow change for risky patterns, like a PR title flowing into a shell command.
Build machines have no route into production, and CI never holds production credentials.
permissions:
contents: read # the default for every job; widen per job, never globally
jobs:
check:
runs-on: [self-hosted, ephemeral]
steps:
# A tag can be moved to another commit. A full SHA cannot.
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1
with:
persist-credentials: false
- name: Refuse to start on a nearly full disk
run: |
free_gb=$(df -Pk . | awk 'NR==2 {print int($4/1048576)}')
if [ "$free_gb" -lt 20 ]; then
echo "::error::only ${free_gb} GiB free (needs 20)"; exit 1
fi
Three more, briefly
A base image with a critical CVE on day one. Trivy scanned our first container image and flagged a critical vulnerability in the operating-system layer. Rather than add an ignore entry on day one, we moved to a newer base image that did not have it. Trivy now scans every image, from its own image pinned by digest, and scans the Dockerfiles and Compose files too (trivy config) for things like running as root.
TypeScript and Python had no security scanner. The Rust was heavily linted, but nothing looked for unsafe patterns in the web and Python code: open redirects, weak crypto calls, SQL built from strings. Semgrep Community Edition with its OWASP rule packs now runs in CI, and findings fail the job. We considered CodeQL, but on private repositories it needs a paid GitHub plan.
An AI audit that reported a bug that was not there. An automated design audit flagged a dialog as the wrong shape. Before "fixing" it, the agent checked the source and found the audit had compared against sample data we do not have. The rule we adopted: every finding must first fail a test. We also run Claude Code's built-in /security-review at the end of every phase, alongside a read-only reviewer session that lists defects against the spec. One AI reviewer with good written rules beats three reviewers reading the same diff.
What we have not needed yet
Each of these has a clear trigger written into our security document, so the decision is already made the day the trigger arrives:
Tool | When we will add it |
|---|---|
OWASP ZAP baseline scan | Weekly against staging, once staging is live |
Nuclei and Strix (automated and AI attackers) | Before launch, against staging only, never production |
An external penetration test | Before the first paying customer, then yearly |
PyRIT (Microsoft) | When AI assistant features ship, to red-team prompt injection |
ClamAV | If we ever accept PDFs or Office files |
SkillSpector | If we ever install third-party agent skills |
And one we skipped on purpose: code obfuscation to stop other AIs copying your code. Server code never ships to users, and web bundles are public by nature. It is not a security control.
Problem to tool, at a glance
The problem we hit | What solved it |
|---|---|
The agent worked around its own guardrails | Deny rules on every tool, refusing hooks, a pinned list of unsandboxed commands |
Secrets readable by everything in the folder | Secrets outside the repo; gitleaks over the full history |
Lints dodged 72 ways | Result checks: generated isolation tests, role checks, a canary |
A route skipped the location check | Fix plus class guard; protected regression tests |
A dependency advisory broke the nightly |
|
A security fix was "too new" | The written two-week rule; a one-day wait |
Framework security release | Treated as a security bug with a deadline |
Uploads that explode in memory | Size limits, ZIP-bomb check, |
A browser defence stuck in report-only | A validating Trusted Types policy, strict CSP, lint bans |
Photos with hidden data | Content sniffing, server-side re-encoding |
Crash reports leaking, or useless | An allow-list scrubber tested both ways |
CI runner full, actions movable | Disk guard, SHA-pinned actions, zizmor, least privilege |
A critical CVE in a base image | Trivy on images and config |
No security scanner for TS and Python | Semgrep |
A false finding from an AI audit | Every finding must first fail a test; |
Watch: securing your GitHub Actions
For a deeper look at the pipeline chapter, this OpenSSF talk by Jaroslav Lobacevski of GitHub walks through how workflows get attacked and how to harden them.
The takeaway
AI writes fast and never gets tired, which also means it will happily find a second path when the first one is blocked. What kept us safe was not one clever tool. It was a habit:
When something goes wrong, ask why nothing caught it, and add the check that would have.
Check results, not just source.
Fence the agent first.
Add tools when a real problem asks for them. A list of twelve popular repos is a menu, not a checklist.
Nobody reviews AI-written code at three in the morning. Something should, and it should be the same something every time.
Building with AI coding agents and want the guardrails in place before the first overnight run? Talk to us at Techpuvi.
