Skip to content

Commit 7cee270

Browse files
committed
Phase 1: validated configuration, redacted logging, /health skeleton (plan v2.4)
1 parent 282cd11 commit 7cee270

11 files changed

Lines changed: 944 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ reports/
1515
__pycache__/
1616
*.pyc
1717
.ruff_cache/
18+
.pytest_cache/
1819

1920
# Raw corpora and models (frozen eval datasets\ ARE committed; raw corpora are not)
2021
corpora/

‎pyproject.toml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,10 @@ explicit = true
4040

4141
[tool.uv.sources]
4242
torch = [{ index = "pytorch-cpu" }]
43+
44+
[tool.pytest.ini_options]
45+
# Phase 1: reproducible local test runs - offline, deterministic, small fixtures.
46+
# Run from the project root with the project venv:
47+
# .venv\Scripts\python.exe -m pytest
48+
testpaths = ["tests"]
49+
pythonpath = ["src"]

‎src/rag_platform/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""RAG Platform package (plan v2.4, Phase 1: config, redacted logging, /health skeleton)."""
2+
3+
__version__ = "0.0.1"

‎src/rag_platform/config.py‎

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
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+
}

‎src/rag_platform/logging_setup.py‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
"""Redacted logging (plan v2.4 Phase 1; invariants I6, and I10/I15 for records).
2+
3+
Every log line emitted through a handler produced by :func:`make_redacting_handler`
4+
(or wired by :func:`configure_logging`) passes through :class:`RedactingFilter`,
5+
which deterministically scrubs secret-shaped content from the formatted message
6+
before it reaches any sink.
7+
8+
Patterns covered (documented, bounded, stdlib-only - no external dependencies):
9+
10+
- ``Authorization: ...`` header-style values (including ``Bearer <token>``).
11+
- ``name=value`` / ``"name": "value"`` shapes for api_key, token, secret,
12+
password, and relatives (case-insensitive; quote-tolerant).
13+
- Provider-shaped key literals (``sk-...``, ``gsk_...``, ``rk-...``, ``AKIA...``,
14+
``AIza...``) appearing anywhere in a message.
15+
16+
Known limitations (honest, Phase 1 scope):
17+
18+
- Exception tracebacks (``exc_info`` / ``exc_text``) are NOT redacted yet - they
19+
are rendered later by the formatter, outside this filter. The application must
20+
never log secrets in the first place (I6); this filter is defense in depth, not
21+
a license to log credentials.
22+
- Only messages routed through handlers carrying this filter are scrubbed; root
23+
handlers configured elsewhere are outside this module's control.
24+
25+
Redaction is idempotent: re-processing an already-redacted message changes
26+
nothing (``[REDACTED]`` never matches the patterns).
27+
"""
28+
29+
from __future__ import annotations
30+
31+
import logging
32+
import re
33+
34+
REDACTED = "[REDACTED]"
35+
36+
# Order matters: specific "name" shapes first, then bare key/value shapes, then
37+
# free-floating provider-shaped literals. Every pattern is a plain regex over the
38+
# already-formatted message string.
39+
_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
40+
# Authorization header: `Authorization: Bearer abc` / `authorization=abc`.
41+
(
42+
re.compile(r"(?i)\b(authorization\s*[:=]\s*)(\S+(?:[ \t]+\S+)?)"),
43+
r"\1" + REDACTED,
44+
),
45+
# Standalone bearer tokens: `Bearer abc123...`.
46+
(
47+
re.compile(r"(?i)\b(bearer[ \t]+)([A-Za-z0-9._~+/=-]{8,})"),
48+
r"\1" + REDACTED,
49+
),
50+
# name = value / "name": "value" shapes. Longer names first; an optional
51+
# closing quote after the name tolerates JSON-style logging.
52+
(
53+
re.compile(
54+
r"(?i)\b((?:access[_-]?token|refresh[_-]?token|api[_-]?key|apikey|"
55+
r"client[_-]?secret|password|passwd|token|secret)[\"']?\s*[:=]\s*)"
56+
r"(\"[^\"]*\"|'[^']*'|\S+)"
57+
),
58+
r"\1" + REDACTED,
59+
),
60+
# Provider-shaped key literals anywhere in a message.
61+
(re.compile(r"\b(?:sk|gsk|rk|AKIA)[-_][A-Za-z0-9]{6,}\b"), REDACTED),
62+
(re.compile(r"\bAIza[0-9A-Za-z_-]{8,}\b"), REDACTED),
63+
)
64+
65+
66+
def redact(text: str) -> str:
67+
"""Return ``text`` with all secret-shaped content replaced by ``[REDACTED]``.
68+
69+
Deterministic and idempotent; never raises on arbitrary input.
70+
"""
71+
for pattern, replacement in _PATTERNS:
72+
text = pattern.sub(replacement, text)
73+
return text
74+
75+
76+
class RedactingFilter(logging.Filter):
77+
"""Scrubs the formatted message of a log record before it is emitted.
78+
79+
Applied at handler level so every record routed through that handler is
80+
processed exactly once, after lazy ``%``-style args have been interpolated.
81+
"""
82+
83+
def filter(self, record: logging.LogRecord) -> bool: # noqa: A003
84+
try:
85+
message = record.getMessage()
86+
except Exception:
87+
# Never let redaction break logging itself; drop to a safe marker.
88+
record.msg = "<unformattable log record dropped by RedactingFilter>"
89+
record.args = ()
90+
return True
91+
scrubbed = redact(message)
92+
if scrubbed != message:
93+
record.msg = scrubbed
94+
record.args = ()
95+
return True
96+
97+
98+
def make_redacting_handler(stream: object | None = None) -> logging.Handler:
99+
"""Build a stream handler with formatting + redaction attached (I6)."""
100+
if stream is None:
101+
handler: logging.Handler = logging.StreamHandler()
102+
else:
103+
handler = logging.StreamHandler(stream) # type: ignore[arg-type]
104+
handler.setFormatter(
105+
logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")
106+
)
107+
handler.addFilter(RedactingFilter())
108+
handler._rag_platform_handler = True # marker for idempotency checks
109+
return handler
110+
111+
112+
def configure_logging(
113+
level: str = "INFO", stream: object | None = None
114+
) -> logging.Logger:
115+
"""Configure the ``rag_platform`` logger exactly once and return it.
116+
117+
Idempotent: repeated calls (app factory re-entry, tests) do not stack
118+
handlers. Child loggers under ``rag_platform`` propagate to this logger and
119+
therefore inherit redaction for their records.
120+
"""
121+
logger = logging.getLogger("rag_platform")
122+
logger.setLevel(level)
123+
logger.propagate = False
124+
already_wired = any(
125+
getattr(handler, "_rag_platform_handler", False) for handler in logger.handlers
126+
)
127+
if not already_wired:
128+
logger.addHandler(make_redacting_handler(stream))
129+
return logger

0 commit comments

Comments
 (0)