mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-23 22:07:07 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0e76645ea | ||
|
|
47fcb90893 |
@@ -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: ","
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -261,18 +261,6 @@ 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"
|
||||
@@ -339,8 +327,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 = normalize_ffmpeg_args(ffmpeg_input_args)
|
||||
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
|
||||
self.ffmpeg_input_args = ffmpeg_input_args
|
||||
self.ffmpeg_output_args = ffmpeg_output_args
|
||||
self.cpu_fallback = cpu_fallback
|
||||
self.chapters = chapters
|
||||
self.stream = stream
|
||||
|
||||
@@ -143,37 +143,6 @@ 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."""
|
||||
|
||||
|
||||
@@ -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"])
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user