How to Rotate Secrets in an App You Built With an AI Coding Tool: A Playbook by Secret Type
Rotate a secret in an AI-built app by creating the new value at the provider, updating it everywhere the app reads it, redeploying, confirming it works, and only then revoking the old value. Before any of that, find ever
Rotate a secret in an AI-built app by creating the new value at the provider, updating it everywhere the app reads it, redeploying, confirming it works, and only then revoking the old value. Before any of that, find every copy of the secret, including in Git history, frontend bundles, server logs, and AI chat transcripts, because a rotated secret that still sits in one of those places is still exposed.
Disclosure: Control Plane publishes this guide.
TL;DR
Rotate any secret by following five steps in order: find every copy, create a new value, update all consumers, redeploy, then revoke the old value. If the secret has already leaked, revoke it within minutes, even if that causes downtime.
- Find every copy of the secret across source code, environment variables, Git history, logs, CI pipelines, frontend bundles, and AI chat transcripts.
- Overlap the old and new values for as long as the provider permits so that running instances keep working during the transition.
- Redeploy every service that consumes the secret. Confirm the new value is in use by checking provider usage logs.
- If the secret already leaked, revoke it within minutes. Create and deploy the replacement first only if that also takes minutes; otherwise accept temporary breakage.
- Control Plane stores secrets encrypted, injects them as environment variables or mounted files, enforces identity-based access through policies, and provides a tamper-proof audit trail. The Control Plane MCP server lets AI assistants create or rotate a secret without its value passing through the chat.
How do I rotate secrets in an app I built with an AI coding tool?
The rotation process is the same regardless of which AI tool generated your code, but AI-built apps require an extra discovery step because secrets end up in more places than hand-written projects.
Step 1: Discover every copy of the secret
Run a scanner such as gitleaks or TruffleHog across your repository, including its full Git history. Check CI logs, error tracking services, and any AI chat transcripts where you may have pasted the value. Look inside frontend bundles for variables prefixed with NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_, REACT_APP_, NUXT_PUBLIC_, or PUBLIC_ (SvelteKit, Astro), which are embedded in client-side JavaScript and visible to anyone who opens your app.
Step 2: Create the new secret at the provider
Go to the provider’s dashboard or API and generate a new key, password, or token. Do not revoke the old one yet. Most providers, including OpenAI, Anthropic, Stripe, AWS, Google Cloud, and Microsoft Entra ID, allow two or more active credentials at the same time, which gives you a safe overlap window.
Step 3: Store the new secret and update consumers
Place the new value in your secrets manager or environment variable configuration. Update every service, background worker, and CI pipeline that reads the secret. If you use multiple environments, update staging first and confirm the new value works before touching production.
Step 4: Redeploy
Restart or redeploy every workload that consumes the secret. Environment variables require a redeploy to take effect. If your platform refreshes secrets mounted as files, the app must still re-read the file to pick up the new value.
Step 5: Confirm and revoke
Check the provider’s usage logs to verify that all traffic is now using the new credential. Last-used data is often coarse or delayed, so also check your own app logs. Once you are confident no consumer still depends on the old value, revoke it. Document the rotation, including who performed it, when, and which systems were updated.
How do you rotate each type of secret without downtime?
Whether you can rotate without downtime depends on whether the old and new values can be active at the same time. This table covers the most common secret types in AI-built apps.
| Secret type | Can old and new work at the same time? | How to rotate without downtime | What breaks if you get it wrong |
|---|---|---|---|
| OpenAI or Anthropic API key | Yes. Multiple keys can exist per OpenAI project or Anthropic workspace. | Create a new key, deploy it, confirm API calls succeed, then delete the old key. | If you revoke the old key before deploying the new one, all API calls fail until the new key is live. |
| Stripe secret key | Yes. Stripe’s Rotate key option keeps the old key working for up to 7 days. | Use Rotate key on the API keys page in the Stripe Dashboard and pick an expiration for the old key. Deploy the new key. Let the old key expire automatically or revoke it after confirming. | Revoking the old key too early breaks payment processing. Charges, refunds, and webhook handlers that call the Stripe API all fail. |
| Stripe or GitHub webhook signing secret | Yes, with caveats. Stripe lets you roll an endpoint’s signing secret and keep the old one active for up to 7 days. GitHub supports a single active secret per webhook, so check the provider. | For Stripe, roll the endpoint secret with a delayed expiration. Stripe sends one signature per active secret during the overlap, so deploying the new secret is enough. For GitHub, deploy code that accepts a signature from either the old or new secret, change the secret in GitHub, then remove the old one. Redeliver any failed events from the webhook’s delivery log. | Webhook signature verification fails, causing your app to reject legitimate events. |
| Database password (MySQL) | Yes, with dual passwords. MySQL 8.0+ supports dual passwords for a single user. | Set the new password with RETAIN CURRENT PASSWORD. Deploy the new password to all consumers. Then discard the old password. | Connection pools holding the old password fail on reconnect. Background workers crash. |
| Database password (PostgreSQL) | No dual passwords for a single role. | Keep table ownership on a separate NOLOGIN owner role and make two login roles members of it. On each rotation, set a new password on the idle login role, deploy its credentials, then expire the old role’s password with ALTER ROLE … VALID UNTIL. Do not drop a role that owns objects; dropping it fails, and DROP OWNED deletes the tables. | If you change the password on the only role, every connection using the old password breaks on the next reconnect. |
| JWT signing key | Yes, if you publish both keys by key ID (kid). | Add the new key to your JWKS endpoint. Start signing new tokens with the new key. Keep the old key published until the longest-lived token it signed has expired, including refresh tokens if they are JWTs. Then remove it. | If you remove the old key before tokens expire, users with valid tokens get 401 errors. |
| Session secret (for example, Express secret arrays or the Rails cookie rotator) | Yes, in most frameworks. Express (express-session) accepts a secret array in which the first signs new sessions and all verify, and Rails reads old cookies through cookie rotations. | Add the new secret to the front of the list. Deploy. Old sessions remain valid. Remove the old secret after session expiry. | If your framework does not support a list, every active session is invalidated and all users are signed out. |
| OAuth client secret (Google Cloud, Microsoft Entra ID) | Yes. Google Cloud allows up to two client secrets per client, and Microsoft Entra ID allows multiple. | Create a second client secret. Deploy it. Delete the first after confirming. | Revoking the only active secret breaks all OAuth flows, including login, token refresh, and API access. |
| AWS access key | Yes. AWS allows two access keys per IAM user. | Create a second access key. Deploy it. Deactivate the old key. Delete it after a monitoring period. Where possible, replace static keys with IAM roles or short-lived credentials. | Deleting the only active key locks out every service using that IAM user. |
| Third-party SaaS API keys (general) | Check the provider. Most allow multiple active keys. | Create a new key, deploy, verify, revoke the old one. If the provider allows only one active key, schedule a maintenance window for the cutover. | API calls fail between revocation of the old key and deployment of the new one. |
Where do AI-built apps leak secrets?
AI-assisted development introduces leak vectors that traditional projects rarely encounter. Frontend environment variable prefixes are the most overlooked: anything under a public prefix is bundled into client-side JavaScript that every visitor can read.
| Location | How it happens | How to check | Fix |
|---|---|---|---|
| Hardcoded in source code | The AI assistant writes a key directly into a file as a string literal. | Run gitleaks or TruffleHog on the codebase. | Move the value to an environment variable or secrets manager. |
| Committed .env file | The .env file is not in .gitignore, or the AI tool creates it and commits it. | Check git ls-files for .env files. | Add .env to .gitignore. Remove the file from tracking with git rm –cached. Rotate every secret in the file. |
| Git history after deletion | The secret was removed in a later commit but remains in the repository’s history. | Run TruffleHog or gitleaks against the Git repository; both scan full history. | Rotate the secret. Rewriting history with git filter-repo removes it from the local repo but does not un-leak a secret that was pushed to a remote. |
| Frontend bundle (NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_, REACT_APP_, NUXT_PUBLIC_, PUBLIC_) | The AI tool stores a secret API key under a public prefix, embedding it in the client bundle. | Search the built JavaScript output for the key value. Inspect the framework’s environment variable documentation. | Move the secret to a server-side-only variable. Proxy API calls through your backend. |
| Server logs and error trackers | The secret appears in a stack trace, debug log, or error report sent to a third-party service. | Search log aggregation and error tracking dashboards for the key value or a prefix of it. | Redact secrets from logs. Configure structured logging that excludes sensitive fields. |
| AI chat transcripts and prompts | A developer pastes a live key into the AI assistant’s prompt to debug an error. | Review chat history in the AI tool. Check whether the provider retains prompt data. | Never paste live credentials into an AI assistant. Use placeholder values. Rotate any key that was shared. |
| CI/CD logs | A build step prints the secret to stdout, and the CI system stores the log. | Search CI logs for the key value. | Use the CI platform’s secret masking feature. Avoid echoing variables in build scripts. |
| Screenshots and screen shares | A developer shares a screenshot or recording that includes a terminal or dashboard showing the key. | Audit shared media in team channels and documentation. | Rotate the exposed key. Crop or redact sensitive values before sharing. |
| Shared preview or template projects | The AI tool publishes a preview deployment or template that includes live credentials. | Check public URLs and template repositories for .env files or hardcoded values. | Use separate credentials for preview environments. Revoke and rotate any production secrets found in shared projects. |
How to make a vibe-coded app production ready covers the other fixes to make before launch, and security risks of vibe-coded apps explains who fixes each one.
What changes if the secret already leaked?
A routine rotation and a leaked-secret response share the same tools but follow different priorities. When a secret is known to be compromised, speed matters more than continuity.
| Step | Routine rotation | Leaked secret |
|---|---|---|
| Order of operations | Create new secret first, overlap, then revoke old. | Revoke within minutes. If a new key can be created and deployed in minutes, do that first and then revoke. Never hold a leaked key open for a maintenance window. On AWS, deactivate first, since that is reversible. |
| Urgency | Scheduled. Can wait for a maintenance window. | Immediate. Every minute the old secret is active, an attacker may be using it. |
| Git history cleanup | Not usually necessary. | Run git filter-repo to remove the secret from history. Understand that this does not recall a secret already pushed to a remote or forked by someone else. |
| Audit of usage logs at the provider | Optional but recommended to confirm the new secret is in use. | Mandatory. Review the provider’s usage logs to determine whether the leaked secret was used by an unauthorized party. Also look for credentials or resources the attacker created with the key, such as new IAM users or keys, webhooks, or OAuth apps, and revoke those too. |
| Notifying users or customers | Not required. | Possibly required. GDPR requires notifying the supervisory authority within 72 hours unless the breach is unlikely to put people at risk, HIPAA and US state breach laws have their own triggers, and PCI DSS requires notifying your acquirer. Get legal advice. |
| Follow-up | Update the rotation runbook. | Conduct a post-incident review. Identify how the secret leaked, close the gap, and add detection rules to prevent recurrence. |
If a secret was pushed to a public or shared repository, treat it as compromised regardless of whether you force-push a cleaned history. The original commit may have been cloned, forked, or cached by a third party. On GitHub, old commits stay reachable by SHA, through pull request refs, and in forks, so contact GitHub Support to purge cached views and pull request refs.
How do you keep the AI assistant from leaking secrets again?
A few guardrails reduce the chance that a secret ends up somewhere it should not be.
Keep secrets out of AI chat. Use placeholder values such as sk-test-PLACEHOLDER in prompts, and rotate any real key you paste.
Install pre-commit scanners. Add gitleaks or TruffleHog as a pre-commit hook so that secrets are caught before they reach the repository. Enable GitHub secret scanning and push protection on every repository. Hooks run only where they are installed and can be skipped with –no-verify, which agents sometimes use, so server-side push protection is the enforced layer.
Instruct the AI assistant to use environment variables. In your project’s system prompt or instructions file, tell the assistant to reference process.env.SECRET_NAME instead of hardcoding values. Most AI coding tools follow explicit instructions in a project-level configuration file.
Separate development and production credentials. Use different API keys and database users for each environment. A leaked development key limits blast radius because it cannot access production data.
Use short-lived credentials where possible. Temporary tokens, OIDC federation, and workload identity replace long-lived cloud access keys with tokens that expire in minutes to hours.
Secrets management best practices covers storage, rotation schedules, and short-lived credentials in more depth.
How Control Plane fits
Control Plane stores secrets encrypted, in types including opaque, dictionary, username and password, keypair, TLS, and cloud credentials. A workload can read a secret only if its identity has been granted the reveal permission on that secret through a policy. A workload with no identity cannot access any secrets.
Secrets can be injected as environment variables or mounted as files. Changing a secret used as an environment variable takes effect after a redeploy. A dictionary secret mounted as a directory refreshes inside the running container within about 10 minutes, and the app must re-read it.
The Control Plane MCP server lets AI assistants such as Claude Code, Cursor, Codex, and ChatGPT create or rotate a secret without its value passing through the chat. The MCP tools return secret metadata only, so the credential never appears in a prompt or transcript.
For cloud services on AWS, GCP, and Azure, Control Plane’s Universal Cloud Identity (UCI) lets workloads authenticate through one identity with no long-lived cloud keys in your code, so those keys drop off your rotation list.
Control Plane provides a tamper-proof audit trail of actions in the org, including who created or updated a secret and when.
Control Plane stores and delivers secrets to workloads. It does not rotate keys at third-party providers such as OpenAI or Stripe for you. You still generate the new key at the provider and store it in Control Plane, but from that point forward, delivery, access control, and auditability are handled for you.
Control Plane is the unbreakable platform for running production workloads. It runs serverless, standard, stateful, and cron workloads natively on AWS, GCP, Azure, and Oracle Cloud Infrastructure (OCI), VM workloads on locations joined through Control Plane’s Managed Kubernetes, and workloads on Kubernetes clusters you already run or your own machines, including on premises, active-active across regions and clouds. Control Plane is PCI DSS Level 1, SOC 2 Type II, HIPAA, and GDPR compliant. Control Plane handles Day 2 operations for you, including autoscaling, built-in observability, and security. Control Plane-managed compute runs in AWS, GCP, Azure, and Oracle Cloud regions.
FAQ
Answers to common questions about rotating secrets in AI-built apps.
How do I rotate secrets in an app I built with an AI coding tool?
Create the new secret at the provider, store it in your secrets manager or environment variables, redeploy every service that reads it, confirm the new value is working by checking provider logs, and then revoke the old value. Before starting, scan your codebase, Git history, CI logs, frontend bundles, and AI chat transcripts to find every copy of the secret.
How often should I rotate API keys?
Rotate immediately after any suspected exposure, and otherwise on a schedule your security policy or compliance framework sets. Rotate high-impact keys, such as payment and database credentials, more often than low-impact ones, and automate the schedule so no key is forgotten.
Can I rotate a database password without downtime?
Yes, if your database supports dual passwords or if you use two database roles. MySQL 8.0+ supports dual passwords natively, letting both old and new passwords work during the transition. PostgreSQL does not support dual passwords for a single role, so keep table ownership on a NOLOGIN owner role with two login roles as members. Set a new password on the idle login role, deploy its credentials, then expire the old role’s password with ALTER ROLE … VALID UNTIL.
What should I do if my AI coding assistant exposed an API key?
Revoke the key at the provider within minutes, creating and deploying the replacement first only if that takes minutes too. Confirm your app works on the new key, then audit the provider’s usage logs to check for unauthorized use during the exposure window. Review how the key was exposed, whether through a prompt, a committed file, or generated code, and put guardrails in place to prevent it from happening again.
Are NEXT_PUBLIC_ and VITE_ variables secret?
No. Variables with these prefixes are bundled into client-side JavaScript and sent to every user’s browser. They are public by design. Never store API keys, database passwords, or any sensitive credential under a public prefix. Use these prefixes only for values that are safe to expose, such as a public analytics ID or an app name.
Does deleting a secret from GitHub remove it?
No. Deleting a file or line in a new commit does not remove it from Git history. Anyone with access to the repository can view the old commit and retrieve the secret. You can use tools like git filter-repo to rewrite local history, but if the commit was ever pushed to a remote, treat the secret as compromised and rotate it.
Should I paste API keys into Cursor or Claude?
No. Pasting a live API key into any AI assistant’s prompt can leave it in your chat history and in the provider’s stored conversation data. Use placeholder values when asking for help. If you accidentally paste a real key, rotate it immediately. The Control Plane MCP server provides a safer alternative by letting AI assistants manage secrets without the value ever appearing in the chat.
How does Control Plane handle secret rotation?
Control Plane delivers the new value to workloads after you generate it at the provider; it does not rotate third-party keys for you. Secrets reach workloads only through identity-based policies, the Control Plane MCP server lets AI assistants rotate a secret without exposing its value in the chat, and the tamper-proof audit trail records who changed it.
Do short-lived credentials eliminate the need for rotation?
No. Short-lived credentials, such as OIDC tokens and temporary STS credentials, expire automatically and reduce rotation work, but some providers only offer long-lived keys, and you may still have database passwords, webhook signing secrets, or session secrets that require manual or scheduled rotation.
Talk to the Control Plane team or sign up free to keep secrets out of code and out of chat.
Originally published on the Control Plane blog.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.