mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-25 23:07:07 +03:00
Report a rate limited Frigate+ key validation
A 429 while validating the API key was reported as "unreachable". Add a rate_limited status that records the Retry-After wait, skip asking the server again while that wait is in effect, and include the remaining seconds in the /plus/validate response. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a4e3824b8d
commit
f6d2a1a15e
+10
-4
@@ -1694,11 +1694,17 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
|
|||||||
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
||||||
async def validate_plus_key(request: Request):
|
async def validate_plus_key(request: Request):
|
||||||
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
||||||
status = await request.app.frigate_config.plus_api.validate_key()
|
plus_api = request.app.frigate_config.plus_api
|
||||||
|
status = await plus_api.validate_key()
|
||||||
|
content: dict[str, Any] = {
|
||||||
|
"success": status == PlusKeyStatus.valid,
|
||||||
|
"status": status.value,
|
||||||
|
}
|
||||||
|
|
||||||
return JSONResponse(
|
if status == PlusKeyStatus.rate_limited:
|
||||||
content={"success": status == PlusKeyStatus.valid, "status": status.value}
|
content["retry_after"] = plus_api.rate_limit_remaining()
|
||||||
)
|
|
||||||
|
return JSONResponse(content=content)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
|
|||||||
+12
-1
@@ -31,6 +31,7 @@ class PlusKeyStatus(str, Enum):
|
|||||||
valid = "valid"
|
valid = "valid"
|
||||||
invalid = "invalid"
|
invalid = "invalid"
|
||||||
unreachable = "unreachable"
|
unreachable = "unreachable"
|
||||||
|
rate_limited = "rate_limited"
|
||||||
not_set = "not_set"
|
not_set = "not_set"
|
||||||
|
|
||||||
|
|
||||||
@@ -283,11 +284,16 @@ class PlusApi:
|
|||||||
result reflects the key's current state rather than a cached token.
|
result reflects the key's current state rather than a cached token.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The key's status as reported by the Frigate+ server
|
The key's status as reported by the Frigate+ server. When it is
|
||||||
|
rate_limited, rate_limit_remaining() gives the wait if known.
|
||||||
"""
|
"""
|
||||||
if self.key is None:
|
if self.key is None:
|
||||||
return PlusKeyStatus.not_set
|
return PlusKeyStatus.not_set
|
||||||
|
|
||||||
|
# asking again before the wait is over would only be refused again
|
||||||
|
if self.rate_limit_remaining() is not None:
|
||||||
|
return PlusKeyStatus.rate_limited
|
||||||
|
|
||||||
key_id, _, secret = self.key.partition(":")
|
key_id, _, secret = self.key.partition(":")
|
||||||
|
|
||||||
# Use a single request with a timeout instead of the retrying session,
|
# Use a single request with a timeout instead of the retrying session,
|
||||||
@@ -303,6 +309,7 @@ class PlusApi:
|
|||||||
auth=aiohttp.BasicAuth(key_id, secret),
|
auth=aiohttp.BasicAuth(key_id, secret),
|
||||||
) as r:
|
) as r:
|
||||||
status = r.status
|
status = r.status
|
||||||
|
retry_after = parse_retry_after(r.headers.get("Retry-After"))
|
||||||
token_data = await r.json(content_type=None) if r.ok else None
|
token_data = await r.json(content_type=None) if r.ok else None
|
||||||
except (aiohttp.ClientError, TimeoutError) as err:
|
except (aiohttp.ClientError, TimeoutError) as err:
|
||||||
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
||||||
@@ -314,6 +321,10 @@ class PlusApi:
|
|||||||
if status in (401, 403):
|
if status in (401, 403):
|
||||||
return PlusKeyStatus.invalid
|
return PlusKeyStatus.invalid
|
||||||
|
|
||||||
|
if status == 429:
|
||||||
|
self._note_rate_limit(retry_after)
|
||||||
|
return PlusKeyStatus.rate_limited
|
||||||
|
|
||||||
if status >= 400:
|
if status >= 400:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Unexpected response validating Frigate+ API key: %s", status
|
"Unexpected response validating Frigate+ API key: %s", status
|
||||||
|
|||||||
@@ -12,11 +12,13 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp([Event])
|
super().setUp([Event])
|
||||||
|
|
||||||
def _validate(self, status: PlusKeyStatus) -> dict:
|
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict:
|
||||||
app = self.create_app()
|
app = self.create_app()
|
||||||
|
plus_api = app.frigate_config.plus_api
|
||||||
|
|
||||||
with patch.object(
|
with (
|
||||||
app.frigate_config.plus_api, "validate_key", return_value=status
|
patch.object(plus_api, "validate_key", return_value=status),
|
||||||
|
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
|
||||||
):
|
):
|
||||||
with AuthTestClient(app) as client:
|
with AuthTestClient(app) as client:
|
||||||
response = client.post("/plus/validate")
|
response = client.post("/plus/validate")
|
||||||
@@ -35,6 +37,12 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
{"success": False, "status": "invalid"},
|
{"success": False, "status": "invalid"},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_a_rate_limited_key_includes_the_wait(self):
|
||||||
|
self.assertEqual(
|
||||||
|
self._validate(PlusKeyStatus.rate_limited, 90),
|
||||||
|
{"success": False, "status": "rate_limited", "retry_after": 90},
|
||||||
|
)
|
||||||
|
|
||||||
def test_viewers_cannot_validate(self):
|
def test_viewers_cannot_validate(self):
|
||||||
app = self.create_app()
|
app = self.create_app()
|
||||||
|
|
||||||
|
|||||||
@@ -113,18 +113,26 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
api.host = host
|
api.host = host
|
||||||
api.key = key
|
api.key = key
|
||||||
api._token_data = dict(self.CACHED_TOKEN)
|
api._token_data = dict(self.CACHED_TOKEN)
|
||||||
|
api._rate_limited_until = None
|
||||||
return api
|
return api
|
||||||
|
|
||||||
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
||||||
api = self._api(await self._serve(handler))
|
api = self._api(await self._serve(handler))
|
||||||
return await api.validate_key(), api
|
return await api.validate_key(), api
|
||||||
|
|
||||||
def _replies(self, status: int = 200, body: object = None, text: str | None = None):
|
def _replies(
|
||||||
|
self,
|
||||||
|
status: int = 200,
|
||||||
|
body: object = None,
|
||||||
|
text: str | None = None,
|
||||||
|
headers: dict[str, str] | None = None,
|
||||||
|
):
|
||||||
async def handler(request: web.Request) -> web.Response:
|
async def handler(request: web.Request) -> web.Response:
|
||||||
self.auth = request.headers.get("Authorization")
|
self.auth = request.headers.get("Authorization")
|
||||||
|
self.requests_seen = getattr(self, "requests_seen", 0) + 1
|
||||||
if text is not None:
|
if text is not None:
|
||||||
return web.Response(status=status, text=text)
|
return web.Response(status=status, text=text, headers=headers)
|
||||||
return web.json_response(body, status=status)
|
return web.json_response(body, status=status, headers=headers)
|
||||||
|
|
||||||
return handler
|
return handler
|
||||||
|
|
||||||
@@ -148,6 +156,25 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
|
|
||||||
self.assertEqual(status, PlusKeyStatus.unreachable)
|
self.assertEqual(status, PlusKeyStatus.unreachable)
|
||||||
|
|
||||||
|
async def test_a_rate_limited_key_is_not_reported_as_invalid(self):
|
||||||
|
api = self._api(
|
||||||
|
await self._serve(self._replies(429, {}, headers={"Retry-After": "120"}))
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
|
||||||
|
self.assertAlmostEqual(api.rate_limit_remaining(), 120, delta=1)
|
||||||
|
self.assertEqual(api._token_data, self.CACHED_TOKEN)
|
||||||
|
|
||||||
|
# validating again during the wait doesn't ask the server
|
||||||
|
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
|
||||||
|
self.assertEqual(self.requests_seen, 1)
|
||||||
|
|
||||||
|
async def test_a_rate_limit_without_retry_after(self):
|
||||||
|
status, api = await self._validate(self._replies(429, {}))
|
||||||
|
|
||||||
|
self.assertEqual(status, PlusKeyStatus.rate_limited)
|
||||||
|
self.assertIsNone(api.rate_limit_remaining())
|
||||||
|
|
||||||
async def test_unusable_replies_keep_the_cached_token(self):
|
async def test_unusable_replies_keep_the_cached_token(self):
|
||||||
# a successful reply without a usable token must not replace one that
|
# a successful reply without a usable token must not replace one that
|
||||||
# later Frigate+ requests depend on
|
# later Frigate+ requests depend on
|
||||||
|
|||||||
Reference in New Issue
Block a user