Files
frigate/frigate/config/auth.py
T
Josh HawkinsandGitHub c177849f57 Tweaks (#24684)
* bound recording snapshot lookups by segment length

Ordering the recording snapshot and Frigate+ lookups by stream_type ahead of start_time broke index order, so SQLite fetched and sorted every older recording for the camera on each request (about 100 ms on a 30 day camera, run on the event loop). A start_time lower bound of the frame time minus MAX_SEGMENT_DURATION keeps the lookup to a few rows.

* bound recording overlap queries by segment length

Clip, export, review and recording deletion, debug replay, motion search, and audio transcription found overlapping recordings with an OR clause that gave SQLite no start_time range, so every call read the camera's whole recording history (30 to 300 ms on a 30 day database). The classification and review description point lookups did the same whenever the timestamp had no recording. A shared recording_overlap helper now adds a start_time lower bound of MAX_SEGMENT_DURATION before the range, which drops no rows because segments are always shorter than that.

* probe webrtc before reporting it as not configured

The WebRTC gate read only the Frigate config, so an install with no go2rtc candidates showed WebRTC as not configured, even though go2rtc fills in default candidates at startup (including the internal one under the HA app) and WebRTC often worked. Unset candidates now run the connectivity probe first, and only a failed probe reports not configured. The not-configured reason shows as a neutral note that names the setting and says WebRTC is optional, rather than as a red error.

* validate trusted_proxies at config load

Malformed trusted_proxies entries were only parsed per request in get_remote_addr, so a typo logged a warning on every proxied request and the entry was skipped, collapsing all clients behind that proxy into one rate-limit bucket. The config now rejects unparseable entries at startup and get_remote_addr no longer needs the fallback. Host bits are accepted (192.168.1.1/24 reads as 192.168.1.0/24) so a common typo doesn't take down safe mode, which copies the auth section verbatim.

* remove path data from thumbnail payloads

The thumbnail data carried a full copy of the object's path, which went out as snapshot.path_data in every events message alongside the top level path_data. Nothing reads the snapshot copy, and the path has no length limit, so it only made events payloads larger.

* hide incompatible frigate+ models behind a toggle

* keep the probe failure detail in the not-configured console message

* use a unique id for each show incompatible models toggle

* pad the bottom of the desktop timeline so zoom buttons don't cover segments

* create the admin row when auth is disabled so notification registrations persist

Installs that never enabled auth had no admin row, so registering for notifications returned 200 but saved nothing. Frigate now creates an admin row with an empty password hash when auth is disabled, and treats that empty hash as first-time setup when auth is enabled later so a password is still generated and printed. Registration returns 404 when no user row was updated, and the success toast only shows after the request succeeds. The Users settings page hides Add User and Reset Password when auth is disabled and notes that accounts only apply once built-in auth is enabled.
2026-10-16 13:49:16 -06:00

117 lines
4.1 KiB
Python

import ipaddress
from pydantic import Field, field_validator, model_validator
from .base import FrigateBaseModel
__all__ = ["AuthConfig"]
class AuthConfig(FrigateBaseModel):
enabled: bool = Field(
default=True,
title="Enable authentication",
description="Enable native authentication for the Frigate UI.",
)
reset_admin_password: bool = Field(
default=False,
title="Reset admin password",
description="If true, reset the admin user's password on startup and print the new password in logs.",
)
cookie_name: str = Field(
default="frigate_token",
title="JWT cookie name",
description="Name of the cookie used to store the JWT token for native authentication.",
pattern=r"^[a-z_]+$",
)
cookie_secure: bool = Field(
default=False,
title="Secure cookie flag",
description="Set the secure flag on the auth cookie; should be true when using TLS.",
)
session_length: int = Field(
default=86400,
title="Session length",
description="Session duration in seconds for JWT-based sessions.",
ge=60,
)
refresh_time: int = Field(
default=1800,
title="Session refresh window",
description="When a session is within this many seconds of expiring, refresh it back to full length.",
ge=30,
)
failed_login_rate_limit: str | None = Field(
default=None,
title="Failed login limits",
description="Rate limiting rules for failed login attempts to reduce brute-force attacks.",
)
trusted_proxies: list[str] = Field(
default=[],
title="Trusted proxies",
description="List of trusted proxy IPs used when determining client IP for rate limiting.",
)
# As of Feb 2023, OWASP recommends 600000 iterations for PBKDF2-SHA256
hash_iterations: int = Field(
default=600000,
title="Hash iterations",
description="Number of PBKDF2-SHA256 iterations to use when hashing user passwords.",
)
roles: dict[str, list[str]] = Field(
default_factory=dict,
title="Role mappings",
description="Map roles to camera lists. An empty list grants access to all cameras for the role.",
)
admin_first_time_login: bool | None = Field(
default=False,
title="First-time admin flag",
description=(
"When true the UI may show a help link on the login page informing users how to sign in after an admin password reset. "
),
)
@field_validator("trusted_proxies")
@classmethod
def validate_trusted_proxies(cls, v: list[str]) -> list[str]:
for proxy in v:
ipaddress.ip_network(proxy, strict=False)
return v
@field_validator("roles")
@classmethod
def validate_roles(cls, v: dict[str, list[str]]) -> dict[str, list[str]]:
# Ensure role names are valid (alphanumeric with underscores)
for role in v.keys():
if not role.replace("_", "").isalnum():
raise ValueError(
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"
)
if used_reserved:
raise ValueError(
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
)
# Ensure no role has an empty camera list
for role, allowed_cameras in v.items():
if not allowed_cameras:
raise ValueError(
f"Role '{role}' has no cameras assigned. Custom roles must have at least one camera."
)
return v
@model_validator(mode="after")
def ensure_default_roles(self):
# Ensure admin and viewer are never overridden
self.roles["admin"] = []
self.roles["viewer"] = []
return self