diff --git a/frigate/api/app.py b/frigate/api/app.py index 80584692a7..8cb69762a4 100644 --- a/frigate/api/app.py +++ b/frigate/api/app.py @@ -74,7 +74,7 @@ from frigate.util.config import ( find_config_file, redact_credential, ) -from frigate.util.env import substitute_frigate_vars +from frigate.util.env import candidate_env_vars, substitute_frigate_vars from frigate.util.live_streams import ( generated_transcode_streams, sync_transcode_streams, @@ -589,14 +589,18 @@ def config_raw(): ) -def _go2rtc_config(raw_config: str) -> dict[str, Any]: - """Load the go2rtc section with the same loader Frigate and go2rtc startup use. +def _go2rtc_config(raw_config: str) -> tuple[dict[str, Any], Any]: + """Load the go2rtc section and environment_vars with the same loader Frigate + and go2rtc startup use. Raises ruamel.yaml.YAMLError when the config cannot be parsed. """ loaded = ruamel.yaml.YAML().load(raw_config) - go2rtc = loaded.get("go2rtc") if isinstance(loaded, dict) else None - return go2rtc if isinstance(go2rtc, dict) else {} + if not isinstance(loaded, dict): + return {}, None + + go2rtc = loaded.get("go2rtc") + return go2rtc if isinstance(go2rtc, dict) else {}, loaded.get("environment_vars") def _restricted_go2rtc_response( @@ -608,7 +612,7 @@ def _restricted_go2rtc_response( otherwise load them from the saved config on the next restart. """ try: - new_go2rtc = _go2rtc_config(new_raw_config) + new_go2rtc, new_env_vars = _go2rtc_config(new_raw_config) except ruamel.yaml.YAMLError: logger.warning("Rejected config change that could not be parsed") return JSONResponse( @@ -617,13 +621,13 @@ def _restricted_go2rtc_response( ) try: - old_go2rtc = _go2rtc_config(old_raw_config) + old_go2rtc, _ = _go2rtc_config(old_raw_config) except ruamel.yaml.YAMLError: # with no readable saved config, every source is treated as new old_go2rtc = {} issues = find_restricted_go2rtc_stream_changes( - old_go2rtc.get("streams"), new_go2rtc.get("streams") + old_go2rtc.get("streams"), new_go2rtc.get("streams"), new_env_vars ) exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc) if not issues and not exec_keys: @@ -787,16 +791,20 @@ def config_save(save_option: str, body: Any = Body(media_type="text/plain")): ) -def _restore_masked_camera_paths(config_data: dict, saved: dict) -> str | None: +def _restore_masked_camera_paths( + config_data: dict, saved: dict, shown_env_vars: dict[str, str] +) -> str | None: """Substitute incoming masked camera paths with the saved ones. The /config response masks ffmpeg input credentials, so the settings UI sends the masked path back when sibling fields (e.g. hwaccel_args) are edited. Each masked path is matched to the saved input that masks to the same value, with roles breaking a tie, so deleting or reordering inputs - keeps each path's own credentials. The saved path is restored as written, - keeping any {FRIGATE_*} placeholder. Mutates `config_data` in place and - returns an error message when a masked path has no single match. + keeps each path's own credentials. Saved paths resolve with + `shown_env_vars`, the block the running config and /config used. The saved + path is restored as written, keeping any {FRIGATE_*} placeholder. Mutates + `config_data` in place and returns an error message when a masked path has + no single match. """ cameras = config_data.get("cameras") if not isinstance(cameras, dict): @@ -832,11 +840,13 @@ def _restore_masked_camera_paths(config_data: dict, saved: dict) -> str | None: path = input_obj.get("path") if not isinstance(path, str) or not is_masked_camera_path(path): continue - candidates = [ - inp - for inp in saved_inputs - if clean_camera_user_pass(_resolve_frigate_vars(inp["path"])) == path - ] + with candidate_env_vars(shown_env_vars): + candidates = [ + inp + for inp in saved_inputs + if clean_camera_user_pass(_resolve_frigate_vars(inp["path"])) + == path + ] if len({inp["path"] for inp in candidates}) > 1: candidates = [ inp @@ -880,14 +890,14 @@ def _saved_config_from_memory(config: FrigateConfig) -> dict[str, Any]: def _config_data_to_updates( - config_data: dict, saved: dict[str, Any] + config_data: dict, saved: dict[str, Any], running: FrigateConfig ) -> tuple[dict[str, Any], str | None]: """Flatten a /config/set payload after restoring masked credentials. `saved` is the config the masked values were taken from. Returns the flat updates, or an error message when a masked value can't be restored. """ - error = _restore_masked_camera_paths(config_data, saved) + error = _restore_masked_camera_paths(config_data, saved, running.environment_vars) if error: return {}, error @@ -941,7 +951,9 @@ def _config_set_in_memory(request: Request, body: AppConfigSetBody) -> JSONRespo updates = {} if body.config_data: updates, error = _config_data_to_updates( - body.config_data, _saved_config_from_memory(request.app.frigate_config) + body.config_data, + _saved_config_from_memory(request.app.frigate_config), + request.app.frigate_config, ) if error: return JSONResponse( @@ -1122,6 +1134,7 @@ def config_set(request: Request, body: AppConfigSetBody): updates, error = _config_data_to_updates( body.config_data, saved_config if isinstance(saved_config, dict) else {}, + request.app.frigate_config, ) if error: diff --git a/frigate/config/config.py b/frigate/config/config.py index 196dc10f2d..a435b571df 100644 --- a/frigate/config/config.py +++ b/frigate/config/config.py @@ -4,6 +4,7 @@ import io import json import logging import os +from collections.abc import Mapping from typing import Any, Self import numpy as np @@ -34,7 +35,7 @@ from frigate.util.config import ( get_relative_coordinates, migrate_frigate_config, ) -from frigate.util.env import EnvVars, reload_sources +from frigate.util.env import EnvVars, candidate_env_vars, reload_sources from frigate.util.image import create_mask from frigate.util.live_streams import ( default_transcode_source, @@ -1566,6 +1567,12 @@ class FrigateConfig(FrigateBaseModel): def parse_object( cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False ): - return cls.model_validate( - obj, context={"plus_api": plus_api, "install": install} - ) + context = {"plus_api": plus_api, "install": install} + + if install: + return cls.model_validate(obj, context=context) + + # a candidate config resolves placeholders against its own block + env_vars = obj.get("environment_vars") if isinstance(obj, Mapping) else None + with candidate_env_vars(env_vars): + return cls.model_validate(obj, context=context) diff --git a/frigate/test/http_api/test_http_config_go2rtc_streams.py b/frigate/test/http_api/test_http_config_go2rtc_streams.py index ed32981c47..38ff70a895 100644 --- a/frigate/test/http_api/test_http_config_go2rtc_streams.py +++ b/frigate/test/http_api/test_http_config_go2rtc_streams.py @@ -10,7 +10,13 @@ import ruamel.yaml from frigate.models import Event, Recordings, ReviewSegment from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp -from frigate.util.env import _CONTAINER_ENV, FRIGATE_ENV_VARS, reload_sources +from frigate.util.env import ( + _CONFIG_ENV_VARS, + _CONTAINER_ENV, + FRIGATE_ENV_VARS, + apply_config_env_vars, + reload_sources, +) # shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced _INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'" @@ -18,6 +24,8 @@ _INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'" # an unrestricted ffmpeg: source the operator already has in the file on disk _EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn" +_PLACEHOLDER_SRC = "ffmpeg:rtsp://10.0.0.1:554/{FRIGATE_CAM_PATH}" + _CONFIG = { "mqtt": {"host": "mqtt"}, "go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}}, @@ -111,6 +119,28 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp): headers={"Content-Type": "text/plain"}, ) + def _save(self, config: dict): + with AuthTestClient(self.app) as client: + return client.post( + "/config/save?save_option=saveonly", + content=_dump(config), + headers={"Content-Type": "text/plain"}, + ) + + def _start_with_placeholder_source(self) -> dict: + """Write and install a config whose stream reads FRIGATE_CAM_PATH from + environment_vars, as if Frigate had started with it.""" + config = copy.deepcopy(_CONFIG) + config["environment_vars"] = {"FRIGATE_CAM_PATH": "video"} + config["go2rtc"]["streams"]["front_door"].append(_PLACEHOLDER_SRC) + with open(self.config_path, "w") as f: + f.write(_dump(config)) + + apply_config_env_vars(config["environment_vars"]) + self.addCleanup(reload_sources, warn=False) + self.addCleanup(_CONFIG_ENV_VARS.clear) + return config + # --- config/set --- def test_set_rejects_injected_ffmpeg_source(self): @@ -255,6 +285,52 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp): assert resp.status_code == 200, resp.text assert src in self._read_config() + def test_save_rejects_changed_env_var_in_existing_source(self): + config = self._start_with_placeholder_source() + before = self._read_config() + config["environment_vars"]["FRIGATE_CAM_PATH"] = "video#raw=-vn" + resp = self._save(config) + assert resp.status_code == 400 + assert "Restricted go2rtc stream source" in resp.json()["message"] + assert self._read_config() == before + + def test_save_allows_safe_env_var_change_in_existing_source(self): + config = self._start_with_placeholder_source() + config["environment_vars"]["FRIGATE_CAM_PATH"] = "video2" + resp = self._save(config) + assert resp.status_code == 200, resp.text + + def test_save_resubmitting_placeholder_source_allowed(self): + config = self._start_with_placeholder_source() + resp = self._save(config) + assert resp.status_code == 200, resp.text + + def test_save_rejects_removed_env_var_in_existing_source(self): + config = self._start_with_placeholder_source() + before = self._read_config() + del config["environment_vars"] + resp = self._save(config) + assert resp.status_code == 400 + assert self._read_config() == before + + def test_save_allows_env_var_added_with_its_source(self): + config = copy.deepcopy(_CONFIG) + config["environment_vars"] = {"FRIGATE_NEW_PATH": "video"} + config["go2rtc"]["streams"]["new_stream"] = ( + "ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}" + ) + resp = self._save(config) + assert resp.status_code == 200, resp.text + + def test_save_rejects_unsafe_env_var_added_with_its_source(self): + config = copy.deepcopy(_CONFIG) + config["environment_vars"] = {"FRIGATE_NEW_PATH": "video#raw=-vn"} + config["go2rtc"]["streams"]["new_stream"] = ( + "ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}" + ) + resp = self._save(config) + assert resp.status_code == 400 + # --- go2rtc ffmpeg and ngrok options --- def test_save_rejects_ffmpeg_bin_override(self): diff --git a/frigate/test/http_api/test_http_config_set.py b/frigate/test/http_api/test_http_config_set.py index 009e72573a..8b1db7f04e 100644 --- a/frigate/test/http_api/test_http_config_set.py +++ b/frigate/test/http_api/test_http_config_set.py @@ -624,6 +624,96 @@ class TestConfigSetWildcardPropagation(BaseTestHttp): finally: os.unlink(config_path) + @patch.dict("frigate.util.env._CONFIG_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"}) + @patch.dict("frigate.util.env.FRIGATE_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"}) + @patch("frigate.api.app.find_config_file") + def test_masked_path_matches_after_saved_env_var_swap(self, mock_find_config): + """A no-restart update swaps in a config resolved with the saved + environment_vars, so /config shows the saved value until a restart.""" + path = "rtsp://admin:pw@{FRIGATE_CAM_HOST}:554/live" + self._set_inputs([(path, "detect")]) + self.minimal_config["environment_vars"] = {"FRIGATE_CAM_HOST": "10.0.0.2"} + config_path = self._write_config_file() + mock_find_config.return_value = config_path + + try: + app, _ = self._create_app_with_publisher() + + with AuthTestClient(app) as client: + resp = self._save( + client, {"cameras": {"front_door": {"detect": {"fps": 6}}}} + ) + self.assertEqual(resp.status_code, 200, resp.text) + + camera = client.get("/config").json()["cameras"]["front_door"] + inputs = camera["ffmpeg"]["inputs"] + self.assertIn("10.0.0.2", inputs[0]["path"]) + + resp = self._save( + client, + { + "cameras": { + "front_door": { + "ffmpeg": {"inputs": inputs}, + "detect": {"fps": 7}, + } + } + }, + ) + self.assertEqual(resp.status_code, 200, resp.text) + + _, saved = self._read_config_file(config_path) + self.assertEqual( + saved["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"], path + ) + finally: + os.unlink(config_path) + + @patch.dict( + "frigate.util.env._CONFIG_ENV_VARS", + {"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"}, + ) + @patch.dict( + "frigate.util.env.FRIGATE_ENV_VARS", + {"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"}, + ) + @patch("frigate.api.app.find_config_file") + def test_masked_paths_match_running_env_vars(self, mock_find_config): + """A saved but not yet applied environment_vars change must not make + one input's masked path match another's.""" + path_a = "rtsp://admin:pw@{FRIGATE_HOST_A}:554/live" + path_b = "rtsp://admin:pw@{FRIGATE_HOST_B}:554/live" + self._set_inputs([(path_a, "detect"), (path_b, "record")]) + self.minimal_config["environment_vars"] = { + "FRIGATE_HOST_A": "10.0.0.1", + "FRIGATE_HOST_B": "10.0.0.2", + } + app, _ = self._create_app_with_publisher() + + self.minimal_config["environment_vars"]["FRIGATE_HOST_A"] = "10.0.0.2" + config_path = self._write_config_file() + mock_find_config.return_value = config_path + + try: + with AuthTestClient(app) as client: + camera = client.get("/config").json()["cameras"]["front_door"] + inputs = camera["ffmpeg"]["inputs"] + inputs[0]["roles"], inputs[1]["roles"] = ["record"], ["detect"] + + resp = self._save( + client, {"cameras": {"front_door": {"ffmpeg": {"inputs": inputs}}}} + ) + self.assertEqual(resp.status_code, 200, resp.text) + + _, saved = self._read_config_file(config_path) + saved_inputs = saved["cameras"]["front_door"]["ffmpeg"]["inputs"] + self.assertEqual( + [(inp["path"], inp["roles"]) for inp in saved_inputs], + [(path_a, ["record"]), (path_b, ["detect"])], + ) + finally: + os.unlink(config_path) + @patch("frigate.api.app.find_config_file") def test_over_masked_path_round_trips(self, mock_find_config): path = "rtsp://10.0.0.1:554/live?x=a@b" diff --git a/frigate/test/test_env.py b/frigate/test/test_env.py index 4493ca8821..de5c372df6 100644 --- a/frigate/test/test_env.py +++ b/frigate/test/test_env.py @@ -518,11 +518,47 @@ class TestSecretsReload(unittest.TestCase): """ env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "from_config"}) config = FrigateConfig.parse_yaml( + "environment_vars:\n FRIGATE_MQTT_HOST: from_config\n" 'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n' ) self.assertEqual(config.mqtt.host, "from_config") self.assertEqual(env._CONFIG_ENV_VARS["FRIGATE_MQTT_HOST"], "from_config") + def test_candidate_env_var_resolves_before_install(self): + """A non-install parse resolves against the candidate's own block, so + an entry can be added and referenced in the same save.""" + env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "running"}) + config = FrigateConfig.parse_yaml( + "environment_vars:\n FRIGATE_MQTT_HOST: candidate\n" + " FRIGATE_MQTT_USER: added\n" + 'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\n' + ' user: "{FRIGATE_MQTT_USER}"\n password: secret\ncameras: {}\n' + ) + self.assertEqual(config.mqtt.host, "candidate") + self.assertEqual(config.mqtt.user, "added") + self.assertEqual(env._CONFIG_ENV_VARS, {"FRIGATE_MQTT_HOST": "running"}) + self.assertNotIn("FRIGATE_MQTT_USER", os.environ) + + def test_removed_candidate_env_var_fails_validation(self): + """Removing an entry that is still referenced fails now, not at the + next start.""" + env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "running"}) + with self.assertRaises(ValidationError): + FrigateConfig.parse_yaml( + 'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n' + ) + + def test_candidate_env_var_keeps_lowest_precedence(self): + """secrets.yaml still outranks the candidate's block.""" + with open(os.path.join(self._dir.name, "secrets.yaml"), "w") as f: + f.write("FRIGATE_MQTT_HOST: from_secrets\n") + + config = FrigateConfig.parse_yaml( + "environment_vars:\n FRIGATE_MQTT_HOST: candidate\n" + 'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n' + ) + self.assertEqual(config.mqtt.host, "from_secrets") + class TestSourceRobustness(unittest.TestCase): """Reload behavior, bad input, and the os.environ export.""" diff --git a/frigate/util/env.py b/frigate/util/env.py index a87ed93b79..06a80b7c6f 100644 --- a/frigate/util/env.py +++ b/frigate/util/env.py @@ -3,7 +3,9 @@ import logging import os import re -from collections.abc import Mapping +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from contextvars import ContextVar from pathlib import Path from typing import Annotated, Any @@ -246,6 +248,35 @@ def apply_config_env_vars(values: Mapping[str, object]) -> None: reload_sources(warn=False) +_CANDIDATE_ENV_VARS: ContextVar[dict[str, str] | None] = ContextVar( + "candidate_env_vars", default=None +) + + +@contextmanager +def candidate_env_vars(values: object) -> Iterator[None]: + """Resolve placeholders against a candidate config's environment_vars. + + Its FRIGATE_ keys replace the installed block at the same lowest + precedence. Nothing is installed or exported to os.environ. + """ + merged = { + str(key): str(value) + for key, value in (values.items() if isinstance(values, Mapping) else ()) + if str(key).startswith("FRIGATE_") + } + + for _, source in _SOURCES: + if source is not _CONFIG_ENV_VARS: + merged.update(source) + + token = _CANDIDATE_ENV_VARS.set(merged) + try: + yield + finally: + _CANDIDATE_ENV_VARS.reset(token) + + # Matches a FRIGATE_* identifier following an opening brace. _FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+") @@ -258,7 +289,8 @@ def substitute_frigate_vars(value: str) -> str: (e.g. ffmpeg `%{localtime\\:...}` expressions) untouched: * `{{` and `}}` collapse to literal `{` / `}` (the documented escape). - * `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`; an unknown name + * `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`, or from the + sources set by `candidate_env_vars`; an unknown name raises `UnknownVariableError` to preserve the existing "Invalid substitution" error path. * A `{` that begins `{FRIGATE_` but is not a well-formed @@ -268,6 +300,10 @@ def substitute_frigate_vars(value: str) -> str: error. * Any other `{` or `}` is treated as a literal and passed through. """ + env_vars = _CANDIDATE_ENV_VARS.get() + if env_vars is None: + env_vars = FRIGATE_ENV_VARS + out: list[str] = [] i = 0 n = len(value) @@ -288,12 +324,12 @@ def substitute_frigate_vars(value: str) -> str: and value[ident_match.end()] == "}" ): key = ident_match.group(0) - if key not in FRIGATE_ENV_VARS: + if key not in env_vars: raise UnknownVariableError( f"{key} is not defined in the environment, " "secrets.yaml, or the environment_vars config" ) - out.append(FRIGATE_ENV_VARS[key]) + out.append(env_vars[key]) i = ident_match.end() + 1 continue # Looks like a FRIGATE placeholder but is malformed diff --git a/frigate/util/services.py b/frigate/util/services.py index 03eb61782d..2c15ad1308 100644 --- a/frigate/util/services.py +++ b/frigate/util/services.py @@ -30,7 +30,11 @@ from frigate.const import ( SHM_FRAMES_VAR, ) from frigate.util.builtin import clean_camera_user_pass, escape_special_characters -from frigate.util.env import UnknownVariableError, substitute_frigate_vars +from frigate.util.env import ( + UnknownVariableError, + candidate_env_vars, + substitute_frigate_vars, +) from frigate.util.live_streams import is_valid_go2rtc_stream_name logger = logging.getLogger(__name__) @@ -1228,16 +1232,27 @@ class Go2rtcStreamIssue(str, Enum): invalid_name = "invalid_name" +def _resolve_running_frigate_vars(source: str) -> str | None: + try: + return substitute_frigate_vars(source) + except ValueError: + return None + + def find_restricted_go2rtc_stream_changes( - old_streams: dict[str, Any] | None, new_streams: dict[str, Any] | None + old_streams: dict[str, Any] | None, + new_streams: dict[str, Any] | None, + new_env_vars: object, ) -> dict[str, Go2rtcStreamIssue]: """Return the go2rtc streams with new sources that must be rejected. - Used when the config is changed through the API. A source that is already - in the saved config for the same stream is left alone, so streams the - operator configured on disk keep working; any other source must resolve - its {FRIGATE_*} placeholders and pass `is_restricted_go2rtc_api_source`. - New stream names must pass `is_valid_go2rtc_stream_name`. + Used when the config is changed through the API. Every source must resolve + its {FRIGATE_*} placeholders against the new config's environment_vars. A + source that is already in the saved config for the same stream and + resolves to the same value as it does now is left alone, so streams the + operator configured on disk keep working; any other source must pass + `is_restricted_go2rtc_api_source`. New stream names must pass + `is_valid_go2rtc_stream_name`. """ old_streams = old_streams if isinstance(old_streams, dict) else {} new_streams = new_streams if isinstance(new_streams, dict) else {} @@ -1251,20 +1266,17 @@ def find_restricted_go2rtc_stream_changes( existing = _go2rtc_stream_sources(old_streams.get(name)) for source in _go2rtc_stream_sources(stream): - if source in existing: - continue - if not isinstance(source, str): # the map form is only usable with arbitrary exec enabled - if is_go2rtc_arbitrary_exec_allowed(): + if source in existing or is_go2rtc_arbitrary_exec_allowed(): continue issues[name] = Go2rtcStreamIssue.restricted break - # only sources whose placeholders resolve here are accepted, so the - # resolved value checked below is what go2rtc loads at startup + # the resolved value checked below is what go2rtc loads at startup try: - resolved_source = substitute_frigate_vars(source) + with candidate_env_vars(new_env_vars): + resolved_source = substitute_frigate_vars(source) except UnknownVariableError: issues[name] = Go2rtcStreamIssue.unknown_variable break @@ -1272,6 +1284,11 @@ def find_restricted_go2rtc_stream_changes( issues[name] = Go2rtcStreamIssue.invalid_placeholder break + if source in existing and resolved_source == ( + _resolve_running_frigate_vars(source) + ): + continue + if is_restricted_go2rtc_api_source( source ) or is_restricted_go2rtc_api_source(resolved_source):