Compare commits

...
Author SHA1 Message Date
Josh Hawkins f0e76645ea normalize a null proxy default_role to none
/config drops null fields, so the settings form filled in viewer for a null default_role while /auth denied those users. The config now stores a null default_role as none, which the API returns and the widget shows, and the unreachable null branch in the widget is removed.
2026-11-23 09:53:35 -06:00
Josh Hawkins 47fcb90893 deny proxy users whose role can't be resolved instead of falling back to viewer
Proxy role resolution fell back to viewer, which grants every camera, in several accidental cases. A default_role that was misspelled, null, or named a deleted role became viewer. A role_map group whose mapped role had been deleted (for example, emptied by a camera delete) got the default role. Direct role headers were lowercased but compared to case-sensitive role names, so a custom role like Garage never matched, and a custom role named Admin resolved to the built-in admin.

- match header values, default_role and role_map roles against configured roles regardless of case
- deny when default_role or a matched role_map role doesn't exist, and warn at config load for an unknown default_role
- reserve admin and viewer in every casing and reject role names that differ only by case, in config validation and the Create Role dialog
- show a null default_role as none in the settings widget
2026-11-23 09:34:33 -06:00
Josh HawkinsandGitHub 3bca9b8676 Miscellaneous fixes (#25048)
CI / AMD64 Smoke Test (push) Blocked by required conditions
CI / ARM Build (push) Waiting to run
CI / Jetson Jetpack 6 (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / AMD64 Build (push) Waiting to run
CI / ARM Extra Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
* add default filters for labels tracked at runtime

Adding a tracked label through Debug Replay or a profile left it without an object filter, so the first detection raised a KeyError in the false positive check and killed detected_frames_processor, stopping detection on every camera. Runtime objects updates now create a default filter for each tracked label that lacks one, the same as startup.

* fix nginx header inheritance and ws proxy path

Locations that include auth_request.conf declare their own add_header lines, so nginx dropped the server-level nosniff and Referrer-Policy headers on /recordings/, /exports/, /ws, /live/*, and several /api/ routes. auth_request.conf now includes security_headers.conf itself, and the duplicate includes in /vod/, /stream/, /clips/, and /api/ are removed. The /ws proxy_pass no longer carries a trailing slash, so nginx forwards the original path instead of rewriting /ws to /, which closes the path normalization gap gixy flagged.

* don't end push notification titles with "detected in" when there are no zones

* include audio labels in push notification titles

* use a plain anchor for the camera webui_url link

react-router 7.18.6 throws during render when a Link target looks like a scheme URL but isn't scheme://, so a malformed webui_url such as http:/192.168.1.5 (which the camera form accepts) crashed the object debug view into the route error boundary. A plain anchor renders any value, and a URL with a leading space no longer becomes a relative link.

* catch all OSErrors when moving the preview restart cache
2026-11-23 07:02:15 -07:00
16 changed files with 153 additions and 41 deletions
@@ -22,3 +22,6 @@ 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,7 +152,6 @@ 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;
@@ -161,7 +160,6 @@ http {
location /stream/ {
include auth_request.conf;
include security_headers.conf;
add_header Cache-Control "no-store";
expires off;
@@ -185,7 +183,6 @@ http {
}
expires 7d;
include security_headers.conf;
add_header Cache-Control "public";
autoindex on;
root /media/frigate;
@@ -226,7 +223,7 @@ http {
location /ws {
include auth_request.conf;
proxy_pass http://mqtt_ws/;
proxy_pass http://mqtt_ws;
include proxy.conf;
}
@@ -290,7 +287,6 @@ 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" or "viewer"
# Optional: The default role to use for proxy auth. Must be "admin", "viewer", a custom role, or "none" to deny
default_role: viewer
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
separator: ","
+4 -1
View File
@@ -234,6 +234,8 @@ 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:
...
@@ -266,7 +268,8 @@ 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 `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
- 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.
**Note on matching semantics:**
+13 -16
View File
@@ -580,8 +580,9 @@ 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 'viewer'.
The literal value 'none' is a valid default and means access should be denied.
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'.
Args:
headers (dict): Incoming request headers (case-insensitive).
@@ -594,17 +595,11 @@ def resolve_role(
default_role = proxy_config.default_role
role_header = proxy_config.header_map.role
# 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"
# 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")
if not role_header:
logger.debug(
@@ -631,7 +626,7 @@ def resolve_role(
logger.debug("Parsed groups from role header: %s", groups)
matched_roles = {
role_name
role_name.lower()
for role_name, required_groups in proxy_config.header_map.role_map.items()
if any(group in groups for group in required_groups)
}
@@ -643,9 +638,11 @@ 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 in matched_roles), validated_default
(r for r in config_roles if r.lower() in matched_roles), "none"
)
logger.debug("Resolved role (with role_map) to '%s'.", resolved)
return resolved
@@ -664,7 +661,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 in roles_from_header),
(r for r in config_roles if r.lower() in roles_from_header),
validated_default,
)
if resolved == validated_default and roles_from_header:
+9 -1
View File
@@ -581,6 +581,7 @@ 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"
@@ -617,7 +618,14 @@ class WebPushClient(Communicator):
else:
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
title = f"{titlecase(', '.join(sorted_objects).replace('_', ' '))}{' was' if state == 'end' else ''} detected in {', '.join(formatted_zone_names)}"
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)}"
message = f"Detected on {camera_name}"
if ended:
+6 -5
View File
@@ -88,16 +88,17 @@ class AuthConfig(FrigateBaseModel):
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
)
# '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"
)
# 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"))
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,6 +1041,15 @@ 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():
+3 -4
View File
@@ -55,10 +55,9 @@ class ProxyConfig(FrigateBaseModel):
@field_validator("default_role", mode="before")
@classmethod
def normalize_deny_sentinel(cls, v):
# 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":
# 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"):
return "none"
return v
+1 -1
View File
@@ -379,7 +379,7 @@ def move_preview_frames(loc: str) -> None:
src,
dst,
)
except shutil.Error:
except OSError:
logger.error(
"Failed to move preview restart cache from %s to %s",
src,
+27
View File
@@ -4,6 +4,7 @@ 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
@@ -98,6 +99,32 @@ 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
+11
View File
@@ -8,6 +8,7 @@ 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
@@ -502,6 +503,16 @@ 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."""
+50 -1
View File
@@ -95,6 +95,42 @@ 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):
@@ -190,6 +226,9 @@ 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")
@@ -221,8 +260,18 @@ 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):
"""Only 'none' folds case; other role names are untouched."""
"""A mixed-case custom name is fine when it is not reserved."""
config = AuthConfig(roles={"Operator": ["front_door"]})
self.assertEqual(config.roles["Operator"], ["front_door"])
+8 -1
View File
@@ -1191,7 +1191,11 @@ 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 RuntimeFilterConfig, RuntimeMotionConfig
from frigate.config.config import (
FilterConfig,
RuntimeFilterConfig,
RuntimeMotionConfig,
)
current = getattr(camera_config, section, None)
if current is None:
@@ -1224,6 +1228,9 @@ 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)
@@ -61,7 +61,9 @@ export default function CreateRoleDialog({
(config.cameras[b]?.ui?.order ?? 0),
);
const existingRoles = Object.keys(config.auth?.roles || {});
const existingRoles = Object.keys(config.auth?.roles || {}).map((role) =>
role.toLowerCase(),
);
const formSchema = z.object({
role: z
@@ -70,7 +72,7 @@ export default function CreateRoleDialog({
.regex(/^[A-Za-z0-9._]+$/, {
message: t("roles.dialog.form.role.roleOnlyInclude"),
})
.refine((role) => !existingRoles.includes(role), {
.refine((role) => !existingRoles.includes(role.toLowerCase()), {
message: t("roles.dialog.form.role.roleExists"),
}),
cameras: z
@@ -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">
<Link
to={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
<a
href={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" />
</Link>
</a>
</div>
</div>
)}