Compare commits

..
Author SHA1 Message Date
Josh Hawkins 16784d055c normalize whitespace in custom export ffmpeg args
The custom export validator tokenized args on any whitespace, but the export command was built by splitting on single spaces, so repeated spaces, tabs, or newlines produced a different argv than the one that was validated. The exporter now rejoins custom args with single spaces so ffmpeg receives exactly the tokens the validator checked.
2026-11-23 09:38:33 -06:00
10 changed files with 75 additions and 92 deletions
@@ -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:**
+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:
+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
+14 -2
View File
@@ -261,6 +261,18 @@ def validate_ffmpeg_args(args: str) -> tuple[bool, str]:
return True, ""
def normalize_ffmpeg_args(args: str | None) -> str | None:
"""Rejoin args with single spaces.
validate_ffmpeg_args tokenizes on any whitespace, while export commands are
built with split(" "). Normalizing keeps the two token lists identical.
"""
if args is None:
return None
return " ".join(args.split())
class PlaybackSourceEnum(str, Enum):
recordings = "recordings"
preview = "preview"
@@ -327,8 +339,8 @@ class RecordingExporter(threading.Thread):
self.end_time = end_time
self.playback_source = playback_source
self.export_case_id = export_case_id
self.ffmpeg_input_args = ffmpeg_input_args
self.ffmpeg_output_args = ffmpeg_output_args
self.ffmpeg_input_args = normalize_ffmpeg_args(ffmpeg_input_args)
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
self.cpu_fallback = cpu_fallback
self.chapters = chapters
self.stream = stream
+31
View File
@@ -143,6 +143,37 @@ class TestValidateFfmpegArgs(unittest.TestCase):
self.assertRejected("-metadata comment=x")
class TestCustomArgsTokenization(unittest.TestCase):
"""The built command must contain exactly the tokens the validator checked."""
def test_irregular_whitespace_does_not_shift_tokens(self) -> None:
output_args = "-c:v libx264\t-crf 23\n -r 25 "
self.assertTrue(validate_ffmpeg_args(output_args)[0])
with patch("frigate.record.export.Path.mkdir"):
exporter = RecordingExporter(
MagicMock(),
"front_abc123",
"front",
None,
None,
1_000,
2_000,
PlaybackSourceEnum.recordings,
ffmpeg_input_args=" -an ",
ffmpeg_output_args=output_args,
)
exporter.config.ffmpeg.ffmpeg_path = "ffmpeg"
exporter.staged_runs = ["/cache/stage_0.mp4"]
cmd, _ = exporter.get_record_export_command("/exports/out.mp4")
for token in cmd[: cmd.index("-metadata")]:
self.assertNotEqual(token, "")
self.assertEqual(token.split(), [token])
self.assertIn("-c:v libx264 -crf 23 -r 25", " ".join(cmd))
class TestExportVideoPath(unittest.TestCase):
"""Tests for the file path an export takes once the user names it."""
+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"])
@@ -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