mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-10-19 13:12:48 +03:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea268533e5 | ||
|
|
777b33f849 | ||
|
|
f08e4aac69 | ||
|
|
2d632f4b70 | ||
|
|
2f3338f950 | ||
|
|
f650ccb3b5 | ||
|
|
19d3047fb9 | ||
|
|
5d81da8c00 | ||
|
|
72183983b0 |
@@ -36,8 +36,8 @@ else
|
||||
lefile="/config/tls/fullchain.pem"
|
||||
fi
|
||||
|
||||
tls_enabled=`python3 /usr/local/nginx/get_nginx_settings.py | jq -r .tls.enabled`
|
||||
listen_external_port=`python3 /usr/local/nginx/get_nginx_settings.py | jq -r .listen.external_port`
|
||||
tls_enabled=`python3 -I /usr/local/nginx/get_nginx_settings.py | jq -r .tls.enabled`
|
||||
listen_external_port=`python3 -I /usr/local/nginx/get_nginx_settings.py | jq -r .listen.external_port`
|
||||
|
||||
while true
|
||||
do
|
||||
|
||||
@@ -11,30 +11,13 @@ if [[ "$(id -u)" -eq 0 ]]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# /root survives s6-setuidgid and breaks cache writes after the drop; set
|
||||
# before opt_in_out so the opt-out marker lands where the service will look
|
||||
if [[ "$runs_as_root" -eq 0 ]]; then
|
||||
export HOME=/config
|
||||
fi
|
||||
|
||||
# detector runtimes installed at first start (pip install --user) live under
|
||||
# $HOME/.local; the dynamic loader only reads LD_LIBRARY_PATH at exec time
|
||||
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}${HOME}/.local/lib"
|
||||
export PATH="${PATH}:${HOME}/.local/bin"
|
||||
|
||||
# opt out of openvino telemetry
|
||||
if [ -e /usr/local/bin/opt_in_out ]; then
|
||||
/usr/local/bin/opt_in_out --opt_out > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
# Logs should be sent to stdout so that s6 can collect them
|
||||
|
||||
# Tell S6-Overlay not to restart this service
|
||||
s6-svc -O .
|
||||
|
||||
# Runs as root with root's HOME and LD_LIBRARY_PATH; -I skips user site-packages
|
||||
function set_libva_version() {
|
||||
local ffmpeg_path
|
||||
ffmpeg_path=$(python3 /usr/local/ffmpeg/get_ffmpeg_path.py)
|
||||
ffmpeg_path=$(python3 -I /usr/local/ffmpeg/get_ffmpeg_path.py)
|
||||
LIBAVFORMAT_VERSION_MAJOR=$("$ffmpeg_path" -version | grep -Po "libavformat\W+\K\d+")
|
||||
export LIBAVFORMAT_VERSION_MAJOR
|
||||
}
|
||||
@@ -42,14 +25,32 @@ function set_libva_version() {
|
||||
echo "[INFO] Preparing Frigate..."
|
||||
set_libva_version
|
||||
|
||||
# HOME=/root survives s6-setuidgid, so any run that is not root gets
|
||||
# HOME=/config explicitly. The runtime user owns /config, so these paths go
|
||||
# only to the service process, never to root. Detector runtimes installed at
|
||||
# first start (pip install --user) live under $HOME/.local.
|
||||
run_as=()
|
||||
runtime_home="${HOME}"
|
||||
if [[ "$runs_as_root" -eq 0 ]]; then
|
||||
runtime_home=/config
|
||||
if [[ "$(id -u)" -eq 0 ]]; then
|
||||
run_as=(s6-setuidgid frigate)
|
||||
fi
|
||||
fi
|
||||
run_as+=(env
|
||||
"HOME=${runtime_home}"
|
||||
"LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}${runtime_home}/.local/lib"
|
||||
"PATH=${PATH}:${runtime_home}/.local/bin")
|
||||
|
||||
# opt out of openvino telemetry; the marker lands under the service's HOME
|
||||
if [ -e /usr/local/bin/opt_in_out ]; then
|
||||
"${run_as[@]}" /usr/local/bin/opt_in_out --opt_out > /dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
echo "[INFO] Starting Frigate..."
|
||||
|
||||
cd /opt/frigate || echo "[ERROR] Failed to change working directory to /opt/frigate"
|
||||
|
||||
# Replace the bash process with the Frigate process, redirecting stderr to stdout
|
||||
exec 2>&1
|
||||
if [[ "$(id -u)" -ne 0 || "$runs_as_root" -eq 1 ]]; then
|
||||
exec python3 -u -m frigate
|
||||
else
|
||||
exec s6-setuidgid frigate python3 -u -m frigate
|
||||
fi
|
||||
exec "${run_as[@]}" python3 -u -m frigate
|
||||
|
||||
@@ -59,38 +59,33 @@ function get_ip_and_port_from_supervisor() {
|
||||
|
||||
function set_libva_version() {
|
||||
local ffmpeg_path
|
||||
ffmpeg_path=$(python3 /usr/local/ffmpeg/get_ffmpeg_path.py)
|
||||
ffmpeg_path=$(python3 -I /usr/local/ffmpeg/get_ffmpeg_path.py)
|
||||
LIBAVFORMAT_VERSION_MAJOR=$("$ffmpeg_path" -version | grep -Po "libavformat\W+\K\d+")
|
||||
export LIBAVFORMAT_VERSION_MAJOR
|
||||
}
|
||||
|
||||
set_libva_version
|
||||
|
||||
if [[ -f "/dev/shm/go2rtc.yaml" ]]; then
|
||||
echo "[INFO] Removing stale config from last run..."
|
||||
rm /dev/shm/go2rtc.yaml
|
||||
# create_config.py creates the file exclusively and fails if anything
|
||||
# reappears at this path
|
||||
rm -f /dev/shm/go2rtc.yaml
|
||||
|
||||
echo "[INFO] Preparing new go2rtc config..."
|
||||
|
||||
if [[ -n "${SUPERVISOR_TOKEN:-}" ]]; then
|
||||
# Running as a Home Assistant Add-on, infer the IP address and port
|
||||
get_ip_and_port_from_supervisor
|
||||
fi
|
||||
|
||||
if [[ ! -f "/dev/shm/go2rtc.yaml" ]]; then
|
||||
echo "[INFO] Preparing new go2rtc config..."
|
||||
|
||||
if [[ -n "${SUPERVISOR_TOKEN:-}" ]]; then
|
||||
# Running as a Home Assistant Add-on, infer the IP address and port
|
||||
get_ip_and_port_from_supervisor
|
||||
fi
|
||||
|
||||
python3 /usr/local/go2rtc/create_config.py
|
||||
else
|
||||
echo "[WARNING] Unable to remove existing go2rtc config. Changes made to your frigate config file may not be recognized. Please remove the /dev/shm/go2rtc.yaml from your docker host manually."
|
||||
fi
|
||||
python3 -I /usr/local/go2rtc/create_config.py
|
||||
|
||||
# HomeKit persistence. The helper is symlink-safe; hand off to go2rtc only when dropping.
|
||||
readonly homekit_config_path="/config/go2rtc_homekit.yml"
|
||||
if [[ "$(id -u)" -eq 0 && "$runs_as_root" -eq 0 ]]; then
|
||||
python3 /usr/local/go2rtc/prepare_homekit.py "${homekit_config_path}" --chown
|
||||
chown go2rtc:go2rtc /dev/shm/go2rtc.yaml 2>/dev/null || true
|
||||
python3 -I /usr/local/go2rtc/prepare_homekit.py "${homekit_config_path}" --chown
|
||||
chown -h go2rtc:go2rtc /dev/shm/go2rtc.yaml 2>/dev/null || true
|
||||
else
|
||||
python3 /usr/local/go2rtc/prepare_homekit.py "${homekit_config_path}"
|
||||
python3 -I /usr/local/go2rtc/prepare_homekit.py "${homekit_config_path}"
|
||||
fi
|
||||
|
||||
readonly config_path="/config"
|
||||
|
||||
@@ -124,7 +124,7 @@ fi
|
||||
mkdir -p /etc/letsencrypt/www 2>/dev/null || true
|
||||
|
||||
# nginx settings are read once; both templates consume them
|
||||
nginx_settings=$(python3 /usr/local/nginx/get_nginx_settings.py)
|
||||
nginx_settings=$(python3 -I /usr/local/nginx/get_nginx_settings.py)
|
||||
|
||||
# build templates for optional FRIGATE_BASE_PATH environment variable
|
||||
echo "$nginx_settings" | \
|
||||
|
||||
@@ -198,9 +198,13 @@ if config.get("birdseye", {}).get("restream", False):
|
||||
else:
|
||||
go2rtc_config["streams"] = {"birdseye": ffmpeg_cmd}
|
||||
|
||||
# Write go2rtc_config to /dev/shm/go2rtc.yaml
|
||||
with open("/dev/shm/go2rtc.yaml", "w") as f:
|
||||
# The run script removes the old file first. Exclusive create never follows a
|
||||
# link the go2rtc user planted in sticky /dev/shm. The config contains camera
|
||||
# credentials, so it is not world-readable.
|
||||
fd = os.open(
|
||||
"/dev/shm/go2rtc.yaml",
|
||||
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
||||
0o640,
|
||||
)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
yaml.dump(go2rtc_config, f)
|
||||
|
||||
# config contains camera credentials; do not leave it world-readable
|
||||
os.chmod("/dev/shm/go2rtc.yaml", 0o640)
|
||||
|
||||
@@ -19,11 +19,6 @@ location /auth {
|
||||
# this cannot be spoofed
|
||||
proxy_set_header X-Go2rtc-Stream-Proxy $go2rtc_stream_proxy;
|
||||
proxy_set_header X-Server-Port $server_port;
|
||||
# inputs for the cross-origin check on websocket and go2rtc stream requests
|
||||
proxy_set_header Origin $http_origin;
|
||||
proxy_set_header X-Original-Host $http_host;
|
||||
proxy_set_header X-Forwarded-Host $forwarded_host;
|
||||
proxy_set_header X-Original-Upgrade $http_upgrade;
|
||||
proxy_set_header Content-Length "";
|
||||
# Pass along auth related info
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
|
||||
@@ -54,13 +54,6 @@ http {
|
||||
default 1;
|
||||
}
|
||||
|
||||
# keep an outer proxy's X-Forwarded-Host so the websocket servers can
|
||||
# match a browser's Origin when that proxy rewrites Host
|
||||
map $http_x_forwarded_host $forwarded_host {
|
||||
"" $http_host;
|
||||
default $http_x_forwarded_host;
|
||||
}
|
||||
|
||||
upstream frigate_api {
|
||||
server 127.0.0.1:5001;
|
||||
keepalive 1024;
|
||||
|
||||
@@ -4,7 +4,7 @@ proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
proxy_set_header X-Original-URL $request_uri;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $forwarded_host;
|
||||
proxy_set_header X-Forwarded-Host $http_host;
|
||||
proxy_set_header X-Forwarded-URI $request_uri;
|
||||
proxy_set_header X-Forwarded-Ssl on;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
sys.path.insert(0, "/opt/frigate")
|
||||
from frigate.util.config import find_config_file
|
||||
from frigate.util.config import find_config_file, parse_listen_address
|
||||
|
||||
sys.path.remove("/opt/frigate")
|
||||
|
||||
@@ -35,20 +35,29 @@ ipv6_config: dict[str, Any] = networking_config.get("ipv6", {})
|
||||
ipv6_config.setdefault("enabled", False)
|
||||
|
||||
listen_config: dict[str, Any] = networking_config.get("listen", {})
|
||||
listen_config.setdefault("internal", 5000)
|
||||
listen_config.setdefault("external", 8971)
|
||||
|
||||
# handle case where internal port is a string with ip:port
|
||||
internal_port = listen_config["internal"]
|
||||
if type(internal_port) is str:
|
||||
internal_port = int(internal_port.split(":")[-1])
|
||||
listen_config["internal_port"] = internal_port
|
||||
# Frigate's own validation runs elsewhere, and a bad value here must not stop nginx
|
||||
# from serving the safe-mode UI. Valid values are kept so a fallback never widens
|
||||
# the unauthenticated internal listener beyond the configured address.
|
||||
for key, default in (("internal", 5000), ("external", 8971)):
|
||||
try:
|
||||
value, port = parse_listen_address(listen_config.get(key, default))
|
||||
except ValueError:
|
||||
print(
|
||||
f"[WARN] Invalid networking.listen.{key}, using {default}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
value, port = default, default
|
||||
|
||||
# handle case where external port is a string with ip:port
|
||||
external_port = listen_config["external"]
|
||||
if type(external_port) is str:
|
||||
external_port = int(external_port.split(":")[-1])
|
||||
listen_config["external_port"] = external_port
|
||||
listen_config[key] = value
|
||||
listen_config[f"{key}_port"] = port
|
||||
|
||||
if listen_config["internal_port"] == listen_config["external_port"]:
|
||||
print(
|
||||
"[ERROR] networking.listen.internal and external share a port",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
base_path = os.environ.get("FRIGATE_BASE_PATH", "")
|
||||
|
||||
|
||||
@@ -360,7 +360,6 @@ For example, in Nginx:
|
||||
|
||||
```
|
||||
location /frigate {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Ingress-Path /frigate;
|
||||
proxy_pass http://frigate_backend;
|
||||
}
|
||||
|
||||
@@ -37,8 +37,6 @@ Your reverse proxy must be configured to forward the `Upgrade` and `Connection`
|
||||
|
||||
Note that some proxies disable WebSocket support by default. For example, Nginx Proxy Manager has a "Websockets Support" toggle that must be enabled.
|
||||
|
||||
Frigate rejects WebSocket connections opened from a page on another site. Your proxy must either preserve the original `Host` header or send it in `X-Forwarded-Host`, otherwise Frigate cannot tell the connection came from its own UI.
|
||||
|
||||
## Proxies
|
||||
|
||||
There are many solutions available to implement reverse proxies and the community is invited to help out documenting others through a contribution to this page.
|
||||
@@ -163,7 +161,6 @@ The settings below enabled connection upgrade, sets up logging (optional) and pr
|
||||
error_log /data/logs/proxy-host-40_error.log warn;
|
||||
|
||||
location / {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $http_connection;
|
||||
proxy_http_version 1.1;
|
||||
|
||||
@@ -55,10 +55,6 @@ To install the optional companion Lovelace card, please see the [separate
|
||||
installation instructions](https://github.com/dermotduffy/frigate-hass-card) for
|
||||
that card.
|
||||
|
||||
Frigate rejects browser connections to its live streams that come from another
|
||||
origin, such as a Home Assistant dashboard. Configure cards to stream through the
|
||||
integration's proxy rather than pointing them directly at Frigate's port.
|
||||
|
||||
## Configuration
|
||||
|
||||
When configuring the integration, you will be asked for the `URL` of your Frigate instance which can be pointed at the internal unauthenticated port (`5000`) or the authenticated port (`8971`) for your instance. This may look like `http://<host>:5000/`.
|
||||
|
||||
+1
-27
@@ -39,7 +39,6 @@ from frigate.config import AuthConfig, ProxyConfig
|
||||
from frigate.const import CONFIG_DIR, JWT_SECRET_ENV_VAR, PASSWORD_HASH_ALGORITHM
|
||||
from frigate.models import User
|
||||
from frigate.notices import raise_notice
|
||||
from frigate.util.origin import origin_allowed
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -690,17 +689,6 @@ def auth(request: Request):
|
||||
|
||||
success_response = Response("", status_code=202)
|
||||
|
||||
original_url = request.headers.get("x-original-url")
|
||||
|
||||
if _is_cross_origin_stream_request(original_url, request):
|
||||
logger.warning(
|
||||
"Rejected cross-origin request: origin=%s, host=%s, x-forwarded-host=%s",
|
||||
request.headers.get("origin"),
|
||||
request.headers.get("x-original-host"),
|
||||
request.headers.get("x-forwarded-host"),
|
||||
)
|
||||
return Response("", status_code=403)
|
||||
|
||||
# dont require auth if the request is on the internal port
|
||||
# this header is set by Frigate's nginx proxy, so it cant be spoofed.
|
||||
# the port is the boot-time snapshot rather than the live config value:
|
||||
@@ -724,6 +712,7 @@ def auth(request: Request):
|
||||
logger.debug("X-Proxy-Secret header does not match configured secret value")
|
||||
return fail_response
|
||||
|
||||
original_url = request.headers.get("x-original-url")
|
||||
frigate_config = request.app.frigate_config
|
||||
|
||||
# if auth is disabled, just apply the proxy header map and return success
|
||||
@@ -1296,21 +1285,6 @@ def _is_go2rtc_stream_proxy_request(path: str, request: Request) -> bool:
|
||||
return any(normalized.startswith(p) for p in GO2RTC_STREAM_PROXY_PATHS)
|
||||
|
||||
|
||||
def _is_cross_origin_stream_request(original_url: str | None, request: Request) -> bool:
|
||||
# the internal port grants admin, so a browser on another site must be
|
||||
# stopped before that early return
|
||||
upgrade = request.headers.get("x-original-upgrade", "").lower()
|
||||
path = split_request_uri(original_url or "")[0]
|
||||
if upgrade != "websocket" and not _is_go2rtc_stream_proxy_request(path, request):
|
||||
return False
|
||||
|
||||
return not origin_allowed(
|
||||
request.headers.get("origin"),
|
||||
request.headers.get("x-original-host"),
|
||||
request.headers.get("x-forwarded-host"),
|
||||
)
|
||||
|
||||
|
||||
def deny_response_for_go2rtc_stream(
|
||||
original_url: str | None, role: str | None, request: Request
|
||||
) -> int | None:
|
||||
|
||||
+1
-24
@@ -40,7 +40,6 @@ from frigate.const import (
|
||||
)
|
||||
from frigate.models import User
|
||||
from frigate.output.ws_auth import ws_has_camera_access
|
||||
from frigate.util.origin import origin_allowed
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -473,28 +472,6 @@ def _materialize_for_ws(
|
||||
return None
|
||||
|
||||
|
||||
class OriginCheckedWebSocketApplication(WebSocketWSGIApplication): # type: ignore[misc]
|
||||
"""ws4py application that rejects cross-origin browser handshakes."""
|
||||
|
||||
def __call__(self, environ: dict[str, Any], start_response: Callable) -> Any:
|
||||
if not origin_allowed(
|
||||
environ.get("HTTP_ORIGIN"),
|
||||
environ.get("HTTP_HOST"),
|
||||
environ.get("HTTP_X_FORWARDED_HOST"),
|
||||
):
|
||||
logger.warning(
|
||||
"Rejected cross-origin websocket handshake: origin=%s, host=%s, "
|
||||
"x-forwarded-host=%s",
|
||||
environ.get("HTTP_ORIGIN"),
|
||||
environ.get("HTTP_HOST"),
|
||||
environ.get("HTTP_X_FORWARDED_HOST"),
|
||||
)
|
||||
start_response("403 Forbidden", [("Content-Length", "0")])
|
||||
return []
|
||||
|
||||
return super().__call__(environ, start_response)
|
||||
|
||||
|
||||
class WebSocket(WebSocket_): # type: ignore[misc]
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
@@ -644,7 +621,7 @@ class WebSocketClient(Communicator):
|
||||
5002,
|
||||
server_class=WSGIServer,
|
||||
handler_class=WebSocketWSGIRequestHandler,
|
||||
app=OriginCheckedWebSocketApplication(handler_cls=_WebSocketHandler),
|
||||
app=WebSocketWSGIApplication(handler_cls=_WebSocketHandler),
|
||||
)
|
||||
self.websocket_server.initialize_websockets_manager()
|
||||
self.websocket_thread = threading.Thread(
|
||||
|
||||
+12
-11
@@ -1,18 +1,12 @@
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
from frigate.util.config import parse_listen_address
|
||||
|
||||
from .base import FrigateBaseModel
|
||||
|
||||
__all__ = ["IPv6Config", "ListenConfig", "NetworkingConfig"]
|
||||
|
||||
|
||||
def parse_listen_port(value: int | str) -> int:
|
||||
"""Return the port number from a bare port or an "address:port" value."""
|
||||
if isinstance(value, str):
|
||||
return int(value.split(":")[-1])
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class IPv6Config(FrigateBaseModel):
|
||||
enabled: bool = Field(
|
||||
default=False,
|
||||
@@ -33,13 +27,20 @@ class ListenConfig(FrigateBaseModel):
|
||||
description="External listening port for Frigate (default 8971).",
|
||||
)
|
||||
|
||||
# Runs before pydantic coerces a bool to an int port, which
|
||||
# get_nginx_settings.py rejects when it reads the raw YAML
|
||||
@field_validator("internal", "external", mode="before")
|
||||
@classmethod
|
||||
def validate_listen(cls, value: int | str) -> int | str:
|
||||
return parse_listen_address(value)[0]
|
||||
|
||||
@property
|
||||
def internal_port(self) -> int:
|
||||
return parse_listen_port(self.internal)
|
||||
return parse_listen_address(self.internal)[1]
|
||||
|
||||
@property
|
||||
def external_port(self) -> int:
|
||||
return parse_listen_port(self.external)
|
||||
return parse_listen_address(self.external)[1]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_distinct_ports(self) -> "ListenConfig":
|
||||
|
||||
@@ -14,11 +14,12 @@ from ws4py.server.wsgirefserver import (
|
||||
WebSocketWSGIRequestHandler,
|
||||
WSGIServer,
|
||||
)
|
||||
from ws4py.server.wsgiutils import WebSocketWSGIApplication
|
||||
|
||||
from frigate.comms.config_updater import ConfigSubscriber
|
||||
from frigate.comms.detections_updater import DetectionSubscriber, DetectionTypeEnum
|
||||
from frigate.comms.ws import OriginCheckedWebSocketApplication, WebSocket
|
||||
from frigate.config import AuthConfig, FrigateConfig
|
||||
from frigate.comms.ws import WebSocket
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.config.camera.updater import (
|
||||
CameraConfigUpdateEnum,
|
||||
CameraConfigUpdateSubscriber,
|
||||
@@ -135,7 +136,7 @@ class OutputProcess(FrigateProcess):
|
||||
8082,
|
||||
server_class=WSGIServer,
|
||||
handler_class=WebSocketWSGIRequestHandler,
|
||||
app=OriginCheckedWebSocketApplication(handler_cls=WebSocket),
|
||||
app=WebSocketWSGIApplication(handler_cls=WebSocket),
|
||||
)
|
||||
websocket_server.initialize_websockets_manager()
|
||||
websocket_thread = threading.Thread(target=websocket_server.serve_forever)
|
||||
@@ -153,7 +154,6 @@ class OutputProcess(FrigateProcess):
|
||||
],
|
||||
)
|
||||
birdseye_config_subscriber = ConfigSubscriber("config/birdseye", exact=True)
|
||||
auth_config_subscriber = ConfigSubscriber("config/auth", exact=True)
|
||||
|
||||
jsmpeg_cameras: dict[str, JsmpegCamera] = {}
|
||||
birdseye: Birdseye | None = None
|
||||
@@ -194,15 +194,6 @@ class OutputProcess(FrigateProcess):
|
||||
self.config.birdseye = birdseye_config
|
||||
logger.debug("Applied dynamic birdseye config update")
|
||||
|
||||
# user endpoints publish None on this topic and role edits an AuthConfig
|
||||
while True:
|
||||
auth_topic, auth_config = auth_config_subscriber.check_for_update()
|
||||
if auth_topic is None:
|
||||
break
|
||||
if isinstance(auth_config, AuthConfig):
|
||||
self.config.auth = auth_config
|
||||
logger.debug("Applied dynamic auth config update")
|
||||
|
||||
# drain review updates every iteration, not just when birdseye is
|
||||
# being consumed, so a dropped end never strands a camera
|
||||
if birdseye is not None:
|
||||
@@ -339,7 +330,6 @@ class OutputProcess(FrigateProcess):
|
||||
|
||||
config_subscriber.stop()
|
||||
birdseye_config_subscriber.stop()
|
||||
auth_config_subscriber.stop()
|
||||
websocket_server.manager.close_all()
|
||||
websocket_server.manager.stop()
|
||||
websocket_server.manager.join()
|
||||
|
||||
@@ -101,71 +101,6 @@ class TestAuthInternalPort(BaseTestHttp):
|
||||
self.assertEqual(resp.headers["remote-user"], "anonymous")
|
||||
self.assertEqual(resp.headers["remote-role"], "admin")
|
||||
|
||||
def _internal_auth(self, original_url: str, **headers: str):
|
||||
app = self._create_app()
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
return client.get(
|
||||
"/auth",
|
||||
headers={
|
||||
"x-server-port": "5000",
|
||||
"x-original-url": original_url,
|
||||
"x-original-host": "frigate.lan:5000",
|
||||
**{k.replace("_", "-"): v for k, v in headers.items()},
|
||||
},
|
||||
)
|
||||
|
||||
def test_cross_origin_websocket_on_internal_port_denied(self):
|
||||
resp = self._internal_auth(
|
||||
"/ws", origin="https://evil.example", x_original_upgrade="websocket"
|
||||
)
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
|
||||
def test_cross_origin_go2rtc_stream_denied(self):
|
||||
resp = self._internal_auth(
|
||||
"/live/mse/api/ws?src=front_door",
|
||||
origin="https://evil.example",
|
||||
x_original_upgrade="websocket",
|
||||
x_go2rtc_stream_proxy="1",
|
||||
)
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
|
||||
def test_cross_origin_webrtc_post_denied(self):
|
||||
# the offer POST is not an upgrade, so the stream marker alone gates it
|
||||
resp = self._internal_auth(
|
||||
"/api/go2rtc/webrtc?src=front_door",
|
||||
origin="https://evil.example",
|
||||
x_go2rtc_stream_proxy="1",
|
||||
)
|
||||
self.assertEqual(resp.status_code, 403)
|
||||
|
||||
def test_same_origin_websocket_allowed(self):
|
||||
resp = self._internal_auth(
|
||||
"/live/mse/api/ws?src=front_door",
|
||||
origin="http://frigate.lan:5000",
|
||||
x_original_upgrade="websocket",
|
||||
x_go2rtc_stream_proxy="1",
|
||||
)
|
||||
self.assertEqual(resp.status_code, 202)
|
||||
|
||||
def test_websocket_without_origin_allowed(self):
|
||||
resp = self._internal_auth("/ws", x_original_upgrade="websocket")
|
||||
self.assertEqual(resp.status_code, 202)
|
||||
|
||||
def test_forwarded_host_origin_allowed(self):
|
||||
# Home Assistant integration proxy: Host is Frigate, Origin is HA
|
||||
resp = self._internal_auth(
|
||||
"/api/go2rtc/webrtc?src=front_door",
|
||||
origin="https://ha.example.com:8123",
|
||||
x_forwarded_host="ha.example.com:8123",
|
||||
x_go2rtc_stream_proxy="1",
|
||||
)
|
||||
self.assertEqual(resp.status_code, 202)
|
||||
|
||||
def test_cross_origin_plain_http_not_checked(self):
|
||||
resp = self._internal_auth("/api/events", origin="https://evil.example")
|
||||
self.assertEqual(resp.status_code, 202)
|
||||
|
||||
def test_external_port_requires_auth(self):
|
||||
app = self._create_app()
|
||||
|
||||
|
||||
@@ -36,6 +36,73 @@ class TestListenConfig(unittest.TestCase):
|
||||
self.assertEqual(listen.internal_port, 5001)
|
||||
self.assertEqual(listen.external_port, 8971)
|
||||
|
||||
def test_valid_listen_values_are_rebuilt(self):
|
||||
cases = {
|
||||
5000: 5000,
|
||||
"5000": 5000,
|
||||
"127.0.0.1:5000": "127.0.0.1:5000",
|
||||
"0.0.0.0:5000": "0.0.0.0:5000",
|
||||
"[::1]:5000": "[::1]:5000",
|
||||
"[::]:5000": "[::]:5000",
|
||||
"[2001:DB8:0:0::1]:5000": "[2001:db8::1]:5000",
|
||||
" 5000 ": 5000,
|
||||
"5000\n": 5000,
|
||||
" 127.0.0.1:5000 ": "127.0.0.1:5000",
|
||||
"localhost:5000": "localhost:5000",
|
||||
"frigate-host.lan:5000": "frigate-host.lan:5000",
|
||||
"*:5000": "*:5000",
|
||||
}
|
||||
|
||||
for value, expected in cases.items():
|
||||
with self.subTest(value=value):
|
||||
listen = ListenConfig(internal=value)
|
||||
|
||||
self.assertEqual(listen.internal, expected)
|
||||
self.assertEqual(listen.internal_port, 5000)
|
||||
|
||||
def test_invalid_listen_values_rejected(self):
|
||||
cases = [
|
||||
"5000; location /x/ { alias /; autoindex on; } #:5000",
|
||||
"127.0.0.1:5000; include /etc/passwd",
|
||||
"5000 ssl",
|
||||
"5000;",
|
||||
"::1:5000",
|
||||
"[127.0.0.1]:5000",
|
||||
"[fe80::1%eth0]:5000",
|
||||
"local host:5000",
|
||||
"localhost;:5000",
|
||||
"local{host}:5000",
|
||||
"host#:5000",
|
||||
"'localhost':5000",
|
||||
'"localhost":5000',
|
||||
"-host:5000",
|
||||
"host-:5000",
|
||||
"host..lan:5000",
|
||||
"**:5000",
|
||||
"*.lan:5000",
|
||||
"unix:/tmp/sock:5000",
|
||||
"5000 5001",
|
||||
":5000",
|
||||
"127.0.0.1:",
|
||||
"127.0.0.1:+5000",
|
||||
0,
|
||||
65536,
|
||||
-1,
|
||||
]
|
||||
|
||||
for value in cases:
|
||||
with self.subTest(value=value):
|
||||
with self.assertRaises(ValidationError):
|
||||
ListenConfig(internal=value)
|
||||
|
||||
def test_bool_listen_value_rejected(self):
|
||||
# get_nginx_settings.py sees the raw bool and falls back to the default,
|
||||
# so accepting it as port 1 would split nginx and the auth port check
|
||||
for value in (True, False):
|
||||
with self.subTest(value=value):
|
||||
with self.assertRaises(ValidationError):
|
||||
ListenConfig(internal=value)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
from frigate.config import AuthConfig, FrigateConfig
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.output.ws_auth import ws_has_camera_access
|
||||
|
||||
|
||||
@@ -55,11 +55,3 @@ class TestWsHasCameraAccess(unittest.TestCase):
|
||||
self.assertFalse(
|
||||
ws_has_camera_access(self._make_ws("limited_user"), "birdseye", self.config)
|
||||
)
|
||||
|
||||
def test_replaced_auth_config_revokes_camera(self):
|
||||
ws = self._make_ws("limited_user")
|
||||
self.assertTrue(ws_has_camera_access(ws, "front_door", self.config))
|
||||
|
||||
self.config.auth = AuthConfig(roles={"limited_user": ["back_door"]})
|
||||
self.assertFalse(ws_has_camera_access(ws, "front_door", self.config))
|
||||
self.assertTrue(ws_has_camera_access(ws, "back_door", self.config))
|
||||
|
||||
@@ -1,126 +0,0 @@
|
||||
"""Tests for the same-origin check on WebSocket handshakes."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from frigate.comms.ws import OriginCheckedWebSocketApplication, WebSocket
|
||||
from frigate.util.origin import origin_allowed
|
||||
|
||||
|
||||
def ws_origin_allowed(environ: dict[str, str]) -> bool:
|
||||
return origin_allowed(
|
||||
environ.get("HTTP_ORIGIN"),
|
||||
environ.get("HTTP_HOST"),
|
||||
environ.get("HTTP_X_FORWARDED_HOST"),
|
||||
)
|
||||
|
||||
|
||||
class TestOriginAllowed(unittest.TestCase):
|
||||
def test_missing_origin_allowed(self):
|
||||
self.assertTrue(ws_origin_allowed({"HTTP_HOST": "frigate.lan"}))
|
||||
|
||||
def test_direct_access_same_origin(self):
|
||||
# nginx forwards Host without the port and X-Forwarded-Host with it
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "http://192.168.1.10:5000",
|
||||
"HTTP_HOST": "192.168.1.10",
|
||||
"HTTP_X_FORWARDED_HOST": "192.168.1.10:5000",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
def test_default_port_origin(self):
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://frigate.example.com",
|
||||
"HTTP_HOST": "frigate.example.com",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
def test_host_comparison_is_case_insensitive(self):
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://Frigate.Example.com",
|
||||
"HTTP_HOST": "frigate.example.COM",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
def test_ipv6_host(self):
|
||||
environ = {"HTTP_ORIGIN": "http://[::1]:8971", "HTTP_HOST": "[::1]"}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
def test_cross_origin_rejected(self):
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://evil.example",
|
||||
"HTTP_HOST": "frigate.lan",
|
||||
"HTTP_X_FORWARDED_HOST": "frigate.lan:5000",
|
||||
}
|
||||
self.assertFalse(ws_origin_allowed(environ))
|
||||
|
||||
def test_null_origin_rejected(self):
|
||||
self.assertFalse(
|
||||
ws_origin_allowed({"HTTP_ORIGIN": "null", "HTTP_HOST": "frigate.lan"})
|
||||
)
|
||||
|
||||
def test_proxy_rewriting_host_with_forwarded_host(self):
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://frigate.example.com",
|
||||
"HTTP_HOST": "10.0.0.5",
|
||||
"HTTP_X_FORWARDED_HOST": "frigate.example.com",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
def test_forwarded_host_list_uses_first_entry(self):
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://frigate.example.com",
|
||||
"HTTP_HOST": "10.0.0.5",
|
||||
"HTTP_X_FORWARDED_HOST": "frigate.example.com, proxy.internal",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
environ["HTTP_ORIGIN"] = "https://proxy.internal"
|
||||
self.assertFalse(ws_origin_allowed(environ))
|
||||
|
||||
def test_home_assistant_ingress(self):
|
||||
# HA core copies Host and sets X-Forwarded-Host to its own host
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://ha.example.com:8123",
|
||||
"HTTP_HOST": "ha.example.com",
|
||||
"HTTP_X_FORWARDED_HOST": "ha.example.com:8123",
|
||||
"HTTP_X_INGRESS_PATH": "/api/hassio_ingress/abc123",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
def test_ingress_path_does_not_bypass_origin_check(self):
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://evil.example",
|
||||
"HTTP_HOST": "frigate.example.com",
|
||||
"HTTP_X_INGRESS_PATH": "/frigate",
|
||||
}
|
||||
self.assertFalse(ws_origin_allowed(environ))
|
||||
|
||||
def test_home_assistant_integration_proxy(self):
|
||||
# hass-web-proxy-lib drops Host, so Host is the integration's Frigate URL
|
||||
environ = {
|
||||
"HTTP_ORIGIN": "https://ha.example.com:8123",
|
||||
"HTTP_HOST": "frigate.lan",
|
||||
"HTTP_X_FORWARDED_HOST": "ha.example.com:8123",
|
||||
}
|
||||
self.assertTrue(ws_origin_allowed(environ))
|
||||
|
||||
|
||||
class TestOriginCheckedWebSocketApplication(unittest.TestCase):
|
||||
def test_cross_origin_handshake_gets_403(self):
|
||||
app = OriginCheckedWebSocketApplication(handler_cls=WebSocket)
|
||||
start_response = MagicMock()
|
||||
environ = {
|
||||
"REQUEST_METHOD": "GET",
|
||||
"HTTP_ORIGIN": "https://evil.example",
|
||||
"HTTP_HOST": "frigate.lan",
|
||||
}
|
||||
|
||||
self.assertEqual(app(environ, start_response), [])
|
||||
start_response.assert_called_once()
|
||||
self.assertEqual(start_response.call_args.args[0], "403 Forbidden")
|
||||
self.assertNotIn("ws4py.websocket", environ)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,8 +1,10 @@
|
||||
"""configuration utils."""
|
||||
|
||||
import asyncio
|
||||
import ipaddress
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from functools import cache
|
||||
from typing import Any
|
||||
@@ -126,6 +128,49 @@ def redact_credential(obj: dict[str, Any], key: str) -> None:
|
||||
obj.pop(key, None)
|
||||
|
||||
|
||||
LISTEN_HOSTNAME = re.compile(
|
||||
r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
|
||||
r"(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*"
|
||||
)
|
||||
|
||||
|
||||
def parse_listen_address(value: int | str) -> tuple[int | str, int]:
|
||||
"""Validate a networking.listen value and rebuild it from its parsed parts.
|
||||
|
||||
Accepts a port, "host:port", "*:port", or "[IPv6]:port", where host is an
|
||||
IPv4 address or an RFC 1123 hostname. nginx receives the rebuilt value
|
||||
verbatim, so anything else raises ValueError.
|
||||
|
||||
Returns:
|
||||
The normalized value (an int for a bare port) and the port
|
||||
"""
|
||||
if isinstance(value, bool) or not isinstance(value, int | str):
|
||||
raise ValueError(f"invalid listen value: {value!r}")
|
||||
|
||||
host, sep, port_text = str(value).strip().rpartition(":")
|
||||
|
||||
if not re.fullmatch(r"[0-9]{1,5}", port_text) or not (1 <= int(port_text) <= 65535):
|
||||
raise ValueError(f"invalid listen port: {value!r}")
|
||||
|
||||
port = int(port_text)
|
||||
|
||||
if not sep:
|
||||
return port, port
|
||||
|
||||
if host.startswith("[") and host.endswith("]"):
|
||||
address = ipaddress.IPv6Address(host[1:-1])
|
||||
|
||||
if address.scope_id:
|
||||
raise ValueError(f"listen address must not have a scope ID: {value!r}")
|
||||
|
||||
return f"[{address}]:{port}", port
|
||||
|
||||
if host != "*" and not LISTEN_HOSTNAME.fullmatch(host):
|
||||
raise ValueError(f"invalid listen address: {value!r}")
|
||||
|
||||
return f"{host}:{port}", port
|
||||
|
||||
|
||||
def find_config_file() -> str:
|
||||
"""Return the path of the config file to use.
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
"""Same-origin check for browser WebSocket handshakes and go2rtc stream requests."""
|
||||
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
def _hostname(value: str) -> str | None:
|
||||
try:
|
||||
return urlsplit(value).hostname
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def origin_allowed(
|
||||
origin: str | None, host: str | None, forwarded_host: str | None
|
||||
) -> bool:
|
||||
"""Return True unless a browser sent the request from a foreign origin.
|
||||
|
||||
Browsers always send Origin on a WebSocket handshake, so a missing Origin
|
||||
means a non-browser client. A page cannot add headers to a handshake, so
|
||||
X-Forwarded-Host comes from a proxy. Ports are ignored because nginx
|
||||
forwards Host without one.
|
||||
"""
|
||||
if origin is None:
|
||||
return True
|
||||
|
||||
origin_host = _hostname(origin)
|
||||
if not origin_host:
|
||||
return False
|
||||
|
||||
hosts = ((forwarded_host or "").split(",")[0].strip(), host or "")
|
||||
return any(origin_host == _hostname(f"//{h}") for h in hosts if h)
|
||||
@@ -28,6 +28,7 @@ export default defineConfig({
|
||||
},
|
||||
"/live": {
|
||||
target: `ws://${proxyHost}`,
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user