Compare commits

..
Author SHA1 Message Date
Josh Hawkins 3fd261b8bc remove event retain and retain_indefinitely
Retaining an event only protected its footage during low-disk cleanup, and cleanup undid that a cycle later: it marked every event in the deleted time window as having no clip, including retained events it had kept, so the next pass deleted their footage. The UI hasn't set the flag in many versions and exports are the supported way to keep footage, so this removes the /events/{event_id}/retain endpoints, the favorites filter and the retain_indefinitely column. Storage cleanup is now a single oldest-first pass. Migration 007 now adds the column with raw SQL because add_fields put the field back on the Event model in the process that ran migrations, which broke inserts after 041 dropped it on fresh installs.
2026-11-23 08:16:11 -06:00
36 changed files with 91 additions and 451 deletions
@@ -22,6 +22,3 @@ add_header Set-Cookie $auth_cookie;
## Pass the location header back up if it exists
auth_request_set $redirection_url $upstream_http_location;
add_header Location $redirection_url;
## The add_header lines above stop this location inheriting server-level headers
include security_headers.conf;
@@ -152,6 +152,7 @@ http {
sub_filter '.m4s' '.m4s$is_args$args';
sub_filter '.mp4"' '.mp4$is_args$args"';
include security_headers.conf;
add_header Cache-Control "no-store";
expires off;
@@ -160,6 +161,7 @@ http {
location /stream/ {
include auth_request.conf;
include security_headers.conf;
add_header Cache-Control "no-store";
expires off;
@@ -183,6 +185,7 @@ http {
}
expires 7d;
include security_headers.conf;
add_header Cache-Control "public";
autoindex on;
root /media/frigate;
@@ -223,7 +226,7 @@ http {
location /ws {
include auth_request.conf;
proxy_pass http://mqtt_ws;
proxy_pass http://mqtt_ws/;
include proxy.conf;
}
@@ -287,6 +290,7 @@ http {
location /api/ {
include auth_request.conf;
include security_headers.conf;
add_header Cache-Control "no-store";
expires off;
proxy_pass http://frigate_api/;
@@ -102,7 +102,7 @@ proxy:
# Optional: Auth secret that is checked against the X-Proxy-Secret header sent from
# the proxy. If not set, all requests are trusted regardless of origin.
auth_secret: None
# Optional: The default role to use for proxy auth. Must be "admin", "viewer", a custom role, or "none" to deny
# Optional: The default role to use for proxy auth. Must be "admin" or "viewer"
default_role: viewer
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
separator: ","
+1 -4
View File
@@ -234,8 +234,6 @@ proxy:
Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in.
A `default_role` that does not name a configured role is treated as `none`.
```yaml
proxy:
...
@@ -268,8 +266,7 @@ In this example:
- If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role.
- If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role.
- If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`.
- If a group matches but its mapped role no longer exists (for example, a deleted custom role), access is denied.
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name, matched without regard to case.
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
**Note on matching semantics:**
-81
View File
@@ -4608,14 +4608,6 @@ 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
@@ -5146,75 +5138,6 @@ 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:
@@ -8455,9 +8378,6 @@ components:
has_snapshot:
type: boolean
title: Has Snapshot
retain_indefinitely:
type: boolean
title: Retain Indefinitely
plus_id:
anyOf:
- type: string
@@ -8495,7 +8415,6 @@ components:
- thumbnail
- has_clip
- has_snapshot
- retain_indefinitely
- plus_id
- model_hash
- detector_type
+16 -13
View File
@@ -580,9 +580,8 @@ def resolve_role(
(split by proxy_config.separator) and map to roles.
Admin matches short-circuit to admin.
- If no role_map is configured, treat the header as role names directly.
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'none'.
The literal value 'none' means access should be denied.
A role_map match whose mapped roles no longer exist in config_roles also resolves to 'none'.
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'viewer'.
The literal value 'none' is a valid default and means access should be denied.
Args:
headers (dict): Incoming request headers (case-insensitive).
@@ -595,11 +594,17 @@ def resolve_role(
default_role = proxy_config.default_role
role_header = proxy_config.header_map.role
# Role names match case-insensitively, as header values are lowercased.
# "none" is the deny sentinel; an unknown or missing default also denies,
# since falling back to viewer would grant every camera.
roles_by_name = {r.lower(): r for r in config_roles}
validated_default = roles_by_name.get((default_role or "").lower(), "none")
# Validate default_role against config; fallback to 'viewer' if invalid.
# "none" is a sentinel meaning "deny access when no mapping matches"; it is
# reserved in AuthConfig.validate_roles so it is never a configured role.
validated_default = (
default_role
if default_role in config_roles or default_role == "none"
else "viewer"
)
if not config_roles:
# Edge case: no roles defined
validated_default = "none" if default_role == "none" else "viewer"
if not role_header:
logger.debug(
@@ -626,7 +631,7 @@ def resolve_role(
logger.debug("Parsed groups from role header: %s", groups)
matched_roles = {
role_name.lower()
role_name
for role_name, required_groups in proxy_config.header_map.role_map.items()
if any(group in groups for group in required_groups)
}
@@ -638,11 +643,9 @@ def resolve_role(
logger.debug("Resolved role (with role_map) to 'admin'.")
return "admin"
# A mapped role that was deleted or renamed denies rather than
# widening to the default role
if matched_roles:
resolved = next(
(r for r in config_roles if r.lower() in matched_roles), "none"
(r for r in config_roles if r in matched_roles), validated_default
)
logger.debug("Resolved role (with role_map) to '%s'.", resolved)
return resolved
@@ -661,7 +664,7 @@ def resolve_role(
logger.debug("Parsed roles directly from header: %s", roles_from_header)
resolved = next(
(r for r in config_roles if r.lower() in roles_from_header),
(r for r in config_roles if r in roles_from_header),
validated_default,
)
if resolved == validated_default and roles_from_header:
@@ -29,7 +29,6 @@ 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,7 +15,6 @@ 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,7 +137,6 @@ 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
@@ -162,7 +161,6 @@ def events(
Event.has_clip,
Event.has_snapshot,
Event.plus_id,
Event.retain_indefinitely,
Event.sub_label,
Event.top_score,
Event.false_positive,
@@ -307,9 +305,6 @@ 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)
@@ -410,7 +405,6 @@ def events_explore(
Event.has_clip,
Event.has_snapshot,
Event.plus_id,
Event.retain_indefinitely,
Event.top_score,
Event.false_positive,
Event.box,
@@ -451,7 +445,6 @@ 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,
@@ -1026,34 +1019,6 @@ 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,
@@ -1278,35 +1243,6 @@ 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,
+1 -9
View File
@@ -581,7 +581,6 @@ class WebPushClient(Communicator):
sorted_objects.add(obj)
sorted_objects.update(payload["after"]["data"]["sub_labels"])
sorted_objects.update(payload["after"]["data"]["audio"])
image = f"{payload['after']['thumb_path'].replace(BASE_DIR, '')}"
ended = state == "end" or state == "genai"
@@ -618,14 +617,7 @@ class WebPushClient(Communicator):
else:
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
object_names = titlecase(
", ".join(sorted(sorted_objects)).replace("_", " ")
)
title = f"{object_names}{' was' if state == 'end' else ''} detected"
if formatted_zone_names:
title += f" in {', '.join(formatted_zone_names)}"
title = f"{titlecase(', '.join(sorted_objects).replace('_', ' '))}{' was' if state == 'end' else ''} detected in {', '.join(formatted_zone_names)}"
message = f"Detected on {camera_name}"
if ended:
+5 -6
View File
@@ -88,17 +88,16 @@ class AuthConfig(FrigateBaseModel):
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
)
# Proxy role headers match role names case-insensitively, so reserved
# names are reserved in every casing and names must differ beyond case
used_reserved = sorted(r for r in v if r.lower() in ("admin", "viewer", "none"))
# 'none' is the deny sentinel for proxy.default_role, where it is matched
# case-insensitively, so every casing of it has to be reserved here
used_reserved = sorted(
r for r in v if r in ("admin", "viewer") or r.lower() == "none"
)
if used_reserved:
raise ValueError(
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
)
if len({r.lower() for r in v}) != len(v):
raise ValueError("Role names must be unique regardless of letter case.")
# Ensure no role has an empty camera list
for role, allowed_cameras in v.items():
if not allowed_cameras:
-9
View File
@@ -1041,15 +1041,6 @@ class FrigateConfig(FrigateBaseModel):
# set notifications state
self.notifications.enabled_in_config = self.notifications.enabled
default_role = (self.proxy.default_role or "").lower()
if default_role != "none" and default_role not in {
r.lower() for r in self.auth.roles
}:
logger.warning(
"proxy.default_role '%s' is not a configured role, so proxy users without a matching role are denied",
self.proxy.default_role,
)
# validate genai: each role (chat, descriptions, embeddings, transcribe) at most once
role_to_name: dict[GenAIRoleEnum, str] = {}
for name, genai_cfg in self.genai.items():
+4 -3
View File
@@ -55,9 +55,10 @@ class ProxyConfig(FrigateBaseModel):
@field_validator("default_role", mode="before")
@classmethod
def normalize_deny_sentinel(cls, v):
# Fail closed: "none" in any casing and a null default both deny.
# Normalizing null keeps the value through /config, which drops nulls
if v is None or (isinstance(v, str) and v.strip().lower() == "none"):
# Fail closed on capitalization: an unnormalized "None" would miss the
# sentinel and fall back to viewer, granting the access it was meant to
# deny. Other role names stay case-sensitive.
if isinstance(v, str) and v.strip().lower() == "none":
return "none"
return v
-6
View File
@@ -92,7 +92,6 @@ 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()
@@ -114,7 +113,6 @@ 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,
)
@@ -170,7 +168,6 @@ 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()
@@ -222,7 +219,6 @@ class EventCleanup(threading.Thread):
.where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
)
.namedtuples()
.iterator()
@@ -252,7 +248,6 @@ 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 = []
@@ -297,7 +292,6 @@ class EventCleanup(threading.Thread):
)
.where(
Event.camera == name,
Event.retain_indefinitely == False,
(
(
(Event.data["max_severity"] != "detection")
-1
View File
@@ -40,7 +40,6 @@ 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
+1 -1
View File
@@ -379,7 +379,7 @@ def move_preview_frames(loc: str) -> None:
src,
dst,
)
except OSError:
except shutil.Error:
logger.error(
"Failed to move preview restart cache from %s to %s",
src,
+8 -76
View File
@@ -263,92 +263,24 @@ 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
keep = False
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
# 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. Retained recordings must be deleted."
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared."
)
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")
-27
View File
@@ -4,7 +4,6 @@ from unittest.mock import Mock, patch
import frigate.genai
from frigate.config import GenAIProviderEnum
from frigate.config.config import RuntimeFilterConfig
from frigate.const import MODEL_CACHE_DIR, REDACTED_CREDENTIAL_SENTINEL
from frigate.genai import GenAIClient
from frigate.models import Event, Recordings, ReviewSegment
@@ -99,32 +98,6 @@ class TestHttpApp(BaseTestHttp):
assert response.status_code == 200
assert app.frigate_config.cameras["front_door"].objects.track == ["person"]
def test_config_set_in_memory_adds_filters_for_new_tracked_labels(self):
self.minimal_config["cameras"]["front_door"]["objects"] = {
"track": ["person"],
}
app = super().create_app()
app.config_publisher = Mock()
with AuthTestClient(app) as client:
response = client.put(
"/config/set",
json={
"requires_restart": 0,
"skip_save": True,
"update_topic": "config/cameras/front_door/objects",
"config_data": {
"cameras": {
"front_door": {"objects": {"track": ["person", "cat"]}}
}
},
},
)
assert response.status_code == 200
filters = app.frigate_config.cameras["front_door"].objects.filters
assert isinstance(filters["cat"], RuntimeFilterConfig)
@patch("frigate.detectors.detector_config.load_labels")
def test_config_set_in_memory_rebinds_replay_model_on_scene_change(
self, mock_labels
+3 -33
View File
@@ -374,22 +374,6 @@ 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"
@@ -527,42 +511,32 @@ 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, 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="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="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",
@@ -570,7 +544,6 @@ class TestHttpApp(BaseTestHttp):
label="inside",
start=ts_start,
end=ts_end,
retain=True,
)
_insert_mock_event(
id="252627.random",
@@ -578,21 +551,18 @@ 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,7 +122,6 @@ 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,7 +242,6 @@ 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,7 +59,6 @@ class TestEventCleanupSnapshots(unittest.TestCase):
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
-1
View File
@@ -68,7 +68,6 @@ class TestEventCleanupSubRetention(unittest.TestCase):
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
-11
View File
@@ -8,7 +8,6 @@ from unittest.mock import MagicMock, patch
from frigate.config import BirdseyeModeEnum, FrigateConfig
from frigate.config.camera.profile import CameraProfileConfig
from frigate.config.config import RuntimeFilterConfig
from frigate.config.profile import ProfileDefinitionConfig
from frigate.config.profile_manager import PERSISTENCE_FILE, ProfileManager
from frigate.const import MODEL_CACHE_DIR
@@ -503,16 +502,6 @@ class TestProfileManager(unittest.TestCase):
back = self.config.cameras["back"]
assert back.notifications.enabled is True
@patch.object(ProfileManager, "_persist_active_profile")
def test_activate_profile_adds_filters_for_new_tracked_labels(self, mock_persist):
"""Labels a profile adds to objects.track get default filters."""
err = self.manager.activate_profile("armed")
assert err is None
filters = self.config.cameras["front"].objects.filters
for label in ["person", "car", "package"]:
assert isinstance(filters[label], RuntimeFilterConfig)
@patch.object(ProfileManager, "_persist_active_profile")
def test_deactivate_profile(self, mock_persist):
"""Deactivating a profile restores base config."""
+1 -50
View File
@@ -95,42 +95,6 @@ class TestProxyRoleResolution(unittest.TestCase):
role = resolve_role(headers, self.proxy_config, self.config_roles)
self.assertEqual(role, self.proxy_config.default_role)
def test_custom_role_direct_header_ignores_case(self):
config = self.proxy_config
config.header_map.role_map = None
headers = {"x-remote-role": "garage"}
role = resolve_role(headers, config, ["admin", "viewer", "Garage"])
self.assertEqual(role, "Garage")
def test_role_map_to_missing_role_denies(self):
"""A group mapped to a deleted role must not widen to default_role."""
self.proxy_config.header_map.role_map = {"garage": ["group_garage"]}
headers = {"x-remote-role": "group_garage"}
role = resolve_role(headers, self.proxy_config, self.config_roles)
self.assertEqual(role, "none")
def test_unknown_default_role_denies(self):
for default in ("operatr", None):
with self.subTest(default_role=default):
config = ProxyConfig(
default_role=default,
header_map=HeaderMappingConfig(role="x-remote-role"),
)
role = resolve_role({}, config, self.config_roles)
self.assertEqual(role, "none")
def test_default_role_and_role_map_ignore_case(self):
roles = ["admin", "viewer", "Garage"]
config = ProxyConfig(
default_role="garage",
header_map=HeaderMappingConfig(
role="x-remote-role", role_map={"GARAGE": ["group_garage"]}
),
)
self.assertEqual(resolve_role({}, config, roles), "Garage")
headers = {"x-remote-role": "group_garage"}
self.assertEqual(resolve_role(headers, config, roles), "Garage")
class TestDefaultRoleNone(unittest.TestCase):
def setUp(self):
@@ -226,9 +190,6 @@ class TestDefaultRoleNone(unittest.TestCase):
)
self.assertEqual(role, "none")
def test_null_default_role_normalizes_to_none(self):
self.assertEqual(ProxyConfig(default_role=None).default_role, "none")
def test_other_role_names_stay_case_sensitive(self):
"""Only the deny sentinel is normalized; role names are untouched."""
config = ProxyConfig(default_role="Operator")
@@ -260,18 +221,8 @@ class TestReservedRoleNames(unittest.TestCase):
with self.assertRaises(ValidationError):
AuthConfig(roles={name: ["front_door"]})
def test_admin_and_viewer_reserved_in_every_casing(self):
for name in ("Admin", "VIEWER"):
with self.subTest(role=name):
with self.assertRaises(ValidationError):
AuthConfig(roles={name: ["front_door"]})
def test_role_names_differing_only_by_case_rejected(self):
with self.assertRaises(ValidationError):
AuthConfig(roles={"garage": ["front_door"], "Garage": ["back"]})
def test_case_variant_of_a_normal_role_still_allowed(self):
"""A mixed-case custom name is fine when it is not reserved."""
"""Only 'none' folds case; other role names are untouched."""
config = AuthConfig(roles={"Operator": ["front_door"]})
self.assertEqual(config.roles["Operator"], ["front_door"])
@@ -98,7 +98,6 @@ class TestRegeneratedSubLabels(unittest.TestCase):
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
+19 -17
View File
@@ -1,4 +1,5 @@
import datetime
import gc
import logging
import os
import tempfile
@@ -447,12 +448,7 @@ class TestHttp(unittest.TestCase):
id = "123456.keep"
time_keep = datetime.datetime.now().timestamp()
_insert_mock_event(
id,
time_keep,
time_keep + 30,
True,
)
_insert_mock_event(id, time_keep, time_keep + 30)
rec_k_id = "1234567.keep"
rec_k2_id = "1234568.keep"
rec_k3_id = "1234569.keep"
@@ -477,7 +473,7 @@ class TestHttp(unittest.TestCase):
id2 = "7890.delete"
time_delete = datetime.datetime.now().timestamp() - 360
_insert_mock_event(id2, time_delete, time_delete + 30, False)
_insert_mock_event(id2, time_delete, time_delete + 30)
rec_d_id = "78901.delete"
rec_d2_id = "78902.delete"
rec_d3_id = "78903.delete"
@@ -510,14 +506,15 @@ class TestHttp(unittest.TestCase):
Recordings.get(Recordings.id == rec_d2_id)
Recordings.get(Recordings.id == rec_d3_id)
def test_storage_cleanup_keeps_retained(self):
"""Ensure cleanup steps over retained segments to reach newer ones."""
def test_storage_cleanup_deletes_oldest_first(self):
"""Ensure cleanup deletes the oldest segments and only expires their events."""
config = FrigateConfig(**self.minimal_config)
storage = StorageMaintainer(config, MagicMock())
seg_len = 600
base = datetime.datetime.now().timestamp() - 7200
_insert_mock_event("123456.keep", base, base + 2.5 * seg_len, True)
_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)
paths = {}
for i in range(10):
@@ -527,16 +524,23 @@ 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 needs all 56 MB of unretained
# segments and must pass the older retained ones to get there.
# Hourly bandwidth is 48 MB, so cleanup removes the oldest 56 MB
storage.calculate_camera_bandwidth()
storage.reduce_storage_consumption()
retained = {"segment-0", "segment-1", "segment-2"}
# 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"}
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, retained)
self.assertEqual(on_disk, retained)
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.assertFalse(storage.retention_unmet)
def test_unmet_retention_sets_the_live_flag(self):
@@ -566,7 +570,6 @@ def _insert_mock_event(
id: str,
start: int,
end: int,
retain: bool,
camera: str = "front_door",
label: str = "Mock",
) -> Event:
@@ -586,7 +589,6 @@ def _insert_mock_event(
area=0,
has_clip=True,
has_snapshot=True,
retain_indefinitely=retain,
).execute()
+1 -8
View File
@@ -1191,11 +1191,7 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
Returns:
None on success, or an error message string on failure.
"""
from frigate.config.config import (
FilterConfig,
RuntimeFilterConfig,
RuntimeMotionConfig,
)
from frigate.config.config import RuntimeFilterConfig, RuntimeMotionConfig
current = getattr(camera_config, section, None)
if current is None:
@@ -1228,9 +1224,6 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
except AttributeError:
pass
for label in new_objects.track:
new_objects.filters.setdefault(label, FilterConfig())
# Rebuild RuntimeFilterConfig with merged global + per-object masks
for obj_name, filt in new_objects.filters.items():
merged_mask = dict(filt.mask)
+4 -6
View File
@@ -23,17 +23,15 @@ 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):
migrator.add_fields(
Event,
retain_indefinitely=pw.BooleanField(default=False),
# 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'
)
def rollback(migrator, database, fake=False, **kwargs):
migrator.remove_fields(Event, ["retain_indefinitely"])
migrator.sql('ALTER TABLE "event" DROP COLUMN "retain_indefinitely"')
@@ -0,0 +1,15 @@
"""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, "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]]}}]
[{"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]]}}]
@@ -234,7 +234,6 @@ def generate_events():
thumbnail=None,
has_clip=True,
has_snapshot=True,
retain_indefinitely=False,
plus_id=None,
model_hash="abc123",
detector_type="cpu",
@@ -265,7 +264,6 @@ def generate_events():
thumbnail=None,
has_clip=True,
has_snapshot=True,
retain_indefinitely=False,
plus_id=None,
model_hash="def456",
detector_type="cpu",
@@ -296,7 +294,6 @@ 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,7 +42,6 @@ const GROUPED_EVENT = {
thumbnail: null,
has_clip: true,
has_snapshot: true,
retain_indefinitely: false,
plus_id: null,
model_hash: "abc123",
detector_type: "cpu",
@@ -426,7 +425,6 @@ test.describe("FaceSelectionDialog @high", () => {
thumbnail: null,
has_clip: true,
has_snapshot: true,
retain_indefinitely: false,
plus_id: null,
model_hash: "abc123",
detector_type: "cpu",
@@ -61,9 +61,7 @@ export default function CreateRoleDialog({
(config.cameras[b]?.ui?.order ?? 0),
);
const existingRoles = Object.keys(config.auth?.roles || {}).map((role) =>
role.toLowerCase(),
);
const existingRoles = Object.keys(config.auth?.roles || {});
const formSchema = z.object({
role: z
@@ -72,7 +70,7 @@ export default function CreateRoleDialog({
.regex(/^[A-Za-z0-9._]+$/, {
message: t("roles.dialog.form.role.roleOnlyInclude"),
})
.refine((role) => !existingRoles.includes(role.toLowerCase()), {
.refine((role) => !existingRoles.includes(role), {
message: t("roles.dialog.form.role.roleExists"),
}),
cameras: z
-1
View File
@@ -10,7 +10,6 @@ export interface Event {
thumbnail: string;
has_clip: boolean;
has_snapshot: boolean;
retain_indefinitely: boolean;
plus_id?: string;
model_hash?: string;
data: {
@@ -184,8 +184,8 @@ export default function ObjectSettingsView({
{config?.cameras[cameraConfig.name]?.webui_url && (
<div className="mb-5 text-sm text-muted-foreground">
<div className="mt-2 flex flex-row items-center text-primary">
<a
href={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
<Link
to={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
target="_blank"
rel="noopener noreferrer"
className="inline"
@@ -194,7 +194,7 @@ export default function ObjectSettingsView({
camera: cameraName,
})}
<LuExternalLink className="ml-2 inline-flex size-3" />
</a>
</Link>
</div>
</div>
)}