AI Security
Scoped API Keys for Cloudflare Workers AI: A Practical Guide for Small Teams
TL;DR: Use Cloudflare Workers AI’s built‑in token scopes to limit each automation to the exact model and data it needs, store keys in encrypted environment variables, rotate them regularly, and audit usage with Cloudflare’s Logs API. This reduces the blast radius if a key is leaked and keeps compliance simple for small teams.
Why does token scoping matter for AI‑driven workflows?
AI automations often call external services – model endpoints, vector stores, or third‑party APIs. An unrestricted API key can be used to:
- Run expensive model calls that blow your budget.
- Read or write data you never intended to expose.
- Trigger malicious prompts that exfiltrate information.
How to define minimal scopes for Cloudflare Workers AI models
Cloudflare Workers AI supports granular scopes when you create a token in the dashboard. Follow these steps:
- Create a dedicated token per automation. In the Workers AI documentation, navigate to API Tokens → Create Token.
- Select only the models you need. Use the
account:readscope for read‑only access and theworkers:scriptscope for the specific model (e.g.,ai:run:claude-3-sonnet). - Restrict the token to a single Worker script. Add a resource condition like
resource:worker:my-summary-workerso the token cannot be reused elsewhere. - Disable unnecessary permissions. Uncheck
account:edit,billing:read, or anydnsscopes unless the automation truly needs them.
Result: a token that can only invoke the Claude 3 Sonnet model from one Worker, nothing else.
How to store and rotate API keys securely in a small team
Even with tight scopes, keys must be protected at rest:
- Use encrypted environment variables. In the Workers dashboard, set the token under Settings → Secrets. Secrets are encrypted at rest and never exposed to the client.
- Leverage a secrets manager. If you already use a tool like HashiCorp Vault or 1Password Teams, store the token there and inject it at deploy time via CI/CD.
- Automate rotation. Write a small script that calls the Cloudflare API to revoke the old token and create a new one. Schedule it weekly or monthly using a cron Worker.
curl -X POST "https://api.cloudflare.com/client/v4/user/tokens" \ -H "Authorization: Bearer $MASTER_TOKEN" \ -d '{"name":"summary‑worker‑token","policies":[{"effect":"allow","resources":["workers:script:my-summary-worker"],"permission_groups":["ai:run:claude-3-sonnet"]}]}'
How to enforce least‑privilege when calling external APIs from AI workflows
Beyond Cloudflare, your Worker may call other services (e.g., a CRM API). Apply the same pattern:
- Generate a separate token for each third‑party service.
- Scope the token to the exact HTTP methods and endpoints needed.
- Store the token in
envsecrets, not in source code. - Validate the token’s audience on each request (most APIs return the token’s scopes in the response headers).
When a request fails due to insufficient scope, you instantly know the permission was too narrow – a good sign that you’re following least‑privilege.
How to audit and monitor key usage
Cloudflare provides a Logs API that can be piped to a SIEM or a simple spreadsheet. Set up a Worker that forwards log entries to a Slack channel:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const logs = await fetch('https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/workers/logs', {
headers: { 'Authorization': `Bearer ${ADMIN_TOKEN}` }
})
const data = await logs.json()
// Filter for our scoped token ID
const filtered = data.filter(entry => entry.auth_token_id === 'TOKEN_ID')
await fetch(SLACK_WEBHOOK_URL, {
method: 'POST',
body: JSON.stringify({ text: JSON.stringify(filtered, null, 2) })
})
return new Response('Logged')
}
Regularly review the log for:
- Unexpected model calls (e.g., a different model than the one you scoped).
- Calls from IPs outside your Cloudflare Workers network.
- Spike in usage that could indicate a compromised key.
Putting it all together
1. Identify the exact AI capability you need. Choose the model and create a token with only that model’s ai:run permission.
2. Bind the token to a single Worker script. Use resource‑level conditions.
3. Store the token as an encrypted secret. Never commit it.
4. Rotate the token on a schedule. Automate revocation and creation via the Cloudflare API.
5. Audit usage daily. Forward logs to a channel you monitor.
By following these steps, a small business can keep AI automation costs predictable, protect sensitive data, and stay compliant with minimal overhead.
If you need a hands‑on review of your token strategy or help wiring up automated rotation, AISecAll offers a quick security audit tailored for startups and solo founders.
Need a practical AI security review?
AISecAll reviews prompts, tool permissions, document flows, and agent behavior so small teams can use AI without guessing where the risk sits.