Skip to main content

Virtual keys

A virtual key is the credential an application or a person uses to call the gateway. It looks like a provider key, a random string that starts with sk-, but it never reaches a provider. The gateway swaps it for the real provider credentials it holds, and attaches to the key everything you want to control, which models it may call, how much it may spend, how fast it may go, and who owns it. If a key leaks you block or rotate it and the provider credentials stay safe. Keys need a database, so set DATABASE_URL and a master key before you start.

general_settings:
master_key: os.environ/SPANWAY_MASTER_KEY
database_url: os.environ/DATABASE_URL
About SPANWAY_API_KEY

The examples on this site read your key from the SPANWAY_API_KEY environment variable, which holds your master key or a virtual key. Export it before running an example. The gateway refuses to start when its master key is unset, empty, or a publicly known example value, so always generate a real master key, for example with openssl rand -hex 32.

When you would use this​

The billing team is about to ship a service that calls two models. You create one key for it with a 50 dollar monthly budget, 120 requests per minute, a 90 day expiry and a tag that names the owner. The service gets the key and nothing else. When its spend hits 50 dollars it is stopped until the budget resets, and when the service is retired you delete the key and the provider credentials never change.

Before you start​

The master key can call every management route. In the Admin UI a proxy admin can manage every key, a team admin the keys of their team, and an internal user their own keys, as access control describes. The Admin UI calls the same routes as the curl examples below.

Step by step​

  1. Create a key. In the Admin UI open Virtual Keys and click + Create New Key. Under Key Ownership pick You, Service Account, Another User or Agent, and a Team if the key belongs to one. Under Key Details type the Key Name, pick the Models and leave Key Type on AI APIs. Open Optional Settings to set Max Budget (USD), Reset Budget, Requests per minute Limit (RPM), Metadata and, under Key Lifecycle, Expire Key. Click Create Key. Over the API call POST /key/generate.

    curl -X POST http://localhost:4000/key/generate \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "key_alias": "billing-service",
    "models": ["claude-sonnet-5-5", "gpt-6.1-sol"],
    "max_budget": 50,
    "budget_duration": "30d",
    "duration": "90d",
    "rpm_limit": 120,
    "metadata": {"owner": "billing-team"}
    }'
    {
    "key": "sk-9f3a2c7e41b8d605",
    "key_name": "sk-...efgh",
    "key_alias": "billing-service",
    "token_id": "d5345c0ecc68ae6295c69f91926b2bd379e25481a40c34b5884d157a9f65d8fa",
    "expires": "2027-02-19T10:15:00Z",
    "models": ["claude-sonnet-5-5", "gpt-6.1-sol"],
    "max_budget": 50.0,
    "budget_duration": "30d",
    "rpm_limit": 120,
    "metadata": {"owner": "billing-team"}
    }

    The full key value is shown only once, in the Save your Key dialog and in this response. The gateway stores a hash of it, and later responses show the key_name preview and the token_id hash. Leaving models empty lets the key call every model the gateway serves, unless the key belongs to a team, in which case the team's model list applies.

  2. Give the key to the application and make a request with it.

    curl -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer sk-9f3a2c7e41b8d605" \
    -H "Content-Type: application/json" \
    -d '{"model": "claude-sonnet-5-5", "messages": [{"role": "user", "content": "Hello"}]}'
  3. Inspect the key. Click the key's alias on Virtual Keys to open its detail view. The Overview tab shows Spend, Rate Limits and Models, and the Settings tab lists every stored field. Over the API call GET /key/info with the key's hash, which keeps the raw key out of URLs and access logs.

    curl "http://localhost:4000/key/info?key=d5345c0ecc68ae6295c69f91926b2bd379e25481a40c34b5884d157a9f65d8fa" \
    -H "Authorization: Bearer $SPANWAY_API_KEY"
  4. Change the key. On the Settings tab click Edit Settings, change Max Budget (USD) or Models and click Save Changes. Over the API send only the fields you want to change to POST /key/update.

    curl -X POST http://localhost:4000/key/update \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"key": "sk-9f3a2c7e41b8d605", "max_budget": 100, "models": ["claude-sonnet-5-5"]}'
  5. Rotate a key that leaked. Click Regenerate Key on the detail view, optionally type a Grace Period such as 24h so both secrets work during the cutover, and click Regenerate. Over the API call POST /key/regenerate. The key keeps its settings, budget and spend history and gets a new value. Regenerating needs a Spanway license, and without one the button is disabled and the route answers 403.

    curl -X POST http://localhost:4000/key/regenerate \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"key": "sk-9f3a2c7e41b8d605", "duration": "90d"}'
  6. Block or delete a key. In the key's actions menu click Block Key to stop its requests while keeping its spend history, and Unblock Key to let them through again. Delete Key asks you to type the alias and then removes the key for good. Over the API call POST /key/block, POST /key/unblock and POST /key/delete.

    curl -X POST http://localhost:4000/key/block \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"key": "sk-9f3a2c7e41b8d605"}'

    curl -X POST http://localhost:4000/key/delete \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"keys": ["sk-9f3a2c7e41b8d605"]}'

What you should see​

The key appears in the Virtual Keys table with an Active badge, its team and its Spend / Budget meter. Each request made with it adds to spend, which /key/info returns and the detail view charts. When spend reaches max_budget the gateway rejects further requests from the key with a budget exceeded error until the budget resets. A blocked key answers 401 on every request, and a deleted key stops working at once and stays visible under the Deleted status filter for audit and spend history. On a gateway with an Enterprise license, or with spanway_settings.store_audit_logs: true, every create, update, rotation, block, unblock, spend reset and delete writes an audit log row, see audit logs.

Fields​

FieldMeaning
key_aliasA readable name. Unique across all keys on the gateway, in every team. spanway_settings.enable_key_alias_format_validation or key_alias_pattern can also restrict its format, see key creation rules.
durationHow long the key is valid, such as 30s, 30m, 30h or 30d. Omit for a key that never expires.
modelsPublic model names or access groups the key may call.
max_budget, budget_durationSpend cap in US dollars and how often it resets.
soft_budgetSpend level that triggers an alert without blocking.
rpm_limit, tpm_limit, max_parallel_requestsRate limits across all models.
model_rpm_limit, model_tpm_limit, model_max_budgetPer-model limits and budgets, see users.
team_id, user_id, organization_id, project_idOwner of the key. Team, project and organization limits apply on top of the key.
access_group_idsAccess groups that grant models, MCP servers and agents.
guardrails, policiesGuardrails that always run for this key.
metadata, tagsFree-form data recorded in spend logs and usable for routing.
allowed_routes, allowed_ipsRoutes and client addresses the key may use, see access control and allow lists.
router_settingsRetries, fallbacks and routing overrides for this key, see key and team router settings.
keyBring your own key value. It must start with sk- and be at least 16 characters (MINIMUM_CUSTOM_KEY_LENGTH). Admins can turn custom values off with disable_custom_api_keys, see key creation rules.
enable_prompt_cachingOn: the gateway marks the reusable start of this key's prompts as cacheable for Claude on Anthropic, AWS Bedrock, Vertex AI and Azure AI, so a long prompt that repeats is billed at the cached rate. Off (the default): the key adds no cache marks of its own, while the gateway-wide prompt caching switch still applies. In the Admin UI it is Enable Prompt Caching on the key create and edit forms, see prompt caching.
throttle_on_budget_exceededOn: once the key is over its max_budget it keeps working at a reduced speed instead of being refused, at the share of its TPM and RPM limits set in spanway_settings.budget_exceeded_throttle_percentage. Needs a TPM or RPM limit on the key. Off (the default): an over-budget key is refused. Only proxy admins can turn it on.

Setting tags or team_member_key_duration on a key needs a license that includes the key_controls feature. The other fields are free. /key/list pages through keys with filters for team, user, organization and alias, and /key/bulk_update and /team/key/bulk_update change many keys in one call.

MethodPathSummary
GET/key/spend/reportSpend report for one key
POST/key/generateCreate a virtual key
POST/key/service-account/generateCreate a service account key for a team
POST/key/updateUpdate a virtual key
POST/key/bulk_updateUpdate several keys at once
POST/key/deleteDelete virtual keys
GET/key/infoGet a key's settings and spend
POST/key/regenerateRotate a virtual key
POST/key/{key}/regenerateRotate a virtual key
POST/key/{key}/reset_spendReset a key's recorded spend
GET/key/listList virtual keys
GET/key/aliasesList the key aliases the caller can see
POST/key/blockBlock a key
POST/key/unblockUnblock a key
POST/key/healthCheck a key's logging settings
GET/key/hygiene/summaryCount the keys each hygiene finding flags
GET/key/hygieneList the keys with one hygiene finding

Key creation rules​

A proxy admin can decide who may create keys and what every key must look like. These settings live in config.yaml and are listed with their defaults in the settings reference.

spanway_settings:
default_key_generate_params:
max_budget: 10
upperbound_key_generate_params:
max_budget: 100
duration: 90d
key_generation_settings:
personal_key_generation:
allowed_user_roles: ["proxy_admin"]
team_key_generation:
allowed_team_member_roles: ["admin"]
required_params: ["tags"]
enable_key_alias_format_validation: true
general_settings:
disable_custom_api_keys: true
disable_key_generate_for_org_admin: false
SettingWhat it does
default_key_generate_paramsFills in values a new key request leaves out, so every key starts with a budget.
upperbound_key_generate_paramsRefuses a key whose max_budget, budget_duration, duration, tpm_limit or rpm_limit is above the cap, with 400 <field> is over max limit set in config - user_value=...; max_value=....
key_generation_settings.personal_key_generation.allowed_user_rolesOnly these roles may create keys that belong to no team. Others get 403 Personal key creation has been restricted by admin....
key_generation_settings.team_key_generation.allowed_team_member_rolesOnly these team roles may create team keys.
required_paramsFields every new key must carry, under either setting above.
enable_key_alias_format_validation, key_alias_patternMake every key_alias match the built-in safe pattern or your own regular expression. A mismatch is 400 Invalid key_alias format....
disable_custom_api_keysOn: every key value is generated, and sending key is 403. Off (the default): callers may bring their own sk- value.
disable_key_generate_for_org_adminOn: organization admins cannot create keys, they get 403 key generation is disabled for org admins. Contact your proxy admin. Off (the default): they can.

Scheduled key rotation​

A key with auto_rotate: true and a rotation_interval such as 30d gets a new value on a schedule, so a leaked copy stops working without anyone having to notice the leak. Set both on /key/generate or /key/update, or turn on Enable Auto-Rotation under Key Lifecycle when you create or edit a key in the Admin UI.

curl -X POST http://localhost:4000/key/update \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"key": "sk-9f3a2c7e41b8d605", "auto_rotate": true, "rotation_interval": "30d"}'

Scheduled rotation needs a Spanway license, like /key/regenerate. Without one, auto_rotate: true is refused with a 403 and the Admin UI switch is disabled with a note saying why. A key that already rotates can still be switched off. The rotation job only runs when SPANWAY_KEY_ROTATION_ENABLED=true is set on the gateway, and checks for keys that are due every SPANWAY_KEY_ROTATION_CHECK_INTERVAL_SECONDS (one day by default). When SPANWAY_KEY_ROTATION_GRACE_PERIOD is set, for example 24h, the old value keeps working for that long after a rotation, so clients have time to pick up the new one. Each rotation emits a key.rotated event, and a rotation that fails, for example because the license lapsed, emits key.rotation_failed and is retried on the next check. When the gateway writes keys to a secret manager (store_virtual_keys: true with an access_mode of write_only or read_and_write), a key that rotates needs a key_alias so its stored secret keeps a stable name. Otherwise /key/generate answers 400 with key_alias is required when auto_rotate=True and store_virtual_keys is enabled. With the default read_only access mode nothing is written to the store, so no alias is needed.

CI jobs and cloud workloads that already have an OIDC identity can trade it for a virtual key that expires after a few minutes, so no long-lived key has to be stored for them. See workload identity federation.

Managing auth - upgrade/downgrade models​

The aliases field maps a model name the client sends to a different model group, for one key only. This lets you move a single application to a newer model, or downgrade a noisy client to a cheaper model, without changing its code.

curl -X POST http://localhost:4000/key/generate \
-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"models": ["claude-haiku-5-5"], "aliases": {"claude-sonnet-5-5": "claude-haiku-5-5"}}'

A request from this key for claude-sonnet-5-5 is served by claude-haiku-5-5. Aliases are applied on top of the router's model_group_alias.

Managing auth - tracking spend​

Every request records its cost against the key, its user, team, organization and end user. /key/info returns the running spend, and /spend/logs returns per-request rows with model, tokens, cost and metadata.

curl "http://localhost:4000/spend/logs?api_key=sk-9f3a2c7e41b8d605&start_date=2026-11-01&end_date=2026-11-21" \
-H "Authorization: Bearer $SPANWAY_API_KEY"

Costs come from the bundled price map or your custom pricing. See cost tracking for reports by team, tag and model.

Custom auth​

If your organisation already has an auth system, you can replace key checking with your own function. Point general_settings.custom_auth at a Python function that receives the request and the presented key and returns a UserAPIKeyAuth object, or raises to reject the call.

general_settings:
custom_auth: custom_auth.user_api_key_auth

The function runs on every request, so keep it fast and cache lookups. The full contract and modes are on the custom auth page.

Errors​

ErrorCauseFix
401 Authentication Error, Invalid proxy server token passedThe key does not exist or was deleted.Check the key with /key/info, or create a new one.
401 Authentication Error, Key is blocked. Update via /key/unblock if you're an admin.An admin blocked the key, for example after a leak.Ask an admin to unblock it with /key/unblock, or use another key.
401 with expired in the messageThe key passed its expires date.Regenerate it with a new duration, or create a new key.
422 Budget has been exceeded! with type budget_exceeded, the current cost and max budgetThe key, its team, project or user spent its budget. The status is 429 when spanway_settings.budget_exceeded_status_code is 429.Raise max_budget, wait for the reset, or use Reset Spend on the key.
401 or 403 naming a modelThe model is not in the key's models, or the team's list does not allow it.Add the model to the key, or to the team with /team/model/add.
429 Max parallel request limit reached or a rate limit messagerpm_limit, tpm_limit or max_parallel_requests was hit.Raise the limit or slow the client down.
400 Key with alias '<alias>' already exists. Unique key aliases across all keys are required.Another key, in any team, has the alias.Pick a different key_alias.
403 naming a key management route and a teamA team member called a route the team's member permissions do not allow.Ask a team admin to allow it, see team member permissions.
403 on /key/regenerate or auto_rotateThe gateway has no Spanway license.Add a license, or delete the key and create a new one.
400 Invalid key formatA bring-your-own key does not start with sk-.Prefix the value with sk-.
400 Invalid key format. Spanway Virtual Key must be at least 16 characters long.A bring-your-own key is too short.Use a longer value.
403 Custom API key values are disabled by your administrator. Keys must be auto-generated.disable_custom_api_keys is on.Leave key out and let the gateway generate one.
403 Personal key creation has been restricted by admin. Allowed roles=[...]. Your role=...key_generation_settings.personal_key_generation does not include your role.Create the key in a team, or ask a proxy admin.
403 Only proxy admins can enable throttle_on_budget_exceeded on a key.A non admin sent throttle_on_budget_exceeded: true.Ask a proxy admin.
403 Only proxy admins can bind a key to an agent or change the agent of a key (`agent_id`).A non admin sent agent_id on a new key, or changed it on an existing one. A key bound to an agent uses that agent's stored credentials, so binding is an admin decision.Ask a proxy admin to create the agent's key.
400 <field> is over max limit set in config - user_value=...; max_value=...The value is above upperbound_key_generate_params.Use a lower value.
400 Allocated RPM limit=... + Key RPM limit=... is greater than team RPM limit=... (also TPM)The team's or project's limit is already shared out to other keys.Lower the key's limit or raise the team's.
400 <field> is immutable once set and cannot be changed via update.The update tried to change a field that cannot change after creation.Create a new key instead.
400 metadata.workload_identity is reserved for keys issued by workload identity federation and cannot be set by hand.The request put a workload_identity entry in a key's metadata. Only workload identity federation may set it, because the cleanup job deletes expired keys that carry it.Remove the entry, or use a different metadata name.
400 User ids that start with workload_identity: are reserved for workload identity federation and cannot create keys.The caller's user id starts with the prefix that marks keys made by workload identity federation.Create the key as a user whose id does not start with workload_identity:.
400 Invalid duration format: <value>. Use a number followed by s, m, h, d, w or mo, for example 30dduration or rotation_interval cannot be read.Send a value such as 90d.
400 reset_to must be >= 0, reset_to (...) must be <= current spend (...) or ... must be <= budget (...)POST /key/{key}/reset_spend got a value outside the allowed range.Send a value between 0 and the key's current spend.
400 Not all keys passed in were deleted. ...Some keys in a /key/delete call do not exist or belong to someone else.Check the list, the others were not deleted.

Logs​

LevelLineMeaningAction
WARNINGCustom API key rejected: disable_custom_api_keys is enabledSomeone sent their own key value while only generated keys are allowed.None, the caller got a 403.
ERRORspanway.proxy.proxy_server.generate_key_fn(): Exception occured - <error>Creating a key failed or was refused.None for a 4xx you expected, check the database for a 500.
WARNINGFailed to send key created email: <error>The key was created, but the email to its owner was not sent.Check the email settings.
WARNINGFailed to rotate virtual key in secret manager: <error> or Failed to rename virtual key in secret manager: <error>The key changed in the gateway but not in your secret manager.Check the secret manager credentials and rotate or rename the key again.

See the log reference.