Secrets and Scoped API Tokens for AI Agents
Keep production secrets out of agent sessions. Choose scoped API tokens, isolate credentials on Ubuntu 24.04 LTS, and verify access before allowing writes.

On this page
- Separate permission to act from permission to read secrets
- Scope each token to a specific job
- Choose storage that fits a single VPS
- Run Claude Code without your administrator identity
- Put production writes behind a narrow tool
- Verify allowed access and rejected requests
- Make rotation and emergency revocation routine
- Replace one broad credential before the next task
- FAQ
Keeping API keys in a secret manager does not make an AI agent safe. If its shell can retrieve an administrator token, it still has administrator access. Give Claude Code a separate identity with narrowly scoped credentials, preferably behind tools that keep secrets outside its session. Start with read access, enforce resource limits at the provider, and verify that forbidden operations fail.
Separate permission to act from permission to read secrets
On a single VPS running Ubuntu 24.04 LTS, we would start with a dedicated agent account and no production credentials in its login environment. Your application keeps its own service account. The agent receives only the access needed for the current operational task.
A secret manager answers where credentials live and who can retrieve them. It does not reduce the authority of a credential after retrieval. An agent with permission to fetch your main infrastructure token can perform the same operations as any other holder of that token.
Distinguish secret disclosure from credential use. A tool can authenticate a request without returning the token to the conversation, but that tool still grants authority. A hidden administrator credential behind an unrestricted API proxy remains administrator access.
Treat repository files and tool responses as untrusted input that can influence an agent's next action. Written instructions help express your intent, but the operating system and provider must enforce the boundary. Use the same separation described in production guardrails for AI agents: the agent can propose changes without automatically receiving permission to execute them.
Scope each token to a specific job
Before creating a token, write the operation it must perform and the resource it may touch. Include the environment in that description. A token called ops-agent tells you little; dns-inspect-production gives you something concrete to review.
| Agent task | Starting permission | Resource boundary | Keep separate |
|---|---|---|---|
| Investigate DNS | DNS read access | Selected zone | DNS changes |
| Review application source | Repository contents read access | Selected repository | Publishing and administration |
| Inspect service health | Read selected status and sanitized logs | Named service | Service configuration changes |
| Upload a backup | Create backup objects where supported | Dedicated backup location | Deletion and retention changes |
Cloudflare lets you select permissions and resources separately, with optional expiry and client IP restrictions. For DNS investigation, choose DNS Read on the selected zone. DNS Edit includes deletion, so it is too broad for an inspection task. Follow the official token creation procedure and review the resulting scope before copying the secret.
GitHub fine-grained personal access tokens can be restricted to selected repositories and specific permissions, although some operations have limitations. Start with the required repository access and add permissions only when the documented endpoint requires them. Check GitHub's token documentation before assuming a permission covers your workflow.
An expiry limits how long a stolen token remains useful; it does not constrain damage while the token works. Read access also deserves scrutiny because logs and private source can contain sensitive information. If a provider cannot express your required boundary, keep the operation manual or enforce a narrower boundary in a separate tool.
Choose storage that fits a single VPS
We would not introduce a separate secrets platform solely to hold a small collection of service credentials on one server. Protected files can be a reasonable starting point when ownership is clear and recovery is documented. Choose a managed secret store when you need centralized access control or coordinated rotation across services.
| Storage choice | Good fit | Boundary you still need |
|---|---|---|
| Protected file outside the checkout | A small, stable service setup | Separate service identity and restricted directory access |
| systemd credentials | A service that accepts credentials through files | Agent cannot access the service identity or alter its executable |
| Managed secret store | Shared administration and coordinated rotation | Retrieval identity limited to named secrets |
| Environment injection | Software that only accepts environment variables | Dedicated process environment and controlled diagnostic output |
For a compatible service, systemd's LoadCredential= supplies a credential through a file in its runtime credential directory. The service reads it through CREDENTIALS_DIRECTORY; the secret value need not appear in its command line. This handles delivery to the service, not provider permissions or rotation. See the systemd credential documentation.
Keep source credentials outside the repository and unreadable to the agent account. Owner-only permissions do not help if the agent runs as that owner, and root can cross ordinary file permission boundaries. Also restrict the parent directory so the agent cannot replace the credential file.
If an application requires environment variables, inject them only into that service rather than exporting them before starting an agent session. Child processes may inherit environment values, and diagnostic commands can print them. A git-ignored .env avoids accidental staging in ordinary use; it provides no access control.
Run Claude Code without your administrator identity
We recommend Claude Code for this workflow, running under a dedicated account without unrestricted sudo. Do not give that account access to the application's service identity or a privileged container socket. Those routes can undo otherwise careful file permissions.
Enable Claude Code's shell sandbox and explicitly restrict sensitive reads; enabling it alone does not hide credential files. Configure file-tool permissions as well, because built-in file tools and MCP servers are outside the shell sandbox. Disable unsandboxed retries and configure failure when sandboxing is unavailable. The official sandbox documentation explains these separate boundaries.
Keep operational tokens out of Claude Code's startup environment. Review helper processes separately rather than assuming they inherit the shell sandbox's restrictions. Choose where to run Claude Code for VPS operations based partly on which credentials and local files that process can reach.
Protect the code that consumes secrets, too. If the agent can modify an application and deploy that revision without review, it can make the application disclose its own credentials. Require approval of the exact revision before a privileged deployment process runs it.
Put production writes behind a narrow tool
For occasional production changes, we prefer an agent-generated proposal followed by human execution. When a repeated task justifies automation, use a small broker: a separate service that holds the credential and exposes only the operation you intend to delegate. Its policy must live outside files the agent can edit.
A useful DNS tool might allow updating an approved record to an approved destination. It should not accept an arbitrary URL or a raw provider request body. The tool must validate the target and allowed values before using its credential.
- Authenticate the caller and map that identity to allowed operations.
- Resolve resource identifiers against a fixed allowlist owned by the administrator.
- Require approval for the exact production change, including its target and proposed value.
- Return selected result fields and record the operation without recording authentication headers.
Keep the provider token narrow even when a broker enforces additional limits. A bug in the broker should not expose unrelated resources. Bind approval to the submitted change so the agent cannot obtain approval for one target and substitute another.
MCP provides a way to expose these tools; it does not automatically make them safe. Review what the server can do with its own identity and what each tool returns. The practical access decisions are covered in connecting an agent to Cloudflare with limits.
Verify allowed access and rejected requests
Validate permissions before assigning production work. Run the checks through the same identity and tool path the agent will use, because an administrator's successful request proves little about the agent's access. Keep secret values out of the evidence you save.
First, perform the intended read against an allowed resource. Record the resource identifier and the provider's result status, with only the response fields needed to establish success.
Next, attempt the same read against a known existing resource you own that is outside the permitted scope. Confirm its existence independently through your administrator account so a typo cannot masquerade as successful access control.
Then check a forbidden write using a disposable resource or the provider's authorization simulator where available. Do not attempt deletion against production to demonstrate that deletion is denied. If you lack a safe write target, review the policy and leave write access disabled until you can validate it.
Finally, create a harmless dummy credential protected like the real one and ask the agent to read it through each enabled execution path. Exercise the broker's rejected inputs as well. Inspect captured output for the dummy value before introducing a real secret.
Make rotation and emergency revocation routine
Maintain a credential inventory containing metadata rather than secret values. Give each credential an owner and document which service consumes it. Separate agent credentials from application credentials so revoking an agent's access does not also stop customer-facing work.
- Record the provider's token identifier and its intended task.
- Record the permitted operations and resource boundaries.
- Record the storage location, consumer identity and expiry.
- Record the revocation procedure and the person responsible for replacement.
For planned rotation, create the replacement with the same reviewed scope and install it through an administrator-controlled path. Reload or restart the consumer as its credential-loading behavior requires, then verify the intended operation. Revoke the old token and confirm that it no longer authenticates.
For suspected exposure, revoke the affected credential first even if the automation becomes unavailable. Review provider activity for unexpected use and remove leaked copies from accessible logs or artifacts. Deleting a transcript does not invalidate a token that someone may already have copied.
Keep account recovery credentials outside the agent's reach. If the agent can retrieve a recovery credential or mint a broader token, its narrow operational token no longer defines its actual authority. Your recovery procedure must still work after the agent identity has been disabled.
Replace one broad credential before the next task
Choose the broadest credential your agent can currently reach and identify one real task that depends on it. Write down the minimum operation and resource needed for that task. Use the division of responsibilities in the AI operations playbook if you have not decided whether that operation belongs with the agent.
Create a task-specific replacement and place it behind the chosen access boundary. Run the allowed and denied checks through the agent's actual tool path. Move the task to that credential only after the checks support the intended policy.
Remove the broad credential from the agent's environment and accessible files, then revoke it after migrating any legitimate consumers. Close sessions that may still hold it and start a fresh session with the reduced access. Assign the next task using that narrower identity and retain the sanitized verification results with the credential inventory.
FAQ
What is the best approach to AI agent secrets management?
Start by deciding which operations the agent should perform, then choose how those operations authenticate. A storage product cannot make that decision for you. For a small server setup, protected service credentials and a restricted agent identity can be sufficient. Add centralized secret storage when managing ownership and replacement across services becomes difficult.
How do I create scoped API tokens for agents?
Translate the task into the provider's permission model. Select the required operation, restrict it to the intended resources, and set an expiry appropriate to the work. Check whether the chosen permission also grants deletion or administration. If the provider bundles too much authority together, do not compensate with a prompt instruction; use a constrained intermediary or keep the task manual.
Can I store agent API keys in a .env file?
You can use a file to supply credentials to software, but its location and ownership determine who can read it. Keeping it out of Git does not stop an agent running as the file owner from opening it. Avoid placing production keys in the agent's checkout, and never ask the agent to print the file while troubleshooting configuration.
Does a read-only API token make an agent safe?
Read-only access reduces the risk of unauthorized changes, but it can still expose confidential data. A token that reads every support record or application log may reveal more than an investigation requires. Restrict the resources and returned fields, and consider whether the agent needs raw data or a sanitized result produced by a separate tool.
Should an AI agent receive short-lived credentials?
Prefer credentials that expire when the task no longer needs them, provided renewal is dependable. Short lifetimes reduce the period of exposure but do not prevent immediate misuse. Pay attention to the renewal identity: an agent that can continually issue new credentials retains continuing access. Keep issuance privileges separate from ordinary task execution.
Put this guide in the bigger picture
See how this topic connects to the rest of your product. Our free field guide explains apps, infrastructure and AI, with checklists to help you make business decisions.






