Stop re-adding go2rtc streams that have credentials in their URL (#193436)

This commit is contained in:
Franck Nijhof
2026-11-19 17:52:17 +01:00
committed by GitHub
parent dbc47089f2
commit a393643bd3
2 changed files with 66 additions and 1 deletions
+21 -1
View File
@@ -2,6 +2,7 @@
from dataclasses import dataclass
import logging
import re
from secrets import token_hex
import shutil
from tempfile import mkdtemp
@@ -76,6 +77,8 @@ _LOGGER = logging.getLogger(__name__)
_FFMPEG = "ffmpeg"
_AUTH = "auth"
# Mirrors go2rtc 1.9.15+, which masks the userinfo of URLs in its API responses
_USERINFO = re.compile(r"://[A-Za-z0-9\-._~!$&'()*+,;=%:]+@")
def _validate_auth(config: dict) -> dict:
@@ -309,6 +312,7 @@ class WebRTCProvider(CameraWebRTCProvider):
self._rest_client = rest_client
self._sessions: dict[str, _SessionInfo] = {}
self._supported_schemes: set[str] = set()
self._added_stream_sources: dict[str, str] = {}
@property
@override
@@ -447,7 +451,8 @@ class WebRTCProvider(CameraWebRTCProvider):
identifier = get_camera_identifier(camera)
if (stream := streams.get(identifier)) is None or not any(
stream_source == producer.url for producer in stream.producers
self._is_added_stream_source(identifier, stream_source, producer.url)
for producer in stream.producers
):
await self._rest_client.streams.add(
identifier,
@@ -460,6 +465,20 @@ class WebRTCProvider(CameraWebRTCProvider):
f"ffmpeg:{identifier}#audio=opus#query=log_level=debug",
],
)
self._added_stream_sources[identifier] = stream_source
def _is_added_stream_source(
self, identifier: str, stream_source: str, producer_url: str
) -> bool:
if producer_url == stream_source:
return True
# A masked URL hides credential changes, so it only counts when it
# belongs to the source we added last
if self._added_stream_sources.get(identifier) != stream_source:
return False
return producer_url == _USERINFO.sub("://***@", stream_source)
async def _update_preload_stream(self, camera: Camera) -> None:
identifier = get_camera_identifier(camera)
@@ -509,6 +528,7 @@ class WebRTCProvider(CameraWebRTCProvider):
"""Will be called when the provider is unregistered for a camera."""
await self._close_camera_sessions(camera)
identifier = get_camera_identifier(camera)
self._added_stream_sources.pop(identifier, None)
if identifier in await self._rest_client.preload.list():
await self._rest_client.preload.disable(identifier)
+45
View File
@@ -6,6 +6,7 @@ from datetime import timedelta
from http import HTTPStatus
import logging
from pathlib import Path
import re
from typing import NamedTuple
from unittest.mock import ANY, AsyncMock, Mock, patch
@@ -1061,6 +1062,50 @@ async def test_async_get_image(
await async_get_image(hass, camera.entity_id)
@pytest.mark.usefixtures("init_integration")
async def test_stream_with_credentials_not_added_again(
init_test_integration: MockCamera,
rest_client: AsyncMock,
) -> None:
"""Test a stream with credentials is only added again when its source changes."""
camera = init_test_integration
assert isinstance(camera.webrtc_provider, WebRTCProvider)
identifier = get_camera_identifier(camera)
server_streams: dict[str, Stream] = {}
async def add_stream(name: str, sources: list[str]) -> None:
# go2rtc 1.9.15+ masks the userinfo of producer URLs in API responses
server_streams[name] = Stream(
[Producer(re.sub(r"://[^/@]+@", "://***@", source)) for source in sources]
)
rest_client.streams.add.side_effect = add_stream
rest_client.streams.list.side_effect = lambda: server_streams
camera.set_stream_source("rtsp://user:pass@192.168.1.124:554/stream1")
await camera.webrtc_provider.async_get_image(camera)
assert rest_client.streams.add.call_count == 1
await camera.webrtc_provider.async_get_image(camera)
assert rest_client.streams.add.call_count == 1
camera.set_stream_source("rtsp://user:new_pass@192.168.1.124:554/stream1")
await camera.webrtc_provider.async_get_image(camera)
assert rest_client.streams.add.call_count == 2
assert rest_client.streams.add.call_args[0] == (
identifier,
[
"rtsp://user:new_pass@192.168.1.124:554/stream1",
f"ffmpeg:{identifier}#audio=opus#query=log_level=debug",
],
)
# A restarted go2rtc server has no streams, so the stream is added again
server_streams.clear()
await camera.webrtc_provider.async_get_image(camera)
assert rest_client.streams.add.call_count == 3
@pytest.mark.usefixtures("init_integration")
async def test_async_get_image_go2rtc_error(
hass: HomeAssistant,