Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(utils): env one-door — env_str/env_bool/env_int (plan 77 F4)

Juan Denis5d691540029d
diff --git a/backend/app/api/system.py b/backend/app/api/system.py
index 5bb78015..fe79f1ff 100644
--- a/backend/app/api/system.py
+++ b/backend/app/api/system.py
@@ -1,4 +1,5 @@
import os
+from app.utils.env import env_bool
import time
import urllib.request
import json
@@ -164,7 +165,7 @@ def health_check():
# Staging instances (plan 37 testbed) run with SERVERKIT_STAGING set. Echo
# it here so the verify step can prove WHICH instance answered and the UI
# can show its STAGING banner.
- staging = os.environ.get('SERVERKIT_STAGING', '').strip().lower() in ('1', 'true', 'yes', 'on')
+ staging = env_bool('SERVERKIT_STAGING')
return jsonify({
'status': 'healthy',
diff --git a/backend/app/middleware/demo.py b/backend/app/middleware/demo.py
index 852988b6..f3453a6e 100644
--- a/backend/app/middleware/demo.py
+++ b/backend/app/middleware/demo.py
@@ -6,6 +6,7 @@ Activation: env ``SERVERKIT_DEMO_MODE=1`` (wins) or the ``demo_mode``
system setting. Default OFF.
"""
import os
+from app.utils.env import env_bool
from flask import request, jsonify
@@ -22,9 +23,8 @@ ALLOWLIST = {
def is_demo_mode_active():
"""True when demo mode is on. The env var wins over the setting."""
- env = os.environ.get('SERVERKIT_DEMO_MODE')
- if env is not None:
- return env.strip().lower() in ('1', 'true', 'yes', 'on')
+ if os.environ.get('SERVERKIT_DEMO_MODE') is not None:
+ return env_bool('SERVERKIT_DEMO_MODE')
try:
from app.services.settings_service import SettingsService
return bool(SettingsService.get('demo_mode', False))
diff --git a/backend/app/services/plugin_service.py b/backend/app/services/plugin_service.py
index 72fb16ff..eb455f35 100644
--- a/backend/app/services/plugin_service.py
+++ b/backend/app/services/plugin_service.py
@@ -21,6 +21,7 @@ import zipfile
import requests
from app import db
+from app.utils.env import env_bool
from app.models.plugin import InstalledPlugin
logger = logging.getLogger(__name__)
@@ -355,7 +356,7 @@ def _assert_url_safe(url):
if scheme == 'http':
raise ValueError(
'Plain-http extension downloads are only allowed for loopback dev hosts')
- if os.environ.get('SERVERKIT_ALLOW_PRIVATE_DOWNLOADS', '').lower() in ('1', 'true', 'yes'):
+ if env_bool('SERVERKIT_ALLOW_PRIVATE_DOWNLOADS'):
return
bad = sorted(ip for ip in ips if not _ip_is_public(ip))
if bad:
@@ -1796,7 +1797,7 @@ _MAX_REQUIREMENTS_BYTES = 64 * 1024
def plugin_pip_enabled():
"""Whether the operator has opted into installing plugin Python deps."""
- return os.environ.get(PLUGIN_PIP_ENV, '').lower() in ('1', 'true', 'yes')
+ return env_bool(PLUGIN_PIP_ENV)
def pending_requirements(plugin):
diff --git a/backend/app/utils/env.py b/backend/app/utils/env.py
new file mode 100644
index 00000000..f85b25ac
--- /dev/null
+++ b/backend/app/utils/env.py
@@ -0,0 +1,36 @@
+"""One door for call-time environment access (plan 77 F4).
+
+Boolean env parsing existed in three incompatible variants across the app —
+`('1', 'true', 'yes', 'on')` in config.py, `('1', 'true', 'yes')` in
+plugin_service (where `SERVERKIT_ALLOW_PRIVATE_DOWNLOADS=on` silently read
+false), and ad-hoc copies elsewhere. This module owns the parsers; config.py
+imports them back. Deliberately dependency-free (os only) so config.py can
+import it before the app package finishes initializing.
+"""
+import os
+
+#: The one set of truthy spellings for env vars.
+TRUTHY = ('1', 'true', 'yes', 'on')
+
+
+def env_str(name, default=None):
+ """Raw env string, ``default`` when unset."""
+ value = os.environ.get(name)
+ return default if value is None else value
+
+
+def env_bool(name, default=False):
+ """Parse a boolean env var. Accepts the usual truthy spellings; anything
+ else (including unset) falls back to ``default``."""
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ return raw.strip().lower() in TRUTHY
+
+
+def env_int(name, default):
+ """Parse an int env var, falling back to ``default`` on unset/garbage."""
+ try:
+ return int(os.environ.get(name, default))
+ except (TypeError, ValueError):
+ return default
diff --git a/backend/config.py b/backend/config.py
index 539cf021..5d71ca5c 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -32,21 +32,9 @@ def is_insecure_secret(value):
)
-def _env_bool(name, default=False):
- """Parse a boolean env var. Accepts the usual truthy spellings; anything
- else (including unset) falls back to ``default``."""
- raw = os.environ.get(name)
- if raw is None:
- return default
- return raw.strip().lower() in ('1', 'true', 'yes', 'on')
-
-
-def _env_int(name, default):
- """Parse an int env var, falling back to ``default`` on unset/garbage."""
- try:
- return int(os.environ.get(name, default))
- except (TypeError, ValueError):
- return default
+# Env parsing lives in app/utils/env.py (plan 77 F4) — one parser for the
+# whole app; the historical private names stay importable from here.
+from app.utils.env import env_bool as _env_bool, env_int as _env_int # noqa: E402
def _resolve_ssl_mode():
diff --git a/backend/tests/test_env_one_door.py b/backend/tests/test_env_one_door.py
new file mode 100644
index 00000000..f30af4e5
--- /dev/null
+++ b/backend/tests/test_env_one_door.py
@@ -0,0 +1,79 @@
+"""Plan 77 F4 — utils/env.py is the one env parser.
+
+The bug class: truthiness parsed in incompatible variants —
+SERVERKIT_ALLOW_PRIVATE_DOWNLOADS=on silently read false in plugin_service
+because its private tuple lacked 'on'. env_bool is the single parser
+(config.py imports it back); the ratchet stops new hand-rolled env
+truthiness tuples.
+"""
+import re
+from pathlib import Path
+
+import pytest
+
+from app.utils.env import env_bool, env_int, env_str
+
+APP = Path(__file__).resolve().parents[1] / 'app'
+
+
[email protected]('raw,expected', [
+ ('1', True), ('true', True), ('YES', True), ('on', True), (' On ', True),
+ ('0', False), ('false', False), ('off', False), ('garbage', False), ('', False),
+])
+def test_env_bool_spellings(monkeypatch, raw, expected):
+ monkeypatch.setenv('X_FLAG', raw)
+ assert env_bool('X_FLAG') is expected
+
+
+def test_env_bool_default(monkeypatch):
+ monkeypatch.delenv('X_FLAG', raising=False)
+ assert env_bool('X_FLAG') is False
+ assert env_bool('X_FLAG', True) is True
+
+
+def test_env_int_garbage_falls_back(monkeypatch):
+ monkeypatch.setenv('X_NUM', 'not-a-number')
+ assert env_int('X_NUM', 7) == 7
+ monkeypatch.setenv('X_NUM', '42')
+ assert env_int('X_NUM', 7) == 42
+
+
+def test_env_str(monkeypatch):
+ monkeypatch.delenv('X_S', raising=False)
+ assert env_str('X_S') is None
+ assert env_str('X_S', 'd') == 'd'
+ monkeypatch.setenv('X_S', 'v')
+ assert env_str('X_S', 'd') == 'v'
+
+
+def test_private_downloads_accepts_on(monkeypatch):
+ """The measured bug: '=on' must read true on the plugin download gate."""
+ monkeypatch.setenv('SERVERKIT_ALLOW_PRIVATE_DOWNLOADS', 'on')
+ assert env_bool('SERVERKIT_ALLOW_PRIVATE_DOWNLOADS') is True
+
+
+def test_config_imports_the_shared_parser():
+ import config as config_mod
+ from app.utils import env as env_mod
+ assert config_mod._env_bool is env_mod.env_bool
+ assert config_mod._env_int is env_mod.env_int
+
+
+def test_no_new_env_truthiness_tuples():
+ """Ratchet: no hand-rolled `os.environ… .lower() in (…)` truthiness
+ outside utils/env.py (vendored plugin copies excluded)."""
+ offenders = []
+ for f in APP.rglob('*.py'):
+ rel = f.relative_to(APP).as_posix()
+ if rel == 'utils/env.py' or rel.startswith('plugins/') or '__pycache__' in rel:
+ continue
+ lines = f.read_text(encoding='utf-8', errors='replace').split('\n')
+ for i, line in enumerate(lines):
+ if 'os.environ' in line:
+ window = line + (lines[i + 1] if i + 1 < len(lines) else '')
+ if re.search(r"\.lower\(\)\s*in\s*\(", window):
+ offenders.append(f'{rel}:{i + 1}')
+ assert not offenders, (
+ f"Hand-rolled env truthiness at {offenders} — use "
+ "app.utils.env.env_bool instead (plan 77 F4)."
+ )