diff --git a/server/deploy/poorbird.env.example b/server/deploy/poorbird.env.example index c011804..f172078 100644 --- a/server/deploy/poorbird.env.example +++ b/server/deploy/poorbird.env.example @@ -9,6 +9,9 @@ # --- database --------------------------------------------------------------- # Loopback TCP with scram-sha-256, deliberately not a Unix socket. +# Required: the app has no built-in default and refuses to start without it. +# The literal CHANGE_ME below is rejected at startup, so you cannot copy this +# file and forget to edit it. POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird # --- http ------------------------------------------------------------------- diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py index a60bf63..2b3b9b0 100644 --- a/server/src/poorbird/cli.py +++ b/server/src/poorbird/cli.py @@ -81,23 +81,27 @@ def cmd_check(_args: argparse.Namespace) -> int: print(f" python {sys.version.split()[0]}") # Never print the password. - url = settings.database_url - if "@" in url: - scheme, _, rest = url.partition("://") - url = f"{scheme}://***@{rest.rpartition('@')[2]}" - print(f" database_url {url}") + if not settings.database_url_is_set: + print(" database_url NOT SET (POORBIRD_DATABASE_URL)") + problems.append("POORBIRD_DATABASE_URL not set") + else: + url = settings.database_url + if "@" in url: + scheme, _, rest = url.partition("://") + url = f"{scheme}://***@{rest.rpartition('@')[2]}" + print(f" database_url {url}") - try: - from sqlalchemy import text + try: + from sqlalchemy import text - from .db import engine + from .db import engine - with engine.connect() as conn: - version = conn.execute(text("SHOW server_version")).scalar() - print(f" database reachable (PostgreSQL {version})") - except Exception as exc: # noqa: BLE001 - print(f" database UNREACHABLE: {type(exc).__name__}: {exc}") - problems.append("database unreachable") + with engine.connect() as conn: + version = conn.execute(text("SHOW server_version")).scalar() + print(f" database reachable (PostgreSQL {version})") + except Exception as exc: # noqa: BLE001 + print(f" database UNREACHABLE: {type(exc).__name__}: {exc}") + problems.append("database unreachable") try: from alembic import command diff --git a/server/src/poorbird/config.py b/server/src/poorbird/config.py index 11b40c4..b1921e4 100644 --- a/server/src/poorbird/config.py +++ b/server/src/poorbird/config.py @@ -12,9 +12,13 @@ from functools import lru_cache from pathlib import Path from typing import Literal -from pydantic import SecretStr +from pydantic import SecretStr, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict +# Values that mean "nobody filled this in". The .example files ship with these, +# and a copied-but-unedited example must not boot as if it were configured. +_PLACEHOLDERS = frozenset({"change_me", "changeme", "todo", "xxx", "secret"}) + class Settings(BaseSettings): model_config = SettingsConfigDict( @@ -27,7 +31,12 @@ class Settings(BaseSettings): # --- database --------------------------------------------------------- # Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket # is the one genuinely container-hostile choice (TODO.md Phase 1.2). - database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird" + # + # No default. A working URL in code means real credentials in code, and the + # module docstring above already promises none (REVIEW SEC-006). Absence is + # reported by ``poorbird check`` and raised with a readable message by db.py, + # rather than silently connecting to whatever happens to be on localhost. + database_url: str = "" db_pool_size: int = 5 db_echo: bool = False @@ -50,6 +59,10 @@ class Settings(BaseSettings): # Shared bootstrap secret presented by a device in X-Enroll-Secret. # See firmware/API.md: do NOT rotate this without shipping new firmware, # or you remove the last-resort recovery path for a mounted camera. + # + # Environment only, never a literal here (REVIEW SEC-001). Empty is allowed + # so the Phase 1 commands still run on a fresh clone; the device endpoints + # refuse to serve without it. enroll_secret: SecretStr = SecretStr("") # --- worker ----------------------------------------------------------- @@ -63,6 +76,31 @@ class Settings(BaseSettings): log_level: str = "INFO" log_format: Literal["text", "json"] = "text" + @field_validator("database_url") + @classmethod + def _reject_unedited_example(cls, v: str) -> str: + if any(p in v.lower() for p in _PLACEHOLDERS): + raise ValueError( + "POORBIRD_DATABASE_URL still contains a placeholder from the " + "example file. Put the real password in, or leave the variable " + "unset." + ) + return v + + @field_validator("enroll_secret") + @classmethod + def _reject_placeholder_secret(cls, v: SecretStr) -> SecretStr: + if v.get_secret_value().strip().lower() in _PLACEHOLDERS: + raise ValueError( + "POORBIRD_ENROLL_SECRET is a placeholder. Generate one with " + "'openssl rand -hex 32', or leave it unset until Phase 2." + ) + return v + + @property + def database_url_is_set(self) -> bool: + return bool(self.database_url.strip()) + @property def enroll_secret_is_set(self) -> bool: return bool(self.enroll_secret.get_secret_value()) diff --git a/server/src/poorbird/db.py b/server/src/poorbird/db.py index a479968..b1bb7a7 100644 --- a/server/src/poorbird/db.py +++ b/server/src/poorbird/db.py @@ -18,6 +18,16 @@ from .config import get_settings _settings = get_settings() +if not _settings.database_url_is_set: + # create_engine("") raises "Could not parse SQLAlchemy URL from string ''", + # which sends people looking in the wrong place. Say what to actually do. + raise RuntimeError( + "POORBIRD_DATABASE_URL is not set. Export it, or put it in server/.env:\n" + " POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:" + "@127.0.0.1:5432/poorbird\n" + "See server/deploy/poorbird.env.example. Run 'poorbird check' to verify." + ) + engine = create_engine( _settings.database_url, pool_size=_settings.db_pool_size, diff --git a/server/tests/test_config.py b/server/tests/test_config.py index 14192a2..113a0cc 100644 --- a/server/tests/test_config.py +++ b/server/tests/test_config.py @@ -1,5 +1,8 @@ from __future__ import annotations +import pytest +from pydantic import ValidationError + from poorbird.config import Settings @@ -18,8 +21,9 @@ def test_every_setting_reads_from_the_environment(monkeypatch): assert s.enroll_secret_is_set -def test_database_url_is_tcp_not_a_unix_socket(): +def test_database_url_is_tcp_not_a_unix_socket(monkeypatch): """A Unix socket is the one genuinely container-hostile choice.""" + monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@127.0.0.1:5432/poorbird") s = Settings(_env_file=None) assert "@" in s.database_url and ":" in s.database_url.rpartition("@")[2] assert "/var/run/postgresql" not in s.database_url @@ -28,3 +32,52 @@ def test_database_url_is_tcp_not_a_unix_socket(): def test_enroll_secret_is_not_leaked_by_repr(): s = Settings(_env_file=None, enroll_secret="hunter2") assert "hunter2" not in repr(s) + + +# --- SEC-006: no credentials baked into code -------------------------------- + + +def test_no_database_credentials_are_baked_in(monkeypatch): + """A default URL in code is a password in code, however harmless it looks.""" + monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False) + s = Settings(_env_file=None) + assert s.database_url == "" + assert not s.database_url_is_set + + +def test_unset_database_url_fails_with_a_readable_message(monkeypatch): + """Graceful, not a SQLAlchemy URL parse error from three frames down.""" + monkeypatch.delenv("POORBIRD_DATABASE_URL", raising=False) + monkeypatch.setattr("poorbird.config.get_settings", lambda: Settings(_env_file=None)) + + import importlib + import sys + + sys.modules.pop("poorbird.db", None) + with pytest.raises(RuntimeError, match="POORBIRD_DATABASE_URL is not set"): + importlib.import_module("poorbird.db") + sys.modules.pop("poorbird.db", None) + + +def test_placeholder_database_url_is_rejected(monkeypatch): + monkeypatch.setenv( + "POORBIRD_DATABASE_URL", "postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird" + ) + with pytest.raises(ValidationError, match="placeholder"): + Settings(_env_file=None) + + +# --- SEC-001: enroll secret comes from the environment only ----------------- + + +def test_enroll_secret_has_no_value_baked_in(monkeypatch): + monkeypatch.delenv("POORBIRD_ENROLL_SECRET", raising=False) + s = Settings(_env_file=None) + assert s.enroll_secret.get_secret_value() == "" + assert not s.enroll_secret_is_set + + +def test_placeholder_enroll_secret_is_rejected(monkeypatch): + monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "CHANGE_ME") + with pytest.raises(ValidationError, match="placeholder"): + Settings(_env_file=None)