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.

fix(env-vars): make .env export/import lossless and injection-safe

Juan Denisde609526dfc0
diff --git a/backend/app/services/env_service.py b/backend/app/services/env_service.py
index 1a4968d2..15bd115c 100644
--- a/backend/app/services/env_service.py
+++ b/backend/app/services/env_service.py
@@ -447,6 +447,16 @@ class EnvService:
return count, errors
+ @staticmethod
+ def _unescape_double_quoted(value):
+ """Reverse the escaping export_to_env_format applies inside double
+ quotes: \\\\ -> \\, \\" -> ", \\n -> newline. Unknown sequences stay
+ as written so hand-authored values like C:\\path are not mangled."""
+ return re.sub(
+ r'\\([\\"n])',
+ lambda m: '\n' if m.group(1) == 'n' else m.group(1),
+ value)
+
@staticmethod
def parse_env_file(content):
"""
@@ -491,8 +501,11 @@ class EnvService:
current_key = key
current_value = value[1:] # Remove opening quote
elif value.startswith('"') and value.endswith('"') and len(value) > 1:
- # Quoted value (single line)
- env_vars[key] = value[1:-1]
+ # Quoted value (single line). Decode the escapes
+ # export_to_env_format writes (\\, \", \n) so an
+ # export → import cycle is lossless; any other
+ # backslash sequence is left untouched.
+ env_vars[key] = EnvService._unescape_double_quoted(value[1:-1])
elif value.startswith("'") and value.endswith("'") and len(value) > 1:
# Single-quoted value
env_vars[key] = value[1:-1]
@@ -535,18 +548,26 @@ class EnvService:
if ev.is_secret and not include_secrets:
lines.append(f"# {ev.key}=<secret>")
else:
- value = ev.value
+ value = ev.value or ''
# Quote values that contain special characters
if any(c in value for c in [' ', '"', "'", '\n', '#', '$']):
- # Escape existing quotes and wrap in quotes
- value = value.replace('\\', '\\\\').replace('"', '\\"')
+ # Escape quotes/backslashes and encode newlines so the
+ # value stays on one line — parse_env_file reverses
+ # exactly these three escapes on import.
+ value = (value.replace('\\', '\\\\')
+ .replace('"', '\\"')
+ .replace('\n', '\\n'))
lines.append(f'{ev.key}="{value}"')
else:
lines.append(f"{ev.key}={value}")
- # Add description as comment if present
+ # Add description as comment if present. Whitespace-collapsed so
+ # user text cannot break out of the comment and inject KEY=value
+ # lines into the re-import (same hardening as the cron marker).
if ev.description:
- lines[-1] = f"# {ev.description}\n" + lines[-1]
+ clean_desc = re.sub(r'\s+', ' ', str(ev.description)).strip()
+ if clean_desc:
+ lines[-1] = f"# {clean_desc}\n" + lines[-1]
return '\n'.join(lines)
diff --git a/backend/tests/test_env_export_import_roundtrip.py b/backend/tests/test_env_export_import_roundtrip.py
new file mode 100644
index 00000000..f375c8d2
--- /dev/null
+++ b/backend/tests/test_env_export_import_roundtrip.py
@@ -0,0 +1,91 @@
+"""Env export → import round trip.
+
+export_to_env_format escaped quotes/backslashes that parse_env_file never
+unescaped (values grew literal backslashes each cycle), and wrote the
+user-supplied description as a raw ``# ...`` comment line — a newline in a
+description injected brand-new KEY=value lines into the re-import. Same
+write/read join hardening as the cron #117 fix: the cycle must be lossless
+and user text must not be able to fabricate entries.
+"""
+from app import db
+from app.services.env_service import EnvService
+
+
+def _seed(app, pairs):
+ from factories import make_application, make_user
+
+ user = make_user(db, role='admin')
+ application = make_application(db, name='env-rt-app', user_id=user.id)
+ for key, value, desc in pairs:
+ EnvService.set_env_var(application.id, key, value,
+ description=desc, user_id=user.id)
+ return application
+
+
+def _roundtrip(app, pairs):
+ with app.app_context():
+ application = _seed(app, pairs)
+ content = EnvService.export_to_env_format(application.id)
+ parsed, errors = EnvService.parse_env_file(content)
+ return content, parsed, errors
+
+
+def test_quotes_and_backslashes_survive_one_cycle(app):
+ value = 'say "hi" via C:\\temp and a $HOME too'
+ _, parsed, errors = _roundtrip(app, [('GREETING', value, None)])
+ assert errors == []
+ assert parsed == {'GREETING': value}
+
+
+def test_cycle_is_stable_not_compounding(app):
+ # The old parser kept the export-side escapes, so every cycle grew
+ # literal backslashes. Two cycles must equal one.
+ value = 'quote " backslash \\ end'
+ content, parsed, _ = _roundtrip(app, [('V', value, None)])
+ assert parsed == {'V': value}
+ reparsed, errors = EnvService.parse_env_file(content)
+ assert errors == []
+ assert reparsed == parsed
+
+
+def test_newline_value_stays_one_line_and_round_trips(app):
+ value = 'line one\nline two'
+ content, parsed, errors = _roundtrip(app, [('MULTI', value, None)])
+ assert errors == []
+ assert parsed == {'MULTI': value}
+ # The value must be encoded onto a single line, not written as a raw
+ # multiline quote the parser mangles.
+ assert 'MULTI="line one\\nline two"' in content
+
+
+def test_description_newline_cannot_inject_variables(app):
+ evil = 'looks harmless\nINJECTED_TOKEN=attacker'
+ _, parsed, _ = _roundtrip(app, [('SAFE', 'ok', evil)])
+ assert 'INJECTED_TOKEN' not in parsed
+ assert parsed == {'SAFE': 'ok'}
+
+
+def test_description_still_exported_as_comment(app):
+ content, _, _ = _roundtrip(app, [('DB_URL', 'sqlite://x y', 'where data lives')])
+ assert '# where data lives\n' in content
+
+
+def test_none_value_exports_as_empty(app):
+ with app.app_context():
+ application = _seed(app, [('EMPTYABLE', 'x', None)])
+ from app.models import EnvironmentVariable
+ ev = EnvironmentVariable.query.filter_by(
+ application_id=application.id, key='EMPTYABLE').first()
+ ev.value = None
+ db.session.commit()
+ content = EnvService.export_to_env_format(application.id)
+ parsed, errors = EnvService.parse_env_file(content)
+ assert errors == []
+ assert parsed == {'EMPTYABLE': ''}
+
+
+def test_hand_written_windows_path_not_mangled():
+ # Unknown backslash sequences in hand-authored files stay as written.
+ parsed, errors = EnvService.parse_env_file('DIR="C:\\projects\\app"\n')
+ assert errors == []
+ assert parsed == {'DIR': 'C:\\projects\\app'}