Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions docs/bdd/self-service-api-key-usage.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
Feature: Self-service API key usage and account quota visibility

Background:
Given OmniRoute has usage accounting enabled
And management APIs require a dashboard session or a key with "manage" or "admin"

Scenario: A delegated key reads its own cost and token usage
Given an API key named "team-a" has the scope "self:usage"
And "team-a" already has a monthly USD budget of 50 configured in the existing budget UI
And "team-a" has current-period spend of 12.50 USD
And "team-a" has current-period token usage:
| input | output | cache_read | cache_creation | reasoning |
| 900000 | 32000 | 120000 | 10000 | 5000 |
When "team-a" calls GET "/api/v1/me/status" with its Bearer token
Then the response status should be 200
And the response apiKey.name should be "team-a"
And the response usage.cost.limitUsd should be 50
And the response usage.cost.usedUsd should be 12.50
And the response usage.cost.usedPercent should be 25
And the response usage.tokens.totalTokens should be 1067000

Scenario: A delegated key cannot query another key by id
Given an API key named "team-a" has the scope "self:usage"
And an API key named "team-b" has the scope "self:usage"
And "team-b" has current-period spend of 99.00 USD
When "team-a" calls GET "/api/v1/me/status?apiKeyId=<team-b-id>" with its Bearer token
Then the response status should be 200
And the response apiKey.name should be "team-a"
And the response should not contain "team-b"
And the response should not contain "99.00" as team-b usage

Scenario: Anonymous client API mode does not expose self-service status
Given global client API auth allows anonymous local traffic
When an anonymous caller calls GET "/api/v1/me/status"
Then the response status should be 401

Scenario: Self-service usage scope does not grant management access
Given an API key named "team-a" has the scope "self:usage"
And "team-a" does not have the scope "manage"
And "team-a" does not have the scope "admin"
When "team-a" calls GET "/api/usage/history" with its Bearer token
Then the response status should be 403

Scenario: Own usage visibility can be disabled
Given an API key named "team-a" does not have the scope "self:usage"
When "team-a" calls GET "/api/v1/me/status" with its Bearer token
Then the response status should be 403

Scenario: Existing ordinary keys are backfilled for own usage visibility
Given an ordinary API key named "legacy-key" existed before self-service usage scopes
And "legacy-key" does not have the scope "self:usage"
When OmniRoute runs the compatibility migration
Then "legacy-key" should have the scope "self:usage"
And "legacy-key" should not have the scope "self:account-quota"

Scenario: Shared account quota is hidden by default
Given an API key named "team-a" has the scope "self:usage"
And "team-a" does not have the scope "self:account-quota"
And "team-a" is restricted to a Codex connection with available quota
When "team-a" calls GET "/api/v1/me/status" with its Bearer token
Then the response status should be 200
And the response should not include shared account quota details

Scenario: Shared Codex account quota is visible with explicit permission
Given an API key named "team-a" has the scope "self:usage"
And "team-a" has the scope "self:account-quota"
And "team-a" is restricted to exactly one Codex connection
And Codex reports a session quota with 1 percent used
And Codex reports a weekly quota with 97 percent used
When "team-a" calls GET "/api/v1/me/status" with its Bearer token
Then the response status should be 200
And the response accountQuota.provider should be "codex"
And the response accountQuota.shared should be true
And the response accountQuota.quotas.session.remainingPercentage should be 99
And the response accountQuota.quotas.weekly.remainingPercentage should be 3

Scenario: Account quota is not guessed for multi-connection keys
Given an API key named "team-a" has the scope "self:usage"
And "team-a" has the scope "self:account-quota"
And "team-a" is allowed to use two provider connections
When "team-a" calls GET "/api/v1/me/status" with its Bearer token
Then the response status should be 200
And the response accountQuota.available should be false
And the response accountQuota.reason should be "ambiguous_connection"

Scenario: Account quota is not guessed for unrestricted connection keys
Given an API key named "team-a" has the scope "self:usage"
And "team-a" has the scope "self:account-quota"
And "team-a" has no explicit allowed connection restrictions
When "team-a" calls GET "/api/v1/me/status" with its Bearer token
Then the response status should be 200
And the response accountQuota.available should be false
And the response accountQuota.reason should be "ambiguous_connection"

Scenario: Existing budget endpoint stays management-only
Given an API key named "team-a" has the scope "self:usage"
And "team-a" does not have the scope "manage"
When "team-a" calls GET "/api/usage/budget?apiKeyId=<another-key-id>" with its Bearer token
Then the response status should be 403

Scenario: API Manager defaults are privacy-preserving
Given an operator opens the create API key dialog
Then the own cost and token usage visibility control should be checked
And the shared account quota visibility control should be unchecked
And management access should be unchecked
And the dialog should not include a second budget editor

Scenario: API Manager preserves unrelated scopes
Given an API key has scopes:
| scope |
| self:usage |
| custom:scope |
When an operator enables shared account quota in the permissions dialog
And saves the permissions
Then the API key scopes should include "self:usage"
And the API key scopes should include "self:account-quota"
And the API key scopes should include "custom:scope"

Scenario: API Manager uses existing budget configuration
Given an operator wants to set a monthly USD budget for an API key
When the operator uses the dashboard
Then the operator should use the existing budget configuration surface
And the create key dialog should not save budget limits

Scenario: New API Manager text is localized
Given the dashboard locale is not English
When the API Manager renders self-service visibility controls
Then the labels should come from the API Manager translation namespace
And the component should not render hard-coded English strings for the new controls
65 changes: 65 additions & 0 deletions docs/openspec/changes/self-service-api-key-usage/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Change: Self-Service API Key Usage and Quota Visibility

## Summary

Add a client-facing self-service status endpoint and dashboard controls that let each OmniRoute API key inspect its own USD usage, token usage, and percent used against its existing USD budget configuration. Optionally expose shared upstream account quota when an operator grants a dedicated per-key scope.

## Motivation

OmniRoute can route multiple delegated API keys through one upstream coding account. Operators need per-key accountability without giving every delegated key management access. Existing management usage APIs are too broad for delegated clients because they can expose other keys and operational state.

This change creates a narrow own-key API and UI controls:

- Own cost and token usage are visible by default for ordinary new keys.
- Shared account quota remains opt-in because it is account-level and sensitive.
- USD budgets remain the enforcement mechanism; token totals are reporting only.

## Scope

In scope:

- New `GET /api/v1/me/status` endpoint authenticated by normal Bearer API key.
- New self-service API key scopes: `self:usage` and `self:account-quota`.
- Per-key cost and token aggregation for the calling key.
- Optional normalized provider account quota for unambiguous single-connection keys.
- API Manager create/edit controls for visibility scopes.
- Reuse the existing budget configuration surface for USD limits.
- i18n message keys for all new dashboard text.
- Tests and docs for the new behavior.

Out of scope:

- Token quota enforcement.
- Cross-key reporting through the self-service endpoint.
- Changing management usage APIs.
- Changing provider routing or quota preflight behavior.
- Raw upstream quota payload exposure.
- A second budget editor inside key creation or permissions dialogs.

## Compatibility

Existing keys should continue to work. A migration or first-start normalization step should backfill `self:usage` onto existing ordinary keys so they receive the same default own-usage visibility as newly created keys. Existing keys must not receive shared account quota visibility unless `self:account-quota` is explicitly granted.

The new scopes must not grant management access. Only `manage` and `admin` remain management-grade.

## Risks

- Scope editing in the current dashboard can collapse scopes to only management access; implementation must preserve unrelated scopes.
- Shared account quota can reveal account exhaustion; it must remain disabled by default.
- Multi-connection and unrestricted-connection keys are ambiguous; first implementation should decline account quota rather than guessing.
- Backfill must be idempotent so upgrades do not repeatedly rewrite API keys or re-enable a permission an operator later disabled.
- New UI text can regress non-English dashboards if translation keys are not added consistently.
- The current scope validation cap is 16 entries; adding self-service scopes may require raising that cap.
- The current `/api/usage/budget` route relies on route-level authz rather than handler-level `requireManagementAuth()`, so the PR should harden it or explicitly test the proxy guard.

## Rollout

1. Add constants, validation, and helper tests.
2. Raise or otherwise adapt scope validation limits.
3. Add idempotent existing-key backfill for `self:usage`.
4. Harden `/api/usage/budget` with handler-level management auth or add explicit proxy-guard tests.
5. Add self-service status endpoint.
6. Add create/edit dashboard controls.
7. Add i18n message keys for dashboard text.
8. Add API/reference docs.
9. Verify against release branch used for upstream PR.
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
# Specification: API Key Self-Service Usage

## ADDED Requirements

### Requirement: Self-service status endpoint

OmniRoute SHALL provide `GET /api/v1/me/status` for a valid Bearer API key to retrieve status for that same API key.

#### Scenario: Valid key reads own status

- GIVEN a valid API key with own-usage visibility
- WHEN it calls `GET /api/v1/me/status`
- THEN the response status SHALL be `200`
- AND the response SHALL include the API key id and name
- AND the response SHALL include cost usage for that key
- AND the response SHALL include token usage for that key

#### Scenario: Invalid key is rejected

- GIVEN a missing or invalid Bearer token
- WHEN the caller calls `GET /api/v1/me/status`
- THEN the response status SHALL be `401`

#### Scenario: Anonymous client API mode does not bypass self-service auth

- GIVEN global client API auth allows anonymous local traffic
- WHEN a caller without a Bearer API key calls `GET /api/v1/me/status`
- THEN the response status SHALL be `401`

#### Scenario: Environment management key is not a self-service key

- GIVEN the deployment has an environment management key
- WHEN that key calls `GET /api/v1/me/status`
- THEN the response SHALL NOT expose delegated API key usage

### Requirement: Own-key isolation

The self-service endpoint SHALL derive the API key id from the authenticated Bearer key and SHALL NOT accept caller-supplied key ids for lookup.

#### Scenario: Caller tries to query another key

- GIVEN API key A and API key B both have usage
- WHEN API key A calls `GET /api/v1/me/status?apiKeyId=<key-b-id>`
- THEN the response SHALL contain only API key A identity and usage
- AND the response SHALL NOT contain API key B usage

### Requirement: USD budget status

The self-service endpoint SHALL report per-key USD budget usage using the existing budget system.

#### Scenario: Key has an active monthly budget

- GIVEN an API key has a monthly USD budget of `50`
- AND the key has current-period cost of `12.50`
- WHEN the key calls the self-service status endpoint
- THEN `usage.cost.limitUsd` SHALL be `50`
- AND `usage.cost.usedUsd` SHALL be `12.50`
- AND `usage.cost.usedPercent` SHALL be `25`
- AND `usage.cost.remainingUsd` SHALL be `37.50`

#### Scenario: Key has no budget

- GIVEN an API key has no configured budget
- WHEN the key calls the self-service status endpoint
- THEN `usage.cost.limitUsd` SHALL be `null`
- AND `usage.cost.usedPercent` SHALL be `null`
- AND cost and token totals SHALL still be returned for the default display period

### Requirement: Token usage reporting

The self-service endpoint SHALL report token totals from `usage_history` for the authenticated API key and selected reporting period.

#### Scenario: Token totals include all tracked categories

- GIVEN an API key has usage rows with input, output, cache read, cache creation, and reasoning tokens
- WHEN the key calls the self-service status endpoint
- THEN the response SHALL include each token category total
- AND `totalTokens` SHALL include all reported token categories

### Requirement: Self-service scopes

OmniRoute SHALL support `self:usage` and `self:account-quota` API key scopes. These scopes SHALL NOT grant management API access.

#### Scenario: Self-service scope is not management

- GIVEN an API key has `self:usage`
- AND it does not have `manage` or `admin`
- WHEN it calls a management usage endpoint
- THEN the response SHALL be forbidden

#### Scenario: New key defaults

- GIVEN an operator opens the create API key UI
- THEN own cost and token usage visibility SHALL be enabled by default
- AND shared account quota visibility SHALL be disabled by default

#### Scenario: Existing keys receive own-usage visibility on upgrade

- GIVEN an ordinary API key existed before this feature
- AND it does not have `self:usage`
- WHEN the compatibility migration or startup normalization runs
- THEN the API key SHALL have `self:usage`
- AND the API key SHALL NOT have `self:account-quota`

#### Scenario: Key without own-usage scope is denied

- GIVEN a valid API key does not have `self:usage`
- WHEN it calls `GET /api/v1/me/status`
- THEN the response status SHALL be `403`

### Requirement: Shared account quota permission

The self-service endpoint SHALL include shared account quota only when the authenticated key has `self:account-quota`.

#### Scenario: Account quota hidden by default

- GIVEN a valid API key has own-usage visibility
- AND it does not have `self:account-quota`
- WHEN it calls the self-service endpoint
- THEN the response SHALL NOT include shared account quota details

#### Scenario: Codex quota shown with explicit permission

- GIVEN a valid API key has `self:account-quota`
- AND it is restricted to exactly one Codex connection
- AND Codex quota data is available
- WHEN it calls the self-service endpoint
- THEN the response SHALL include normalized `session` and `weekly` quota windows
- AND each window SHALL include used percentage, remaining percentage, and reset timestamp when known

#### Scenario: Multiple connections are ambiguous

- GIVEN a valid API key has `self:account-quota`
- AND it is allowed to use more than one connection
- WHEN it calls the self-service endpoint
- THEN `accountQuota.available` SHALL be `false`
- AND `accountQuota.reason` SHALL be `ambiguous_connection`

#### Scenario: Unrestricted connections are ambiguous

- GIVEN a valid API key has `self:account-quota`
- AND its `allowedConnections` list is empty, meaning all connections are allowed
- WHEN it calls the self-service endpoint
- THEN `accountQuota.available` SHALL be `false`
- AND `accountQuota.reason` SHALL be `ambiguous_connection`

### Requirement: Dashboard configuration

The API Manager SHALL allow operators to configure self-service visibility and SHALL reuse the existing budget configuration surface for USD limits.

#### Scenario: Edit preserves unrelated scopes

- GIVEN an API key has scopes `["self:usage", "custom:scope"]`
- WHEN an operator enables shared account quota in the permissions UI
- THEN the saved scopes SHALL include `self:usage`
- AND the saved scopes SHALL include `self:account-quota`
- AND the saved scopes SHALL still include `custom:scope`

#### Scenario: Budget editing remains in existing budget UI

- GIVEN an operator wants to change a key's USD budget limit
- WHEN they use the dashboard
- THEN OmniRoute SHALL direct them to the existing budget configuration surface
- AND the create-key dialog SHALL NOT introduce a second budget editor

#### Scenario: No budget is displayed as not configured

- GIVEN an API key has no configured budget
- WHEN the API Manager shows self-service usage for that key
- THEN the UI SHALL show usage and token totals
- AND the budget limit, remaining amount, and percent SHALL be shown as not configured

### Requirement: Dashboard internationalization

All new API Manager text for self-service usage visibility, shared account quota visibility, and no-budget display SHALL use OmniRoute's existing i18n message system.

#### Scenario: New UI strings use translation keys

- GIVEN the API Manager renders the new self-service controls
- THEN labels, descriptions, tooltips, empty states, and errors SHALL come from translation keys
- AND no new user-visible dashboard text SHALL be hard-coded in the component

#### Scenario: Locale files stay structurally compatible

- GIVEN new API Manager translation keys are added
- WHEN the translation consistency check runs
- THEN supported locale message files SHALL have compatible key structure

### Requirement: Existing budget management remains protected

The existing `/api/usage/budget` management endpoint SHALL NOT become an own-key self-service data source.

#### Scenario: Self-service key cannot read arbitrary budget endpoint

- GIVEN an API key has `self:usage`
- AND it does not have `manage` or `admin`
- WHEN it calls `/api/usage/budget?apiKeyId=<another-key-id>`
- THEN the response SHALL be rejected by management auth
Loading