mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 22:37:08 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89fbdd7207 | ||
|
|
758b2c96e1 |
Vendored
+8
-6
@@ -2311,8 +2311,8 @@ paths:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- frigateUserAuth: []
|
||||
x-required-role: any
|
||||
description: '**Access:** Any authenticated user.'
|
||||
x-required-role: camera
|
||||
description: '**Access:** Authenticated user with access to the referenced camera.'
|
||||
/review/{review_id}:
|
||||
get:
|
||||
tags:
|
||||
@@ -6152,7 +6152,9 @@ paths:
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
anyOf:
|
||||
- type: string
|
||||
- type: 'null'
|
||||
title: Camera Name
|
||||
- name: frame_time
|
||||
in: path
|
||||
@@ -6173,9 +6175,9 @@ paths:
|
||||
schema:
|
||||
$ref: '#/components/schemas/HTTPValidationError'
|
||||
security:
|
||||
- frigateAdminAuth: []
|
||||
x-required-role: admin
|
||||
description: '**Access:** Admin role required.'
|
||||
- frigateUserAuth: []
|
||||
x-required-role: camera
|
||||
description: '**Access:** Authenticated user with access to the referenced camera.'
|
||||
/{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4:
|
||||
get:
|
||||
tags:
|
||||
|
||||
@@ -434,7 +434,7 @@ async def get_snapshot_from_recording(
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{camera_name}/plus/{frame_time}", dependencies=[Depends(require_role(["admin"]))]
|
||||
"/{camera_name}/plus/{frame_time}", dependencies=[Depends(require_camera_access)]
|
||||
)
|
||||
async def submit_recording_snapshot_to_plus(
|
||||
request: Request, camera_name: str, frame_time: str
|
||||
|
||||
@@ -311,9 +311,6 @@ def deny_response_for_media_uri(
|
||||
if not role or role == "admin":
|
||||
return None
|
||||
|
||||
if resolution == MediaAuthResolution.ADMIN_ONLY:
|
||||
return 403
|
||||
|
||||
if not is_role_restricted(role, frigate_config):
|
||||
return None
|
||||
|
||||
@@ -322,6 +319,7 @@ def deny_response_for_media_uri(
|
||||
|
||||
if resolution in (
|
||||
MediaAuthResolution.LISTING_MULTI_CAMERA,
|
||||
MediaAuthResolution.ADMIN_ONLY,
|
||||
MediaAuthResolution.UNRESOLVED_MEDIA,
|
||||
):
|
||||
return 403
|
||||
|
||||
@@ -713,18 +713,12 @@ def motion_activity(
|
||||
response_model=ReviewSegmentResponse,
|
||||
dependencies=[Depends(allow_any_authenticated())],
|
||||
)
|
||||
async def get_review_from_event(
|
||||
event_id: str,
|
||||
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
|
||||
):
|
||||
async def get_review_from_event(request: Request, event_id: str):
|
||||
try:
|
||||
review = ReviewSegment.get(
|
||||
(ReviewSegment.camera << allowed_cameras)
|
||||
& (
|
||||
fn.instr(ReviewSegment.data["detections"].cast("text"), f'"{event_id}"')
|
||||
> 0
|
||||
)
|
||||
ReviewSegment.data["detections"].cast("text") % f'*"{event_id}"*'
|
||||
)
|
||||
await require_camera_access(review.camera, request=request)
|
||||
return JSONResponse(model_to_dict(review))
|
||||
except DoesNotExist:
|
||||
return JSONResponse(
|
||||
|
||||
+19
-10
@@ -180,6 +180,8 @@ class WebPushClient(Communicator):
|
||||
self.refresh: int = 0
|
||||
self.web_pushers: dict[str, list[WebPusher]] = {}
|
||||
self.expired_subs: dict[str, list[str]] = {}
|
||||
self.expired_subs_lock = threading.Lock()
|
||||
self.cleanup_lock = threading.Lock()
|
||||
self.suspended_cameras: dict[str, int] = {
|
||||
c.name: 0 # type: ignore[misc]
|
||||
for c in self.config.cameras.values()
|
||||
@@ -260,15 +262,23 @@ class WebPushClient(Communicator):
|
||||
self.claim_headers[endpoint] = self.vapid.sign(claim)
|
||||
|
||||
def cleanup_registrations(self) -> None:
|
||||
# delete any expired subs
|
||||
if len(self.expired_subs) > 0:
|
||||
for user, expired in self.expired_subs.items():
|
||||
# concurrent cleanups would each restore what the other removed
|
||||
with self.cleanup_lock:
|
||||
with self.expired_subs_lock:
|
||||
expired_subs, self.expired_subs = self.expired_subs, {}
|
||||
|
||||
for user, expired in expired_subs.items():
|
||||
user_subs = []
|
||||
|
||||
# get all subscriptions, removing ones that are expired
|
||||
stored_user: User = User.get_by_id(user)
|
||||
stored_user: User | None = User.get_or_none(User.username == user)
|
||||
|
||||
# the user was deleted after the endpoint expired
|
||||
if stored_user is None:
|
||||
continue
|
||||
|
||||
for token in stored_user.notification_tokens:
|
||||
if token["endpoint"] in expired:
|
||||
if isinstance(token, dict) and token.get("endpoint") in expired:
|
||||
continue
|
||||
|
||||
user_subs.append(token)
|
||||
@@ -284,8 +294,6 @@ class WebPushClient(Communicator):
|
||||
f"Cleaned up {len(expired)} notification subscriptions for {user}"
|
||||
)
|
||||
|
||||
self.expired_subs = {}
|
||||
|
||||
def suspend_notifications(self, camera: str, minutes: int) -> None:
|
||||
"""Suspend notifications for a specific camera."""
|
||||
suspend_until = int(
|
||||
@@ -460,9 +468,10 @@ class WebPushClient(Communicator):
|
||||
)
|
||||
|
||||
if resp.status_code in (404, 410):
|
||||
self.expired_subs.setdefault(notification.user, []).append(
|
||||
endpoint
|
||||
)
|
||||
with self.expired_subs_lock:
|
||||
self.expired_subs.setdefault(notification.user, []).append(
|
||||
endpoint
|
||||
)
|
||||
logger.debug(
|
||||
f"Notification endpoint expired for {notification.user}, received {resp.status_code}"
|
||||
)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import Request
|
||||
from peewee import DoesNotExist
|
||||
@@ -841,42 +840,6 @@ class TestHttpReview(BaseTestHttp):
|
||||
response_json,
|
||||
)
|
||||
|
||||
def test_review_event_wildcards_match_literally(self):
|
||||
now = datetime.now().timestamp()
|
||||
super().insert_mock_review_segment(
|
||||
"123456.review.random",
|
||||
now + 1,
|
||||
now + 2,
|
||||
data={"detections": ["1763812345.0-abc123"]},
|
||||
)
|
||||
|
||||
with AuthTestClient(self.app) as client:
|
||||
for pattern in ["1763812345*", "176381234?.0-abc123", "176381234[0-9]*"]:
|
||||
response = client.get(f"/review/event/{quote(pattern, safe='')}")
|
||||
assert response.status_code == 404
|
||||
|
||||
response = client.get("/review/event/1763812345.0-abc123")
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_review_event_on_forbidden_camera_is_not_found(self):
|
||||
now = datetime.now().timestamp()
|
||||
event_id = "1763812345.0-abc123"
|
||||
super().insert_mock_review_segment(
|
||||
"123456.review.random",
|
||||
now + 1,
|
||||
now + 2,
|
||||
data={"detections": [event_id]},
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
with AuthTestClient(self.app) as client:
|
||||
response = client.get(f"/review/event/{event_id}")
|
||||
assert response.status_code == 404
|
||||
self.assertDictEqual(
|
||||
{"success": False, "message": "Review item not found"},
|
||||
response.json(),
|
||||
)
|
||||
|
||||
####################################################################################################################
|
||||
################################### GET /review/{review_id} Endpoint #######################################
|
||||
####################################################################################################################
|
||||
|
||||
@@ -332,18 +332,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
|
||||
self.assertIsNone(self._deny("/clips/back_door-1.jpg", "viewer"))
|
||||
self.assertIsNone(self._deny("/clips/", "viewer"))
|
||||
|
||||
def test_unrestricted_role_blocked_admin_only(self):
|
||||
for uri in (
|
||||
"/clips/faces/",
|
||||
"/clips/faces/train/foo.webp",
|
||||
"/clips/faces/alice/ref.webp",
|
||||
"/clips/genai-requests/x/0.jpg",
|
||||
"/clips/preview_restart_cache/x.mp4",
|
||||
"/clips/some_model/train/x.jpg",
|
||||
"/clips/some_model/dataset/cat/x.jpg",
|
||||
):
|
||||
self.assertEqual(self._deny(uri, "viewer"), 403, uri)
|
||||
|
||||
def test_restricted_role_allowed_camera(self):
|
||||
self.assertIsNone(self._deny("/clips/front_door-1.jpg", "limited_user"))
|
||||
self.assertIsNone(
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Tests for expired push subscription cleanup."""
|
||||
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.comms.webpush import WebPushClient
|
||||
from frigate.models import User
|
||||
|
||||
LIVE = {"endpoint": "https://push.example.com/live", "keys": {}}
|
||||
DEAD = {"endpoint": "https://push.example.com/dead", "keys": {}}
|
||||
|
||||
|
||||
class TestCleanupRegistrations(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.db = SqliteDatabase(":memory:")
|
||||
self.enterContext(self.db.bind_ctx([User]))
|
||||
self.db.create_tables([User])
|
||||
|
||||
User.create(
|
||||
username="alice", password_hash="x", notification_tokens=[LIVE, DEAD]
|
||||
)
|
||||
|
||||
self.client = WebPushClient.__new__(WebPushClient)
|
||||
self.client.web_pushers = {}
|
||||
self.client.expired_subs = {}
|
||||
self.client.expired_subs_lock = threading.Lock()
|
||||
self.client.cleanup_lock = threading.Lock()
|
||||
|
||||
def tearDown(self):
|
||||
self.db.close()
|
||||
|
||||
@patch("frigate.comms.webpush._build_web_pushers", return_value=[])
|
||||
def test_skips_deleted_user_and_prunes_the_rest(self, _build):
|
||||
self.client.expired_subs = {
|
||||
"deleted": ["https://push.example.com/gone"],
|
||||
"alice": [DEAD["endpoint"]],
|
||||
}
|
||||
|
||||
self.client.cleanup_registrations()
|
||||
|
||||
self.assertEqual(User.get_by_id("alice").notification_tokens, [LIVE])
|
||||
self.assertEqual(self.client.expired_subs, {})
|
||||
_build.assert_called_once_with("alice", [LIVE])
|
||||
|
||||
@patch("frigate.comms.webpush._build_web_pushers", return_value=[])
|
||||
def test_keeps_malformed_tokens_and_prunes_expired(self, _build):
|
||||
malformed = [None, {"keys": {}}]
|
||||
User.update(notification_tokens=[LIVE, *malformed, DEAD]).execute()
|
||||
self.client.expired_subs = {"alice": [DEAD["endpoint"]]}
|
||||
|
||||
self.client.cleanup_registrations()
|
||||
|
||||
self.assertEqual(
|
||||
User.get_by_id("alice").notification_tokens, [LIVE, *malformed]
|
||||
)
|
||||
Reference in New Issue
Block a user