mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-09-25 18:58:58 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
abf8a1875c | ||
|
|
172b404a93 |
Vendored
+3
-3
@@ -2316,7 +2316,7 @@ paths:
|
||||
- Review
|
||||
summary: Generate Review Summary
|
||||
description: |-
|
||||
**Access:** Authenticated user with access to all cameras.
|
||||
**Access:** Admin role required.
|
||||
|
||||
Use GenAI to summarize review items over a period of time.
|
||||
operationId:
|
||||
@@ -2347,8 +2347,8 @@ paths:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- frigateUserAuth: []
|
||||
x-required-role: all_cameras
|
||||
- frigateAdminAuth: []
|
||||
x-required-role: admin
|
||||
/:
|
||||
get:
|
||||
tags:
|
||||
|
||||
+3
-25
@@ -971,7 +971,6 @@ def delete_user(request: Request, username: str):
|
||||
summary="Update user password",
|
||||
description="Updates a user's password. Users can only change their own password unless they have admin role. Requires the current password to verify identity for non-admin users. Password must be at least 12 characters long. If user changes their own password, a new JWT cookie is automatically issued.",
|
||||
)
|
||||
@limiter.limit(limit_value=rateLimiter.get_limit)
|
||||
async def update_password(
|
||||
request: Request,
|
||||
username: str,
|
||||
@@ -985,11 +984,10 @@ async def update_password(
|
||||
current_username = current_user.get("username")
|
||||
current_role = current_user.get("role")
|
||||
|
||||
# Only admins may target another account. This has to cover every non-admin
|
||||
# role rather than just viewer, since custom roles are arbitrary names
|
||||
if current_role != "admin" and current_username != username:
|
||||
# viewers can only change their own password
|
||||
if current_role == "viewer" and current_username != username:
|
||||
raise HTTPException(
|
||||
status_code=403, detail="Users can only update their own password"
|
||||
status_code=403, detail="Viewers can only update their own password"
|
||||
)
|
||||
|
||||
HASH_ITERATIONS = request.app.frigate_config.auth.hash_iterations
|
||||
@@ -1253,23 +1251,3 @@ async def get_allowed_cameras_for_filter(request: Request):
|
||||
all_camera_names = set(request.app.frigate_config.cameras.keys())
|
||||
roles_dict = request.app.frigate_config.auth.roles
|
||||
return User.get_allowed_cameras(role, roles_dict, all_camera_names)
|
||||
|
||||
|
||||
async def require_full_camera_access(
|
||||
request: Request,
|
||||
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
|
||||
):
|
||||
"""Dependency for endpoints returning data that spans every camera.
|
||||
|
||||
Some responses cannot be meaningfully scoped to a subset of cameras, so
|
||||
rather than filter them the endpoint is limited to callers who can already
|
||||
see every camera. Admin and viewer always qualify; a custom role qualifies
|
||||
only when its camera list covers all configured cameras.
|
||||
"""
|
||||
all_camera_names = set(request.app.frigate_config.cameras.keys())
|
||||
|
||||
if not all_camera_names.issubset(allowed_cameras):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="Access to all cameras is required for this endpoint",
|
||||
)
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
"""Notification apis."""
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
@@ -21,95 +19,6 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=[Tags.notifications])
|
||||
|
||||
# Push endpoints are opaque URLs but stay well under this in practice
|
||||
MAX_ENDPOINT_LENGTH = 2048
|
||||
|
||||
# Suffixes that only ever resolve on the local network
|
||||
INTERNAL_HOST_SUFFIXES = (".local", ".localdomain", ".internal", ".home.arpa")
|
||||
|
||||
|
||||
def _validate_push_endpoint(endpoint: Any) -> str | None:
|
||||
"""Return a reason the endpoint is unusable, or None when it is valid.
|
||||
|
||||
Subscriptions are issued by the browser vendor's push service, so a valid
|
||||
endpoint is always a public https URL. Anything else is either a broken
|
||||
registration or an attempt to aim the notification sender somewhere it
|
||||
should not reach.
|
||||
"""
|
||||
if not isinstance(endpoint, str) or not endpoint:
|
||||
return "endpoint must be a url"
|
||||
|
||||
if len(endpoint) > MAX_ENDPOINT_LENGTH:
|
||||
return "endpoint is too long"
|
||||
|
||||
try:
|
||||
parsed = urlparse(endpoint)
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
return "endpoint is not a valid url"
|
||||
|
||||
if parsed.scheme != "https":
|
||||
return "endpoint must use https"
|
||||
|
||||
if parsed.username or parsed.password:
|
||||
return "endpoint must not include credentials"
|
||||
|
||||
if port is not None and port != 443:
|
||||
return "endpoint must use the default https port"
|
||||
|
||||
hostname = parsed.hostname
|
||||
|
||||
if not hostname:
|
||||
return "endpoint must include a hostname"
|
||||
|
||||
try:
|
||||
address = ipaddress.ip_address(hostname)
|
||||
except ValueError:
|
||||
address = None
|
||||
|
||||
if address is not None:
|
||||
# A push service is never reachable at an address only this network can
|
||||
# route, so anything non-global is a misconfiguration at best
|
||||
if not address.is_global:
|
||||
return "endpoint must not use a private address"
|
||||
elif hostname == "localhost" or "." not in hostname:
|
||||
return "endpoint must use a fully qualified hostname"
|
||||
elif hostname.endswith(INTERNAL_HOST_SUFFIXES):
|
||||
return "endpoint must not use an internal hostname"
|
||||
|
||||
# The subscription token lives in the path, and webpush.py assumes there is
|
||||
# a separator after the host when it builds the VAPID audience
|
||||
if len(parsed.path) <= 1:
|
||||
return "endpoint must include a subscription path"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _validate_subscription(sub: Any) -> str | None:
|
||||
"""Return a reason the subscription is unusable, or None when it is valid."""
|
||||
if not isinstance(sub, dict):
|
||||
return "subscription must be an object"
|
||||
|
||||
reason = _validate_push_endpoint(sub.get("endpoint"))
|
||||
|
||||
if reason:
|
||||
return reason
|
||||
|
||||
keys = sub.get("keys")
|
||||
|
||||
if not isinstance(keys, dict):
|
||||
return "subscription must include keys"
|
||||
|
||||
# WebPusher raises on a missing key, which would break every send for the
|
||||
# user rather than just this registration
|
||||
for name in ("p256dh", "auth"):
|
||||
value = keys.get(name)
|
||||
|
||||
if not isinstance(value, str) or not value:
|
||||
return f"subscription keys must include {name}"
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@router.get(
|
||||
"/notifications/pubkey",
|
||||
@@ -162,17 +71,6 @@ def register_notifications(request: Request, body: dict = None):
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
reason = _validate_subscription(sub)
|
||||
|
||||
if reason:
|
||||
logger.warning(
|
||||
"Rejected notification registration for %s: %s", username, reason
|
||||
)
|
||||
return JSONResponse(
|
||||
content={"success": False, "message": f"Invalid subscription: {reason}"},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
try:
|
||||
User.update(notification_tokens=User.notification_tokens.append(sub)).where(
|
||||
User.username == username
|
||||
|
||||
@@ -17,7 +17,6 @@ from frigate.api.auth import (
|
||||
get_allowed_cameras_for_filter,
|
||||
get_current_user,
|
||||
require_camera_access,
|
||||
require_full_camera_access,
|
||||
require_role,
|
||||
)
|
||||
from frigate.api.defs.query.review_query_parameters import (
|
||||
@@ -747,12 +746,9 @@ async def set_not_reviewed(
|
||||
)
|
||||
|
||||
|
||||
# Intentionally not camera scoped, as the summary correlates each flagged event
|
||||
# with overlapping activity on other cameras. Restricted to callers who can
|
||||
# already see every camera, so the unscoped query discloses nothing.
|
||||
@router.post(
|
||||
"/review/summarize/start/{start_ts}/end/{end_ts}",
|
||||
dependencies=[Depends(require_full_camera_access)],
|
||||
dependencies=[Depends(require_role(["admin"]))],
|
||||
description="Use GenAI to summarize review items over a period of time.",
|
||||
)
|
||||
def generate_review_summary(request: Request, start_ts: float, end_ts: float):
|
||||
|
||||
@@ -396,6 +396,7 @@ class CameraState:
|
||||
"attributes": new_obj.obj_data["attributes"],
|
||||
"current_estimated_speed": 0,
|
||||
"velocity_angle": 0,
|
||||
"path_data": [],
|
||||
"recognized_license_plate": None,
|
||||
"recognized_license_plate_score": None,
|
||||
}
|
||||
|
||||
+4
-63
@@ -3,8 +3,6 @@
|
||||
import errno
|
||||
import json
|
||||
import logging
|
||||
import queue
|
||||
import socket
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
@@ -76,9 +74,6 @@ _WS_VIEWER_TOPICS = frozenset(
|
||||
# Camera-scoped command topics a camera-authorized (non-admin) user may send.
|
||||
_WS_CAMERA_COMMAND_TOPICS = frozenset({"ptz"})
|
||||
|
||||
# Max outbound messages waiting on a client's writer thread.
|
||||
WS_MAX_PENDING_MESSAGES = 256
|
||||
|
||||
|
||||
def _check_ws_authorization(
|
||||
topic: str,
|
||||
@@ -451,63 +446,6 @@ def _materialize_for_ws(
|
||||
|
||||
|
||||
class WebSocket(WebSocket_): # type: ignore[misc]
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._send_queue: queue.Queue[tuple[Any, bool] | None] = queue.Queue(
|
||||
maxsize=WS_MAX_PENDING_MESSAGES
|
||||
)
|
||||
self._writer: threading.Thread | None = None
|
||||
self._aborted = False
|
||||
|
||||
def opened(self) -> None:
|
||||
# every client gets its own writer so a client that stops reading only
|
||||
# blocks itself, never the thread that called publish()
|
||||
self._writer = threading.Thread(
|
||||
target=self._drain_send_queue, name="ws_writer", daemon=True
|
||||
)
|
||||
self._writer.start()
|
||||
|
||||
def send(self, payload: Any, binary: bool = False) -> None:
|
||||
try:
|
||||
self._send_queue.put_nowait((payload, binary))
|
||||
except queue.Full:
|
||||
self._abort("Websocket client is not keeping up, disconnecting it")
|
||||
|
||||
def _drain_send_queue(self) -> None:
|
||||
while True:
|
||||
item = self._send_queue.get()
|
||||
if item is None or self.terminated or self.sock is None:
|
||||
return
|
||||
try:
|
||||
super().send(*item)
|
||||
except Exception:
|
||||
self._abort()
|
||||
return
|
||||
|
||||
def _abort(self, reason: str | None = None) -> None:
|
||||
# publish() keeps hitting a full queue until the manager thread removes
|
||||
# the connection, so only act (and log) the first time
|
||||
if self._aborted:
|
||||
return
|
||||
self._aborted = True
|
||||
if reason:
|
||||
logger.warning(reason)
|
||||
|
||||
# shutdown rather than close so the ws4py manager thread sees EOF and
|
||||
# runs its normal unregister/terminate; this also unblocks a stuck sendall
|
||||
sock = self.sock
|
||||
if sock is not None:
|
||||
try:
|
||||
sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def closed(self, code: int, reason: str | None = None) -> None:
|
||||
try:
|
||||
self._send_queue.put_nowait(None)
|
||||
except queue.Full:
|
||||
pass
|
||||
|
||||
def unhandled_error(self, error: Any) -> None:
|
||||
"""
|
||||
Handles the unfriendly socket closures on the server side
|
||||
@@ -642,7 +580,10 @@ class WebSocketClient(Communicator):
|
||||
)
|
||||
if message is None:
|
||||
continue
|
||||
ws.send(message)
|
||||
try:
|
||||
ws.send(message)
|
||||
except (ConnectionResetError, BrokenPipeError, ValueError):
|
||||
pass
|
||||
|
||||
def stop(self) -> None:
|
||||
if self.websocket_server is not None:
|
||||
|
||||
@@ -166,6 +166,29 @@ class TestCameraAccessEventReview(BaseTestHttp):
|
||||
resp = client.get("/review/rev1")
|
||||
assert resp.status_code == 403
|
||||
|
||||
def test_review_not_reviewed_access(self):
|
||||
super().insert_mock_review_segment("rev1", camera="front_door")
|
||||
|
||||
# Allowed
|
||||
async def mock_require_allowed(camera: str, request: Request = None):
|
||||
if camera == "front_door":
|
||||
return
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
with patch("frigate.api.review.require_camera_access", mock_require_allowed):
|
||||
with AuthTestClient(self.app) as client:
|
||||
resp = client.delete("/review/rev1/viewed")
|
||||
assert resp.status_code == 200
|
||||
|
||||
# Disallowed
|
||||
async def mock_require_disallowed(camera: str, request: Request = None):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
with patch("frigate.api.review.require_camera_access", mock_require_disallowed):
|
||||
with AuthTestClient(self.app) as client:
|
||||
resp = client.delete("/review/rev1/viewed")
|
||||
assert resp.status_code == 403
|
||||
|
||||
def test_event_search_access(self):
|
||||
super().insert_mock_event("event1", camera="front_door")
|
||||
super().insert_mock_event("event2", camera="back_door")
|
||||
@@ -440,68 +463,3 @@ class TestGo2rtcStreamAccess(BaseTestHttp):
|
||||
f"limited_user should be denied on alias back_door_main; "
|
||||
f"got {resp.status_code}"
|
||||
)
|
||||
|
||||
|
||||
class TestReviewSummaryAccess(BaseTestHttp):
|
||||
"""Tests for POST /review/summarize/start/{start_ts}/end/{end_ts}.
|
||||
|
||||
The summary correlates each flagged event with overlapping activity on
|
||||
other cameras, so it is gated on full camera access rather than scoped to
|
||||
the caller's cameras. These tests pin that decision so the dependency is
|
||||
not loosened without first scoping the query.
|
||||
|
||||
GenAI is not configured in unit tests, so an authorized request returns 400
|
||||
while an unauthorized one is rejected with 403 before the handler runs.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp([Event, ReviewSegment, Recordings])
|
||||
self.minimal_config = _MULTI_CAMERA_CONFIG
|
||||
self.app = super().create_app()
|
||||
|
||||
def tearDown(self):
|
||||
self.app.dependency_overrides.clear()
|
||||
super().tearDown()
|
||||
|
||||
def _summarize(self, allowed_cameras: list[str]):
|
||||
async def mock_cameras(request: Request):
|
||||
return allowed_cameras
|
||||
|
||||
self.app.dependency_overrides[get_allowed_cameras_for_filter] = mock_cameras
|
||||
with AuthTestClient(self.app) as client:
|
||||
return client.post("/review/summarize/start/0/end/9999999999")
|
||||
|
||||
def _assert_allowed(self, resp):
|
||||
assert resp.status_code not in (401, 403), (
|
||||
f"Caller should not be blocked; got {resp.status_code}"
|
||||
)
|
||||
|
||||
def test_partial_camera_access_blocked(self):
|
||||
assert self._summarize(["front_door"]).status_code == 403
|
||||
|
||||
def test_no_camera_access_blocked(self):
|
||||
assert self._summarize([]).status_code == 403
|
||||
|
||||
def test_full_camera_access_allowed(self):
|
||||
# Covers admin and viewer, which always resolve to every camera, and a
|
||||
# custom role whose list happens to name them all.
|
||||
self._assert_allowed(self._summarize(["front_door", "back_door"]))
|
||||
|
||||
def _summarize_as_role(self, role: str):
|
||||
"""Summarize using the real role to allowed-cameras resolution."""
|
||||
self.app.dependency_overrides.pop(get_allowed_cameras_for_filter, None)
|
||||
with AuthTestClient(self.app) as client:
|
||||
return client.post(
|
||||
"/review/summarize/start/0/end/9999999999",
|
||||
headers={"remote-user": "test", "remote-role": role},
|
||||
)
|
||||
|
||||
def test_viewer_role_allowed(self):
|
||||
# viewer is never camera restricted, so it resolves to every camera.
|
||||
self._assert_allowed(self._summarize_as_role("viewer"))
|
||||
|
||||
def test_admin_role_allowed(self):
|
||||
self._assert_allowed(self._summarize_as_role("admin"))
|
||||
|
||||
def test_restricted_role_blocked(self):
|
||||
assert self._summarize_as_role("limited_user").status_code == 403
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
"""Tests for password change authorization."""
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from frigate.api.auth import get_current_user, hash_password, verify_password
|
||||
from frigate.models import Event, Recordings, ReviewSegment, User
|
||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||
|
||||
# Config carrying a custom role, which is the class of user the literal
|
||||
# "viewer" check used to let through.
|
||||
_CUSTOM_ROLE_CONFIG = {
|
||||
"mqtt": {"host": "mqtt"},
|
||||
"auth": {"roles": {"neighbor": ["front_door"]}, "hash_iterations": 10},
|
||||
"cameras": {
|
||||
"front_door": {
|
||||
"ffmpeg": {
|
||||
"inputs": [{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
ADMIN_PASSWORD = "admin-real-password"
|
||||
NEW_PASSWORD = "AttackerChosenPassword123!"
|
||||
|
||||
|
||||
class TestUpdatePasswordAccess(BaseTestHttp):
|
||||
def setUp(self):
|
||||
super().setUp([Event, ReviewSegment, Recordings, User])
|
||||
self.minimal_config = _CUSTOM_ROLE_CONFIG
|
||||
self.app = super().create_app()
|
||||
User.insert(
|
||||
username="admin",
|
||||
password_hash=hash_password(ADMIN_PASSWORD, iterations=10),
|
||||
role="admin",
|
||||
notification_tokens=[],
|
||||
).execute()
|
||||
|
||||
async def mock_get_current_user(request: Request):
|
||||
return {
|
||||
"username": request.headers.get("remote-user"),
|
||||
"role": request.headers.get("remote-role"),
|
||||
}
|
||||
|
||||
self.app.dependency_overrides[get_current_user] = mock_get_current_user
|
||||
|
||||
def tearDown(self):
|
||||
self.app.dependency_overrides.clear()
|
||||
super().tearDown()
|
||||
|
||||
def _change_password(self, actor: str, role: str, target: str, old_password: str):
|
||||
with AuthTestClient(self.app) as client:
|
||||
return client.put(
|
||||
f"/users/{target}/password",
|
||||
json={"password": NEW_PASSWORD, "old_password": old_password},
|
||||
headers={"remote-user": actor, "remote-role": role},
|
||||
)
|
||||
|
||||
def _admin_password_unchanged(self) -> bool:
|
||||
return verify_password(ADMIN_PASSWORD, User.get_by_id("admin").password_hash)
|
||||
|
||||
def test_custom_role_cannot_target_another_account(self):
|
||||
resp = self._change_password("neighbor", "neighbor", "admin", "wrong-guess")
|
||||
assert resp.status_code == 403
|
||||
assert self._admin_password_unchanged()
|
||||
|
||||
def test_custom_role_cannot_target_another_account_with_correct_password(self):
|
||||
# The 403 must land before old_password is checked, so knowing the
|
||||
# target's password is not a way through
|
||||
resp = self._change_password("neighbor", "neighbor", "admin", ADMIN_PASSWORD)
|
||||
assert resp.status_code == 403
|
||||
assert self._admin_password_unchanged()
|
||||
|
||||
def test_viewer_cannot_target_another_account(self):
|
||||
resp = self._change_password("viewer_user", "viewer", "admin", ADMIN_PASSWORD)
|
||||
assert resp.status_code == 403
|
||||
assert self._admin_password_unchanged()
|
||||
|
||||
def test_admin_can_target_another_account(self):
|
||||
User.insert(
|
||||
username="neighbor",
|
||||
password_hash=hash_password("neighbor-password", iterations=10),
|
||||
role="neighbor",
|
||||
notification_tokens=[],
|
||||
).execute()
|
||||
|
||||
resp = self._change_password("admin", "admin", "neighbor", "")
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_non_admin_can_change_own_password(self):
|
||||
User.insert(
|
||||
username="neighbor",
|
||||
password_hash=hash_password("neighbor-password", iterations=10),
|
||||
role="neighbor",
|
||||
notification_tokens=[],
|
||||
).execute()
|
||||
|
||||
resp = self._change_password(
|
||||
"neighbor", "neighbor", "neighbor", "neighbor-password"
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_non_admin_own_password_still_requires_old_password(self):
|
||||
User.insert(
|
||||
username="neighbor",
|
||||
password_hash=hash_password("neighbor-password", iterations=10),
|
||||
role="neighbor",
|
||||
notification_tokens=[],
|
||||
).execute()
|
||||
|
||||
resp = self._change_password("neighbor", "neighbor", "neighbor", "wrong-guess")
|
||||
assert resp.status_code == 401
|
||||
@@ -1,150 +0,0 @@
|
||||
"""Tests for push notification subscription validation."""
|
||||
|
||||
import unittest
|
||||
|
||||
from frigate.api.notification import _validate_push_endpoint, _validate_subscription
|
||||
|
||||
VALID_ENDPOINTS = [
|
||||
"https://fcm.googleapis.com/fcm/send/dGhpcy1pcy1hLXRva2Vu",
|
||||
"https://updates.push.services.mozilla.com/wpush/v2/dGhpcy1pcy1hLXRva2Vu",
|
||||
"https://web.push.apple.com/dGhpcy1pcy1hLXRva2Vu",
|
||||
"https://wns2-by3p.notify.windows.com/w/?token=dGhpcy1pcy1hLXRva2Vu",
|
||||
"https://fcm.googleapis.com:443/fcm/send/dGhpcy1pcy1hLXRva2Vu",
|
||||
]
|
||||
|
||||
|
||||
def _subscription(endpoint: str) -> dict:
|
||||
return {
|
||||
"endpoint": endpoint,
|
||||
"keys": {"p256dh": "cHVibGljLWtleQ", "auth": "YXV0aC1zZWNyZXQ"},
|
||||
}
|
||||
|
||||
|
||||
class TestValidatePushEndpoint(unittest.TestCase):
|
||||
def test_accepts_real_push_service_endpoints(self):
|
||||
for endpoint in VALID_ENDPOINTS:
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_http(self):
|
||||
self.assertIsNotNone(
|
||||
_validate_push_endpoint("http://fcm.googleapis.com/fcm/send/token")
|
||||
)
|
||||
|
||||
def test_rejects_non_http_schemes(self):
|
||||
for endpoint in (
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.com/token",
|
||||
"//example.com/token",
|
||||
):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_localhost(self):
|
||||
for endpoint in (
|
||||
"https://localhost/token",
|
||||
"https://localhost:443/token",
|
||||
"https://127.0.0.1/token",
|
||||
"https://[::1]/token",
|
||||
):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_private_addresses(self):
|
||||
for endpoint in (
|
||||
"https://192.168.1.10/token",
|
||||
"https://10.0.0.5/token",
|
||||
"https://172.16.0.1/token",
|
||||
"https://169.254.169.254/token",
|
||||
"https://0.0.0.0/token",
|
||||
):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_internal_hostnames(self):
|
||||
for endpoint in (
|
||||
"https://frigate/token",
|
||||
"https://nas.local/token",
|
||||
"https://push.internal/token",
|
||||
"https://host.home.arpa/token",
|
||||
):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_non_default_port(self):
|
||||
self.assertIsNotNone(
|
||||
_validate_push_endpoint("https://fcm.googleapis.com:8080/fcm/send/token")
|
||||
)
|
||||
|
||||
def test_rejects_embedded_credentials(self):
|
||||
self.assertIsNotNone(
|
||||
_validate_push_endpoint(
|
||||
"https://user:pass@fcm.googleapis.com/fcm/send/token"
|
||||
)
|
||||
)
|
||||
|
||||
def test_rejects_endpoint_without_path(self):
|
||||
for endpoint in ("https://fcm.googleapis.com", "https://fcm.googleapis.com/"):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_endpoint_that_breaks_audience_parsing(self):
|
||||
# webpush.py locates the host by searching for a separator after index
|
||||
# 10, which raises ValueError when the url has no path at all
|
||||
endpoint = "https://fcm.googleapis.com"
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
endpoint.index("/", 10)
|
||||
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_missing_or_non_string_endpoint(self):
|
||||
for endpoint in (None, "", 5, {"url": "https://example.com/token"}):
|
||||
with self.subTest(endpoint=endpoint):
|
||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
||||
|
||||
def test_rejects_overlong_endpoint(self):
|
||||
self.assertIsNotNone(
|
||||
_validate_push_endpoint(f"https://fcm.googleapis.com/{'a' * 4096}")
|
||||
)
|
||||
|
||||
|
||||
class TestValidateSubscription(unittest.TestCase):
|
||||
def test_accepts_valid_subscription(self):
|
||||
self.assertIsNone(_validate_subscription(_subscription(VALID_ENDPOINTS[0])))
|
||||
|
||||
def test_accepts_extra_fields_sent_by_the_browser(self):
|
||||
sub = _subscription(VALID_ENDPOINTS[0])
|
||||
sub["expirationTime"] = None
|
||||
self.assertIsNone(_validate_subscription(sub))
|
||||
|
||||
def test_rejects_non_object(self):
|
||||
for sub in ("https://fcm.googleapis.com/fcm/send/token", ["endpoint"], 5):
|
||||
with self.subTest(sub=sub):
|
||||
self.assertIsNotNone(_validate_subscription(sub))
|
||||
|
||||
def test_rejects_bad_endpoint(self):
|
||||
self.assertIsNotNone(
|
||||
_validate_subscription(_subscription("https://localhost/t"))
|
||||
)
|
||||
|
||||
def test_rejects_missing_keys(self):
|
||||
sub = _subscription(VALID_ENDPOINTS[0])
|
||||
del sub["keys"]
|
||||
self.assertIsNotNone(_validate_subscription(sub))
|
||||
|
||||
def test_rejects_incomplete_keys(self):
|
||||
for keys in (
|
||||
{"p256dh": "cHVibGljLWtleQ"},
|
||||
{"auth": "YXV0aC1zZWNyZXQ"},
|
||||
{"p256dh": "cHVibGljLWtleQ", "auth": ""},
|
||||
{"p256dh": None, "auth": "YXV0aC1zZWNyZXQ"},
|
||||
):
|
||||
with self.subTest(keys=keys):
|
||||
sub = _subscription(VALID_ENDPOINTS[0])
|
||||
sub["keys"] = keys
|
||||
self.assertIsNotNone(_validate_subscription(sub))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,107 +0,0 @@
|
||||
"""Outbound websocket sends must never block the thread calling publish()."""
|
||||
|
||||
import socket
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from frigate.comms.ws import WS_MAX_PENDING_MESSAGES, WebSocket
|
||||
|
||||
|
||||
class _FakeSock:
|
||||
"""Socket stand-in; ``block`` makes sendall hang like a client that stopped reading."""
|
||||
|
||||
def __init__(self, block: bool = False) -> None:
|
||||
self.block = block
|
||||
self.released = threading.Event()
|
||||
self.shutdown_called = threading.Event()
|
||||
self.frames: list[bytes] = []
|
||||
|
||||
def sendall(self, data: bytes) -> None:
|
||||
if self.block and not self.released.is_set():
|
||||
self.released.wait(timeout=10)
|
||||
raise BrokenPipeError()
|
||||
self.frames.append(data)
|
||||
|
||||
def shutdown(self, how: int) -> None:
|
||||
assert how == socket.SHUT_RDWR
|
||||
self.shutdown_called.set()
|
||||
self.released.set()
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
def fileno(self) -> int:
|
||||
return 99
|
||||
|
||||
|
||||
def _wait_for(predicate, timeout: float = 2.0) -> bool:
|
||||
deadline = threading.Event()
|
||||
for _ in range(int(timeout / 0.01)):
|
||||
if predicate():
|
||||
return True
|
||||
deadline.wait(0.01)
|
||||
return predicate()
|
||||
|
||||
|
||||
class TestWebSocketSendQueue(unittest.TestCase):
|
||||
def _open(self, sock: _FakeSock) -> WebSocket:
|
||||
ws = WebSocket(sock)
|
||||
ws.opened()
|
||||
return ws
|
||||
|
||||
def test_stalled_client_does_not_block_publisher(self):
|
||||
sock = _FakeSock(block=True)
|
||||
ws = self._open(sock)
|
||||
|
||||
def publish_many():
|
||||
for i in range(WS_MAX_PENDING_MESSAGES + 5):
|
||||
ws.send(f"message {i}")
|
||||
|
||||
publisher = threading.Thread(target=publish_many, daemon=True)
|
||||
publisher.start()
|
||||
publisher.join(timeout=2.0)
|
||||
|
||||
self.assertFalse(publisher.is_alive(), "publish() blocked on a stalled client")
|
||||
self.assertTrue(
|
||||
sock.shutdown_called.wait(timeout=2.0),
|
||||
"a client that cannot keep up should be disconnected",
|
||||
)
|
||||
|
||||
def test_overflow_warns_and_shuts_down_once(self):
|
||||
sock = _FakeSock(block=True)
|
||||
ws = self._open(sock)
|
||||
shutdown_calls = []
|
||||
original_shutdown = sock.shutdown
|
||||
sock.shutdown = lambda how: (shutdown_calls.append(how), original_shutdown(how))
|
||||
|
||||
with self.assertLogs("frigate.comms.ws", level="WARNING") as logs:
|
||||
# keep publishing after overflow, as the dispatcher does until the
|
||||
# manager thread removes the connection
|
||||
for i in range(WS_MAX_PENDING_MESSAGES * 3):
|
||||
ws.send(f"message {i}")
|
||||
|
||||
self.assertEqual(len(logs.output), 1)
|
||||
self.assertEqual(len(shutdown_calls), 1)
|
||||
|
||||
def test_messages_delivered_in_order(self):
|
||||
sock = _FakeSock()
|
||||
ws = self._open(sock)
|
||||
for i in range(3):
|
||||
ws.send(f"message {i}")
|
||||
|
||||
self.assertTrue(_wait_for(lambda: len(sock.frames) == 3))
|
||||
for i, frame in enumerate(sock.frames):
|
||||
self.assertIn(f"message {i}".encode(), frame)
|
||||
self.assertFalse(sock.shutdown_called.is_set())
|
||||
|
||||
def test_closed_stops_writer_thread(self):
|
||||
sock = _FakeSock()
|
||||
ws = self._open(sock)
|
||||
writer = ws._writer
|
||||
ws.closed(1000, "bye")
|
||||
writer.join(timeout=2.0)
|
||||
self.assertFalse(writer.is_alive())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -164,6 +164,7 @@ class TrackedObject:
|
||||
"attributes": obj_data["attributes"],
|
||||
"current_estimated_speed": self.current_estimated_speed,
|
||||
"velocity_angle": self.velocity_angle,
|
||||
"path_data": self.path_data.copy(),
|
||||
"recognized_license_plate": obj_data.get(
|
||||
"recognized_license_plate"
|
||||
),
|
||||
|
||||
@@ -94,7 +94,6 @@ SPEC_SERVERS = [
|
||||
PUBLIC = "public"
|
||||
AUTHENTICATED = "any"
|
||||
CAMERA = "camera"
|
||||
ALL_CAMERAS = "all_cameras"
|
||||
ADMIN = "admin"
|
||||
|
||||
ADMIN_SCHEME = "frigateAdminAuth"
|
||||
@@ -129,7 +128,6 @@ ACCESS_NOTES = {
|
||||
PUBLIC: "**Access:** Public — no authentication required.",
|
||||
AUTHENTICATED: "**Access:** Any authenticated user.",
|
||||
CAMERA: "**Access:** Authenticated user with access to the referenced camera.",
|
||||
ALL_CAMERAS: "**Access:** Authenticated user with access to all cameras.",
|
||||
ADMIN: "**Access:** Admin role required.",
|
||||
}
|
||||
|
||||
@@ -199,8 +197,6 @@ def _route_markers(route: APIRoute) -> tuple[set[str], list[str] | None]:
|
||||
pass
|
||||
elif name in ("require_camera_access", "require_go2rtc_stream_access"):
|
||||
markers.add(CAMERA)
|
||||
elif name == "require_full_camera_access":
|
||||
markers.add(ALL_CAMERAS)
|
||||
elif "auth_checker" in qualname:
|
||||
markers.add(AUTHENTICATED)
|
||||
elif "public_checker" in qualname:
|
||||
@@ -258,8 +254,6 @@ def _classify_base(
|
||||
# Explicit route-level markers win, in order of specificity.
|
||||
if ADMIN in markers:
|
||||
return ADMIN, admin_roles or ["admin"], None
|
||||
if ALL_CAMERAS in markers:
|
||||
return ALL_CAMERAS, None, None
|
||||
if CAMERA in markers:
|
||||
return CAMERA, None, None
|
||||
if AUTHENTICATED in markers:
|
||||
@@ -343,8 +337,8 @@ def security_for(level: str) -> list:
|
||||
return []
|
||||
if level == ADMIN:
|
||||
return [{ADMIN_SCHEME: []}]
|
||||
# AUTHENTICATED, CAMERA and ALL_CAMERAS all require any authenticated
|
||||
# session; the camera scoping is conveyed in the note and x-required-role.
|
||||
# AUTHENTICATED and CAMERA both require any authenticated session; the
|
||||
# camera-specific scoping is conveyed in the note and x-required-role.
|
||||
return [{USER_SCHEME: []}]
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user