|
| 1 | +"""Deterministic configuration validation (plan v2.4 Phase 1). |
| 2 | +
|
| 3 | +Construction of :class:`Settings` performs all validation: invalid settings raise |
| 4 | +``pydantic.ValidationError`` before any application object exists, which is the |
| 5 | +Phase 1 "startup-rejection" behaviour (plan v2.4 section 15, Phase 1 row). |
| 6 | +
|
| 7 | +Security-relevant rules implemented here: |
| 8 | +
|
| 9 | +- I3 / Z4: ``EGRESS_MODE`` defaults to ``off``. With egress off the allowlist must |
| 10 | + be empty; a half-configured state is rejected loudly instead of being ignored. |
| 11 | +- I4: enabling egress (``EGRESS_MODE=allowlist``) requires at least one exact |
| 12 | + ``https://`` origin: exact host, no wildcards, no path/query/fragment, no |
| 13 | + embedded credentials. Anything weaker fails validation. |
| 14 | +- I3: the Ollama base URL must be a loopback origin (localhost / 127.0.0.1 / ::1); |
| 15 | + configuration can never point the app at a non-local host. An arbitrary loopback |
| 16 | + *port* is deliberately allowed so a misconfigured port can be exercised at |
| 17 | + runtime (plan BG-1b unavailability proof) - a wrong port is a runtime |
| 18 | + ``retrieval-only`` condition, not a startup error. |
| 19 | +- Z9: project data paths must resolve inside the project root (D:\\rag-platform); |
| 20 | + a path outside the project (e.g. on C:) is rejected at startup. Relative paths |
| 21 | + resolve against the project root, never the current working directory. |
| 22 | +- I6: this module contains no credential fields at all. Provider settings are a |
| 23 | + future, separately gated concern (plan v2.4 D16) and are deliberately absent, |
| 24 | + so no configuration value here can be a secret. |
| 25 | +- Plan defaults preserved: local generation disabled (D3 default / v2.4 section |
| 26 | + 5.3), ``ADAPTIVE_RETRIEVAL=off`` (v2.4 section 4.3 kill switch). |
| 27 | +
|
| 28 | +Construction is pure validation: no network access, no service calls, no file |
| 29 | +writes (paths are validated, not created). |
| 30 | +""" |
| 31 | + |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +from pathlib import Path |
| 35 | +from typing import Literal |
| 36 | +from urllib.parse import urlparse |
| 37 | + |
| 38 | +from pydantic import Field, ValidationInfo, field_validator, model_validator |
| 39 | +from pydantic_settings import BaseSettings, SettingsConfigDict |
| 40 | + |
| 41 | +#: Project root derived from this file's location: <root>/src/rag_platform/config.py. |
| 42 | +PROJECT_ROOT = Path(__file__).resolve().parents[2] |
| 43 | + |
| 44 | +_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"}) |
| 45 | + |
| 46 | + |
| 47 | +def _validate_port(port: int, what: str) -> int: |
| 48 | + if not 1 <= port <= 65535: |
| 49 | + raise ValueError(f"{what} must be in 1..65535, got {port}") |
| 50 | + return port |
| 51 | + |
| 52 | + |
| 53 | +def _validate_allowlist_entry(entry: str) -> None: |
| 54 | + """One allowlist entry must be an exact ``https://host[:port]`` origin (I4). |
| 55 | +
|
| 56 | + The entry is validated verbatim - no normalization or stripping is applied - |
| 57 | + so the value settings retain is exactly the value that was checked |
| 58 | + (fail-closed; Phase 1 audit correction A, 2026-10-19). |
| 59 | + """ |
| 60 | + if entry != entry.strip(): |
| 61 | + raise ValueError( |
| 62 | + f"allowlist entry {entry!r} must not have leading or trailing " |
| 63 | + "whitespace; entries are stored verbatim and validated exactly (I4)" |
| 64 | + ) |
| 65 | + if not entry: |
| 66 | + raise ValueError("egress allowlist entries must be non-empty exact origins") |
| 67 | + parsed = urlparse(entry) |
| 68 | + if parsed.scheme != "https": |
| 69 | + raise ValueError(f"allowlist entry {entry!r} must use https (I4: TLS required)") |
| 70 | + host = parsed.hostname |
| 71 | + if not host: |
| 72 | + raise ValueError(f"allowlist entry {entry!r} has no host") |
| 73 | + if "*" in host: |
| 74 | + raise ValueError( |
| 75 | + f"allowlist entry {entry!r} must be an exact host; wildcards are never accepted (I4)" |
| 76 | + ) |
| 77 | + if any(ch.isspace() or ch == "\\" for ch in host): |
| 78 | + raise ValueError( |
| 79 | + f"allowlist entry {entry!r} host must contain neither whitespace nor " |
| 80 | + "backslashes (exact RFC 3986 origin, I4)" |
| 81 | + ) |
| 82 | + if parsed.username or parsed.password: |
| 83 | + raise ValueError(f"allowlist entry {entry!r} must not embed credentials (I6)") |
| 84 | + if parsed.path.rstrip("/") != "" or parsed.query or parsed.fragment: |
| 85 | + raise ValueError( |
| 86 | + f"allowlist entry {entry!r} must be scheme://host[:port] only (exact-host allowlist, I4)" |
| 87 | + ) |
| 88 | + if parsed.port is not None: |
| 89 | + _validate_port(parsed.port, f"allowlist entry {entry!r} port") |
| 90 | + |
| 91 | + |
| 92 | +class Settings(BaseSettings): |
| 93 | + """Application settings with fail-loud validation. |
| 94 | +
|
| 95 | + Environment mapping (case-insensitive, pydantic-settings): ``EGRESS_MODE``, |
| 96 | + ``EGRESS_ALLOWLIST`` (JSON list), ``OLLAMA_BASE_URL``, ``PORT``, |
| 97 | + ``LOCAL_GENERATION_ENABLED``, ``ADAPTIVE_RETRIEVAL``, ``LOG_LEVEL``, |
| 98 | + ``DATA_DIR``, ``REPORTS_DIR``. A project-root ``.env`` file is read when |
| 99 | + present (``.env`` is gitignored; ``.env.example`` documents the keys). |
| 100 | + """ |
| 101 | + |
| 102 | + model_config = SettingsConfigDict( |
| 103 | + env_file=str(PROJECT_ROOT / ".env"), |
| 104 | + env_file_encoding="utf-8", |
| 105 | + extra="forbid", |
| 106 | + ) |
| 107 | + |
| 108 | + # Egress guard (I3/I4, Z4): off is the default and the only shipped state. |
| 109 | + egress_mode: Literal["off", "allowlist"] = "off" |
| 110 | + egress_allowlist: list[str] = Field(default_factory=list) |
| 111 | + |
| 112 | + # Local endpoint only (I3); loopback enforced by validator below. |
| 113 | + ollama_base_url: str = "http://localhost:11434" |
| 114 | + |
| 115 | + # API port for the future server (Phase 7); validated range here. |
| 116 | + port: int = 8000 |
| 117 | + |
| 118 | + # Plan defaults: generation disabled (D3 / v2.4 5.3), adaptive budget off (4.3). |
| 119 | + local_generation_enabled: bool = False |
| 120 | + adaptive_retrieval: Literal["on", "off"] = "off" |
| 121 | + |
| 122 | + log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO" |
| 123 | + |
| 124 | + # Project-local artifact paths (Z9): must stay under the project root on D:. |
| 125 | + data_dir: Path = PROJECT_ROOT / "data" |
| 126 | + reports_dir: Path = PROJECT_ROOT / "reports" |
| 127 | + |
| 128 | + @field_validator("ollama_base_url") |
| 129 | + @classmethod |
| 130 | + def _ollama_must_be_loopback_origin(cls, value: str) -> str: |
| 131 | + parsed = urlparse(value) |
| 132 | + if parsed.scheme not in ("http", "https"): |
| 133 | + raise ValueError("ollama_base_url must use http or https") |
| 134 | + host = parsed.hostname |
| 135 | + if host not in _LOOPBACK_HOSTS: |
| 136 | + raise ValueError( |
| 137 | + "ollama_base_url must be loopback (localhost, 127.0.0.1 or ::1); " |
| 138 | + f"got host {host!r} (I3: only the local socket is ever contacted)" |
| 139 | + ) |
| 140 | + if parsed.username or parsed.password: |
| 141 | + raise ValueError("ollama_base_url must not embed credentials (I6)") |
| 142 | + if parsed.path not in ("", "/") or parsed.query or parsed.fragment: |
| 143 | + raise ValueError( |
| 144 | + "ollama_base_url must be a plain origin (no path, query or fragment)" |
| 145 | + ) |
| 146 | + if parsed.port is not None: |
| 147 | + _validate_port(parsed.port, "ollama_base_url port") |
| 148 | + return value |
| 149 | + |
| 150 | + @field_validator("port") |
| 151 | + @classmethod |
| 152 | + def _port_range(cls, value: int) -> int: |
| 153 | + return _validate_port(value, "port") |
| 154 | + |
| 155 | + @field_validator("data_dir", "reports_dir") |
| 156 | + @classmethod |
| 157 | + def _paths_must_stay_on_project(cls, value: Path, info: ValidationInfo) -> Path: |
| 158 | + path = Path(value).expanduser() |
| 159 | + if not path.is_absolute(): |
| 160 | + path = PROJECT_ROOT / path |
| 161 | + resolved = path.resolve() |
| 162 | + root = PROJECT_ROOT.resolve() |
| 163 | + if resolved == root or not resolved.is_relative_to(root): |
| 164 | + raise ValueError( |
| 165 | + f"{info.field_name} must resolve under the project root {root} " |
| 166 | + "(Z9: all project artifacts stay on D:)" |
| 167 | + ) |
| 168 | + return resolved |
| 169 | + |
| 170 | + @model_validator(mode="after") |
| 171 | + def _egress_configuration_must_be_coherent(self) -> "Settings": |
| 172 | + if self.egress_mode == "off": |
| 173 | + if self.egress_allowlist: |
| 174 | + raise ValueError( |
| 175 | + "egress_mode='off' requires an empty egress_allowlist (I3/Z4): " |
| 176 | + "allowlist entries present while egress is disabled - fix the " |
| 177 | + "configuration instead of leaving it ambiguous" |
| 178 | + ) |
| 179 | + else: # egress_mode == "allowlist" |
| 180 | + if not self.egress_allowlist: |
| 181 | + raise ValueError( |
| 182 | + "egress_mode='allowlist' requires at least one exact https " |
| 183 | + "allowlist entry (I4); egress stays fully off until enablement " |
| 184 | + "is completely configured and owner-approved" |
| 185 | + ) |
| 186 | + for entry in self.egress_allowlist: |
| 187 | + _validate_allowlist_entry(entry) |
| 188 | + return self |
| 189 | + |
| 190 | + |
| 191 | +def settings_summary(settings: Settings) -> dict[str, object]: |
| 192 | + """Sanitized configuration summary for /health (I6). |
| 193 | +
|
| 194 | + Booleans and mode labels only - never URLs, paths, or any value that could |
| 195 | + echo configuration internals. ``configured`` reports presence of state, not |
| 196 | + its content. |
| 197 | + """ |
| 198 | + return { |
| 199 | + "egress_mode": settings.egress_mode, |
| 200 | + "egress_allowlist_configured": bool(settings.egress_allowlist), |
| 201 | + "local_generation_enabled": settings.local_generation_enabled, |
| 202 | + "paths_on_project": ( |
| 203 | + settings.data_dir.is_relative_to(PROJECT_ROOT) |
| 204 | + and settings.reports_dir.is_relative_to(PROJECT_ROOT) |
| 205 | + ), |
| 206 | + } |
0 commit comments