Compare commits

..
Author SHA1 Message Date
Josh Hawkins 96fa39bbf7 strip the query before matching go2rtc paths in the origin check 2026-10-18 13:12:32 -05:00
Josh Hawkins 0fc0170461 note that cards must stream through the integration proxy 2026-10-18 13:12:32 -05:00
Josh Hawkins 8dccc937e6 drain all queued auth updates in the output process 2026-10-18 12:40:12 -05:00
Josh Hawkins 3373b1cd05 set Host in the nginx proxy doc examples 2026-10-18 12:40:12 -05:00
Josh Hawkins 31c3638767 reject cross-origin go2rtc stream requests in /auth
The go2rtc websockets and the webrtc offer POST still accepted any Origin, since go2rtc runs with origin "*" and /auth grants admin on the internal port, so a page on another site could pull live video through a LAN user's browser. nginx now passes Origin, Host, X-Forwarded-Host and Upgrade to /auth, which rejects a websocket upgrade or go2rtc stream request with a foreign Origin before the internal-port early return. The hostname rule moves to frigate/util/origin.py so /auth and the ws4py servers share it.
2026-10-18 12:40:12 -05:00
Josh Hawkins 0aa7cf9de9 tidy origin check docstring and auth update comment 2026-10-18 12:19:48 -05:00
Josh Hawkins 4fbde770d7 apply runtime role changes to jsmpeg streams
The output process never subscribed to config/auth, so role edits from the Roles UI (requires_restart 0) did not reach it and jsmpeg kept streaming cameras that had been removed from a role until restart. The output process now replaces its auth config on config/auth updates, which the camera and birdseye broadcast threads read through the shared config.
2026-10-18 12:16:01 -05:00
Josh Hawkins ab8b41934c reject cross-origin websocket handshakes
Neither /ws nor the jsmpeg websockets checked Origin, and the internal port grants admin to everyone, so any page a LAN user visited could open ws://frigate:5000/ws and send commands or read streams. Both servers now reject a browser handshake whose Origin host matches neither Host nor X-Forwarded-Host, and allow handshakes without an Origin for non-browser clients. nginx now forwards an outer proxy's X-Forwarded-Host instead of overwriting it, so proxies that rewrite Host and the Home Assistant integration's proxy still match.
2026-10-18 12:14:30 -05:00
22 changed files with 418 additions and 350 deletions
@@ -19,6 +19,11 @@ 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,6 +54,13 @@ 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 $http_host;
proxy_set_header X-Forwarded-Host $forwarded_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;
@@ -360,6 +360,7 @@ For example, in Nginx:
```
location /frigate {
proxy_set_header Host $host;
proxy_set_header X-Ingress-Path /frigate;
proxy_pass http://frigate_backend;
}
+3
View File
@@ -37,6 +37,8 @@ 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.
@@ -161,6 +163,7 @@ 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;
+4
View File
@@ -55,6 +55,10 @@ 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/`.
+27 -1
View File
@@ -39,6 +39,7 @@ 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__)
@@ -689,6 +690,17 @@ 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:
@@ -712,7 +724,6 @@ 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
@@ -1285,6 +1296,21 @@ 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:
+66 -2
View File
@@ -1,8 +1,10 @@
"""Notification apis."""
import ipaddress
import logging
import os
from typing import Any
from urllib.parse import urlparse
from cryptography.hazmat.primitives import serialization
from fastapi import APIRouter, Depends, Request
@@ -11,7 +13,6 @@ from py_vapid import Vapid01, utils
from frigate.api.auth import allow_any_authenticated
from frigate.api.defs.tags import Tags
from frigate.comms.webpush import validate_push_endpoint
from frigate.const import CONFIG_DIR
from frigate.models import User
@@ -19,13 +20,76 @@ logger = logging.getLogger(__name__)
router = APIRouter(tags=[Tags.notifications])
# Push endpoints are opaque URLs but stay well under this in practice
MAX_ENDPOINT_LENGTH = 2048
# Suffixes that only ever resolve on the local network
INTERNAL_HOST_SUFFIXES = (".local", ".localdomain", ".internal", ".home.arpa")
def _validate_push_endpoint(endpoint: Any) -> str | None:
"""Return a reason the endpoint is unusable, or None when it is valid.
Subscriptions are issued by the browser vendor's push service, so a valid
endpoint is always a public https URL. Anything else is either a broken
registration or an attempt to aim the notification sender somewhere it
should not reach.
"""
if not isinstance(endpoint, str) or not endpoint:
return "endpoint must be a url"
if len(endpoint) > MAX_ENDPOINT_LENGTH:
return "endpoint is too long"
try:
parsed = urlparse(endpoint)
port = parsed.port
except ValueError:
return "endpoint is not a valid url"
if parsed.scheme != "https":
return "endpoint must use https"
if parsed.username or parsed.password:
return "endpoint must not include credentials"
if port is not None and port != 443:
return "endpoint must use the default https port"
hostname = parsed.hostname
if not hostname:
return "endpoint must include a hostname"
try:
address = ipaddress.ip_address(hostname)
except ValueError:
address = None
if address is not None:
# A push service is never reachable at an address only this network can
# route, so anything non-global is a misconfiguration at best
if not address.is_global:
return "endpoint must not use a private address"
elif hostname == "localhost" or "." not in hostname:
return "endpoint must use a fully qualified hostname"
elif hostname.endswith(INTERNAL_HOST_SUFFIXES):
return "endpoint must not use an internal hostname"
# The subscription token lives in the path, and webpush.py assumes there is
# a separator after the host when it builds the VAPID audience
if len(parsed.path) <= 1:
return "endpoint must include a subscription path"
return None
def _validate_subscription(sub: Any) -> str | None:
"""Return a reason the subscription is unusable, or None when it is valid."""
if not isinstance(sub, dict):
return "subscription must be an object"
reason = validate_push_endpoint(sub.get("endpoint"))
reason = _validate_push_endpoint(sub.get("endpoint"))
if reason:
return reason
+2 -12
View File
@@ -490,12 +490,7 @@ class Dispatcher:
def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
"""Handle publishing to communicators."""
for comm in self.comms:
try:
comm.publish(topic, payload, retain)
except Exception:
logger.exception(
"Error publishing %s to %s", topic, type(comm).__name__
)
comm.publish(topic, payload, retain)
def publish_local(self, topic: str, payload: Any) -> None:
"""Publish to every communicator except MQTT.
@@ -506,12 +501,7 @@ class Dispatcher:
if isinstance(comm, MqttClient):
continue
try:
comm.publish(topic, payload, False)
except Exception:
logger.exception(
"Error publishing %s to %s", topic, type(comm).__name__
)
comm.publish(topic, payload, False)
def _publish_notices(self) -> None:
if self.notice_registry is None:
+1 -7
View File
@@ -50,13 +50,7 @@ class InterProcessCommunicator(Communicator):
if isinstance(raw, list):
(topic, value) = raw
# REP owes a reply, so a handler error must not end the thread
try:
response = self._dispatcher(topic, value)
except Exception:
logger.exception("Error handling IPC topic %s", topic)
response = None
response = self._dispatcher(topic, value)
else:
logging.warning(
f"Received unexpected data type in ZMQ recv_json: {type(raw)}"
+5 -117
View File
@@ -1,7 +1,6 @@
"""Handle sending notifications for Frigate via Firebase."""
import datetime
import ipaddress
import json
import logging
import os
@@ -11,9 +10,7 @@ from collections.abc import Callable, Iterator
from dataclasses import dataclass
from multiprocessing.synchronize import Event as MpEvent
from typing import Any
from urllib.parse import urlparse
import requests
from py_vapid import Vapid01
from pywebpush import WebPusher
from titlecase import titlecase
@@ -44,124 +41,14 @@ class PushNotification:
ttl: int = 0
# Push endpoints are opaque URLs but stay well under this in practice
MAX_ENDPOINT_LENGTH = 2048
# Suffixes that only ever resolve on the local network
INTERNAL_HOST_SUFFIXES = (".local", ".localdomain", ".internal", ".home.arpa")
def validate_push_endpoint(endpoint: Any) -> str | None:
"""Return a reason the endpoint is unusable, or None when it is valid.
Subscriptions are issued by the browser vendor's push service, so a valid
endpoint is always a public https URL. Anything else is either a broken
registration or an attempt to aim the notification sender somewhere it
should not reach.
"""
if not isinstance(endpoint, str) or not endpoint:
return "endpoint must be a url"
if len(endpoint) > MAX_ENDPOINT_LENGTH:
return "endpoint is too long"
try:
parsed = urlparse(endpoint)
port = parsed.port
except ValueError:
return "endpoint is not a valid url"
if parsed.scheme != "https":
return "endpoint must use https"
if parsed.username or parsed.password:
return "endpoint must not include credentials"
if port is not None and port != 443:
return "endpoint must use the default https port"
hostname = parsed.hostname
if not hostname:
return "endpoint must include a hostname"
try:
address = ipaddress.ip_address(hostname)
except ValueError:
address = None
if address is not None:
# A push service is never reachable at an address only this network can
# route, so anything non-global is a misconfiguration at best
if not address.is_global:
return "endpoint must not use a private address"
elif hostname == "localhost" or "." not in hostname:
return "endpoint must use a fully qualified hostname"
elif "" in hostname.split("."):
return "endpoint hostname must not contain empty labels"
elif hostname.endswith(INTERNAL_HOST_SUFFIXES):
return "endpoint must not use an internal hostname"
# The subscription token lives in the path
if len(parsed.path) <= 1:
return "endpoint must include a subscription path"
return None
class _NoRedirectSession(requests.Session):
"""Session that never follows redirects.
A push endpoint could otherwise redirect the send to an internal URL.
"""
def request(self, *args: Any, **kwargs: Any) -> requests.Response:
kwargs["allow_redirects"] = False
return super().request(*args, **kwargs)
_push_session = _NoRedirectSession()
def _vapid_audience(endpoint: str) -> str:
parsed = urlparse(endpoint)
return f"{parsed.scheme}://{parsed.netloc}"
def _build_web_pushers(user: str, subs: list[dict[str, Any]]) -> list[WebPusher]:
"""Build pushers for a user's stored subscriptions, skipping unusable ones."""
pushers: list[WebPusher] = []
for sub in subs:
# Stored rows may predate registration validation, so only skip the
# endpoints that would break building the VAPID audience
endpoint = sub.get("endpoint") if isinstance(sub, dict) else None
if not isinstance(endpoint, str):
logger.warning(
"Skipping notification subscription for %s: no endpoint", user
)
continue
try:
hostname = urlparse(endpoint).hostname or ""
except ValueError:
logger.warning(
"Skipping notification subscription for %s: unparsable endpoint", user
)
continue
if "" in hostname.split("."):
logger.warning(
"Skipping notification subscription for %s: invalid endpoint host %r",
user,
hostname,
)
continue
# WebPusher decodes the stored keys and raises on malformed ones
try:
pushers.append(WebPusher(sub, requests_session=_push_session))
pushers.append(WebPusher(sub))
except Exception:
logger.warning("Skipping invalid notification subscription for %s", user)
@@ -244,7 +131,7 @@ class WebPushClient(Communicator):
for pushers in self.web_pushers.values():
for push in pushers:
endpoint: str = push.subscription_info["endpoint"]
endpoints.add(_vapid_audience(endpoint))
endpoints.add(endpoint[0 : endpoint.index("/", 10)])
# create new claim
for endpoint in endpoints:
@@ -433,8 +320,9 @@ class WebPushClient(Communicator):
for pusher in self.web_pushers[notification.user]:
endpoint = pusher.subscription_info["endpoint"]
headers = self.claim_headers[_vapid_audience(endpoint)].copy()
headers = self.claim_headers[
endpoint[: endpoint.index("/", 10)]
].copy()
headers["urgency"] = "high"
resp = pusher.send(
+24 -1
View File
@@ -40,6 +40,7 @@ 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__)
@@ -472,6 +473,28 @@ 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)
@@ -621,7 +644,7 @@ class WebSocketClient(Communicator):
5002,
server_class=WSGIServer,
handler_class=WebSocketWSGIRequestHandler,
app=WebSocketWSGIApplication(handler_cls=_WebSocketHandler),
app=OriginCheckedWebSocketApplication(handler_cls=_WebSocketHandler),
)
self.websocket_server.initialize_websockets_manager()
self.websocket_thread = threading.Thread(
+14 -4
View File
@@ -14,12 +14,11 @@ 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 WebSocket
from frigate.config import FrigateConfig
from frigate.comms.ws import OriginCheckedWebSocketApplication, WebSocket
from frigate.config import AuthConfig, FrigateConfig
from frigate.config.camera.updater import (
CameraConfigUpdateEnum,
CameraConfigUpdateSubscriber,
@@ -136,7 +135,7 @@ class OutputProcess(FrigateProcess):
8082,
server_class=WSGIServer,
handler_class=WebSocketWSGIRequestHandler,
app=WebSocketWSGIApplication(handler_cls=WebSocket),
app=OriginCheckedWebSocketApplication(handler_cls=WebSocket),
)
websocket_server.initialize_websockets_manager()
websocket_thread = threading.Thread(target=websocket_server.serve_forever)
@@ -154,6 +153,7 @@ 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,6 +194,15 @@ 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:
@@ -330,6 +339,7 @@ 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,6 +101,71 @@ 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()
-76
View File
@@ -1,76 +0,0 @@
"""Tests that IPC handler errors cannot stall inter-process communication."""
import os
import tempfile
import unittest
from unittest.mock import MagicMock, patch
import zmq
from frigate.comms.dispatcher import Dispatcher
from frigate.comms.inter_process import InterProcessCommunicator
class TestInterProcessHandlerErrors(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.address = f"ipc://{os.path.join(self.tmp.name, 'comms')}"
with patch("frigate.comms.inter_process.SOCKET_REP_REQ", self.address):
self.communicator = InterProcessCommunicator()
self.context = zmq.Context()
self.requestor = self.context.socket(zmq.REQ)
self.requestor.setsockopt(zmq.RCVTIMEO, 5000)
self.requestor.connect(self.address)
def tearDown(self):
self.requestor.close(linger=0)
self.context.destroy(linger=0)
self.communicator.stop()
self.tmp.cleanup()
def test_handler_exception_still_replies_and_keeps_reading(self):
def dispatcher(topic, value):
if topic == "boom":
raise ValueError("handler failed")
return value
self.communicator.subscribe(dispatcher)
self.communicator.start()
with self.assertLogs("frigate.comms.inter_process", level="ERROR"):
self.requestor.send_json(("boom", None))
self.assertEqual(self.requestor.recv_json(), [])
self.requestor.send_json(("echo", "ok"))
self.assertEqual(self.requestor.recv_json(), "ok")
self.assertTrue(self.communicator.reader_thread.is_alive())
class TestDispatcherPublishErrors(unittest.TestCase):
def test_failing_communicator_does_not_block_the_others(self):
failing = MagicMock()
failing.publish.side_effect = ValueError("publish failed")
healthy = MagicMock()
with (
patch("frigate.comms.dispatcher.CameraActivityManager"),
patch("frigate.comms.dispatcher.AudioActivityManager"),
):
dispatcher = Dispatcher(
MagicMock(), MagicMock(), MagicMock(), {}, [failing, healthy]
)
healthy.publish.reset_mock()
with self.assertLogs("frigate.comms.dispatcher", level="ERROR"):
dispatcher.publish("reviews", "{}")
dispatcher.publish_local("notices", "[]")
healthy.publish.assert_any_call("reviews", "{}", False)
healthy.publish.assert_any_call("notices", "[]", False)
if __name__ == "__main__":
unittest.main()
+9 -1
View File
@@ -3,7 +3,7 @@
import unittest
from types import SimpleNamespace
from frigate.config import FrigateConfig
from frigate.config import AuthConfig, FrigateConfig
from frigate.output.ws_auth import ws_has_camera_access
@@ -55,3 +55,11 @@ 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))
+26 -76
View File
@@ -3,13 +3,8 @@
import unittest
from base64 import urlsafe_b64encode
from frigate.api.notification import _validate_subscription
from frigate.comms.webpush import (
_build_web_pushers,
_NoRedirectSession,
_vapid_audience,
validate_push_endpoint,
)
from frigate.api.notification import _validate_push_endpoint, _validate_subscription
from frigate.comms.webpush import _build_web_pushers
VALID_ENDPOINTS = [
"https://fcm.googleapis.com/fcm/send/dGhpcy1pcy1hLXRva2Vu",
@@ -31,11 +26,11 @@ class TestValidatePushEndpoint(unittest.TestCase):
def test_accepts_real_push_service_endpoints(self):
for endpoint in VALID_ENDPOINTS:
with self.subTest(endpoint=endpoint):
self.assertIsNone(validate_push_endpoint(endpoint))
self.assertIsNone(_validate_push_endpoint(endpoint))
def test_rejects_http(self):
self.assertIsNotNone(
validate_push_endpoint("http://fcm.googleapis.com/fcm/send/token")
_validate_push_endpoint("http://fcm.googleapis.com/fcm/send/token")
)
def test_rejects_non_http_schemes(self):
@@ -45,7 +40,7 @@ class TestValidatePushEndpoint(unittest.TestCase):
"//example.com/token",
):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_localhost(self):
for endpoint in (
@@ -55,7 +50,7 @@ class TestValidatePushEndpoint(unittest.TestCase):
"https://[::1]/token",
):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_private_addresses(self):
for endpoint in (
@@ -66,7 +61,7 @@ class TestValidatePushEndpoint(unittest.TestCase):
"https://0.0.0.0/token",
):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_internal_hostnames(self):
for endpoint in (
@@ -76,16 +71,16 @@ class TestValidatePushEndpoint(unittest.TestCase):
"https://host.home.arpa/token",
):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_non_default_port(self):
self.assertIsNotNone(
validate_push_endpoint("https://fcm.googleapis.com:8080/fcm/send/token")
_validate_push_endpoint("https://fcm.googleapis.com:8080/fcm/send/token")
)
def test_rejects_embedded_credentials(self):
self.assertIsNotNone(
validate_push_endpoint(
_validate_push_endpoint(
"https://user:pass@fcm.googleapis.com/fcm/send/token"
)
)
@@ -93,26 +88,26 @@ class TestValidatePushEndpoint(unittest.TestCase):
def test_rejects_endpoint_without_path(self):
for endpoint in ("https://fcm.googleapis.com", "https://fcm.googleapis.com/"):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_empty_hostname_labels(self):
for endpoint in (
"https://./x",
"https://fcm..googleapis.com/token",
"https://.fcm.googleapis.com/token",
"https://fcm.googleapis.com./token",
):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
def test_rejects_endpoint_that_breaks_audience_parsing(self):
# webpush.py locates the host by searching for a separator after index
# 10, which raises ValueError when the url has no path at all
endpoint = "https://fcm.googleapis.com"
with self.assertRaises(ValueError):
endpoint.index("/", 10)
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_missing_or_non_string_endpoint(self):
for endpoint in (None, "", 5, {"url": "https://example.com/token"}):
with self.subTest(endpoint=endpoint):
self.assertIsNotNone(validate_push_endpoint(endpoint))
self.assertIsNotNone(_validate_push_endpoint(endpoint))
def test_rejects_overlong_endpoint(self):
self.assertIsNotNone(
validate_push_endpoint(f"https://fcm.googleapis.com/{'a' * 4096}")
_validate_push_endpoint(f"https://fcm.googleapis.com/{'a' * 4096}")
)
@@ -153,6 +148,10 @@ class TestValidateSubscription(unittest.TestCase):
self.assertIsNotNone(_validate_subscription(sub))
if __name__ == "__main__":
unittest.main()
class TestBuildWebPushers(unittest.TestCase):
def test_skips_subscriptions_with_malformed_keys(self):
bad = _subscription(VALID_ENDPOINTS[0])
@@ -164,52 +163,3 @@ class TestBuildWebPushers(unittest.TestCase):
self.assertEqual(len(pushers), 1)
self.assertEqual(pushers[0].receiver_key, b"\x04" + bytes(64))
def _valid_keys_subscription(self, endpoint: str) -> dict:
sub = _subscription(endpoint)
sub["keys"]["p256dh"] = urlsafe_b64encode(b"\x04" + bytes(64)).decode()
return sub
def test_skips_stored_rows_that_break_the_audience(self):
good = self._valid_keys_subscription(VALID_ENDPOINTS[0])
rows = [
self._valid_keys_subscription("https://./secret-token"),
self._valid_keys_subscription("https://[::1/secret-token"),
{"keys": good["keys"]},
"not-a-dict",
good,
]
with self.assertLogs("frigate.comms.webpush", level="WARNING") as logs:
pushers = _build_web_pushers("viewer", rows)
self.assertEqual(len(logs.output), 4)
self.assertIn("'.'", logs.output[0])
self.assertNotIn("secret-token", "".join(logs.output))
self.assertEqual(len(pushers), 1)
self.assertEqual(pushers[0].subscription_info["endpoint"], VALID_ENDPOINTS[0])
self.assertIsInstance(pushers[0].mod_or_session, _NoRedirectSession)
def test_keeps_stored_self_hosted_endpoints(self):
rows = [
self._valid_keys_subscription("https://ntfy.example.com:8443/up123"),
self._valid_keys_subscription("https://ntfy.example.com/"),
]
pushers = _build_web_pushers("viewer", rows)
self.assertEqual(len(pushers), 2)
class TestVapidAudience(unittest.TestCase):
def test_uses_scheme_and_host(self):
self.assertEqual(
_vapid_audience(VALID_ENDPOINTS[0]), "https://fcm.googleapis.com"
)
self.assertEqual(
_vapid_audience(VALID_ENDPOINTS[4]), "https://fcm.googleapis.com:443"
)
if __name__ == "__main__":
unittest.main()
-45
View File
@@ -1,45 +0,0 @@
"""Tests that push sends never follow redirects."""
import unittest
import requests
from requests.adapters import BaseAdapter
from frigate.comms.webpush import _NoRedirectSession
ENDPOINT = "https://push.example.com/token"
class RedirectAdapter(BaseAdapter):
def __init__(self):
super().__init__()
self.calls = 0
def send(self, request, **kwargs):
self.calls += 1
response = requests.Response()
response.status_code = 307
response.headers["Location"] = "http://127.0.0.1:5000/api/restart"
response.url = request.url
response.request = request
return response
def close(self):
pass
class TestNoRedirectSession(unittest.TestCase):
def test_does_not_follow_redirects(self):
adapter = RedirectAdapter()
session = _NoRedirectSession()
session.mount("https://", adapter)
session.mount("http://", adapter)
response = session.post(ENDPOINT, data=b"payload")
self.assertEqual(response.status_code, 307)
self.assertEqual(adapter.calls, 1)
if __name__ == "__main__":
unittest.main()
+126
View File
@@ -0,0 +1,126 @@
"""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()
+31
View File
@@ -0,0 +1,31 @@
"""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)
+1 -6
View File
@@ -338,12 +338,7 @@ def process_frames(
continue
if datetime.now().astimezone(UTC) > next_region_update:
updated_grid = requestor.send_data(REQUEST_REGION_GRID, camera_config.name)
# A failed request replies empty, so keep the current grid
if updated_grid:
region_grid = updated_grid
region_grid = requestor.send_data(REQUEST_REGION_GRID, camera_config.name)
next_region_update = get_tomorrow_at_time(2)
try:
-1
View File
@@ -28,7 +28,6 @@ export default defineConfig({
},
"/live": {
target: `ws://${proxyHost}`,
changeOrigin: true,
ws: true,
},
},