Skip to content

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

Python

Unwrap a route limit in require_scope only when the decorator below is the rate_limit wrapper itself, never a decorator that inherited its attributes (#484)

Murtaza Nasir686d2d84e30c
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index 07d36a7a..268d3291 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -93,6 +93,10 @@ def rate_limit(limit_string, **limit_options):
wrapper._rate_limit = limit_string
wrapper._rate_limit_options = limit_options
+ # functools.wraps copies these attributes onto any decorator above;
+ # this one points at this wrapper only, so require_scope can tell it
+ # apart from a decorator that merely inherited them.
+ wrapper._rate_limit_wrapper = wrapper
return wrapper
return decorator
diff --git a/src/utils/token_auth.py b/src/utils/token_auth.py
index 857ba021..ba338aa6 100644
--- a/src/utils/token_auth.py
+++ b/src/utils/token_auth.py
@@ -265,8 +265,13 @@ def require_scope(*scopes):
# (src/api/api_v1.py). Its own wrapper would run a second limiter check
# per request, and each check counts every limit of the route, so the
# route limit joins this stack instead and the view runs unwrapped.
- route_limit = getattr(f, '_rate_limit', None)
- route_view = getattr(f, '__wrapped__', None) if route_limit else None
+ # Only when f is that wrapper itself: a decorator in between (an
+ # access check, say) inherits its attributes through functools.wraps
+ # and must not be skipped.
+ route_limit = route_view = None
+ if getattr(f, '_rate_limit_wrapper', None) is f:
+ route_limit = f._rate_limit
+ route_view = f.__wrapped__
@wraps(f)
def wrapper(*args, **kwargs):
diff --git a/tests/test_api_token_scopes.py b/tests/test_api_token_scopes.py
index 6d6dfb56..7bc9bc7f 100644
--- a/tests/test_api_token_scopes.py
+++ b/tests/test_api_token_scopes.py
@@ -413,6 +413,29 @@ def test_concurrent_first_requests_register_the_limits_once(world, live_limiter)
assert sorted(codes) == [200, 200, 200, 429, 429, 429]
+def test_a_decorator_between_require_scope_and_rate_limit_is_never_skipped(live_limiter):
+ """functools.wraps copies _rate_limit onto a decorator above rate_limit();
+ require_scope may unwrap only rate_limit's own wrapper."""
+ from functools import wraps
+ from src.api.api_v1 import rate_limit
+ from src.utils.token_auth import require_scope
+
+ def deny(f):
+ @wraps(f)
+ def check(*args, **kwargs):
+ return "denied"
+ return check
+
+ def view():
+ return "view ran"
+
+ guarded = require_scope("read")(deny(rate_limit("5 per minute")(view)))
+ direct = require_scope("read")(rate_limit("5 per minute")(view))
+ with app.test_request_context("/"):
+ assert guarded() == "denied"
+ assert direct() == "view ran"
+
+
# ------------------------------------------------------------ token cap
def test_the_token_cap_refuses_another_active_token_until_one_is_revoked(world):