Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Account-wide API rate limits on top of the per-token ones, a cap on active tokens per account and a configurable limiter storage (#484)

Murtaza Nasirc3379310ae38
diff --git a/config/env.asr.example b/config/env.asr.example
index 8a283801..88b8da77 100644
--- a/config/env.asr.example
+++ b/config/env.asr.example
@@ -398,6 +398,22 @@ MAX_CONCURRENT_UPLOADS=3
# API_TOKEN_RATE_LIMIT_READ=120 per minute
# API_TOKEN_RATE_LIMIT_WRITE=30 per minute
# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute
+#
+# Account limits: all tokens of one user share one budget per kind, so another
+# token adds no throughput. Default: twice the token limit of the same kind.
+# API_USER_RATE_LIMIT_READ=240 per minute
+# API_USER_RATE_LIMIT_WRITE=60 per minute
+# API_USER_RATE_LIMIT_PROCESS=20 per minute
+#
+# Active API tokens one account may hold; 0 means no limit. Default: 10.
+# API_MAX_TOKENS_PER_USER=10
+#
+# Shared storage for the rate-limit counters. By default each gunicorn worker
+# (three in the standard image) counts in its own memory, so every limit,
+# login and registration included, allows up to about three times its value.
+# A Redis or Memcached URI makes the limits exact; the image needs the redis
+# or pymemcache Python package for it.
+# RATELIMIT_STORAGE_URI=redis://redis:6379/0
# Set to true only when the text, chat and embedding models all run on machines
# you control. API clients read it from /api/v1/capabilities (models_local).
diff --git a/config/env.transcription.example b/config/env.transcription.example
index 031d167a..031bffe7 100644
--- a/config/env.transcription.example
+++ b/config/env.transcription.example
@@ -566,6 +566,22 @@ MAX_CONCURRENT_UPLOADS=3
# API_TOKEN_RATE_LIMIT_READ=120 per minute
# API_TOKEN_RATE_LIMIT_WRITE=30 per minute
# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute
+#
+# Account limits: all tokens of one user share one budget per kind, so another
+# token adds no throughput. Default: twice the token limit of the same kind.
+# API_USER_RATE_LIMIT_READ=240 per minute
+# API_USER_RATE_LIMIT_WRITE=60 per minute
+# API_USER_RATE_LIMIT_PROCESS=20 per minute
+#
+# Active API tokens one account may hold; 0 means no limit. Default: 10.
+# API_MAX_TOKENS_PER_USER=10
+#
+# Shared storage for the rate-limit counters. By default each gunicorn worker
+# (three in the standard image) counts in its own memory, so every limit,
+# login and registration included, allows up to about three times its value.
+# A Redis or Memcached URI makes the limits exact; the image needs the redis
+# or pymemcache Python package for it.
+# RATELIMIT_STORAGE_URI=redis://redis:6379/0
# Files one account can send through the phone's share sheet (installed PWA).
# Default: 20 per hour.
diff --git a/config/env.whisper.example b/config/env.whisper.example
index 29537c5b..ea1a6f39 100644
--- a/config/env.whisper.example
+++ b/config/env.whisper.example
@@ -394,6 +394,22 @@ MAX_CONCURRENT_UPLOADS=3
# API_TOKEN_RATE_LIMIT_READ=120 per minute
# API_TOKEN_RATE_LIMIT_WRITE=30 per minute
# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute
+#
+# Account limits: all tokens of one user share one budget per kind, so another
+# token adds no throughput. Default: twice the token limit of the same kind.
+# API_USER_RATE_LIMIT_READ=240 per minute
+# API_USER_RATE_LIMIT_WRITE=60 per minute
+# API_USER_RATE_LIMIT_PROCESS=20 per minute
+#
+# Active API tokens one account may hold; 0 means no limit. Default: 10.
+# API_MAX_TOKENS_PER_USER=10
+#
+# Shared storage for the rate-limit counters. By default each gunicorn worker
+# (three in the standard image) counts in its own memory, so every limit,
+# login and registration included, allows up to about three times its value.
+# A Redis or Memcached URI makes the limits exact; the image needs the redis
+# or pymemcache Python package for it.
+# RATELIMIT_STORAGE_URI=redis://redis:6379/0
# Set to true only when the text, chat and embedding models all run on machines
# you control. API clients read it from /api/v1/capabilities (models_local).
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
index 3e72a9ea..90728e01 100644
--- a/config/env.whisperx.example
+++ b/config/env.whisperx.example
@@ -309,6 +309,22 @@ MAX_CONCURRENT_UPLOADS=3
# API_TOKEN_RATE_LIMIT_READ=120 per minute
# API_TOKEN_RATE_LIMIT_WRITE=30 per minute
# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute
+#
+# Account limits: all tokens of one user share one budget per kind, so another
+# token adds no throughput. Default: twice the token limit of the same kind.
+# API_USER_RATE_LIMIT_READ=240 per minute
+# API_USER_RATE_LIMIT_WRITE=60 per minute
+# API_USER_RATE_LIMIT_PROCESS=20 per minute
+#
+# Active API tokens one account may hold; 0 means no limit. Default: 10.
+# API_MAX_TOKENS_PER_USER=10
+#
+# Shared storage for the rate-limit counters. By default each gunicorn worker
+# (three in the standard image) counts in its own memory, so every limit,
+# login and registration included, allows up to about three times its value.
+# A Redis or Memcached URI makes the limits exact; the image needs the redis
+# or pymemcache Python package for it.
+# RATELIMIT_STORAGE_URI=redis://redis:6379/0
# Set to true only when the text, chat and embedding models all run on machines
# you control. API clients read it from /api/v1/capabilities (models_local).
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.md
index 2b7ab657..b8603382 100644
--- a/docs/user-guide/api-reference.md
+++ b/docs/user-guide/api-reference.md
@@ -2042,15 +2042,34 @@ All endpoints return consistent error responses:
## Rate Limits
-Requests made with an API token are limited per token, so two integrations on the same machine do not share a limit. Each token has one budget per kind of request:
+Requests made with an API token are held by two limits for each kind of request:
-| Kind | Endpoints | Default limit | Setting |
-|------|-----------|---------------|---------|
-| Read | Endpoints that need only `read` | 120 requests/minute | `API_TOKEN_RATE_LIMIT_READ` |
-| Write | Endpoints that need `write`, `upload`, `share`, `delete`, `webhooks` or `account` | 30 requests/minute | `API_TOKEN_RATE_LIMIT_WRITE` |
-| Process | Endpoints that need `process` | 10 requests/minute | `API_TOKEN_RATE_LIMIT_PROCESS` |
+- **Token limit.** Each token has its own budget, counted separately for each endpoint, so two integrations with their own tokens do not share it.
+- **Account limit.** All tokens of one account draw on one budget across all endpoints, so a further token adds no throughput.
-The limits apply to full-access and scoped tokens alike. A request over the limit gets `429` with a `Retry-After` header in seconds, and responses carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`. Requests from the web interface keep the per-address limits of the application.
+| Kind | Endpoints | Token limit | Account limit |
+|------|-----------|-------------|---------------|
+| Read | Endpoints that need only `read` | 120 requests/minute (`API_TOKEN_RATE_LIMIT_READ`) | 240 requests/minute (`API_USER_RATE_LIMIT_READ`) |
+| Write | Endpoints that need `write`, `upload`, `share`, `delete`, `webhooks` or `account` | 30 requests/minute (`API_TOKEN_RATE_LIMIT_WRITE`) | 60 requests/minute (`API_USER_RATE_LIMIT_WRITE`) |
+| Process | Endpoints that need `process` | 10 requests/minute (`API_TOKEN_RATE_LIMIT_PROCESS`) | 20 requests/minute (`API_USER_RATE_LIMIT_PROCESS`) |
+
+An account limit that is not set is twice the token limit of the same kind, so a client with a single token on one endpoint is held by its token limit. The limits apply to full-access and scoped tokens alike. A request that the token limit refuses does not count against the account limit.
+
+A request over a limit gets `429` with a `Retry-After` header in seconds. The body names the limit that ran out:
+
+```json
+{
+ "error": "Rate limit reached for your account: 240 per minute (read requests), shared by all your API tokens.",
+ "code": "account_rate_limit_exceeded",
+ "limit": "240 per 1 minute"
+}
+```
+
+`code` is `token_rate_limit_exceeded` for the token limit and `account_rate_limit_exceeded` for the account limit. Responses also carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`; while no limit is exceeded, these headers describe the token limit only. Base a client on the `429` body, not on the header values.
+
+Requests from the web interface keep the per-address limits of the application (1000 per hour and 5000 per day). The [ASR Voice Recorder upload](#asr-voice-recorder-upload) carries its token in the form body, so neither limit applies to it; that endpoint keeps its own per-address limit.
+
+**Several worker processes.** By default each worker process keeps its own counters in memory. The standard image runs three gunicorn workers, so every limit, the login and registration limits included, allows up to about three times its configured value. Set `RATELIMIT_STORAGE_URI` to a shared backend, for example `redis://redis:6379/0` or `memcached://memcached:11211`, to make the limits exact. The standard image does not include the client library for either backend; an image that uses one needs the `redis` or `pymemcache` Python package, and Speakr does not start with a backend URI whose client is missing. While the backend is unreachable, counting falls back to memory in each process.
---
diff --git a/docs/user-guide/api-tokens.md b/docs/user-guide/api-tokens.md
index 8a998485..9a91eaf5 100644
--- a/docs/user-guide/api-tokens.md
+++ b/docs/user-guide/api-tokens.md
@@ -203,6 +203,21 @@ Click the trash icon next to any token to revoke it immediately. Revoked tokens:
!!! tip "Best Practice"
Revoke tokens you no longer need. If you suspect a token has been compromised, revoke it immediately and create a new one.
+## Limits
+
+By default an account can hold up to 10 active tokens. Revoked and expired tokens do not count, and revoking a token frees its slot at once. Creating a token beyond the limit gives `409` with `"code": "token_limit_reached"`.
+
+Requests made with a token are held by a limit for the token and by a limit for the whole account, so spreading work over more tokens adds no throughput. [Rate Limits](api-reference.md#rate-limits) lists the values.
+
+Administrators set these limits with environment variables:
+
+| Variable | Default | Meaning |
+|----------|---------|---------|
+| `API_MAX_TOKENS_PER_USER` | `10` | Active tokens per account; `0` means no limit. Tokens above a lowered limit keep working. |
+| `API_TOKEN_RATE_LIMIT_READ`, `API_TOKEN_RATE_LIMIT_WRITE`, `API_TOKEN_RATE_LIMIT_PROCESS` | `120 per minute`, `30 per minute`, `10 per minute` | Budget of each token, per endpoint. |
+| `API_USER_RATE_LIMIT_READ`, `API_USER_RATE_LIMIT_WRITE`, `API_USER_RATE_LIMIT_PROCESS` | Twice the token limit of the same kind | Budget that all tokens of an account share across endpoints. |
+| `RATELIMIT_STORAGE_URI` | Memory of each worker process | Shared storage for the counters, such as `redis://redis:6379/0`. Without it, each of the three worker processes of the standard image counts separately, so a limit allows up to about three times its value. |
+
## Security Best Practices
### Do's
@@ -282,9 +297,13 @@ curl -s -H "Authorization: Bearer $TOKEN" \
- Check if the recording belongs to your account
- With `"code": "insufficient_scope"`, the token lacks a scope the route needs. The answer lists `required_scopes` and the token's own `token_scopes`. Create a token with the missing scope.
+### 409 Conflict When Creating a Token
+
+- With `"code": "token_limit_reached"`, the account already holds the maximum number of active tokens (`API_MAX_TOKENS_PER_USER`, default 10; `0` means no limit). Revoked and expired tokens do not count. Revoke a token you no longer use, and the slot is free at once. Tokens created before an administrator lowered the limit keep working.
+
### 429 Too Many Requests
-- The token sent more requests than its limit allows (see [Rate Limits](api-reference.md#rate-limits)). Wait the number of seconds in the `Retry-After` header.
+- With `"code": "token_rate_limit_exceeded"`, the token sent more requests than its own limit allows. With `"code": "account_rate_limit_exceeded"`, all tokens of the account together reached the account limit, and another token does not help (see [Rate Limits](api-reference.md#rate-limits)). Wait the number of seconds in the `Retry-After` header.
---
diff --git a/src/api/tokens.py b/src/api/tokens.py
index 36304a26..1500714c 100644
--- a/src/api/tokens.py
+++ b/src/api/tokens.py
@@ -5,6 +5,7 @@ This blueprint handles creating, listing, and revoking API tokens
for user authentication.
"""
+import os
import secrets
from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify
@@ -17,6 +18,13 @@ from src.utils.token_auth import hash_token
# Create blueprint
tokens_bp = Blueprint('tokens', __name__, url_prefix='/api/tokens')
+# Active tokens an account may hold (#484); 0 means no limit. Tokens an
+# account already holds above the limit stay valid.
+try:
+ API_MAX_TOKENS_PER_USER = max(0, int(os.environ.get('API_MAX_TOKENS_PER_USER', '10')))
+except ValueError:
+ API_MAX_TOKENS_PER_USER = 10
+
# Extensions (injected after app initialization)
bcrypt = None
csrf = None
@@ -111,6 +119,20 @@ def create_token():
if error:
return jsonify({'error': error, 'code': 'invalid_parameter'}), 400
+ if API_MAX_TOKENS_PER_USER:
+ now = datetime.utcnow()
+ active = (APIToken.query.filter_by(user_id=current_user.id, revoked=False)
+ .filter(db.or_(APIToken.expires_at.is_(None), APIToken.expires_at > now))
+ .count())
+ if active >= API_MAX_TOKENS_PER_USER:
+ return jsonify({
+ 'error': (f'An account can hold at most {API_MAX_TOKENS_PER_USER} active API tokens. '
+ f'Revoke a token you no longer use to create a new one.'),
+ 'code': 'token_limit_reached',
+ 'max_tokens': API_MAX_TOKENS_PER_USER,
+ 'active_tokens': active,
+ }), 409
+
# Generate the token
plaintext_token = generate_token()
token_hash = hash_token(plaintext_token)
diff --git a/src/app.py b/src/app.py
index 93d8205c..084ef732 100644
--- a/src/app.py
+++ b/src/app.py
@@ -550,7 +550,15 @@ bcrypt = Bcrypt()
bcrypt.init_app(app)
# Rate-limit headers, including Retry-After on 429 (mailr spec G1).
app.config.setdefault("RATELIMIT_HEADERS_ENABLED", True)
-limiter.init_app(app) # Initialize the limiter (uses in-memory storage by default)
+# The default in-memory storage counts in each gunicorn worker separately, so
+# every limit is in effect multiplied by the number of workers. A shared
+# backend (redis://, memcached://) makes the limits exact (#484).
+# While that backend is unreachable, counting falls back to memory instead of
+# failing the request.
+if os.environ.get("RATELIMIT_STORAGE_URI"):
+ app.config.setdefault("RATELIMIT_STORAGE_URI", os.environ["RATELIMIT_STORAGE_URI"])
+ app.config.setdefault("RATELIMIT_IN_MEMORY_FALLBACK_ENABLED", True)
+limiter.init_app(app)
from flask_limiter.errors import RateLimitExceeded as _RateLimitExceeded
@@ -573,6 +581,18 @@ def _rate_limit_exceeded(e):
retry = int(e.limit.limit.get_expiry())
except Exception:
retry = 60
+ from src.utils.token_auth import is_token_request, user_rate_key
+ if is_token_request():
+ # API clients get JSON that says which budget ran out: the token's own
+ # or the one all tokens of the account share (#484).
+ from flask import jsonify
+ account = getattr(e.limit, 'key_func', None) is user_rate_key
+ resp = jsonify({
+ 'error': e.description,
+ 'code': 'account_rate_limit_exceeded' if account else 'token_rate_limit_exceeded',
+ 'limit': str(e.limit.limit),
+ })
+ resp.status_code = 429
resp.headers["Retry-After"] = str(retry)
return resp
diff --git a/src/utils/token_auth.py b/src/utils/token_auth.py
index d1f09419..6672762d 100644
--- a/src/utils/token_auth.py
+++ b/src/utils/token_auth.py
@@ -166,6 +166,27 @@ _RATE_LIMITS = {
}
+def _doubled(limit_string):
+ """The same limit with twice the requests, or None when it cannot be parsed."""
+ from limits import parse_many
+ try:
+ items = parse_many(limit_string)
+ except ValueError:
+ return None
+ return '; '.join(
+ f"{2 * item.amount} per {'' if item.multiples == 1 else f'{item.multiples} '}{item.GRANULARITY.name}"
+ for item in items)
+
+
+# Account-wide limits (#484): all tokens of one user draw on one budget per
+# kind, so another token adds no throughput. The default is twice the
+# per-token limit, so a client with a single token is held by its token limit.
+_USER_RATE_LIMITS = {
+ kind: os.environ.get(f'API_USER_RATE_LIMIT_{kind.upper()}') or _doubled(limit) or limit
+ for kind, limit in _RATE_LIMITS.items()
+}
+
+
def _rate_category(scopes):
if 'process' in scopes:
return 'process'
@@ -183,6 +204,15 @@ def token_rate_key():
return get_remote_address()
+def user_rate_key():
+ """Rate-limit key for the account budget: the owner of the token."""
+ api_token = current_api_token()
+ if api_token is not None:
+ return f"user:{api_token.user_id}"
+ from flask_limiter.util import get_remote_address
+ return get_remote_address()
+
+
def is_token_request():
"""True when this request is authenticated by an API token (not a session)."""
return current_api_token() is not None
@@ -190,28 +220,46 @@ def is_token_request():
def require_scope(*scopes):
"""Mark a view with the scopes a scoped token needs, and apply the per-token
- rate limit for its kind (read, write or process).
+ and the per-account rate limits for its kind (read, write or process).
require_scope() with no scopes accepts any valid token. The check itself runs
in the before_request hook in src/app.py, before the view, so a refused
request has no side effect. Full tokens and sessions are not restricted.
"""
required = frozenset(scopes)
- limit_string = _RATE_LIMITS[_rate_category(set(scopes))]
+ category = _rate_category(set(scopes))
def decorator(f):
- state = {'limited': None}
+ state = {'limiter': None, 'limited': None}
@wraps(f)
def wrapper(*args, **kwargs):
from src.app import limiter
if limiter is not None and getattr(limiter, 'enabled', True):
- if state['limited'] is None:
- state['limited'] = limiter.limit(
- limit_string, key_func=token_rate_key,
+ if state['limiter'] is not limiter:
+ # Both limits register under the view's name, so one check
+ # evaluates the two. With equal windows the token limit is
+ # checked first, and a request it refuses is not counted
+ # against the account. The token budget is counted per
+ # route, as before; the account budget is one shared bucket
+ # per kind across all routes.
+ per_token = limiter.limit(
+ lambda: _RATE_LIMITS[category], key_func=token_rate_key,
exempt_when=lambda: not is_token_request(),
- scope=lambda endpoint: f"token-{_rate_category(set(scopes))}",
+ scope=lambda endpoint: f"token-{category}",
+ error_message=lambda: (f"Rate limit reached for this token: "
+ f"{_RATE_LIMITS[category]} ({category} requests)."),
)(f)
+ state['limited'] = limiter.shared_limit(
+ lambda: _USER_RATE_LIMITS[category], scope=f"user-{category}",
+ key_func=user_rate_key,
+ exempt_when=lambda: not is_token_request(),
+ override_defaults=False,
+ error_message=lambda: (f"Rate limit reached for your account: "
+ f"{_USER_RATE_LIMITS[category]} ({category} requests), "
+ f"shared by all your API tokens."),
+ )(per_token)
+ state['limiter'] = limiter
return state['limited'](*args, **kwargs)
return f(*args, **kwargs)
diff --git a/static/locales/de.json b/static/locales/de.json
index 6d6ec9c0..5e475371 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -451,6 +451,7 @@
"description": "Erstellen und verwalten Sie API-Token für den programmgesteuerten Zugriff auf Ihr Konto",
"expires": "Läuft ab",
"lastUsed": "Zuletzt verwendet",
+ "limitReached": "Ihr Konto hat bereits {{max}} aktive API-Tokens, die Höchstzahl. Widerrufen Sie ein nicht mehr benötigtes Token, um ein neues zu erstellen.",
"neverUsed": "Nie verwendet",
"noExpiration": "Kein Ablaufdatum",
"noTokens": "Keine API-Token",
diff --git a/static/locales/en.json b/static/locales/en.json
index 8d67c1a6..6e48872d 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -451,6 +451,7 @@
"description": "Create and manage API tokens for programmatic access to your account",
"expires": "Expires",
"lastUsed": "Last used",
+ "limitReached": "Your account already has {{max}} active API tokens, the most it can hold. Revoke a token you no longer use to create a new one.",
"neverUsed": "Never used",
"noExpiration": "No expiration",
"noTokens": "No API Tokens",
diff --git a/static/locales/es.json b/static/locales/es.json
index 41847d6f..0f148ea8 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -451,6 +451,7 @@
"description": "Crea y gestiona tokens de API para acceso programático a tu cuenta",
"expires": "Expira",
"lastUsed": "Último uso",
+ "limitReached": "Su cuenta ya tiene {{max}} tokens de API activos, el máximo permitido. Revoque un token que ya no use para crear uno nuevo.",
"neverUsed": "Nunca usado",
"noExpiration": "Sin expiración",
"noTokens": "Sin tokens de API",
diff --git a/static/locales/fr.json b/static/locales/fr.json
index d2290740..4dcb16a1 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -451,6 +451,7 @@
"description": "Créez et gérez des jetons API pour l'accès programmatique à votre compte",
"expires": "Expire",
"lastUsed": "Dernière utilisation",
+ "limitReached": "Votre compte possède déjà {{max}} jetons d'API actifs, le maximum autorisé. Révoquez un jeton que vous n'utilisez plus pour en créer un nouveau.",
"neverUsed": "Jamais utilisé",
"noExpiration": "Pas d'expiration",
"noTokens": "Aucun jeton API",
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 7f66eff3..42817ad6 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -451,6 +451,7 @@
"description": "Crie e gerencie tokens de API para acesso programático à sua conta",
"expires": "Expira",
"lastUsed": "Último uso",
+ "limitReached": "Sua conta já tem {{max}} tokens de API ativos, o máximo permitido. Revogue um token que você não usa mais para criar um novo.",
"neverUsed": "Nunca usado",
"noExpiration": "Sem expiração",
"noTokens": "Nenhum Token de API",
diff --git a/static/locales/ru.json b/static/locales/ru.json
index 5f5482dc..e542364d 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -451,6 +451,7 @@
"description": "Создавайте и управляйте API-токенами для программного доступа к вашему аккаунту",
"expires": "Истекает",
"lastUsed": "Последнее использование",
+ "limitReached": "В вашей учётной записи уже {{max}} активных API-токенов, это максимум. Отзовите токен, который больше не используется, чтобы создать новый.",
"neverUsed": "Не использовался",
"noExpiration": "Без срока истечения",
"noTokens": "Нет API-токенов",
diff --git a/static/locales/zh.json b/static/locales/zh.json
index bfc73260..7ae01a9c 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -451,6 +451,7 @@
"description": "创建和管理 API 令牌以编程方式访问您的账户",
"expires": "过期时间",
"lastUsed": "最后使用",
+ "limitReached": "您的账户已有 {{max}} 个有效的 API 令牌,已达上限。请撤销一个不再使用的令牌后再创建新令牌。",
"neverUsed": "从未使用",
"noExpiration": "永不过期",
"noTokens": "没有 API 令牌",
diff --git a/templates/account.html b/templates/account.html
index 4925198c..3920a2af 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -6517,6 +6517,13 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co
if (!response.ok) {
const errorData = await response.json();
+ // The account holds as many active tokens as the server allows (#484).
+ if (errorData.code === 'token_limit_reached') {
+ const key = 'apiTokens.limitReached';
+ const text = window.i18n ? window.i18n.t(key, { max: errorData.max_tokens }) : key;
+ showToast(text !== key ? text : errorData.error, 'error');
+ return;
+ }
throw new Error(errorData.error || 'Failed to create token');
}
diff --git a/tests/test_api_token_scopes.py b/tests/test_api_token_scopes.py
index 7b0e0d8b..2aced6bf 100644
--- a/tests/test_api_token_scopes.py
+++ b/tests/test_api_token_scopes.py
@@ -248,6 +248,131 @@ def test_rate_limits_are_per_token():
assert ta._rate_category({"write"}) == "write" and ta._rate_category({"delete"}) == "write"
+def test_the_account_budget_defaults_to_twice_the_token_budget():
+ from src.utils import token_auth as ta
+ assert ta._doubled("120 per minute") == "240 per minute"
+ assert ta._doubled("10/second; 100 per 5 minutes") == "20 per second; 200 per 5 minute"
+ assert ta._doubled("not a limit") is None
+ if not any(os.environ.get(f"API_USER_RATE_LIMIT_{k}") for k in ("READ", "WRITE", "PROCESS")):
+ assert ta._USER_RATE_LIMITS == {k: ta._doubled(v) for k, v in ta._RATE_LIMITS.items()}
+
+
+def live_limiter():
+ """An enabled limiter with small budgets in place of the suite's disabled one.
+
+ RATELIMIT_ENABLED is false under test, so the app's own limiter was never
+ set up; this one is initialised on a throwaway app and counts in memory.
+ Token budget 3, account budget 5 (read); 2 and 4 (write).
+ """
+ from flask import Flask
+ from flask_limiter import Limiter
+ from flask_limiter.util import get_remote_address
+ import src.app as app_module
+ from src.utils import token_auth as ta
+ live = Limiter(get_remote_address, storage_uri="memory://", enabled=True)
+ live.init_app(Flask("limiter-host"))
+ with patch.object(app_module, "limiter", live), \
+ patch.dict(ta._RATE_LIMITS, {"read": "3 per minute", "write": "2 per minute"}), \
+ patch.dict(ta._USER_RATE_LIMITS, {"read": "5 per minute", "write": "4 per minute"}):
+ yield live
+
+
+def _read(c, plain, path="/api/v1/recordings"):
+ return c.get(path, headers=_h(plain))
+
+
+def test_tokens_of_one_account_share_the_account_budget(world, live_limiter):
+ first, second = world["token"](None), world["token"](["read"])
+ with app.app_context():
+ c = _Client(app, app.response_class)
+ assert [_read(c, first).status_code for _ in range(3)] == [200, 200, 200]
+ over_token = _read(c, first)
+ assert [_read(c, second).status_code for _ in range(2)] == [200, 200]
+ over_account = _read(c, second)
+ # The first token runs out of its own budget; that refusal is not counted
+ # against the account, which the second token then exhausts at 5.
+ assert over_token.status_code == 429 and over_token.headers.get("Retry-After")
+ assert over_token.get_json()["code"] == "token_rate_limit_exceeded"
+ assert "this token" in over_token.get_json()["error"]
+ assert over_account.status_code == 429 and over_account.headers.get("Retry-After")
+ body = over_account.get_json()
+ assert body["code"] == "account_rate_limit_exceeded"
+ assert "your account" in body["error"] and body["limit"] == "5 per 1 minute"
+
+
+def test_a_single_token_meets_its_own_budget_first(world, live_limiter):
+ plain = world["token"](None)
+ with app.app_context():
+ c = _Client(app, app.response_class)
+ codes = [_read(c, plain).status_code for _ in range(4)]
+ refused = _read(c, plain)
+ assert codes == [200, 200, 200, 429]
+ assert refused.get_json()["code"] == "token_rate_limit_exceeded"
+
+
+def test_the_account_budget_spans_routes_and_kinds_stay_apart(world, live_limiter):
+ plain = world["token"](None)
+ with app.app_context():
+ c = _Client(app, app.response_class)
+ # The token budget is counted per route, the account budget across them.
+ codes = [_read(c, plain).status_code for _ in range(3)]
+ codes += [_read(c, plain, "/api/v1/tags").status_code for _ in range(3)]
+ write = c.patch(f"/api/v1/recordings/{world['rec']}", json={"title": "Still allowed"},
+ headers=_h(plain))
+ assert codes == [200, 200, 200, 200, 200, 429]
+ assert write.status_code == 200
+
+
+def test_session_traffic_is_not_held_by_token_budgets(world, live_limiter):
+ c = _session(world)
+ assert {c.get("/api/v1/recordings").status_code for _ in range(8)} == {200}
+
+
+# ------------------------------------------------------------ token cap
+
+def test_the_token_cap_refuses_another_active_token_until_one_is_revoked(world):
+ from datetime import datetime, timedelta
+ from src.api import tokens as tokens_api
+ c = _session(world)
+ with app.app_context():
+ # A revoked or an expired token does not take a slot.
+ for kwargs in ({"revoked": True}, {"expires_at": datetime.utcnow() - timedelta(days=1)}):
+ t = APIToken(user_id=world["user"], token_hash=hash_token(secrets.token_urlsafe(16)), name="old",
+ **kwargs)
+ db.session.add(t)
+ db.session.commit()
+ world["tokens"].append(t.id)
+ with patch.object(tokens_api, "API_MAX_TOKENS_PER_USER", 2):
+ made = [c.post("/api/tokens", json={"name": f"t{i}"}) for i in range(2)]
+ refused = c.post("/api/tokens", json={"name": "t3"})
+ assert c.delete(f"/api/tokens/{made[0].get_json()['id']}").status_code == 200
+ after_revoke = c.post("/api/tokens", json={"name": "t3"})
+ assert [r.status_code for r in made] == [201, 201]
+ assert refused.status_code == 409
+ body = refused.get_json()
+ assert body["code"] == "token_limit_reached" and body["max_tokens"] == 2 and body["active_tokens"] == 2
+ assert "Revoke" in body["error"]
+ assert after_revoke.status_code == 201
+
+
+def test_tokens_above_a_lowered_cap_keep_working(world):
+ from src.api import tokens as tokens_api
+ plains = [world["token"](None) for _ in range(3)]
+ with patch.object(tokens_api, "API_MAX_TOKENS_PER_USER", 1):
+ assert _session(world).post("/api/tokens", json={"name": "x"}).status_code == 409
+ with app.app_context():
+ c = _Client(app, app.response_class)
+ assert {_read(c, p).status_code for p in plains} == {200}
+
+
+def test_a_token_cap_of_zero_means_no_limit(world):
+ from src.api import tokens as tokens_api
+ c = _session(world)
+ with patch.object(tokens_api, "API_MAX_TOKENS_PER_USER", 0):
+ assert {c.post("/api/tokens", json={"name": f"t{i}"}).status_code for i in range(4)} == {201}
+
+
def test_a_token_never_carries_over_to_the_next_request(world):
"""g outlives a request when a caller holds an app context; the token must not."""
plain = world["token"](None)