Compare commits

..
Author SHA1 Message Date
Josh Hawkins c0157d7515 trim go2rtc stream metadata types to producer medias 2026-11-23 09:19:43 -06:00
Josh Hawkins f6eae237bf limit config, stream, stats, and metrics data for non-admin users
Non-admin users received data they never use in the UI: credentials embedded in camera paths, ffmpeg args, and go2rtc settings that the masking regex missed, process command lines over the websocket stats topic, every camera's metrics, and custom classification names for objects their cameras don't track.

- /config drops input paths, ffmpeg args, ffmpeg_cmds, webui_url, genai base_url and provider_options, and go2rtc sections other than stream names and webrtc for non-admins, and redacts profile notification emails
- /go2rtc/streams returns only producer medias to non-admins
- websocket and REST stats share one helper that strips cmdline and bandwidth_usages for non-admins
- /metrics requires admin
- custom classification categories only attach to labels the allowed cameras track
2026-11-23 09:08:27 -06:00
31 changed files with 670 additions and 132 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
# Metrics
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance.
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance. On the authenticated port (8971), the endpoint requires an admin user, so point scrapers at the internal port (5000) as shown below.
## Enabling Telemetry
+84 -3
View File
@@ -2546,7 +2546,7 @@ paths:
- App
summary: Metrics
description: |-
**Access:** Any authenticated user.
**Access:** Admin role required.
Expose Prometheus metrics endpoint and update metrics with latest stats
operationId: metrics_metrics_get
@@ -2557,8 +2557,8 @@ paths:
application/json:
schema: {}
security:
- frigateUserAuth: []
x-required-role: any
- frigateAdminAuth: []
x-required-role: admin
/genai/models:
get:
tags:
@@ -4608,6 +4608,14 @@ paths:
- type: 'null'
default: 1
title: Include Thumbnails
- name: favorites
in: query
required: false
schema:
anyOf:
- type: integer
- type: 'null'
title: Favorites
- name: min_score
in: query
required: false
@@ -5138,6 +5146,75 @@ paths:
security:
- frigateAdminAuth: []
x-required-role: admin
/events/{event_id}/retain:
post:
tags:
- Events
summary: Set event retain indefinitely.
description: |-
**Access:** Admin role required.
Sets an event to retain indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
operationId: set_retain_events__event_id__retain_post
parameters:
- name: event_id
in: path
required: true
schema:
type: string
title: Event Id
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/GenericResponse'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
delete:
tags:
- Events
summary: Stop event from being retained indefinitely
description: |-
**Access:** Admin role required.
Stops an event from being retained indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
operationId: delete_retain_events__event_id__retain_delete
parameters:
- name: event_id
in: path
required: true
schema:
type: string
title: Event Id
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/GenericResponse'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
/events/{event_id}/plus:
post:
tags:
@@ -8378,6 +8455,9 @@ components:
has_snapshot:
type: boolean
title: Has Snapshot
retain_indefinitely:
type: boolean
title: Retain Indefinitely
plus_id:
anyOf:
- type: string
@@ -8415,6 +8495,7 @@ components:
- thumbnail
- has_clip
- has_snapshot
- retain_indefinitely
- plus_id
- model_hash
- detector_type
+46 -35
View File
@@ -64,6 +64,7 @@ from frigate.util.builtin import (
is_masked_camera_path,
load_labels,
process_config_query_string,
scope_stats_for_non_admin,
split_config_key_path,
update_yaml_file_bulk,
)
@@ -131,37 +132,12 @@ def stats(
):
stats_data = request.app.stats_emitter.get_latest_stats()
# Admins see the full snapshot
if request.headers.get("remote-role") == "admin":
return JSONResponse(content=stats_data)
allowed_set = set(allowed_cameras)
# Shallow-copy so we don't mutate the cached stats history entry.
filtered = {**stats_data}
cameras = stats_data.get("cameras")
if cameras is not None:
filtered["cameras"] = {
name: data for name, data in cameras.items() if name in allowed_set
}
bandwidth = stats_data.get("bandwidth_usages")
if bandwidth is not None:
filtered["bandwidth_usages"] = {
name: data for name, data in bandwidth.items() if name in allowed_set
}
# cmdline can leak camera URLs/paths; strip but keep cpu/mem so
# client-side problem heuristics still work.
cpu_usages = stats_data.get("cpu_usages")
if cpu_usages is not None:
filtered["cpu_usages"] = {
pid: {k: v for k, v in usage.items() if k != "cmdline"}
for pid, usage in cpu_usages.items()
}
return JSONResponse(content=filtered)
return JSONResponse(
content=scope_stats_for_non_admin(stats_data, set(allowed_cameras))
)
@router.get("/stats/history", dependencies=[Depends(require_role(["admin"]))])
@@ -172,7 +148,7 @@ def stats_history(request: Request, keys: str = None):
return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys))
@router.get("/metrics", dependencies=[Depends(allow_any_authenticated())])
@router.get("/metrics", dependencies=[Depends(require_role(["admin"]))])
def metrics(request: Request):
"""Expose Prometheus metrics endpoint and update metrics with latest stats"""
# Retrieve the latest statistics and update the Prometheus metrics
@@ -320,10 +296,12 @@ def config(request: Request):
is_admin = request.headers.get("remote-role") == "admin"
# hide environment_vars and the notification email from non-admin users
# hide environment_vars, the notification email and ffmpeg args (which
# can carry auth headers) from non-admin users
if not is_admin:
config.pop("environment_vars", None)
redact_credential(config["notifications"], "email")
_drop_ffmpeg_args(config.get("ffmpeg", {}))
# redact mqtt credentials
redact_credential(config["mqtt"], "password")
@@ -331,11 +309,15 @@ def config(request: Request):
# redact proxy secret
redact_credential(config["proxy"], "auth_secret")
# redact genai api keys
# redact genai api keys; base_url and provider_options can carry proxy auth
for _genai_name, genai_cfg in config.get("genai", {}).items():
if isinstance(genai_cfg, dict):
redact_credential(genai_cfg, "api_key")
if not is_admin:
genai_cfg.pop("base_url", None)
genai_cfg.pop("provider_options", None)
for camera_name, camera in request.app.frigate_config.cameras.items():
camera_dict = config["cameras"][camera_name]
@@ -353,6 +335,19 @@ def config(request: Request):
for cmd in camera_dict["ffmpeg_cmds"]:
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
# masking misses vendor-specific credentials in paths and args, and the
# non-admin UI never reads them
if not is_admin:
ffmpeg = camera_dict.get("ffmpeg", {})
_drop_ffmpeg_args(ffmpeg)
for input in ffmpeg.get("inputs", []):
input["path"] = ""
_drop_ffmpeg_args(input)
camera_dict["ffmpeg_cmds"] = []
camera_dict.pop("webui_url", None)
# ensure that zones are relative
for zone_name, zone in config_obj.cameras[camera_name].zones.items():
camera_dict["zones"][zone_name]["color"] = zone.color
@@ -363,11 +358,13 @@ def config(request: Request):
# over the camera's actual base values (e.g. threshold=20).
if camera.profiles:
for profile_name, profile_config in camera.profiles.items():
camera_dict.setdefault("profiles", {})[profile_name] = (
profile_config.model_dump(
mode="json", warnings="none", exclude_unset=True
)
profile_dict = profile_config.model_dump(
mode="json", warnings="none", exclude_unset=True
)
camera_dict.setdefault("profiles", {})[profile_name] = profile_dict
if not is_admin:
redact_credential(profile_dict.get("notifications") or {}, "email")
# When a profile is active, the top-level camera sections contain
# profile-merged (effective) values. Include the original base
@@ -409,6 +406,15 @@ def config(request: Request):
_redact_go2rtc_credentials(config["go2rtc"])
if not is_admin:
# go2rtc allows arbitrary extra keys, so non-admins get only what the
# UI reads: stream names, and webrtc, whose ice_servers credentials
# the browser needs
config["go2rtc"] = {
"streams": {name: [] for name in config["go2rtc"].get("streams", {})},
"webrtc": config["go2rtc"].get("webrtc", {}),
}
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
for index, model in enumerate(config_obj.models):
@@ -435,6 +441,11 @@ def config(request: Request):
return JSONResponse(content=config)
def _drop_ffmpeg_args(ffmpeg: dict[str, Any]) -> None:
for key in ("global_args", "input_args", "output_args"):
ffmpeg.pop(key, None)
def _redact_go2rtc_credentials(go2rtc: dict[str, Any]) -> None:
"""Redact go2rtc secrets outside of stream URLs, in place."""
for section in ("rtsp", "api", "mqtt"):
+3 -2
View File
@@ -81,10 +81,11 @@ def require_admin_by_default():
"/",
"/version",
"/config/schema.json",
# Authenticated user endpoints (allow_any_authenticated)
# Admin endpoints that enforce require_role on the route
"/metrics",
"/stats",
"/stats/history",
# Authenticated user endpoints (allow_any_authenticated)
"/stats",
"/config",
"/vainfo",
"/nvinfo",
+24 -8
View File
@@ -6,6 +6,7 @@ import logging
import re
from importlib.util import find_spec
from pathlib import Path
from typing import Any
from urllib.parse import quote_plus
import httpx
@@ -82,6 +83,23 @@ def _is_valid_host(host: str) -> bool:
return False
def _clean_stream(request: Request, stream: dict[str, Any]) -> dict[str, Any]:
"""Mask producer urls for admins; others get only producer medias.
Producer and consumer urls and sources can carry credentials that masking
misses, and the non-admin UI only reads producer medias.
"""
producers = stream.get("producers") or []
if request.headers.get("remote-role") != "admin":
return {"producers": [{"medias": p.get("medias")} for p in producers]}
for producer in producers:
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
return stream
@router.get("/go2rtc/streams", dependencies=[Depends(allow_any_authenticated())])
async def go2rtc_streams(request: Request):
try:
@@ -114,10 +132,11 @@ async def go2rtc_streams(request: Request):
if _get_stream_owner_cameras(request, name) & allowed_cameras
}
for data in stream_data.values():
for producer in data.get("producers") or []:
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
return JSONResponse(content=stream_data)
return JSONResponse(
content={
name: _clean_stream(request, data) for name, data in stream_data.items()
}
)
@router.get(
@@ -155,10 +174,7 @@ def go2rtc_camera_stream(request: Request, stream_name: str):
content=({"success": False, "message": "Error fetching stream data"}),
status_code=500,
)
stream_data = r.json()
for producer in stream_data.get("producers", []):
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
return JSONResponse(content=stream_data)
return JSONResponse(content=_clean_stream(request, r.json()))
@router.put(
@@ -29,6 +29,7 @@ class EventsQueryParams(BaseModel):
),
deprecated=True,
)
favorites: int | None = None
min_score: float | None = None
max_score: float | None = None
min_speed: float | None = None
@@ -15,6 +15,7 @@ class EventResponse(BaseModel):
thumbnail: str | None
has_clip: bool
has_snapshot: bool
retain_indefinitely: bool
plus_id: str | None
model_hash: str | None
detector_type: str | None
+64
View File
@@ -137,6 +137,7 @@ def events(
has_snapshot = params.has_snapshot
in_progress = params.in_progress
include_thumbnails = params.include_thumbnails
favorites = params.favorites
min_score = params.min_score
max_score = params.max_score
min_speed = params.min_speed
@@ -161,6 +162,7 @@ def events(
Event.has_clip,
Event.has_snapshot,
Event.plus_id,
Event.retain_indefinitely,
Event.sub_label,
Event.top_score,
Event.false_positive,
@@ -305,6 +307,9 @@ def events(
if include_thumbnails:
selected_columns.append(Event.thumbnail)
if favorites:
clauses.append(Event.retain_indefinitely == favorites)
if max_score is not None:
clauses.append(Event.data["score"] <= max_score)
@@ -405,6 +410,7 @@ def events_explore(
Event.has_clip,
Event.has_snapshot,
Event.plus_id,
Event.retain_indefinitely,
Event.top_score,
Event.false_positive,
Event.box,
@@ -445,6 +451,7 @@ def events_explore(
"has_clip": event.has_clip,
"has_snapshot": event.has_snapshot,
"plus_id": event.plus_id,
"retain_indefinitely": event.retain_indefinitely,
"sub_label": event.sub_label,
"top_score": event.top_score,
"false_positive": event.false_positive,
@@ -1019,6 +1026,34 @@ async def event(event_id: str, request: Request):
return JSONResponse(content="Event not found", status_code=404)
@router.post(
"/events/{event_id}/retain",
response_model=GenericResponse,
dependencies=[Depends(require_role(["admin"]))],
summary="Set event retain indefinitely.",
description="""Sets an event to retain indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
""",
)
def set_retain(event_id: str):
try:
event = Event.get(Event.id == event_id)
except DoesNotExist:
return JSONResponse(
content=({"success": False, "message": "Event " + event_id + " not found"}),
status_code=404,
)
event.retain_indefinitely = True
event.save()
return JSONResponse(
content=({"success": True, "message": "Event " + event_id + " retained"}),
status_code=200,
)
@router.post(
"/events/{event_id}/plus",
response_model=EventUploadPlusResponse,
@@ -1243,6 +1278,35 @@ async def false_positive(request: Request, event_id: str):
)
@router.delete(
"/events/{event_id}/retain",
response_model=GenericResponse,
dependencies=[Depends(require_role(["admin"]))],
summary="Stop event from being retained indefinitely",
description="""Stops an event from being retained indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
""",
)
async def delete_retain(event_id: str, request: Request):
try:
event = Event.get(Event.id == event_id)
await require_camera_access(event.camera, request=request)
except DoesNotExist:
return JSONResponse(
content=({"success": False, "message": "Event " + event_id + " not found"}),
status_code=404,
)
event.retain_indefinitely = False
event.save()
return JSONResponse(
content=({"success": True, "message": "Event " + event_id + " un-retained"}),
status_code=200,
)
@router.post(
"/events/{event_id}/sub_label",
response_model=GenericResponse,
+7 -12
View File
@@ -40,6 +40,7 @@ from frigate.const import (
)
from frigate.models import User
from frigate.output.ws_auth import ws_has_camera_access
from frigate.util.builtin import scope_stats_for_non_admin
from frigate.util.origin import origin_allowed
logger = logging.getLogger(__name__)
@@ -210,7 +211,7 @@ _WS_RESHAPE_JOB_STATE_TOPICS = frozenset(
# Topics whose payload mixes global aggregates with a ``cameras`` sub-dict
# keyed by camera name. Aggregates and detector data stay; per-camera entries
# are filtered.
# are filtered and process cmdlines are stripped for non-admins.
_WS_RESHAPE_STATS_TOPICS = frozenset(
{
"stats",
@@ -455,20 +456,14 @@ def _materialize_for_ws(
return _wrap_envelope(topic, filtered_jobs)
if kind == "reshape_stats":
if _ws_is_unrestricted(ws, config):
if "admin" in _ws_valid_roles(ws, config):
return full_message
if not isinstance(parsed_payload, dict):
return None
allowed = _ws_allowed_cameras(ws, config)
cameras_block = parsed_payload.get("cameras")
if isinstance(cameras_block, dict):
filtered_cameras = {
name: data for name, data in cameras_block.items() if name in allowed
}
reshaped = dict(parsed_payload)
reshaped["cameras"] = filtered_cameras
return _wrap_envelope(topic, reshaped)
return full_message
return _wrap_envelope(
topic,
scope_stats_for_non_admin(parsed_payload, _ws_allowed_cameras(ws, config)),
)
return None
+6
View File
@@ -92,6 +92,7 @@ class EventCleanup(threading.Thread):
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True,
)
.namedtuples()
@@ -113,6 +114,7 @@ class EventCleanup(threading.Thread):
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True,
)
@@ -168,6 +170,7 @@ class EventCleanup(threading.Thread):
Event.camera == name,
Event.start_time < expire_after,
Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True,
)
.namedtuples()
@@ -219,6 +222,7 @@ class EventCleanup(threading.Thread):
.where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
)
.namedtuples()
.iterator()
@@ -248,6 +252,7 @@ class EventCleanup(threading.Thread):
query = Event.select(Event.id).where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
)
events_to_update = []
@@ -292,6 +297,7 @@ class EventCleanup(threading.Thread):
)
.where(
Event.camera == name,
Event.retain_indefinitely == False,
(
(
(Event.data["max_severity"] != "detection")
+1
View File
@@ -40,6 +40,7 @@ class Event(Model):
area = (
IntegerField()
) # TODO remove when columns can be dropped without rebuilding table
retain_indefinitely = BooleanField(default=False)
ratio = FloatField(
default=1.0
) # TODO remove when columns can be dropped without rebuilding table
+76 -8
View File
@@ -263,24 +263,92 @@ class StorageMaintainer(threading.Thread):
.iterator()
)
retained_events = (
Event.select(
Event.start_time,
Event.end_time,
)
.where(
Event.retain_indefinitely == True,
Event.has_clip,
)
.order_by(Event.start_time.asc())
.namedtuples()
)
event_start = 0
deleted_recordings = []
for recording in recordings:
# check if 1 hour of storage has been reclaimed
if deleted_segments_size > hourly_bandwidth:
break
try:
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_recordings.append(recording)
deleted_segments_size += recording.segment_size
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
keep = False
# Now look for a reason to keep this recording segment
for idx in range(event_start, len(retained_events)):
event = retained_events[idx]
# if the event starts in the future, stop checking events
# and let this recording segment expire
if event.start_time > recording.end_time:
keep = False
break
# if the event is in progress or ends after the recording starts, keep it
# and stop looking at events
if event.end_time is None or event.end_time >= recording.start_time:
keep = True
break
# if the event ends before this recording segment starts, skip
# this event and check the next event for an overlap.
# since the events and recordings are sorted, we can skip events
# that end before the previous recording segment started on future segments
if event.end_time < recording.start_time:
event_start = idx
# Delete recordings not retained indefinitely
if not keep:
try:
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_recordings.append(recording)
deleted_segments_size += recording.segment_size
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
# check if need to delete retained segments
if deleted_segments_size < hourly_bandwidth:
logger.error(
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared."
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared. Retained recordings must be deleted."
)
recordings = (
Recordings.select(
Recordings.id,
Recordings.camera,
Recordings.start_time,
Recordings.end_time,
Recordings.path,
Recordings.segment_size,
)
.order_by(Recordings.start_time.asc())
.namedtuples()
.iterator()
)
for recording in recordings:
if deleted_segments_size > hourly_bandwidth:
break
try:
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_segments_size += recording.segment_size
deleted_recordings.append(recording)
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
self.retention_unmet = True
else:
logger.info(f"Cleaned up {deleted_segments_size:.2f} MB of recordings")
+177
View File
@@ -1,3 +1,4 @@
import copy
import json
import os
from unittest.mock import Mock, patch
@@ -30,6 +31,23 @@ class TestHttpApp(BaseTestHttp):
response_json = response.json()
assert response_json == self.test_stats
def test_stats_endpoint_strips_cmdline_for_viewers(self):
stats = Mock(spec=StatsEmitter)
stats.get_latest_stats.return_value = {
**self.test_stats,
"cpu_usages": {"52": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
"bandwidth_usages": {"52": {"bandwidth": 1.0}},
}
app = super().create_app(stats)
with AuthTestClient(app) as client:
response = client.get(
"/stats",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.json()["cpu_usages"] == {"52": {"cpu": "1.0"}}
assert "bandwidth_usages" not in response.json()
def test_recordings_storage_requires_admin(self):
stats = Mock(spec=StatsEmitter)
stats.get_latest_stats.return_value = self.test_stats
@@ -154,6 +172,10 @@ class TestHttpApp(BaseTestHttp):
def test_config_response_hides_notification_email_from_viewers(self):
self.minimal_config["notifications"] = {"email": "{FRIGATE_TEST_EMAIL}"}
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
self.minimal_config["cameras"]["front_door"]["profiles"] = {
"away": {"notifications": {"email": "{FRIGATE_TEST_EMAIL}"}}
}
with patch.dict(FRIGATE_ENV_VARS, {"FRIGATE_TEST_EMAIL": "me@example.com"}):
app = super().create_app()
@@ -172,10 +194,165 @@ class TestHttpApp(BaseTestHttp):
config["cameras"]["front_door"]["notifications"]["email"]
== REDACTED_CREDENTIAL_SENTINEL
)
assert (
config["cameras"]["front_door"]["profiles"]["away"]["notifications"][
"email"
]
== REDACTED_CREDENTIAL_SENTINEL
)
response = client.get("/config")
assert response.json()["notifications"]["email"] == "me@example.com"
def test_config_response_limits_urls_and_go2rtc_for_viewers(self):
secret_path = "rtsp://10.0.0.1:554/user=admin_password=hunter2_channel=1"
self.minimal_config["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"] = (
secret_path
)
auth_header = "-headers 'Authorization: Basic c2VjcmV0'"
args = {
"global_args": auth_header,
"input_args": auth_header,
"output_args": {"detect": auth_header},
}
self.minimal_config["ffmpeg"] = dict(args)
front_door = self.minimal_config["cameras"]["front_door"]
front_door["ffmpeg"].update(args)
front_door["ffmpeg"]["inputs"][0].update(
global_args=auth_header, input_args=auth_header
)
front_door["webui_url"] = "http://admin:hunter2@10.0.0.1/"
self.minimal_config["go2rtc"] = {
"streams": {"front_door": [secret_path, "ffmpeg:front_door#audio=opus"]},
"webrtc": {"candidates": ["10.0.0.2:8555"]},
"webtorrent": {"shares": {"share": {"src": "front_door", "pwd": "x"}}},
}
app = super().create_app()
with AuthTestClient(app) as client:
response = client.get(
"/config",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.status_code == 200
config = response.json()
camera = config["cameras"]["front_door"]
assert camera["ffmpeg"]["inputs"][0]["path"] == ""
assert camera["ffmpeg_cmds"] == []
assert "webui_url" not in camera
assert "hunter2" not in response.text
assert "c2VjcmV0" not in response.text
assert config["go2rtc"] == {
"streams": {"front_door": []},
"webrtc": {"candidates": ["10.0.0.2:8555"]},
}
config = client.get("/config").json()
camera = config["cameras"]["front_door"]
assert camera["ffmpeg"]["inputs"][0]["path"] == secret_path
assert camera["ffmpeg"]["inputs"][0]["input_args"] == auth_header
assert camera["ffmpeg"]["input_args"] == auth_header
assert camera["ffmpeg_cmds"]
assert config["go2rtc"]["streams"]["front_door"][0] == secret_path
assert "webtorrent" in config["go2rtc"]
def test_config_response_hides_genai_endpoint_from_viewers(self):
self.minimal_config["genai"] = {
"local": {
"provider": "ollama",
"model": "llava",
"base_url": "http://user:pass@ollama:11434",
"provider_options": {"keep_alive": -1},
}
}
app = super().create_app()
with AuthTestClient(app) as client:
genai = client.get(
"/config",
headers={"remote-user": "viewer", "remote-role": "viewer"},
).json()["genai"]["local"]
assert "base_url" not in genai
assert "provider_options" not in genai
assert genai["provider"] == "ollama"
genai = client.get("/config").json()["genai"]["local"]
assert genai["base_url"] == "http://user:pass@ollama:11434"
def test_metrics_requires_admin(self):
stats = Mock(spec=StatsEmitter)
stats.get_latest_stats.return_value = self.test_stats
app = super().create_app(stats)
with AuthTestClient(app) as client:
response = client.get(
"/metrics",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.status_code == 403
assert client.get("/metrics").status_code == 200
def test_config_response_allows_null_profile_notifications(self):
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
self.minimal_config["cameras"]["front_door"]["profiles"] = {
"away": {"notifications": None}
}
app = super().create_app()
with AuthTestClient(app) as client:
response = client.get(
"/config",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.status_code == 200
def test_go2rtc_stream_producer_sources_hidden_from_viewers(self):
secret_url = "ffmpeg:rtsp://admin:hunter2@10.0.0.1:554/live"
stream = {
"producers": [
{
"url": secret_url,
"source": "ffmpeg -i rtsp://admin:hunter2@10.0.0.1:554/live",
"medias": ["video, recvonly, H264"],
}
],
"consumers": [{"url": "rtmp://a.rtmp.youtube.com/live2/hunter2"}],
}
app = super().create_app()
viewer = {"remote-user": "viewer", "remote-role": "viewer"}
with (
patch("frigate.api.camera.requests.get") as get,
AuthTestClient(app) as client,
):
get.return_value.json.side_effect = lambda: copy.deepcopy(stream)
viewer_stream = {"producers": [{"medias": ["video, recvonly, H264"]}]}
response = client.get("/go2rtc/streams/front_door", headers=viewer)
assert response.json() == viewer_stream
producer = client.get("/go2rtc/streams/front_door").json()["producers"][0]
assert producer["medias"] == ["video, recvonly, H264"]
assert "hunter2" not in producer["url"]
get.return_value.json.side_effect = lambda: {
"front_door": copy.deepcopy(stream)
}
response = client.get("/go2rtc/streams", headers=viewer)
assert response.json() == {"front_door": viewer_stream}
# unconnected streams have url-only producers and null consumers
get.return_value.json.side_effect = lambda: {
"front_door": {"producers": [{"url": secret_url}], "consumers": None}
}
response = client.get("/go2rtc/streams")
assert response.status_code == 200
assert "hunter2" not in response.text
response = client.get("/go2rtc/streams", headers=viewer)
assert response.json() == {"front_door": {"producers": [{"medias": None}]}}
def test_config_response_keeps_plus_model_reference(self):
model_id = "test_plus_reference"
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
+33 -3
View File
@@ -374,6 +374,22 @@ class TestHttpApp(BaseTestHttp):
event_after_delete = client.get(f"/events/{id}")
assert event_after_delete.status_code == 404
def test_event_retention(self):
id = "123456.random"
with AuthTestClient(self.app) as client:
super().insert_mock_event(id)
client.post(f"/events/{id}/retain", headers={"remote-role": "admin"})
event = client.get(f"/events/{id}").json()
assert event
assert event["id"] == id
assert event["retain_indefinitely"] is True
client.delete(f"/events/{id}/retain", headers={"remote-role": "admin"})
event = client.get(f"/events/{id}").json()
assert event
assert event["id"] == id
assert event["retain_indefinitely"] is False
def test_event_time_filtering(self):
morning_id = "123456.random"
evening_id = "654321.random"
@@ -511,32 +527,42 @@ class TestHttpApp(BaseTestHttp):
with AuthTestClient(self.app) as client:
ts_start = datetime.now().timestamp()
ts_end = ts_start + 30
_insert_mock_event(id="abcde.random", start=ts_start, end=ts_end)
_insert_mock_event(id="01234.random", start=ts_start, end=ts_end)
_insert_mock_event(id="56789.random", start=ts_start, end=ts_end)
_insert_mock_event(
id="abcde.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event(
id="01234.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event(
id="56789.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event(
id="101112.random",
label="outside",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="131415.random",
label="outside",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="161718.random",
camera="porch",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="192021.random",
camera="porch",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="222324.random",
@@ -544,6 +570,7 @@ class TestHttpApp(BaseTestHttp):
label="inside",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="252627.random",
@@ -551,18 +578,21 @@ class TestHttpApp(BaseTestHttp):
label="inside",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="282930.random",
label="inside",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="313233.random",
label="inside",
start=ts_start,
end=ts_end,
retain=True,
)
stats_emitter = Mock(spec=StatsEmitter)
@@ -122,6 +122,7 @@ class TestExecuteFindSimilarObjects(unittest.TestCase):
region=[0, 0, 1, 1],
box=[0, 0, 1, 1],
area=1,
retain_indefinitely=False,
ratio=1.0,
plus_id="",
model_hash="",
+1
View File
@@ -242,6 +242,7 @@ class DatabaseTestCase(unittest.TestCase):
region=[0, 0, 1, 1],
box=[0, 0, 1, 1],
area=1,
retain_indefinitely=False,
ratio=1.0,
plus_id="",
model_hash="",
@@ -59,6 +59,7 @@ class TestEventCleanupSnapshots(unittest.TestCase):
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
+1
View File
@@ -68,6 +68,7 @@ class TestEventCleanupSubRetention(unittest.TestCase):
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
+67
View File
@@ -0,0 +1,67 @@
import unittest
from unittest.mock import patch
from frigate.config import FrigateConfig
from frigate.util.object_names import get_categorized_object_names
class TestCategorizedObjectNames(unittest.TestCase):
def setUp(self):
self.config = FrigateConfig(
**{
"mqtt": {"host": "mqtt"},
"cameras": {
"front_door": {
"ffmpeg": {
"inputs": [
{
"path": "rtsp://10.0.0.1:554/video",
"roles": ["detect"],
}
]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
"objects": {"track": ["person"]},
},
"yard": {
"ffmpeg": {
"inputs": [
{
"path": "rtsp://10.0.0.2:554/video",
"roles": ["detect"],
}
]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
"objects": {"track": ["person", "dog"]},
},
},
"classification": {
"custom": {
"pets": {
"object_config": {
"objects": ["dog"],
"classification_type": "sub_label",
}
}
}
},
}
)
@patch(
"frigate.util.object_names._get_classification_categories",
return_value={"rex"},
)
def test_classification_categories_limited_to_tracked_objects(self, _categories):
names = get_categorized_object_names(self.config, ["front_door"])
self.assertNotIn("dog", names)
self.assertNotIn("dog", get_categorized_object_names(self.config, []))
names = get_categorized_object_names(self.config, ["yard"])
self.assertEqual(names["dog"], ["rex"])
if __name__ == "__main__":
unittest.main()
@@ -98,6 +98,7 @@ class TestRegeneratedSubLabels(unittest.TestCase):
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
+17 -19
View File
@@ -1,5 +1,4 @@
import datetime
import gc
import logging
import os
import tempfile
@@ -448,7 +447,12 @@ class TestHttp(unittest.TestCase):
id = "123456.keep"
time_keep = datetime.datetime.now().timestamp()
_insert_mock_event(id, time_keep, time_keep + 30)
_insert_mock_event(
id,
time_keep,
time_keep + 30,
True,
)
rec_k_id = "1234567.keep"
rec_k2_id = "1234568.keep"
rec_k3_id = "1234569.keep"
@@ -473,7 +477,7 @@ class TestHttp(unittest.TestCase):
id2 = "7890.delete"
time_delete = datetime.datetime.now().timestamp() - 360
_insert_mock_event(id2, time_delete, time_delete + 30)
_insert_mock_event(id2, time_delete, time_delete + 30, False)
rec_d_id = "78901.delete"
rec_d2_id = "78902.delete"
rec_d3_id = "78903.delete"
@@ -506,15 +510,14 @@ class TestHttp(unittest.TestCase):
Recordings.get(Recordings.id == rec_d2_id)
Recordings.get(Recordings.id == rec_d3_id)
def test_storage_cleanup_deletes_oldest_first(self):
"""Ensure cleanup deletes the oldest segments and only expires their events."""
def test_storage_cleanup_keeps_retained(self):
"""Ensure cleanup steps over retained segments to reach newer ones."""
config = FrigateConfig(**self.minimal_config)
storage = StorageMaintainer(config, MagicMock())
seg_len = 600
base = datetime.datetime.now().timestamp() - 7200
_insert_mock_event("old.event", base, base + 2.5 * seg_len)
_insert_mock_event("new.event", base + 8 * seg_len, base + 9.5 * seg_len)
_insert_mock_event("123456.keep", base, base + 2.5 * seg_len, True)
paths = {}
for i in range(10):
@@ -524,23 +527,16 @@ class TestHttp(unittest.TestCase):
rec_id, paths[rec_id], base + i * seg_len, base + (i + 1) * seg_len
)
# Hourly bandwidth is 48 MB, so cleanup removes the oldest 56 MB
# Hourly bandwidth is 48 MB, so cleanup needs all 56 MB of unretained
# segments and must pass the older retained ones to get there.
storage.calculate_camera_bandwidth()
storage.reduce_storage_consumption()
# flush the queued writes, and collect the abandoned recordings
# cursor so this connection stops reading its stale snapshot
self.db.stop()
self.db.start()
gc.collect()
kept = {"segment-7", "segment-8", "segment-9"}
retained = {"segment-0", "segment-1", "segment-2"}
remaining = {r.id for r in Recordings.select(Recordings.id)}
on_disk = {rec_id for rec_id, path in paths.items() if os.path.exists(path)}
self.assertEqual(remaining, kept)
self.assertEqual(on_disk, kept)
self.assertFalse(Event.get(Event.id == "old.event").has_clip)
self.assertTrue(Event.get(Event.id == "new.event").has_clip)
self.assertEqual(remaining, retained)
self.assertEqual(on_disk, retained)
self.assertFalse(storage.retention_unmet)
def test_unmet_retention_sets_the_live_flag(self):
@@ -570,6 +566,7 @@ def _insert_mock_event(
id: str,
start: int,
end: int,
retain: bool,
camera: str = "front_door",
label: str = "Mock",
) -> Event:
@@ -589,6 +586,7 @@ def _insert_mock_event(
area=0,
has_clip=True,
has_snapshot=True,
retain_indefinitely=retain,
).execute()
+13
View File
@@ -517,6 +517,8 @@ class TestMaterializeForWs(unittest.TestCase):
"garage": {"camera_fps": 5.0, "pid": 1236},
},
"detectors": {"cpu": {"detection_start": 0.0, "inference_speed": 10}},
"cpu_usages": {"1234": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
"bandwidth_usages": {"1234": {"bandwidth": 1.0}},
"service": {"uptime": 12345, "version": "0.16.0"},
"camera_fps": 15.0,
"detection_fps": 6.0,
@@ -540,6 +542,17 @@ class TestMaterializeForWs(unittest.TestCase):
self.assertIn("detectors", inner)
self.assertIn("service", inner)
def test_stats_non_admin_gets_no_cmdline(self):
for role in ("viewer", "house_only"):
message = self._materialize(_ws(role), "stats", self._stats_payload())
inner = json.loads(json.loads(message)["payload"]) # type: ignore[arg-type]
self.assertEqual(inner["cpu_usages"], {"1234": {"cpu": "1.0"}})
self.assertNotIn("bandwidth_usages", inner)
message = self._materialize(_ws("viewer"), "stats", self._stats_payload())
inner = json.loads(json.loads(message)["payload"]) # type: ignore[arg-type]
self.assertIn("garage", inner["cameras"])
def test_stats_restricted_with_no_allowed_cameras_still_sends_aggregates(self):
"""A restricted role whose allow-list contains only nonexistent cameras
still gets the global aggregates and service block."""
+28
View File
@@ -131,6 +131,34 @@ def clean_camera_user_pass(line: str) -> str:
return re.sub(REGEX_CREDENTIAL_QUERY_PARAM, r"\1*", line)
def scope_stats_for_non_admin(
stats: dict[str, Any], allowed_cameras: set[str]
) -> dict[str, Any]:
"""Return a copy of stats limited to allowed_cameras, without process cmdlines.
cmdline can leak camera URLs and paths. cpu and mem stay so client-side
problem heuristics still work. bandwidth_usages is keyed by pid and can't
be scoped to cameras.
"""
scoped = {**stats}
scoped.pop("bandwidth_usages", None)
if stats.get("cameras") is not None:
scoped["cameras"] = {
name: data
for name, data in stats["cameras"].items()
if name in allowed_cameras
}
if stats.get("cpu_usages") is not None:
scoped["cpu_usages"] = {
pid: {k: v for k, v in usage.items() if k != "cmdline"}
for pid, usage in stats["cpu_usages"].items()
}
return scoped
def _mask_userinfo(match: re.Match[str]) -> str:
# A credential key in the userinfo means a query password holds "@" or a
# password holds a query key. Neither split is safe, so mask the whole URL.
+2 -1
View File
@@ -91,7 +91,8 @@ def get_categorized_object_names(
continue
for label in model_config.object_config.objects:
names.setdefault(label, set()).update(categories)
if label in tracked_objects:
names.setdefault(label, set()).update(categories)
return {
label: sorted(label_names)
+6 -4
View File
@@ -23,15 +23,17 @@ Some examples (model - class or model name)::
import peewee as pw
from frigate.models import Event
SQL = pw.SQL
def migrate(migrator, database, fake=False, **kwargs):
# raw SQL keeps the dropped field off the Event model (removed in 041)
migrator.sql(
'ALTER TABLE "event" ADD COLUMN "retain_indefinitely" INTEGER NOT NULL DEFAULT 0'
migrator.add_fields(
Event,
retain_indefinitely=pw.BooleanField(default=False),
)
def rollback(migrator, database, fake=False, **kwargs):
migrator.sql('ALTER TABLE "event" DROP COLUMN "retain_indefinitely"')
migrator.remove_fields(Event, ["retain_indefinitely"])
@@ -1,15 +0,0 @@
"""Peewee migrations -- 041_remove_retain_indefinitely.py."""
import peewee as pw
SQL = pw.SQL
def migrate(migrator, database, fake=False, **kwargs):
migrator.sql('ALTER TABLE "event" DROP COLUMN "retain_indefinitely"')
def rollback(migrator, database, fake=False, **kwargs):
migrator.sql(
'ALTER TABLE "event" ADD COLUMN "retain_indefinitely" INTEGER NOT NULL DEFAULT 0'
)
+1 -1
View File
@@ -1 +1 @@
[{"id": "event-person-001", "label": "person", "sub_label": null, "camera": "front_door", "start_time": 1780677009.365581, "end_time": 1780677039.365581, "false_positive": false, "zones": ["front_yard"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "plus_id": null, "model_hash": "abc123", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.92, "score": 0.92, "region": [0.1, 0.1, 0.5, 0.8], "box": [0.2, 0.15, 0.45, 0.75], "area": 0.18, "ratio": 0.6, "type": "object", "description": "A person walking toward the front door", "average_estimated_speed": 1.2, "velocity_angle": 45.0, "path_data": [[[0.2, 0.5], 0.0], [[0.3, 0.5], 1.0]]}}, {"id": "event-car-001", "label": "car", "sub_label": null, "camera": "backyard", "start_time": 1780673409.365581, "end_time": 1780673454.365581, "false_positive": false, "zones": ["driveway"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "plus_id": null, "model_hash": "def456", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.87, "score": 0.87, "region": [0.3, 0.2, 0.9, 0.7], "box": [0.35, 0.25, 0.85, 0.65], "area": 0.2, "ratio": 1.25, "type": "object", "description": "A car parked in the driveway", "average_estimated_speed": 0.0, "velocity_angle": 0.0, "path_data": []}}, {"id": "event-person-002", "label": "person", "sub_label": null, "camera": "garage", "start_time": 1780669809.365581, "end_time": 1780669829.365581, "false_positive": false, "zones": [], "thumbnail": null, "has_clip": false, "has_snapshot": true, "plus_id": null, "model_hash": "ghi789", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.78, "score": 0.78, "region": [0.0, 0.0, 0.6, 0.9], "box": [0.1, 0.05, 0.5, 0.85], "area": 0.32, "ratio": 0.5, "type": "object", "description": null, "average_estimated_speed": 0.5, "velocity_angle": 90.0, "path_data": [[[0.1, 0.4], 0.0]]}}]
[{"id": "event-person-001", "label": "person", "sub_label": null, "camera": "front_door", "start_time": 1780677009.365581, "end_time": 1780677039.365581, "false_positive": false, "zones": ["front_yard"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "retain_indefinitely": false, "plus_id": null, "model_hash": "abc123", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.92, "score": 0.92, "region": [0.1, 0.1, 0.5, 0.8], "box": [0.2, 0.15, 0.45, 0.75], "area": 0.18, "ratio": 0.6, "type": "object", "description": "A person walking toward the front door", "average_estimated_speed": 1.2, "velocity_angle": 45.0, "path_data": [[[0.2, 0.5], 0.0], [[0.3, 0.5], 1.0]]}}, {"id": "event-car-001", "label": "car", "sub_label": null, "camera": "backyard", "start_time": 1780673409.365581, "end_time": 1780673454.365581, "false_positive": false, "zones": ["driveway"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "retain_indefinitely": false, "plus_id": null, "model_hash": "def456", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.87, "score": 0.87, "region": [0.3, 0.2, 0.9, 0.7], "box": [0.35, 0.25, 0.85, 0.65], "area": 0.2, "ratio": 1.25, "type": "object", "description": "A car parked in the driveway", "average_estimated_speed": 0.0, "velocity_angle": 0.0, "path_data": []}}, {"id": "event-person-002", "label": "person", "sub_label": null, "camera": "garage", "start_time": 1780669809.365581, "end_time": 1780669829.365581, "false_positive": false, "zones": [], "thumbnail": null, "has_clip": false, "has_snapshot": true, "retain_indefinitely": false, "plus_id": null, "model_hash": "ghi789", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.78, "score": 0.78, "region": [0.0, 0.0, 0.6, 0.9], "box": [0.1, 0.05, 0.5, 0.85], "area": 0.32, "ratio": 0.5, "type": "object", "description": null, "average_estimated_speed": 0.5, "velocity_angle": 90.0, "path_data": [[[0.1, 0.4], 0.0]]}}]
@@ -234,6 +234,7 @@ def generate_events():
thumbnail=None,
has_clip=True,
has_snapshot=True,
retain_indefinitely=False,
plus_id=None,
model_hash="abc123",
detector_type="cpu",
@@ -264,6 +265,7 @@ def generate_events():
thumbnail=None,
has_clip=True,
has_snapshot=True,
retain_indefinitely=False,
plus_id=None,
model_hash="def456",
detector_type="cpu",
@@ -294,6 +296,7 @@ def generate_events():
thumbnail=None,
has_clip=False,
has_snapshot=True,
retain_indefinitely=False,
plus_id=None,
model_hash="ghi789",
detector_type="cpu",
+2
View File
@@ -42,6 +42,7 @@ const GROUPED_EVENT = {
thumbnail: null,
has_clip: true,
has_snapshot: true,
retain_indefinitely: false,
plus_id: null,
model_hash: "abc123",
detector_type: "cpu",
@@ -425,6 +426,7 @@ test.describe("FaceSelectionDialog @high", () => {
thumbnail: null,
has_clip: true,
has_snapshot: true,
retain_indefinitely: false,
plus_id: null,
model_hash: "abc123",
detector_type: "cpu",
+1
View File
@@ -10,6 +10,7 @@ export interface Event {
thumbnail: string;
has_clip: boolean;
has_snapshot: boolean;
retain_indefinitely: boolean;
plus_id?: string;
model_hash?: string;
data: {
+1 -20
View File
@@ -5,30 +5,11 @@ export type VideoResolutionType = {
};
type LiveProducerMetadata = {
type: string;
url: string;
remote_addr: string;
user_agent: string;
sdp: string;
medias?: string[];
receivers?: string[];
recv: number;
};
type LiveConsumerMetadata = {
type: string;
url: string;
remote_addr: string;
user_agent: string;
sdp: string;
medias?: string[];
senders?: string[];
send: number;
medias?: string[] | null;
};
export type LiveStreamMetadata = {
producers: LiveProducerMetadata[];
consumers: LiveConsumerMetadata[];
};
// mse-codec is go2rtc's proof that it has no codec this browser plays;