Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat(setup): 0o600 secret-file hygiene for .env writes (U7)

Matt Van Horn4f0cff17a833
diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.py
index 918c82c9..4e9dde8b 100644
--- a/skills/last30days/scripts/lib/setup_wizard.py
+++ b/skills/last30days/scripts/lib/setup_wizard.py
@@ -7,6 +7,7 @@ presents it), but this module provides the detection and setup actions.
import json
import logging
+import os
import shutil
import subprocess
import time
@@ -98,6 +99,40 @@ def run_auto_setup(config: Dict[str, Any]) -> Dict[str, Any]:
return results
+def _open_secret_append(path: Path):
+ """Open ``path`` for appending as a 0o600 secret file with no readable window.
+
+ ``os.open`` with ``O_CREAT|O_WRONLY|O_APPEND`` and mode ``0o600`` sets
+ restrictive permissions at creation (umask can only further restrict, never
+ widen, so the file is never world-readable even transiently). An explicit
+ ``chmod`` afterwards also tightens a pre-existing loose file. This matters
+ because the .env stores API keys, cookies, and tokens.
+ """
+ fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_APPEND, 0o600)
+ try:
+ os.chmod(path, 0o600)
+ except OSError:
+ pass
+ return os.fdopen(fd, "a", encoding="utf-8")
+
+
+def _format_env_value(value: str) -> str:
+ """Quote a value so it round-trips through env.load_env_file.
+
+ The loader strips a single layer of matching surrounding quotes, so values
+ containing whitespace or a leading quote are wrapped in double quotes to
+ survive the parse. Plain tokens (the common case) are returned unchanged.
+ Embedded double quotes are backslash-escaped. Newlines are not permitted in
+ a single-line env value and are stripped defensively.
+ """
+ value = value.replace("\r", "").replace("\n", " ")
+ needs_quoting = (not value) or value[0] in ("'", '"') or any(c.isspace() for c in value)
+ if not needs_quoting:
+ return value
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"')
+ return f'"{escaped}"'
+
+
def write_setup_config(env_path: Path, from_browser: str = "auto") -> bool:
"""Write SETUP_COMPLETE and FROM_BROWSER to the .env file.
@@ -130,13 +165,14 @@ def write_setup_config(env_path: Path, from_browser: str = "auto") -> bool:
if "SETUP_COMPLETE" not in existing_keys:
lines_to_add.append("SETUP_COMPLETE=true")
if "FROM_BROWSER" not in existing_keys:
- lines_to_add.append(f"FROM_BROWSER={from_browser}")
+ lines_to_add.append(f"FROM_BROWSER={_format_env_value(from_browser)}")
if not lines_to_add:
return True # Nothing to write, already configured
- # Ensure trailing newline before appending
- with open(env_path, "a", encoding="utf-8") as f:
+ # Create/append as a 0o600 secret file: the .env holds tokens and keys,
+ # so it must never be created world-readable.
+ with _open_secret_append(env_path) as f:
if existing_content and not existing_content.endswith("\n"):
f.write("\n")
f.write("\n".join(lines_to_add) + "\n")
diff --git a/tests/test_secret_hygiene.py b/tests/test_secret_hygiene.py
new file mode 100644
index 00000000..c1891580
--- /dev/null
+++ b/tests/test_secret_hygiene.py
@@ -0,0 +1,52 @@
+"""Tests for secret-file write hygiene (U7)."""
+
+import os
+import stat
+from pathlib import Path
+
+from lib import env, setup_wizard
+
+
+def _mode(path: Path) -> int:
+ return stat.S_IMODE(os.stat(path).st_mode)
+
+
+class TestSecureEnvWrite:
+ def test_new_env_file_is_0600(self, tmp_path):
+ env_path = tmp_path / "cfg" / ".env"
+ assert setup_wizard.write_setup_config(env_path, from_browser="auto") is True
+ assert env_path.exists()
+ assert _mode(env_path) == 0o600
+
+ def test_existing_loose_file_tightened_to_0600(self, tmp_path):
+ env_path = tmp_path / ".env"
+ env_path.write_text("EXISTING_KEY=value\n", encoding="utf-8")
+ os.chmod(env_path, 0o644)
+ setup_wizard.write_setup_config(env_path, from_browser="auto")
+ assert _mode(env_path) == 0o600
+
+ def test_written_config_is_loadable(self, tmp_path):
+ env_path = tmp_path / ".env"
+ setup_wizard.write_setup_config(env_path, from_browser="auto")
+ loaded = env.load_env_file(env_path)
+ assert loaded.get("SETUP_COMPLETE") == "true"
+ assert loaded.get("FROM_BROWSER") == "auto"
+
+
+class TestFormatEnvValue:
+ def test_plain_token_unchanged(self):
+ assert setup_wizard._format_env_value("abc123-TOKEN_x") == "abc123-TOKEN_x"
+
+ def test_value_with_spaces_roundtrips(self, tmp_path):
+ env_path = tmp_path / ".env"
+ line = f"SOME_KEY={setup_wizard._format_env_value('two words')}\n"
+ # Write 0o600 via the loader-compatible path and confirm the loader
+ # strips the quoting back to the original value.
+ env_path.write_text(line, encoding="utf-8")
+ os.chmod(env_path, 0o600)
+ loaded = env.load_env_file(env_path)
+ assert loaded["SOME_KEY"] == "two words"
+
+ def test_newline_is_stripped(self):
+ out = setup_wizard._format_env_value("line1\nline2")
+ assert "\n" not in out