Skip to content

Self-improving AI Employees for everyone

fix: harden security defaults (secret generation, webhook fail-closed)

trohitg7c28a043c2c0
diff --git a/cli/commands/build.py b/cli/commands/build.py
index 56d0110d..0cff1f4f 100644
--- a/cli/commands/build.py
+++ b/cli/commands/build.py
@@ -52,9 +52,48 @@ COMPILEALL_SOURCE_DIRS: tuple[str, ...] = (
)
+# Secret keys scaffolded with fresh values when ``.env`` is created from
+# ``.env.template``. The template ships ``dev-`` placeholder values (the
+# exact literals are the SSOT frozenset ``DEV_SECRET_LITERALS`` in
+# ``server/core/config.py``, drift-locked against the template by
+# ``server/tests/core_config/test_dev_secret_guard.py``); anything still
+# carrying that placeholder prefix is replaced so a bare ``company build``
+# never runs with publicly known secrets.
+_SCAFFOLD_SECRET_KEYS: tuple[str, ...] = (
+ "SECRET_KEY",
+ "JWT_SECRET_KEY",
+ "API_KEY_ENCRYPTION_KEY",
+)
+_DEV_PLACEHOLDER_PREFIX = "dev-"
+
+
# ---------------------------------------------------------------- helpers
+def _scaffold_env_secrets(content: str) -> tuple[str, list[str]]:
+ """Replace dev placeholder secrets with freshly generated values.
+
+ Only lines whose value still carries the template's ``dev-``
+ placeholder prefix are touched, so an operator-customised template
+ passes through unchanged. stdlib-only (``secrets``) — this verb must
+ run on bare system Python.
+ """
+ import secrets
+
+ generated: list[str] = []
+ lines = content.splitlines(keepends=True)
+ for i, line in enumerate(lines):
+ key, sep, value = line.strip().partition("=")
+ if not sep or key not in _SCAFFOLD_SECRET_KEYS:
+ continue
+ if not value.startswith(_DEV_PLACEHOLDER_PREFIX):
+ continue
+ ending = line[len(line.rstrip("\r\n")):]
+ lines[i] = f"{key}={secrets.token_hex(24)}{ending}"
+ generated.append(key)
+ return "".join(lines), generated
+
+
def _which_python() -> str | None:
"""Prefer ``python3`` so we don't pick up Python 2.x on POSIX distros."""
for cmd in ("python3", "python"):
@@ -173,8 +212,16 @@ def build_command() -> None:
# timestamped — diff between consecutive timestamps is the wall-clock
# cost of that step, no manual instrumentation needed.
if not env_path.exists() and template_path.exists():
- shutil.copy2(template_path, env_path)
- console.log("[0/6] Created .env from template")
+ content, generated = _scaffold_env_secrets(
+ template_path.read_text(encoding="utf-8")
+ )
+ env_path.write_text(content, encoding="utf-8")
+ if generated:
+ console.log(
+ f"[0/6] Created .env from template (generated fresh secrets: {', '.join(generated)})"
+ )
+ else:
+ console.log("[0/6] Created .env from template")
if not is_postinstall:
console.log("[1/6] Installing dependencies...")
diff --git a/cli/commands/deploy/_secrets.py b/cli/commands/deploy/_secrets.py
index e918b44e..44769e2e 100644
--- a/cli/commands/deploy/_secrets.py
+++ b/cli/commands/deploy/_secrets.py
@@ -48,6 +48,7 @@ def build_app_env(
"WORKSPACE_BASE_DIR": "workspaces",
"SERVE_STATIC_CLIENT": "true",
"VITE_AUTH_ENABLED": "true",
+ "DEPLOYMENT_MODE": "cloud",
"AUTH_MODE": "single",
"JWT_COOKIE_SECURE": "false",
"JWT_COOKIE_SAMESITE": "lax",
diff --git a/server/core/config.py b/server/core/config.py
index f38f3e61..a626cc48 100644
--- a/server/core/config.py
+++ b/server/core/config.py
@@ -6,6 +6,41 @@ from pydantic import Field, field_validator
from pydantic_settings import BaseSettings
+# The dev placeholder secrets shipped in ``.env.template``. SSOT for these
+# literals — ``company build`` scaffolds fresh values over the ``dev-``
+# placeholders and ``company deploy`` mints per-deploy keys. Drift-locked
+# against the template by ``tests/core_config/test_dev_secret_guard.py``.
+DEV_SECRET_LITERALS: frozenset = frozenset(
+ {
+ "dev-secret-key-12345678901234567890123456789012",
+ "dev-jwt-secret-key-12345678901234567890",
+ "dev-encryption-key-12345678901234567890123456",
+ }
+)
+
+
+def dev_secret_offenders(settings) -> list[str]:
+ """Env-var names still carrying dev placeholder secrets, non-dev posture only.
+
+ Dev posture = auth disabled (``VITE_AUTH_ENABLED == "false"``, matching
+ ``middleware/auth.py``) AND ``deployment_mode == "local"`` — returns []
+ there. Duck-typed: accepts any object with the three secret attrs plus
+ ``vite_auth_enabled`` and ``deployment_mode``.
+ """
+ auth_disabled = (settings.vite_auth_enabled or "").lower() == "false"
+ if auth_disabled and settings.deployment_mode == "local":
+ return []
+ offenders: list[str] = []
+ for attr, env_name in (
+ ("secret_key", "SECRET_KEY"),
+ ("jwt_secret_key", "JWT_SECRET_KEY"),
+ ("api_key_encryption_key", "API_KEY_ENCRYPTION_KEY"),
+ ):
+ if getattr(settings, attr, None) in DEV_SECRET_LITERALS:
+ offenders.append(env_name)
+ return offenders
+
+
class Settings(BaseSettings):
"""Application settings driven entirely by environment variables."""
@@ -59,17 +94,18 @@ class Settings(BaseSettings):
# F4.A: per-type activity dispatch. When True, MachinaWorkflow.run() schedules
# `node.{type}.v{version}` per plugin (with task_queue=cls.task_queue) instead
# of the single `execute_node_activity` legacy name. Workers register per-type
- # activities alongside the legacy one. Default off so existing deployments
- # behave identically; flip via TEMPORAL_PER_TYPE_DISPATCH=true.
+ # activities alongside the legacy one. Default on as shipped in
+ # .env.template; TEMPORAL_PER_TYPE_DISPATCH=false is the rollback.
temporal_per_type_dispatch: bool = Field(env="TEMPORAL_PER_TYPE_DISPATCH")
# F4.B: agent-as-child-workflow. When True, MachinaWorkflow.run() schedules
- # AgentWorkflow (child workflow) for the 14 migrating agent types
+ # AgentWorkflow (child workflow) for the 15 migrating agent types
# (aiAgent / chatAgent / 11 specialized agents / 2 team leads) instead of
# an activity. Tool calls inside the agent become per-type Temporal
# activities. `rlm_agent`, `claude_code_agent` continue to run as F4.A
# per-type activities (NOT migrated -- their external session state would
- # break across activity boundaries). Default off. Implies
- # temporal_per_type_dispatch=True.
+ # break across activity boundaries). Default on as shipped in
+ # .env.template; TEMPORAL_AGENT_WORKFLOW_ENABLED=false is the rollback.
+ # Implies temporal_per_type_dispatch=True.
temporal_agent_workflow_enabled: bool = Field(
env="TEMPORAL_AGENT_WORKFLOW_ENABLED",
)
diff --git a/server/main.py b/server/main.py
index 2697642e..08efde7f 100644
--- a/server/main.py
+++ b/server/main.py
@@ -46,7 +46,7 @@ from fastapi.middleware.cors import CORSMiddleware
# [debug] ...``) because the supervisor already prepends
# ``[HH:MM:SS.fff]`` to every aggregated line.
_startup_log("Importing settings + logging...")
-from core.config import Settings
+from core.config import Settings, dev_secret_offenders
from core.logging import configure_logging, get_logger, setup_websocket_logging, shutdown_websocket_logging
from core.tracing import init_tracing
@@ -78,6 +78,22 @@ async def lifespan(app: FastAPI):
# Startup
_startup_log("Lifespan startup begin")
+ # Non-fatal security posture check: warn loudly when the shipped dev
+ # placeholder secrets are still in use outside a local dev posture
+ # (auth enabled, or DEPLOYMENT_MODE != local). Never raises — the
+ # operator gets a prominent banner instead of a bricked server.
+ offenders = dev_secret_offenders(settings)
+ if offenders:
+ logger.error(
+ "SECURITY WARNING: dev placeholder secrets detected in a non-dev posture.\n"
+ "The following env vars still carry the publicly known .env.template values:\n"
+ " %s\n"
+ "Generate real secrets, e.g.:\n"
+ " python -c \"import secrets; print(secrets.token_hex(24))\"\n"
+ "and set them in .env (or the process environment), then restart.",
+ ", ".join(offenders),
+ )
+
# Wave 10.C: discover node plugins so their register_node() calls
# populate the four registries before any router serves NodeSpec.
# Side-effect import; the package __init__ walks its submodules.
diff --git a/server/services/events/webhook.py b/server/services/events/webhook.py
index 5c795e03..c15ce3d4 100644
--- a/server/services/events/webhook.py
+++ b/server/services/events/webhook.py
@@ -80,15 +80,22 @@ class WebhookSource(PushEventSource):
if self.verifier is not None:
secret = await self._resolve_secret()
if not secret:
+ # Fail closed: a declared verifier with no secret means we
+ # cannot authenticate the sender — reject instead of
+ # accepting an unverifiable event.
logger.warning(
- "[%s] no signing secret available; accepting unverified event",
+ "[%s] no signing secret available; rejecting event (503)",
self.type or self.path,
)
- else:
- try:
- self.verifier.verify(dict(request.headers), body, secret)
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
+ raise HTTPException(
+ status_code=503,
+ detail=f"webhook signing secret for {self.path!r} unavailable; retry later",
+ headers={"Retry-After": "5"},
+ )
+ try:
+ self.verifier.verify(dict(request.headers), body, secret)
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e))
try:
payload = json.loads(body.decode() or "{}")
diff --git a/server/tests/core_config/conftest.py b/server/tests/core_config/conftest.py
new file mode 100644
index 00000000..f309c8ec
--- /dev/null
+++ b/server/tests/core_config/conftest.py
@@ -0,0 +1,19 @@
+"""Fixtures for the core-config test suite.
+
+Isolated from tests/conftest.py (which stubs core.logging for LLM provider tests).
+This suite needs the REAL core.config module.
+"""
+
+import sys
+from pathlib import Path
+
+# Make sure server/ is importable even when pytest is invoked from repo root.
+SERVER_DIR = Path(__file__).resolve().parents[2]
+if str(SERVER_DIR) not in sys.path:
+ sys.path.insert(0, str(SERVER_DIR))
+
+# The parent conftest at server/tests/conftest.py unconditionally stubs `core`
+# and `core.logging` for the LLM provider tests. We need the REAL modules.
+# Wipe ANY core.* entries so subsequent imports load from disk.
+for mod_name in [name for name in list(sys.modules) if name == "core" or name.startswith("core.")]:
+ del sys.modules[mod_name]
diff --git a/server/tests/core_config/test_dev_secret_guard.py b/server/tests/core_config/test_dev_secret_guard.py
new file mode 100644
index 00000000..4c296f74
--- /dev/null
+++ b/server/tests/core_config/test_dev_secret_guard.py
@@ -0,0 +1,161 @@
+"""Tests for the dev-secret startup guard (core.config).
+
+Locks three contracts:
+ 1. Drift lock: the dev placeholder values shipped in ``.env.template``
+ are exactly the ones ``DEV_SECRET_LITERALS`` knows about.
+ 2. ``dev_secret_offenders`` posture logic: silent in dev posture
+ (auth disabled AND local), loud otherwise.
+ 3. Dev literals never hard-fail ``Settings`` construction — the guard
+ is a warning, not a gate.
+"""
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from core.config import DEV_SECRET_LITERALS, Settings, dev_secret_offenders
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+SECRET_ENV_VARS = ("SECRET_KEY", "JWT_SECRET_KEY", "API_KEY_ENCRYPTION_KEY")
+
+
+def _read_env_template() -> dict:
+ """Simple KEY=VALUE reader for .env.template (skips comments/blanks)."""
+ values: dict = {}
+ for raw in (REPO_ROOT / ".env.template").read_text(encoding="utf-8").splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ key, _, value = line.partition("=")
+ values[key.strip()] = value.strip()
+ return values
+
+
+_TEMPLATE = _read_env_template()
+# Dev literals sourced from the template (SSOT), never re-typed here.
+DEV_SECRET = _TEMPLATE["SECRET_KEY"]
+DEV_JWT = _TEMPLATE["JWT_SECRET_KEY"]
+DEV_ENC = _TEMPLATE["API_KEY_ENCRYPTION_KEY"]
+
+
[email protected](autouse=True)
+def _clean_env(monkeypatch):
+ """Ambient env must not leak into posture / secret detection."""
+ for var in (*SECRET_ENV_VARS, "VITE_AUTH_ENABLED", "DEPLOYMENT_MODE"):
+ monkeypatch.delenv(var, raising=False)
+
+
+def _ns(**overrides) -> SimpleNamespace:
+ """Duck-typed settings object with a dev-posture, dev-literal baseline."""
+ base = dict(
+ secret_key=DEV_SECRET,
+ jwt_secret_key=DEV_JWT,
+ api_key_encryption_key=DEV_ENC,
+ vite_auth_enabled="false",
+ deployment_mode="local",
+ )
+ base.update(overrides)
+ return SimpleNamespace(**base)
+
+
+class TestTemplateDriftLock:
+ def test_template_secret_values_are_all_known_dev_literals(self):
+ for var in SECRET_ENV_VARS:
+ assert _TEMPLATE[var] in DEV_SECRET_LITERALS, (
+ f".env.template {var} value is not in DEV_SECRET_LITERALS -- "
+ "update core/config.py (and cli/commands/build.py scaffold) together"
+ )
+
+ def test_template_secret_values_carry_dev_prefix(self):
+ # cli/commands/build.py scaffolds fresh secrets by recognising the
+ # "dev-" placeholder prefix; the template must keep shipping it.
+ for var in SECRET_ENV_VARS:
+ assert _TEMPLATE[var].startswith("dev-")
+
+
+class TestDevSecretOffenders:
+ def test_dev_posture_returns_empty(self):
+ assert dev_secret_offenders(_ns()) == []
+
+ def test_auth_enabled_flags_offenders(self):
+ offenders = dev_secret_offenders(_ns(vite_auth_enabled="true"))
+ assert offenders == ["SECRET_KEY", "JWT_SECRET_KEY", "API_KEY_ENCRYPTION_KEY"]
+
+ def test_auth_unset_flags_offenders(self):
+ # None means the middleware default (auth NOT explicitly disabled).
+ offenders = dev_secret_offenders(_ns(vite_auth_enabled=None))
+ assert offenders == ["SECRET_KEY", "JWT_SECRET_KEY", "API_KEY_ENCRYPTION_KEY"]
+
+ def test_single_dev_literal_flags_only_that_var(self):
+ import secrets
+
+ offenders = dev_secret_offenders(
+ _ns(
+ vite_auth_enabled="true",
+ secret_key=secrets.token_hex(24),
+ api_key_encryption_key=secrets.token_hex(24),
+ )
+ )
+ assert offenders == ["JWT_SECRET_KEY"]
+
+ def test_cloud_mode_flags_offenders_even_with_auth_disabled(self):
+ offenders = dev_secret_offenders(_ns(deployment_mode="cloud"))
+ assert offenders == ["SECRET_KEY", "JWT_SECRET_KEY", "API_KEY_ENCRYPTION_KEY"]
+
+ def test_real_secrets_never_flagged(self):
+ import secrets
+
+ offenders = dev_secret_offenders(
+ _ns(
+ vite_auth_enabled="true",
+ deployment_mode="cloud",
+ secret_key=secrets.token_hex(24),
+ jwt_secret_key=secrets.token_hex(24),
+ api_key_encryption_key=secrets.token_hex(24),
+ )
+ )
+ assert offenders == []
+
+
+class TestSettingsConstruction:
+ def _required_kwargs(self) -> dict:
+ """Minimal kwargs for every Field without a default (env-required)."""
+ return {
+ "host": "127.0.0.1",
+ "port": 3010,
+ "jwt_secret_key": DEV_JWT,
+ "secret_key": DEV_SECRET,
+ "cors_origins": ["http://localhost:3001"],
+ "workflow_db_filename": "workflow.db",
+ "temporal_enabled": False,
+ "temporal_server_address": "localhost:7233",
+ "temporal_namespace": "default",
+ "temporal_task_queue": "machina-tasks",
+ "temporal_per_type_dispatch": True,
+ "temporal_agent_workflow_enabled": True,
+ "temporal_graceful_shutdown_seconds": 30,
+ "temporal_frontend_grpc_port": 7233,
+ "temporal_ui_port": 8233,
+ "temporal_sqlite_path": "temporal.db",
+ "temporal_terminate_running_on_startup": True,
+ "api_key_encryption_key": DEV_ENC,
+ }
+
+ def test_settings_constructs_with_dev_literals(self):
+ """Dev literals must never hard-fail startup (guard is non-fatal)."""
+ settings = Settings(_env_file=None, **self._required_kwargs())
+ assert settings.secret_key == DEV_SECRET
+ assert settings.jwt_secret_key == DEV_JWT
+ assert settings.api_key_encryption_key == DEV_ENC
+
+ def test_real_settings_default_posture_flags_offenders(self):
+ # vite_auth_enabled defaults to None (auth not explicitly disabled)
+ # and deployment_mode defaults to "local" -> non-dev posture.
+ settings = Settings(_env_file=None, **self._required_kwargs())
+ assert dev_secret_offenders(settings) == [
+ "SECRET_KEY",
+ "JWT_SECRET_KEY",
+ "API_KEY_ENCRYPTION_KEY",
+ ]
diff --git a/server/tests/services/test_events.py b/server/tests/services/test_events.py
index 4b8d10b1..0fdb739d 100644
--- a/server/tests/services/test_events.py
+++ b/server/tests/services/test_events.py
@@ -334,8 +334,10 @@ class TestWebhookSourceHandle:
_run(src.handle(req))
assert exc.value.status_code == 400
- def test_missing_secret_accepts_unverified(self):
- """No secret captured yet -> log warning, accept event."""
+ def test_missing_secret_rejects_503(self):
+ """Credential resolution fails -> fail closed with 503 + Retry-After."""
+ from fastapi import HTTPException
+
src = self._build_source(secret_value=None)
body = b'{"event":"payload"}'
@@ -346,9 +348,46 @@ class TestWebhookSourceHandle:
return body
with patch("services.event_waiter.dispatch") as dispatch:
- ev = _run(src.handle(FakeReq()))
- assert ev.type == "fake.event"
- dispatch.assert_called_once()
+ with pytest.raises(HTTPException) as exc:
+ _run(src.handle(FakeReq()))
+ assert exc.value.status_code == 503
+ assert exc.value.headers.get("Retry-After") == "5"
+ dispatch.assert_not_called()
+
+ def test_secret_field_absent_rejects_503(self):
+ """Credential resolves but lacks the secret field -> fail closed with 503."""
+ from fastapi import HTTPException
+ from services.events import StripeVerifier, WebhookSource, WorkflowEvent
+
+ class _Cred:
+ @classmethod
+ async def resolve(cls):
+ return {"api_key": "sk_test"} # secret_field key missing
+
+ class FakeSource(WebhookSource):
+ type = "fake.hook"
+ path = "fake"
+ verifier = StripeVerifier
+ secret_field = "test_secret"
+ credential = _Cred
+
+ async def shape(self, request, body, payload):
+ return WorkflowEvent(source="fake://x", type="fake.event", data=payload)
+
+ src = FakeSource()
+ body = b'{"event":"payload"}'
+
+ class FakeReq:
+ headers = {}
+
+ async def body(self):
+ return body
+
+ with patch("services.event_waiter.dispatch") as dispatch:
+ with pytest.raises(HTTPException) as exc:
+ _run(src.handle(FakeReq()))
+ assert exc.value.status_code == 503
+ dispatch.assert_not_called()
# ============================================================================