How to protect secrets when coding agents deploy your app
By Flavio
Updated
Tagged: AI
Learn how coding agents can expose secrets, compare ways to manage access, and add safeguards to builds, deployment pipelines, and production code.
A coding agent can build your app properly and still leak your database password into production.
Sometimes it’s obvious how that happens: a .env file gets copied into the upload folder, a private API key lands in browser JavaScript to get a feature working, or a debug command prints credentials right into the chat history.
Other times it’s sneakier. Even if the agent never sees your production secret, letting it deploy server code means it can ship a new endpoint that reads that secret at runtime and sends it back out.
Keeping secrets out of Git is a start, yet secrets escape in plenty of other ways. We need to lock down what the agent can touch locally and put a real gate between its edits and a production deploy.
To keep this concrete, let’s walk through a small reading club web app with a public site, a server endpoint, and a private database password. The same rules apply whether you’re working on a mobile backend, a CLI release, or a much larger app.
What counts as a secret?
If a value lets someone log in, call a protected API, or prove an identity, it’s a secret.
That includes API tokens, private keys, session cookies, database passwords, and webhook signing secrets. Keep an eye on database connection URLs too, because they often carry the password right inside the string even when the variable name looks harmless.
Not every config value has to be hidden. A public API hostname, an analytics site ID, or a provider’s publishable client key can belong in browser code, though you should always check the provider’s docs before deciding.
The real question is what the value lets you do. Browser keys still need whatever domain or scope restrictions the provider recommends, and an admin token stays a secret no matter how innocently you name it.
Here’s how that breaks down for the reading club app:
| Value | Who needs it? | Where to put it |
|---|---|---|
| Public website URL | Browser and server | Public config |
| Database password | Server app | Runtime secret store |
| Deployment credential | Approved publisher | Isolated deploy job |
| Test database credential | Test runner | Separate dev environment |
| Webhook signing secret | Server handling the webhook | Runtime secret store |
Don’t forget about customer records and private documents. They aren’t credentials, but they’re still sensitive data, and even a read-only database role can dump every row it has permission to see.
How an agent gets access
Most coding agents combine a language model with tools that can read files, run shell commands, open a browser, and call APIs.
Because of those tools, a secret can be exposed in four different ways:
| Exposure | Example | What it allows |
|---|---|---|
| The model sees the value | A command prints an API token | The secret enters the chat context and can show up in later replies |
| An agent-controlled process sees it | A shell inherits a database password | Commands can use or copy the secret without printing it first |
| The agent calls an authenticated tool | A deploy tool holds a token internally | The agent can run whatever actions that tool exposes |
| The agent swaps out privileged code | A deploy updates a server with secret bindings | The new code can use those runtime credentials |
Keeping a secret out of the model’s context helps keep it out of chat replies and logs, which is worth doing. You still have to lock down what the agent’s processes and tools are allowed to run.
Think about a deploy tool that hides its API token from the model. If that tool lets the agent pass any account, destination, and shell command, the agent still has far too much control over your infrastructure.
Why coding agents make this problem harder
Developers have leaked secrets forever, so the risk itself isn’t new. What changes with a coding agent is that one program can explore your files, edit code, run commands, and publish the result in the same session.
Even normal debugging can cross boundaries fast. Say the agent hits an auth error, reads local config, prints the environment to see what’s going on, and copies an example into the frontend. Each step makes sense on its own, and by the end your secret is sitting in the chat history or the client bundle.
Build tools and dependencies also run code. Even when the model follows every rule you give it, a package install script or a changed build script can read any credentials sitting in that process environment.
Then you have prompt injection. Instructions hidden inside an issue, a file in the repo, a web page, or tool output can steer the agent into reading a secret and sending it somewhere else. That’s why OWASP’s prompt injection guidance pushes for enforcing permissions and validating tool parameters outside the model.
Writing “never read .env” in AGENTS.md states the rule clearly and belongs there, and I always pair it with a real filesystem restriction that blocks the read across both the file tool and shell tool.
Map where a secret could escape
Before locking things down, trace where a credential can travel across your development and deploy setup. For the reading club app, the map looks like this:
| Place | Common exposure | Guard to consider |
|---|---|---|
| Working directory | .env, database dumps, copied credentials | Separate workspace and restricted file access |
| Process environment | Inherited tokens, env output, debug traces | Minimal environment and scoped identity |
| Agent conversation | Pasted secrets, command output, screenshots | Keep values out of prompts and tool responses |
| Git | Source files, old commits, config files | Secret scanning and push protection |
| Build output | Copied files, HTML, JavaScript, source maps | Inspect and scan the final public artifact |
| CI | Untrusted scripts running next to deploy tokens | Split build and publish into separate jobs |
| Production runtime | New code reads an existing secret | Review privileged code changes and tighten runtime permissions |
| Logs and storage | Error reports, caches, uploaded artifacts | Redaction, restricted access, and retention limits |
A Git secret scanner protects the Git row in that table, and you definitely want one. Keep an eye on the rest of the pipeline too, because a token that never touches a commit can still slip into a deployed file or a CI log.
Start by giving the agent less to read
For everyday coding, an agent needs our repo and a working dev setup, never our whole home directory or every credential sitting in my terminal.
I run it inside an isolated workspace, container, VM, or dedicated OS user, mounting only the project folder and needed tools while keeping my other credentials outside that boundary.
Check the quiet pass-throughs too: SSH agents, cloud CLI profiles, credential helpers, browser profiles, Docker sockets, and host filesystem mounts. A container with broad host mounts gives an agent almost the same reach as my main machine.
Check your environment variables before you launch the agent. Starting it from your daily shell passes along every token you exported earlier in that session. Give it a stripped-down environment with only the variables the task needs, and combine that with filesystem isolation so processes can’t read credential files off disk instead.
Don’t rely on .gitignore to hide files from an agent. It only tells Git which untracked files to skip, so any shell command or build tool can still open them freely.
The same goes for tool-specific ignore files. Verify what each one controls, since excluding a file from indexing is separate from blocking a shell command from reading it.
A quick way to test your setup is to drop a harmless marker file outside the project folder and ask both the agent’s file tool and its shell tool to read it. If your sandbox is configured right, both requests will be denied.
Use development credentials and synthetic data
You can build and test the reading club app against a test database full of invented books and members.
Give the agent its own development identity, scoped to that test database with only the permissions the task needs. When your provider makes it easy, put dev in a separate project or account so the boundary is hard to cross by mistake.
Lock down admin APIs along with normal data access. A dev token should never be able to list production secrets, change production permissions, or create a stronger identity.
When you’re debugging something that really needs production info, check first whether sanitized logs or a single narrow query will answer your question. If you have to grant direct access, make it temporary, narrow down the dataset, and audit what runs.
Remember that a read-only role still lets the agent read every row it can query. If you want a deeper guide on access scope, rotation, and credential lifecycles, OWASP’s secrets management guidance covers all of it.
Choose how secrets reach trusted code
A secret manager keeps credentials out of scattered plaintext files and gives you one place to control access and rotate keys.
For a closer look at storing and rotating secrets on your own infrastructure, I walk through the setup I use on my Mac, on Cloudflare, and on a Linux VPS.
Different tools cover different layers of the setup:
| Approach | Examples | Main boundary to protect |
|---|---|---|
| Local secret delivery | 1Password CLI | The process receiving plaintext |
| Cloud secret store | AWS, Google, Azure | Identity policies and runtime code |
| Dynamic credentials | Vault | Role scope and credential lifetime |
| Runtime bindings | Cloudflare Workers | Code allowed to use the bindings |
| Restricted service | Publisher or API proxy | Allowed operations and data flows |
AWS Secrets Manager, Google Secret Manager, and Azure Key Vault all have solid access controls and operational features. Stick with the one that already matches your cloud stack before you take on another system to run.
If you want short-lived database credentials, Vault’s database secrets engine can generate them on the fly. A short lease shrinks the window a copied credential stays useful, as long as your database integration and revocation flow work cleanly with it.
For local work on your own machine, check out my 1Password environment variables guide. Browser logins are a separate boundary, which I cover in password managers and agent access.
Injection into a process still exposes the value to that process
1Password’s op run resolves secret references and passes the real values into a subprocess as environment variables. That keeps credentials out of your checked-in .env files, while still handing them to the subprocess at runtime.
If you run an unrestricted agent inside that subprocess, its commands can read those environment variables or send them over the network. Output masking can keep a secret out of terminal logs, while the process itself still has full access to use the credential.
Secret injection just handles delivery. You still have to decide whether you trust the process on the receiving end with the secret.
A restricted service can keep the credential elsewhere
Say your agent only needs to publish the reading club’s static site. Instead of handing it a deploy key, put the deployment token inside a small trusted publisher that only exposes one action: publish this approved artifact to the reading club site.
That publisher pulls the account and destination straight from protected config. It checks the artifact identity and rejects arbitrary command flags, shell fragments, or different upload targets.
For API calls, you can put a small proxy in front of the credential and attach it only to approved hosts and paths. Lock down the allowed request bodies and responses too, because even a whitelisted endpoint can return customer data or trigger an action you didn’t want.
Setting up a publisher or proxy takes more work than pasting a token into an environment variable. It pays off when you want unattended runs limited to a tight, repeatable set of actions.
Replace long-lived deployment tokens where possible
Workload identity lets a CI job prove where it’s running and trade that proof for temporary credentials.
GitHub Actions supports OpenID Connect, so a job can exchange its identity token for short-lived credentials from a compatible provider. You don’t have to park a long-lived cloud key inside your repository secrets.
The trust policy is what makes this work. Lock down the issuer, audience, and subject (plus any other supported claims) so only the exact repository and deployment context you expect can authenticate. A loose policy that trusts every branch or every repo throws away most of the safety margin.
Give id-token: write only to the specific job that needs federation, and keep its permissions on the cloud provider side narrow too.
Also watch the difference between temporary access to a secret manager and the lifetime of the secret you pull out of it. If a five-minute job fetches a permanent API key, that key stays valid long after the job finishes.
Short-lived credentials can still do real damage while they’re active, so keep untrusted code out of any job that can request production access. And if your OIDC subject targets an environment instead of a branch, lock down which branches can deploy to that environment through its protection rules.
Not every host supports the OIDC flow you want. For those targets, create a separate scoped deploy token, keep it inside your protected publisher, and write down how to revoke it when you need to. Check your hosting provider’s docs instead of assuming OIDC works there just because GitHub Actions supports it.
Make the public artifact explicit
Your project folder holds source files, local config, dependencies, and build output in the same directory tree, and only a small slice of that should ever reach the public site.
For a static Astro site, I point the publisher directly at dist/ and never let an upload command accept an agent-generated path or fall back to the project root.
Keep in mind that Astro copies files in public/ into the build untouched. Drop a secret in there and it becomes a public download, even if .gitignore hides it from Git.
Where the public boundary sits depends on how you deploy. An SSR app splits into public assets and a private server bundle, while a container image has its own filesystem and layers. Map out what anyone can download, what executes on the server, and which values each side can read.
Always check the final package after every build and packaging step finishes. A spotless dist/ folder won’t help if a later zip command bundles up the rest of the workspace with it.
Make a deliberate call on source maps too. They can reveal your source code and embedded values, though .map files aren’t secrets on their own and plenty of apps ship them intentionally. Check what’s inside them and who can download them before deciding whether they belong in the deploy.
Keep private values out of browser code
Astro’s environment variable documentation spells out a key rule: anything prefixed with PUBLIC_ can end up in client-side code.
For the reading club app, PUBLIC_API_URL is fine in the browser because it just points to the server. The database password stays strictly server-side.
If an agent hits an undefined variable error and suggests renaming a private token to PUBLIC_DATABASE_TOKEN to fix it, stop right there. Move the privileged work behind an authenticated server endpoint instead.
Then tighten what that endpoint will accept. A server proxy that executes arbitrary database queries or forwards arbitrary upstream URLs gives callers far too much power, even with the password tucked safely on the server.
Server-only variable names only protect a value while it stays on the server. Once your code copies it into HTML, a JSON response, a log line, or a browser bundle, the name won’t save you. Follow where a value goes after you read it, from server routes all the way down to responses and logs.
Scan source and deployment output separately
Combine a maintained secret scanner with artifact rules tailored to your project.
Gitleaks checks both Git history and files on disk. Once you have it installed, run these two commands from your project root:
gitleaks git --redact=100 --no-banner .
gitleaks dir --redact=100 --no-banner dist
The first command scans Git history, and the second scans your build output, catching generated files that were never committed. You can also scan the same targets with Secrets Free, either from the Mac app or with the secretsfree command.
By default, Gitleaks exits with a nonzero status when it spots a leak. Let CI fail on both findings and scanner errors, and never silence it with || true or continue-on-error.
Turn on full redaction so secrets don’t show up in scan reports, and lock down access to CI logs anyway. You should also check how the scanner handles your file types, archives, and size limits. In Gitleaks, scanning inside archives requires turning on archive traversal explicitly.
Keep the scanner config and allowlists in a trusted location. If an agent can edit the rules, add ignore entries, and approve its own build, it can weaken the very check meant to catch it.
GitHub’s push protection adds a useful guard before known secret formats ever hit the repo. Review who has bypass permissions and what exceptions exist. You still need artifact scanning alongside it, because push protection never sees files generated later during a build.
No scanner catches every secret, especially custom token formats, transformed strings, or split values. Keep secrets out of reach first, and treat scanning as a second layer to catch mistakes.
Test the artifact boundary with fake secrets
You can test your publish checks without touching a single real credential.
Save this script as artifact-demo.mjs. It builds a temporary output directory with an invented marker and runs a small file policy against it:
import assert from 'node:assert/strict'
import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const root = await mkdtemp(join(tmpdir(), 'artifact-demo-'))
const output = join(root, 'dist')
const marker = 'DEMO_ONLY_DO_NOT_USE'
const allowed = new Set(['index.html', 'app.js'])
async function check() {
const entries = await readdir(output, { withFileTypes: true })
if (entries.length !== allowed.size) throw new Error('Unexpected artifact entries')
for (const entry of entries) {
if (!entry.isFile() || !allowed.has(entry.name)) {
throw new Error('Unexpected artifact entry')
}
const content = await readFile(join(output, entry.name), 'utf8')
if (content.includes(marker)) throw new Error('Fixture marker exposed')
}
}
try {
await mkdir(output)
await writeFile(join(output, 'index.html'), '<h1>Reading club</h1>')
await writeFile(join(output, 'app.js'), `console.log('${marker}')`)
await assert.rejects(check(), /Fixture marker/)
await writeFile(join(output, 'app.js'), "console.log('Ready')")
await writeFile(join(output, '.env.fixture'), `DEMO_TOKEN=${marker}`)
await assert.rejects(check(), /Unexpected artifact/)
await rm(join(output, '.env.fixture'))
await check()
console.log('Both unsafe fixtures rejected; clean artifact accepted')
} finally {
await rm(root, { recursive: true, force: true })
}
Now run it from your terminal:
node artifact-demo.mjs
The script flags the marker inside app.js, rejects an unexpected environment file, and lets a clean fixture pass. It only reads the files it created and never prints their contents.
That covers two separate checks: which files are present and what’s inside them. The two-file allowlist is just for this demo fixture, not a drop-in scanner for a real Astro site.
On a real project, shape the rules around your actual build output. Block credential filenames, private key files, unexpected archives, and symlinks unless your packaging specifically needs them. Walk nested directories too, and decide up front how to handle hidden files and compressed assets.
Wire a synthetic marker test into your real pipeline as well. Feed a harmless fake value through the same path your real config uses, run the build, and verify the marker never shows up in the public artifact. Then drop that same marker into a browser asset on purpose and verify that the pipeline catches it and fails.
A generic secret scanner probably won’t recognize your invented marker, so pair it with an explicit marker check or a dedicated rule stored alongside your protected policy.
Separate building from publishing
The build job runs repository code. It installs packages, runs scripts, and processes files an agent may have just changed.
The publisher should do much less: grab one specific artifact, confirm the required checks and approvals passed, and push it to a fixed destination. The split looks like this:
For the reading club’s static site, keep production deploy tokens and database passwords out of the build job completely. Hand the publisher only the approved build output and the credential needed to upload that site.
Put a fresh runner or a real isolation boundary between the two jobs. Running separate steps on one compromised machine still lets them share files or leave background processes around, which is an extra risk on long-lived self-hosted runners.
Once the publisher receives the deployment credential, it shouldn’t touch repository install or build scripts. Rely on trusted publishing code and config, and check that your deploy CLI only uploads files instead of quietly running a build, loading plugins, or firing hooks.
If the build needs credentials to pull private packages, issue a separate read-only token limited to that package registry. Keep build access scoped to building instead of sharing the deploy identity.
GitHub’s Actions security guidance is worth reading for untrusted code, token permissions, third-party actions, and runner hardening. Pin third-party actions to reviewed full commit SHAs, and lock down who can update those pins.
Bind approval to the bytes being released
When you approve a release, tie it to the source commit, the built artifact, the destination, and the check results.
If the agent edits code or config after you look at it, require a fresh review. Avoid rebuilding after approval too, because a new build can produce different bytes than the ones you checked.
Save the repo name, build run, immutable artifact ID, and cryptographic digest in a protected release record. When the publisher runs, verify the artifact against that saved record instead of trusting whatever ID and checksum the caller passes in, and reject any mismatch.
GitHub Actions checks artifact digests on download, as covered in GitHub’s artifact documentation, though a mismatch only logs a warning. Add an explicit failure step on mismatch if you want the pipeline to block publication.
Signed artifacts and provenance records make the link back to the build even stronger. Keep the signing keys and verification rules outside the agent’s control, because a bad build can get a valid signature too if the agent controls signing.
Protect the gate from the agent
It’s fine for the agent to propose changes to your deployment config, as long as it can’t turn off the checks guarding those changes on its own.
Lock down workflow files, publishing scripts, scanner policies, and infrastructure permissions with required code owners or reviewers. Double-check that the agent’s repository token can’t bypass branch rules or approve its own pull requests.
On GitHub, check the bypass settings in your protected branch rules. Any account with admin access can quietly override a strict review setup.
You can also use a protected deployment environment to pause a job until a reviewer signs off, so environment secrets become available after approval. Whether you get those protection rules depends on your plan and repo visibility, so verify what your repository supports.
On larger setups, move the publishing policy into a separate service or a reusable workflow managed elsewhere. What matters is who can edit that policy and which code runs with the production credential.
Never run untrusted pull-request code in a privileged job just to post a PR comment or status check. I always review any workflow using pull_request_target or a privileged follow-up trigger before it checks out contributor code.
Deployment access can become runtime secret access
For a server app, this is the boundary that matters most.
Once you set Cloudflare Worker secrets, the dashboard and Wrangler hide their values, and your Worker receives them at runtime. Anyone who can deploy replacement Worker code can write a handler that reads an existing binding and returns it, even when the deploy API has no endpoint to read secrets directly.
That same risk shows up anywhere our app runs with an identity that can fetch secrets or query private data. Here’s how a deployed change can expose a runtime secret:
In the reading club app, restrict the server’s database role to the operations it needs. Before backend changes go live, review edits to authentication, response bodies, outbound requests, and logging.
If the agent only needs to update static pages, put those pages on a publishing path that can’t replace the privileged backend. Separate apps or separate deployment identities keep that boundary solid.
Static asset scanners only inspect files on disk, so backend releases still need an independent review of the executable code before it ships. My Cloudflare secrets and environments guide covers configuring those bindings, while your deployment policy controls which code gets to use them.
Restrict outbound access where it helps
When a process can both read a credential and talk to any host on the internet, leaking that secret takes one request.
In a controlled agent environment, limit outbound traffic to the services the task needs, enforced at the network, proxy, or tool layer. Check DNS queries and alternate network paths too, not just HTTP requests.
Keep an eye on the hosts you do allow. An agent can still push a secret to an allowed Git hosting service, drop it into an allowed logging endpoint, or return it in a response from your own app without contacting a new external domain.
If you run a credential-injecting proxy, attach secrets only for approved hosts and operations, and handle redirects safely so a redirect can’t carry a credential to another host.
When an agent has unrestricted shell access, test whether it can change proxy settings or bypass the network rules. Put the enforcement outside the process you’re restricting.
Don’t hide leaks with masking
Log masking helps with exact matches for known values, though encoded, shortened, or transformed copies can still slip through. Even GitHub’s security guidance warns that automatic redaction isn’t guaranteed.
When you’re debugging, avoid dumping the whole environment, request headers, or full configuration. Log a plain status check instead, like “database credential is configured”, so you verify the setup without printing the value.
CI stdout is only one place secrets end up. Check test reports, crash dumps, screenshots, tracing systems, agent transcripts, preview deployments, caches, and retained build artifacts too.
Limit who can access those systems and shorten how long they keep data. When a scanner catches a secret, report the rule identifier and location with the value redacted, and never paste the raw secret into an issue just to prove the finding.
Watch container builds too
If you deploy containers, deleting a secret in a later Dockerfile instruction still leaves it sitting in an earlier image layer.
Use secret mounts instead of build arguments or environment variables for build-time credentials, following Docker’s build secret documentation.
Secret mounts keep Docker itself from baking the value into a layer, while any command running during that step can still copy the value into a file, print it, or send it over the network. Review the Dockerfile and any scripts that run while that mount is active.
Keep local secret files out of the build context with .dockerignore, and inspect the final image alongside your repository files. Multi-stage builds also help limit what reaches the runtime image, provided you double-check which files get copied between stages.
A practical set of guards
For a small app, I start with this baseline:
| Guard | A useful test |
|---|---|
| Dedicated agent workspace with development credentials | File and shell tools can’t read a marker outside the allowed workspace |
| Separate production identity | Development credentials can’t access production resources |
| Explicit public output directory | A fake .env file in the wrong location blocks publication |
| Source and artifact scanning | A known synthetic detection fixture fails the check |
| Isolated publisher | Repository scripts can’t run with the deployment credential |
| Independent production approval | The agent can’t approve or bypass its own release |
| Artifact identity verification | A modified artifact gets rejected after approval |
| Restricted runtime authority | The app can’t access unrelated databases or secrets |
From there, add controls that match what you operate. Teams handling sensitive data often add outbound network restrictions, dynamic credentials, stronger audit retention, and a separately administered release service.
Test the failure paths too. Try an incorrect destination, an expired credential, a changed artifact, and an unauthorized production request, then confirm the system rejects every one without revealing secret values in the error output.
Use fake values for disclosure tests. For authorization tests, a dummy token fails for the wrong reason, so test with a real restricted identity against a harmless protected resource, or run your provider’s policy simulator.
For a local scan with masked findings, see how to let a coding agent check for API keys without seeing them.
If a secret has already leaked
Start by revoking or rotating the credential at its provider. Deleting the file is just cleanup, because once a value goes out you have to assume someone already copied it.
Take down the exposed deployment, then check older versions, previews, downloaded artifacts, and caches. Follow your hosting provider’s cache-removal process where needed.
Review access logs for the credential and every resource it could reach. Watch for activity outside expected workloads, unexpected data access, and changes to permissions or identities.
Switch legitimate consumers over to the replacement credential. If the leaked value could create other credentials or sessions, track those down and invalidate them too, depending on what that secret could authorize.
Clean repository history, CI logs, and retained outputs where appropriate, while saving incident evidence in a restricted location. My guide to exposed GitHub credentials covers the Git side of that recovery.
Before I wrap up an incident, I add a test at the boundary that failed. If public/.env shipped, I make our artifact policy reject it, and if a privileged job ran untrusted code, I fix that execution path before restoring its access.
How I would set this up for the reading club
I’d give the agent a development environment with synthetic member data where we can edit the app, run tests, and spin up previews against dev-only resources.
I’d keep production database access on the server identity and deployment access inside an isolated publisher with a fixed destination. The agent prepares the release, then I review and approve both the server code and the exact artifact going live.
Before trusting the setup, I’d test sneaking a copied secret into the output, swapping an artifact after approval, and pushing an unapproved backend change, verifying every attempt gets refused.
If you want to go deeper on the underlying concepts, my free Web & API Security Handbook covers trust boundaries, incident response, dependencies, CI, artifacts, and supply-chain hygiene.
Generate a cryptographically random secret key
Create a 16 to 64 byte secret key locally with the Web Crypto API in hex, Base64, or Base64url:
Want me to talk about your product? You can sponsor this site.
Related posts about ai: