only export allowlisted environment_vars

apply_config_env_vars wrote every unprefixed environment_vars key into os.environ and exported every FRIGATE_ key, so a config could set LD_PRELOAD or LIGHTER_ANE_EP to load a library into Frigate or its children, or set FRIGATE_RUN_AS_ROOT to turn off the ffmpeg.path writable-tree guard. Only the documented names are now exported, each with a value check, and a name the container already sets is never overwritten. FRIGATE_ keys still feed substitution, but only FRIGATE_JWT_SECRET is exported. Anything else logs a warning naming the key.
This commit is contained in:
Josh Hawkins
2026-11-07 12:32:06 -06:00
parent 97696d0cbe
commit 40c27fb04f
5 changed files with 153 additions and 40 deletions
@@ -40,16 +40,10 @@ try:
except FileNotFoundError: except FileNotFoundError:
config: dict[str, Any] = {} config: dict[str, Any] = {}
# No validator runs here, so install environment_vars ourselves. FRIGATE_ # No validator runs here, so install environment_vars ourselves.
# names only: anything else lands in os.environ, where the exec gate reads
# GO2RTC_ALLOW_ARBITRARY_EXEC.
config_env_vars = config.get("environment_vars") config_env_vars = config.get("environment_vars")
apply_config_env_vars( apply_config_env_vars(
{ {str(key): value for key, value in config_env_vars.items()}
key: value
for key, value in config_env_vars.items()
if str(key).startswith("FRIGATE_")
}
if isinstance(config_env_vars, dict) if isinstance(config_env_vars, dict)
else {} else {}
) )
@@ -240,7 +240,7 @@ logger:
# Optional: set environment variables # Optional: set environment variables
environment_vars: environment_vars:
EXAMPLE_VAR: value LIBVA_DRIVER_NAME: i965
# Optional: birdseye configuration # Optional: birdseye configuration
# NOTE: Can (enabled, mode) be overridden at the camera level # NOTE: Can (enabled, mode) be overridden at the camera level
+10 -1
View File
@@ -65,7 +65,16 @@ go2rtc:
This section sets environment variables in the Frigate process for those unable to modify the environment of the container, like within Home Assistant OS. It's meant for process settings such as `LIBVA_DRIVER_NAME` or the TensorFlow thread counts below. Docker users should set environment variables in their `docker run` command (`-e LIBVA_DRIVER_NAME=i965`) or `docker-compose.yml` file (`environment:` section) instead. Values set here are stored in plain text in your config file, so credentials belong in `secrets.yaml`, Docker environment variables, or Docker secrets instead. This section sets environment variables in the Frigate process for those unable to modify the environment of the container, like within Home Assistant OS. It's meant for process settings such as `LIBVA_DRIVER_NAME` or the TensorFlow thread counts below. Docker users should set environment variables in their `docker run` command (`-e LIBVA_DRIVER_NAME=i965`) or `docker-compose.yml` file (`environment:` section) instead. Values set here are stored in plain text in your config file, so credentials belong in `secrets.yaml`, Docker environment variables, or Docker secrets instead.
Names prefixed with `FRIGATE_` set here also take part in `{FRIGATE_VARIABLE_NAME}` substitution (see [below](#substitution-sources-and-precedence)), but `secrets.yaml` is the better home for them. Besides `FRIGATE_` names, only these are accepted, and a variable already set in the container environment keeps its container value:
- `LIBVA_DRIVER_NAME` and `HSA_OVERRIDE_GFX_VERSION`
- `TF_INTRA_OP_PARALLELISM_THREADS`, `TF_INTER_OP_PARALLELISM_THREADS`, `TF_DATASET_THREAD_POOL_SIZE`, and `SHM_MAX_FRAMES`
- `USE_FP16`, `HF_HUB_OFFLINE`, and `TRANSFORMERS_OFFLINE`
- `HF_ENDPOINT`, `GITHUB_ENDPOINT`, `GITHUB_RAW_ENDPOINT`, and `TF_KERAS_MOBILENET_V2_WEIGHTS_URL` (an `http://` or `https://` URL)
Any other name is ignored with a warning and must be set in the container environment.
Names prefixed with `FRIGATE_` set here take part in `{FRIGATE_VARIABLE_NAME}` substitution (see [below](#substitution-sources-and-precedence)), but `secrets.yaml` is the better home for them. Of these, only `FRIGATE_JWT_SECRET` is also set in the process environment.
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
+81 -15
View File
@@ -194,15 +194,16 @@ class TestEnvVars(unittest.TestCase):
def setUp(self): def setUp(self):
self._original_env_vars = dict(FRIGATE_ENV_VARS) self._original_env_vars = dict(FRIGATE_ENV_VARS)
self._original_environ = os.environ.copy() self._original_environ = os.environ.copy()
names_patch = patch.object(env, "_CONTAINER_ENV_NAMES", frozenset())
names_patch.start()
self.addCleanup(names_patch.stop)
def tearDown(self): def tearDown(self):
FRIGATE_ENV_VARS.clear() FRIGATE_ENV_VARS.clear()
FRIGATE_ENV_VARS.update(self._original_env_vars) FRIGATE_ENV_VARS.update(self._original_env_vars)
env._CONFIG_ENV_VARS.clear() env._CONFIG_ENV_VARS.clear()
# Clean up any env vars we set os.environ.clear()
for key in list(os.environ.keys()): os.environ.update(self._original_environ)
if key not in self._original_environ:
del os.environ[key]
def _make_context(self, install: bool): def _make_context(self, install: bool):
"""Create a mock ValidationInfo with the given install flag.""" """Create a mock ValidationInfo with the given install flag."""
@@ -215,10 +216,10 @@ class TestEnvVars(unittest.TestCase):
return mock return mock
def test_install_sets_os_environ(self): def test_install_sets_os_environ(self):
"""validate_env_vars with install=True sets os.environ.""" """validate_env_vars with install=True sets allowed names in os.environ."""
ctx = self._make_context(install=True) ctx = self._make_context(install=True)
validate_env_vars({"MY_CUSTOM_VAR": "value123"}, ctx) validate_env_vars({"SHM_MAX_FRAMES": "75"}, ctx)
self.assertEqual(os.environ.get("MY_CUSTOM_VAR"), "value123") self.assertEqual(os.environ.get("SHM_MAX_FRAMES"), "75")
def test_install_updates_frigate_env_vars(self): def test_install_updates_frigate_env_vars(self):
"""validate_env_vars with install=True updates FRIGATE_ENV_VARS for FRIGATE_ keys.""" """validate_env_vars with install=True updates FRIGATE_ENV_VARS for FRIGATE_ keys."""
@@ -229,9 +230,9 @@ class TestEnvVars(unittest.TestCase):
def test_install_skips_non_frigate_in_env_vars_dict(self): def test_install_skips_non_frigate_in_env_vars_dict(self):
"""Non-FRIGATE_ keys are set in os.environ but not in FRIGATE_ENV_VARS.""" """Non-FRIGATE_ keys are set in os.environ but not in FRIGATE_ENV_VARS."""
ctx = self._make_context(install=True) ctx = self._make_context(install=True)
validate_env_vars({"OTHER_VAR": "value"}, ctx) validate_env_vars({"USE_FP16": "False"}, ctx)
self.assertEqual(os.environ.get("OTHER_VAR"), "value") self.assertEqual(os.environ.get("USE_FP16"), "False")
self.assertNotIn("OTHER_VAR", FRIGATE_ENV_VARS) self.assertNotIn("USE_FP16", FRIGATE_ENV_VARS)
def test_no_install_does_not_set(self): def test_no_install_does_not_set(self):
"""validate_env_vars without install=True does not modify state.""" """validate_env_vars without install=True does not modify state."""
@@ -258,10 +259,10 @@ class TestEnvVars(unittest.TestCase):
ctx = self._make_context(install=True) ctx = self._make_context(install=True)
with patch("frigate.util.services.os.path.isfile", return_value=False): with patch("frigate.util.services.os.path.isfile", return_value=False):
for key in ("GO2RTC_ALLOW_ARBITRARY_EXEC", "go2rtc_allow_arbitrary_exec"): for key in ("GO2RTC_ALLOW_ARBITRARY_EXEC", "go2rtc_allow_arbitrary_exec"):
validate_env_vars({key: "true", "OTHER_VAR": "value"}, ctx) validate_env_vars({key: "true", "USE_FP16": "False"}, ctx)
self.assertNotIn(key, os.environ) self.assertNotIn(key, os.environ)
self.assertFalse(is_go2rtc_arbitrary_exec_allowed()) self.assertFalse(is_go2rtc_arbitrary_exec_allowed())
self.assertEqual(os.environ.get("OTHER_VAR"), "value") self.assertEqual(os.environ.get("USE_FP16"), "False")
def test_install_keeps_container_go2rtc_exec_override(self): def test_install_keeps_container_go2rtc_exec_override(self):
"""An override set in the container environment is left untouched.""" """An override set in the container environment is left untouched."""
@@ -307,17 +308,82 @@ class TestVariableSources(unittest.TestCase):
self.assertEqual(env.FRIGATE_ENV_VARS["FRIGATE_CAM_PASS"], "hunter2") self.assertEqual(env.FRIGATE_ENV_VARS["FRIGATE_CAM_PASS"], "hunter2")
def test_config_env_vars_do_not_become_container_env(self): def test_config_env_vars_do_not_become_container_env(self):
"""environment_vars writes os.environ but must not gain env precedence.""" """environment_vars FRIGATE_ keys stay out of os.environ and env precedence."""
env.apply_config_env_vars({"FRIGATE_CAM_PASS": "from_config"}) env.apply_config_env_vars({"FRIGATE_CAM_PASS": "from_config"})
self.assertEqual(os.environ["FRIGATE_CAM_PASS"], "from_config") self.assertNotIn("FRIGATE_CAM_PASS", os.environ)
self.assertNotIn("FRIGATE_CAM_PASS", env._CONTAINER_ENV) self.assertNotIn("FRIGATE_CAM_PASS", env._CONTAINER_ENV)
def test_non_frigate_config_env_vars_only_set_os_environ(self): def test_non_frigate_config_env_vars_only_set_os_environ(self):
"""Unprefixed environment_vars keys reach os.environ but not substitution.""" """Unprefixed environment_vars keys reach os.environ but not substitution."""
env.apply_config_env_vars({"LIBVA_DRIVER_NAME": "i965"}) with patch.object(env, "_CONTAINER_ENV_NAMES", frozenset()):
env.apply_config_env_vars({"LIBVA_DRIVER_NAME": "i965"})
self.assertEqual(os.environ["LIBVA_DRIVER_NAME"], "i965") self.assertEqual(os.environ["LIBVA_DRIVER_NAME"], "i965")
self.assertNotIn("LIBVA_DRIVER_NAME", env.FRIGATE_ENV_VARS) self.assertNotIn("LIBVA_DRIVER_NAME", env.FRIGATE_ENV_VARS)
def test_rejected_names_warn_and_are_not_exported(self):
"""Names off the allowlist log a warning without the value."""
for key in ("MY_CUSTOM_VAR", "LD_PRELOAD", "LIGHTER_ANE_EP", "PATH"):
with self.subTest(key=key):
original = os.environ.get(key)
with self.assertLogs("frigate.util.env", level="WARNING") as logs:
env.apply_config_env_vars({key: "/config/evil.so"})
self.assertEqual(os.environ.get(key), original)
self.assertEqual(len(logs.output), 1)
self.assertIn(key, logs.output[0])
self.assertIn("container environment", logs.output[0])
self.assertNotIn("evil", logs.output[0])
def test_allowed_name_with_bad_value_is_rejected(self):
"""LIBVA_DRIVER_NAME cannot carry a path."""
with patch.object(env, "_CONTAINER_ENV_NAMES", frozenset()):
with self.assertLogs("frigate.util.env", level="WARNING"):
env.apply_config_env_vars({"LIBVA_DRIVER_NAME": "../x"})
self.assertNotEqual(os.environ.get("LIBVA_DRIVER_NAME"), "../x")
def test_unsupported_values_are_rejected_without_crashing(self):
"""Non-ASCII digits and NUL bytes never reach os.environ."""
os.environ.pop("SHM_MAX_FRAMES", None)
os.environ.pop("HF_ENDPOINT", None)
with patch.object(env, "_CONTAINER_ENV_NAMES", frozenset()):
with self.assertLogs("frigate.util.env", level="WARNING") as logs:
env.apply_config_env_vars(
{"SHM_MAX_FRAMES": "\u0663\u0664", "HF_ENDPOINT": "https://x\x00"}
)
self.assertEqual(len(logs.output), 2)
self.assertNotIn("SHM_MAX_FRAMES", os.environ)
self.assertNotIn("HF_ENDPOINT", os.environ)
def test_container_env_wins_over_allowed_name(self):
"""A name the container set is left as the container set it."""
os.environ["LIBVA_DRIVER_NAME"] = "iHD"
with patch.object(
env, "_CONTAINER_ENV_NAMES", frozenset({"LIBVA_DRIVER_NAME"})
):
env.apply_config_env_vars({"LIBVA_DRIVER_NAME": "i965"})
self.assertEqual(os.environ["LIBVA_DRIVER_NAME"], "iHD")
def test_second_apply_is_not_blocked_by_first(self):
"""A safe-mode reload can change a value the first load exported."""
with patch.object(env, "_CONTAINER_ENV_NAMES", frozenset()):
env.apply_config_env_vars({"LIBVA_DRIVER_NAME": "i965"})
env.apply_config_env_vars({"LIBVA_DRIVER_NAME": "radeonsi"})
self.assertEqual(os.environ["LIBVA_DRIVER_NAME"], "radeonsi")
def test_run_as_root_is_substitutable_but_not_exported(self):
"""FRIGATE_RUN_AS_ROOT from the config never reaches os.environ."""
os.environ.pop("FRIGATE_RUN_AS_ROOT", None)
with patch.object(env, "_CONTAINER_ENV_NAMES", frozenset()):
env.apply_config_env_vars({"FRIGATE_RUN_AS_ROOT": "true"})
self.assertNotIn("FRIGATE_RUN_AS_ROOT", os.environ)
self.assertEqual(env.substitute_frigate_vars("{FRIGATE_RUN_AS_ROOT}"), "true")
def test_jwt_secret_is_exported(self):
"""Auth reads FRIGATE_JWT_SECRET from os.environ."""
os.environ.pop("FRIGATE_JWT_SECRET", None)
with patch.object(env, "_CONTAINER_ENV_NAMES", frozenset()):
env.apply_config_env_vars({"FRIGATE_JWT_SECRET": "s3cret"})
self.assertEqual(os.environ["FRIGATE_JWT_SECRET"], "s3cret")
def test_collision_warns_once_naming_the_winner(self): def test_collision_warns_once_naming_the_winner(self):
"""A key from two sources logs one warning naming the source that won.""" """A key from two sources logs one warning naming the source that won."""
with patch.dict(env._CONTAINER_ENV, {"FRIGATE_MQTT_HOST": "from_env"}): with patch.dict(env._CONTAINER_ENV, {"FRIGATE_MQTT_HOST": "from_env"}):
+59 -15
View File
@@ -26,6 +26,8 @@ _SECRETS_FILE: dict[str, str] = {}
_CONTAINER_ENV: dict[str, str] = { _CONTAINER_ENV: dict[str, str] = {
k: v for k, v in os.environ.items() if k.startswith("FRIGATE_") k: v for k, v in os.environ.items() if k.startswith("FRIGATE_")
} }
# Empty image defaults, like ROCm's HSA_OVERRIDE_GFX_VERSION, don't count as set.
_CONTAINER_ENV_NAMES = frozenset(k for k, v in os.environ.items() if v)
_CREDENTIALS_DIR: dict[str, str] = {} _CREDENTIALS_DIR: dict[str, str] = {}
_SOURCES: tuple[tuple[str, dict[str, str]], ...] = ( _SOURCES: tuple[tuple[str, dict[str, str]], ...] = (
@@ -165,38 +167,80 @@ def reload_sources(warn: bool = True) -> None:
_rebuild(warn) _rebuild(warn)
# Security overrides that must come from the container environment, which is _INT = re.compile(r"\d+", re.ASCII)
# controlled by the operator, rather than from the config, which admins can edit _WORD = re.compile(r"\w+", re.ASCII)
_PROTECTED_ENV_VARS = frozenset({"GO2RTC_ALLOW_ARBITRARY_EXEC"}) _URL = re.compile(r"https?://\S+")
# The only unprefixed names the config may export, with the values each accepts.
# Anything else, such as LD_PRELOAD, can load code into Frigate or its children.
_ALLOWED_ENV_VARS: dict[str, re.Pattern[str]] = {
"LIBVA_DRIVER_NAME": re.compile(r"[A-Za-z0-9_]+"),
"TF_INTRA_OP_PARALLELISM_THREADS": _INT,
"TF_INTER_OP_PARALLELISM_THREADS": _INT,
"TF_DATASET_THREAD_POOL_SIZE": _INT,
"SHM_MAX_FRAMES": _INT,
"USE_FP16": _WORD,
"HF_HUB_OFFLINE": _WORD,
"TRANSFORMERS_OFFLINE": _WORD,
"HSA_OVERRIDE_GFX_VERSION": re.compile(r"[0-9.]+"),
"HF_ENDPOINT": _URL,
"GITHUB_ENDPOINT": _URL,
"GITHUB_RAW_ENDPOINT": _URL,
"TF_KERAS_MOBILENET_V2_WEIGHTS_URL": _URL,
}
# Auth reads it from os.environ; every other FRIGATE_ name only feeds substitution.
_EXPORTED_FRIGATE_VARS = frozenset({"FRIGATE_JWT_SECRET"})
def apply_config_env_vars(values: Mapping[str, object]) -> None: def apply_config_env_vars(values: Mapping[str, object]) -> None:
"""Install the environment_vars block as the lowest priority source. """Install the environment_vars block as the lowest priority source.
Unprefixed keys only set os.environ. Protected security overrides are FRIGATE_ keys feed substitution. Allowlisted unprefixed keys with valid
skipped. values are exported to os.environ. A name the container already set is
never overwritten.
""" """
exports: dict[str, str] = {}
for key, value in values.items(): for key, value in values.items():
if key.upper() in _PROTECTED_ENV_VARS: resolved = str(value)
if key.startswith("FRIGATE_"):
_CONFIG_ENV_VARS[key] = resolved
continue
pattern = _ALLOWED_ENV_VARS.get(key)
if pattern is None:
logger.warning( logger.warning(
"Ignoring %s in environment_vars, it must be set in the container environment", "Ignoring %s in environment_vars, it must be set in the container environment",
key, key,
) )
continue continue
resolved = str(value) if not pattern.fullmatch(resolved):
logger.warning("Ignoring %s in environment_vars, unsupported value", key)
continue
if key.startswith("FRIGATE_"): exports[key] = resolved
_CONFIG_ENV_VARS[key] = resolved
else:
os.environ[key] = resolved
_rebuild() _rebuild()
# Export the winning value; auth reads FRIGATE_JWT_SECRET from os.environ. for key in _EXPORTED_FRIGATE_VARS & values.keys():
for key in values: exports[key] = FRIGATE_ENV_VARS[key]
if key.startswith("FRIGATE_"):
os.environ[key] = FRIGATE_ENV_VARS[key] for key, value in exports.items():
if key in _CONTAINER_ENV_NAMES:
logger.info(
"Ignoring %s in environment_vars, the container environment sets it",
key,
)
continue
try:
os.environ[key] = value
except ValueError:
logger.warning("Ignoring %s in environment_vars, unsupported value", key)
reload_sources(warn=False) reload_sources(warn=False)