ui-foundation-backend 4.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. foundation_backend/__init__.py +13 -0
  2. foundation_backend/config.py +118 -0
  3. foundation_backend/db.py +17 -0
  4. foundation_backend/deploy_checks.py +105 -0
  5. foundation_backend/error_reporting.py +230 -0
  6. foundation_backend/errors.py +46 -0
  7. foundation_backend/login_limits.py +120 -0
  8. foundation_backend/migrations/0002_auth.py +61 -0
  9. foundation_backend/migrations/0010_login_limits_totp.py +135 -0
  10. foundation_backend/migrations/0011_oauth.py +150 -0
  11. foundation_backend/migrations/README.md +16 -0
  12. foundation_backend/models.py +131 -0
  13. foundation_backend/openapi_responses.py +38 -0
  14. foundation_backend/py.typed +0 -0
  15. foundation_backend/rate_window.py +32 -0
  16. foundation_backend/routers/__init__.py +0 -0
  17. foundation_backend/routers/auth.py +317 -0
  18. foundation_backend/routers/client_errors.py +80 -0
  19. foundation_backend/routers/environment.py +20 -0
  20. foundation_backend/routers/oauth.py +527 -0
  21. foundation_backend/schemas.py +106 -0
  22. foundation_backend/scripts/__init__.py +2 -0
  23. foundation_backend/scripts/disable_totp.py +49 -0
  24. foundation_backend/scripts/enable_totp.py +81 -0
  25. foundation_backend/scripts/set_password.py +67 -0
  26. foundation_backend/security.py +44 -0
  27. foundation_backend/spa.py +34 -0
  28. foundation_backend/testing/__init__.py +1 -0
  29. foundation_backend/testing/signed_in.py +32 -0
  30. foundation_backend/totp.py +90 -0
  31. ui_foundation_backend-4.25.0.dist-info/METADATA +121 -0
  32. ui_foundation_backend-4.25.0.dist-info/RECORD +34 -0
  33. ui_foundation_backend-4.25.0.dist-info/WHEEL +5 -0
  34. ui_foundation_backend-4.25.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ """The auth and security layer every app built on ui-foundation shares
2
+ (the PyPI package `ui-foundation-backend`). README.md says what is in it
3
+ and how an app uses it.
4
+ """
5
+
6
+ # The release version, the same as @tristan2828/ui-foundation's. The release
7
+ # workflow writes it into pyproject.toml; this reads it back.
8
+ from importlib.metadata import PackageNotFoundError, version
9
+
10
+ try:
11
+ __version__ = version("ui-foundation-backend")
12
+ except PackageNotFoundError: # imported from a source tree, not installed
13
+ __version__ = "0.0.0"
@@ -0,0 +1,118 @@
1
+ """The settings the foundation's backend reads, each from the environment
2
+ once, at import. An app's own `config.py` star-imports this module and
3
+ adds its own settings after it; it calls `load_dotenv()` first, from its
4
+ own file, so its `backend/.env` is read wherever the process starts.
5
+
6
+ Here `.env` is looked for from the working directory up (`backend/` when
7
+ the app runs, its scripts run, or `python -m foundation_backend.scripts.*`
8
+ runs), since this file is installed in site-packages, not in the app.
9
+ Values already in the environment win over the file's.
10
+ """
11
+
12
+ import os
13
+ import ssl
14
+
15
+ from dotenv import find_dotenv, load_dotenv
16
+
17
+ load_dotenv(find_dotenv(usecwd=True))
18
+
19
+ DATABASE_URL: str = os.environ.get(
20
+ "DATABASE_URL",
21
+ "postgresql+asyncpg://ui_foundation:ui_foundation@localhost:5432/ui_foundation",
22
+ )
23
+
24
+ # Cloud Postgres support (docs/cloud-postgres.md).
25
+ # asyncpg's own SSL flag — postgresql+asyncpg:// doesn't parse libpq's
26
+ # sslmode= query param, so this can't be folded into DATABASE_URL itself.
27
+ DATABASE_SSL: bool = os.environ.get("DATABASE_SSL", "false").lower() == "true"
28
+
29
+ # Some managed providers (confirmed on Supabase) serve their Postgres TLS
30
+ # cert from a private CA that isn't in the OS trust store, unlike their own
31
+ # HTTPS endpoints — connecting with just DATABASE_SSL=true then fails
32
+ # certificate verification. Point this at a local PEM file (that CA's root
33
+ # cert) to verify against it explicitly instead of the system trust store.
34
+ DATABASE_SSL_CA_FILE: str | None = os.environ.get("DATABASE_SSL_CA_FILE") or None
35
+
36
+
37
+ def database_connect_args() -> dict[str, object]:
38
+ """asyncpg connect_args for DATABASE_URL — shared by db.py and an
39
+ app's migrations/env.py, which each construct their own engine."""
40
+ if not DATABASE_SSL:
41
+ return {}
42
+ if DATABASE_SSL_CA_FILE:
43
+ return {"ssl": ssl.create_default_context(cafile=DATABASE_SSL_CA_FILE)}
44
+ return {"ssl": True}
45
+
46
+ # "production" turns on deploy_checks.py at startup: the app refuses to
47
+ # start with an insecure cookie or a still-default seeded account. Anything
48
+ # else (the default) is development, with no startup checks.
49
+ APP_ENV: str = os.environ.get("APP_ENV", "development")
50
+
51
+ # Which data this backend serves when it isn't production's: "dev" for a
52
+ # dev branch of the hosted database, "local" for the docker-compose one.
53
+ # Served unauthenticated at GET /api/environment, and the app names it in
54
+ # a banner on every screen (DataEnvironmentBanner: "Dev data: changes here
55
+ # don't reach production"). Unset, the default, means production data and
56
+ # no banner; APP_ENV=production refuses to start with it set.
57
+ DATA_LABEL: str | None = os.environ.get("DATA_LABEL", "").strip() or None
58
+
59
+ # Session cookie. Local dev is plain
60
+ # HTTP, so the Secure flag defaults off; a real deployment sets it.
61
+ COOKIE_SECURE: bool = os.environ.get("COOKIE_SECURE", "false").lower() == "true"
62
+ SESSION_TTL_DAYS: int = int(os.environ.get("SESSION_TTL_DAYS", "7"))
63
+
64
+ # Failed sign-in limits (login_limits.py, docs/deploy.md). Over either,
65
+ # POST /auth/login answers 429 before the password is checked. Per IP needs
66
+ # uvicorn's --proxy-headers behind a proxy it trusts, or every request
67
+ # appears to come from the proxy and this becomes one global limit.
68
+ LOGIN_MAX_FAILURES_PER_IP: int = int(os.environ.get("LOGIN_MAX_FAILURES_PER_IP", "10"))
69
+ LOGIN_IP_WINDOW_SECONDS: int = int(os.environ.get("LOGIN_IP_WINDOW_SECONDS", str(15 * 60)))
70
+ LOGIN_MAX_FAILURES_PER_ACCOUNT: int = int(os.environ.get("LOGIN_MAX_FAILURES_PER_ACCOUNT", "20"))
71
+ LOGIN_ACCOUNT_WINDOW_SECONDS: int = int(os.environ.get("LOGIN_ACCOUNT_WINDOW_SECONDS", str(60 * 60)))
72
+ # A header a CDN or tunnel always overwrites with the client's address
73
+ # (CF-Connecting-IP, True-Client-IP, Fly-Client-IP), read for the per-IP key
74
+ # instead of X-Forwarded-For, which such proxies append to. Unset: ignored.
75
+ # Safe only if every request reaches the app through that proxy.
76
+ CLIENT_IP_HEADER: str | None = os.environ.get("CLIENT_IP_HEADER", "").strip() or None
77
+
78
+ # The TOTP second step (totp.py): how long a sign-in waits for its code
79
+ # after the password, and how many wrong codes it gets before it ends.
80
+ PENDING_LOGIN_TTL_SECONDS: int = int(os.environ.get("PENDING_LOGIN_TTL_SECONDS", str(5 * 60)))
81
+ PENDING_LOGIN_MAX_TRIES: int = int(os.environ.get("PENDING_LOGIN_MAX_TRIES", "5"))
82
+ # The name an authenticator app lists the account under.
83
+ TOTP_ISSUER: str = os.environ.get("TOTP_ISSUER", "UI Foundation")
84
+
85
+ # Error reporting (error_reporting.py, docs/deploy.md "Error reporting").
86
+ # A Sentry-compatible DSN (Sentry, or a self-hosted GlitchTip):
87
+ # https://<key>@<host>/<project id>. Unset, the default, errors are only logged.
88
+ ERROR_REPORTING_DSN: str | None = os.environ.get("ERROR_REPORTING_DSN", "").strip() or None
89
+ # The build a report names: the commit, set by the deploy (unset is fine).
90
+ RELEASE: str | None = os.environ.get("RELEASE", "").strip() or None
91
+ # How many reports one session may send per minute from the browser, after
92
+ # duplicates (the same error) are dropped to one a minute.
93
+ CLIENT_ERRORS_PER_MINUTE: int = int(os.environ.get("CLIENT_ERRORS_PER_MINUTE", "10"))
94
+
95
+ # AI chats reading and writing the app's records through MCP (an app's routers/mcp.py,
96
+ # routers/oauth.py, docs/deploy.md "AI chats (MCP)"). Off by default: with
97
+ # it off, /mcp, /oauth/* and the /.well-known/oauth-* documents answer 404.
98
+ MCP_ENABLED: bool = os.environ.get("MCP_ENABLED", "false").lower() == "true"
99
+ # The app's public https origin, e.g. https://app.example.com: the OAuth
100
+ # issuer, and the base of every address the sign-in documents hand out.
101
+ # Required when MCP_ENABLED and APP_ENV=production (a proxy hides the real
102
+ # one from the app); in development the request's own is used.
103
+ MCP_PUBLIC_URL: str | None = os.environ.get("MCP_PUBLIC_URL", "").strip().rstrip("/") or None
104
+ MCP_ACCESS_TOKEN_TTL_SECONDS: int = int(os.environ.get("MCP_ACCESS_TOKEN_TTL_SECONDS", str(60 * 60)))
105
+ MCP_REFRESH_TOKEN_TTL_DAYS: int = int(os.environ.get("MCP_REFRESH_TOKEN_TTL_DAYS", "30"))
106
+ # How many AI chats may be registered at once, and how many requests one
107
+ # connection may make a minute (counted in each worker's memory).
108
+ MCP_MAX_CLIENTS: int = int(os.environ.get("MCP_MAX_CLIENTS", "50"))
109
+ MCP_REQUESTS_PER_MINUTE: int = int(os.environ.get("MCP_REQUESTS_PER_MINUTE", "120"))
110
+
111
+ # Seeded dev user (migration 0002). Not a
112
+ # production credential; a real deployment sets its own before going live.
113
+ # The defaults are published in the README, which is why production refuses
114
+ # to start while any account still accepts DEFAULT_SEED_PASSWORD.
115
+ DEFAULT_SEED_EMAIL = "dev@example.com"
116
+ DEFAULT_SEED_PASSWORD = "dev-password-123"
117
+ SEED_USER_EMAIL: str = os.environ.get("SEED_USER_EMAIL", DEFAULT_SEED_EMAIL)
118
+ SEED_USER_PASSWORD: str = os.environ.get("SEED_USER_PASSWORD", DEFAULT_SEED_PASSWORD)
@@ -0,0 +1,17 @@
1
+ """Async engine + session dependency. No repository layer on purpose —
2
+ routers call the session directly.
3
+ """
4
+
5
+ from collections.abc import AsyncGenerator
6
+
7
+ from sqlmodel.ext.asyncio.session import AsyncSession
8
+ from sqlalchemy.ext.asyncio import create_async_engine
9
+
10
+ from foundation_backend.config import DATABASE_URL, database_connect_args
11
+
12
+ engine = create_async_engine(DATABASE_URL, echo=False, connect_args=database_connect_args())
13
+
14
+
15
+ async def get_session() -> AsyncGenerator[AsyncSession, None]:
16
+ async with AsyncSession(engine) as session:
17
+ yield session
@@ -0,0 +1,105 @@
1
+ """Startup safety checks for APP_ENV=production (see docs/deploy.md).
2
+
3
+ Development needs none of this and runs no startup query at all. A real
4
+ deployment is refused outright rather than warned about: a warning in a log
5
+ nobody reads is how a published default password ends up on the internet.
6
+ """
7
+
8
+ import json
9
+ from pathlib import Path
10
+
11
+ from fastapi.concurrency import run_in_threadpool
12
+ from sqlmodel import select
13
+ from sqlmodel.ext.asyncio.session import AsyncSession
14
+
15
+ from foundation_backend.config import DEFAULT_SEED_EMAIL, DEFAULT_SEED_PASSWORD, SEED_USER_EMAIL
16
+ from foundation_backend.models import User
17
+ from foundation_backend.security import verify_password
18
+
19
+
20
+ async def production_problems(
21
+ session: AsyncSession,
22
+ *,
23
+ cookie_secure: bool,
24
+ data_label: str | None = None,
25
+ mcp_enabled: bool = False,
26
+ mcp_public_url: str | None = None,
27
+ static_dir: str | None = None,
28
+ ) -> list[str]:
29
+ """Everything that makes this deployment unsafe to serve; empty if none.
30
+
31
+ `static_dir` is the built frontend (STATIC_DIR); None skips its check.
32
+ """
33
+ problems: list[str] = []
34
+
35
+ if static_dir is not None:
36
+ problem = frontend_build_problem(Path(static_dir))
37
+ if problem is not None:
38
+ problems.append(problem)
39
+
40
+ # A label says the data isn't production's, and the app shows it on
41
+ # every screen. Production serves production data, so a label here is
42
+ # a dev backend/.env deployed by mistake.
43
+ if data_label is not None:
44
+ problems.append(
45
+ f"DATA_LABEL is set ({data_label!r}); production data has no label, and every "
46
+ "screen would say it isn't production's. Unset it."
47
+ )
48
+
49
+ # Chats are sent to the issuer's address to sign in, and the OAuth
50
+ # documents name it; behind a proxy the app can't know it, and the
51
+ # protocol requires https.
52
+ if mcp_enabled and (mcp_public_url is None or not mcp_public_url.startswith("https://")):
53
+ problems.append(
54
+ "MCP_ENABLED is true but MCP_PUBLIC_URL is not an https:// address; AI chats can't "
55
+ "sign in without the app's public address (e.g. https://app.example.com)."
56
+ )
57
+
58
+ if not cookie_secure:
59
+ problems.append(
60
+ "COOKIE_SECURE is not true; the session cookie would be sent over plain HTTP."
61
+ )
62
+
63
+ # Migration 0002 seeds whatever SEED_USER_* held when it ran, so check
64
+ # the stored hash, not the environment: both the configured seed email
65
+ # and the published default one, in case the env changed after seeding.
66
+ for email in sorted({DEFAULT_SEED_EMAIL, SEED_USER_EMAIL}):
67
+ result = await session.exec(select(User).where(User.email == email))
68
+ user = result.first()
69
+ if user is not None and await run_in_threadpool(
70
+ verify_password, DEFAULT_SEED_PASSWORD, user.password_hash
71
+ ):
72
+ problems.append(
73
+ f"User {email} still accepts the published default password. Change it "
74
+ "with `python -m foundation_backend.scripts.set_password` before serving this deployment."
75
+ )
76
+
77
+ return problems
78
+
79
+
80
+ BUILD_COMMAND = "Build it with `npm run build:real`, never a plain `npm run build`"
81
+
82
+
83
+ def frontend_build_problem(static_dir: Path) -> str | None:
84
+ """Why the frontend at `static_dir` mustn't be served, or None.
85
+
86
+ The build writes build-info.json (the foundation's Vite plugin) saying
87
+ which API the bundle calls. A mock bundle runs MSW in the browser: the
88
+ app would show fake data to real users and save nothing, with nothing
89
+ saying so. A missing file means a build that predates the plugin, or
90
+ no build at all, so it can't be told apart and is refused too.
91
+ """
92
+ info_file = static_dir / "build-info.json"
93
+ try:
94
+ info = json.loads(info_file.read_text(encoding="utf-8"))
95
+ except FileNotFoundError:
96
+ return f"The frontend has no {info_file}, so it can't be told from a mock build. {BUILD_COMMAND}."
97
+ except (OSError, ValueError):
98
+ return f"{info_file} can't be read as JSON. {BUILD_COMMAND}."
99
+ api = info.get("api") if isinstance(info, dict) else None
100
+ if api != "real":
101
+ return (
102
+ f"The frontend in {static_dir} was built with mocks (api: {api!r} in build-info.json); "
103
+ f"it would serve fake data. {BUILD_COMMAND}."
104
+ )
105
+ return None
@@ -0,0 +1,230 @@
1
+ """Error reporting: one seam, `report_error`, with one built-in destination.
2
+
3
+ Called by the unhandled-exception handler (every 500, errors.py), by
4
+ POST /client-errors (failures the browser saw), and usable by app code.
5
+ It always logs. With ERROR_REPORTING_DSN set it also sends the error, as a
6
+ Sentry envelope over plain HTTP (stdlib only, no SDK), to Sentry itself or
7
+ any Sentry-compatible server such as a self-hosted GlitchTip, which group,
8
+ count and email them. Unset, the default, it only logs.
9
+
10
+ **What a report holds, and only that:** the error's type, message and
11
+ stack; the route *pattern* (`/widgets/{widget_id}`, never the URL); the HTTP
12
+ method and status; the release; the environment; the user's id, never
13
+ their email. Never request or response bodies, cookies, headers, form
14
+ values or query strings: nothing here is given the request, only those
15
+ fields. Messages are scrubbed too: a database error's SQL and parameters,
16
+ and any query string in a URL, are cut (`scrub`).
17
+ """
18
+
19
+ import json
20
+ import logging
21
+ import re
22
+ import threading
23
+ import traceback
24
+ import urllib.request
25
+ import uuid
26
+ from dataclasses import dataclass, field
27
+ from datetime import datetime, timezone
28
+ from typing import Any, Literal
29
+ from urllib.parse import urlsplit
30
+
31
+ from foundation_backend.config import APP_ENV, ERROR_REPORTING_DSN, RELEASE
32
+
33
+ logger = logging.getLogger("app.errors")
34
+
35
+ MAX_MESSAGE = 2000
36
+ MAX_STACK = 16000
37
+ SEND_TIMEOUT_SECONDS = 5
38
+
39
+ Source = Literal["server", "route", "window", "unhandledrejection", "query", "mutation"]
40
+
41
+
42
+ @dataclass
43
+ class ErrorContext:
44
+ """Everything a report may carry besides the error itself."""
45
+
46
+ source: Source = "server"
47
+ route: str | None = None
48
+ method: str | None = None
49
+ status: int | None = None
50
+ user_id: int | None = None
51
+ # The browser's build, for a client report; the server's is RELEASE.
52
+ release: str | None = None
53
+ tags: dict[str, str] = field(default_factory=dict)
54
+
55
+
56
+ @dataclass
57
+ class ReportedError:
58
+ """An error as reported: from a Python exception, or as the browser
59
+ described one (POST /client-errors)."""
60
+
61
+ type: str
62
+ message: str
63
+ frames: list[dict[str, Any]]
64
+ platform: Literal["python", "javascript"]
65
+ stack: str | None = None
66
+
67
+
68
+ # ------------------------------------------------------------------ scrub
69
+
70
+ _SQL_TAIL = re.compile(r"\s*\[(SQL|parameters):.*", re.DOTALL)
71
+ _SQLA_BACKGROUND = re.compile(r"\s*\(Background on this error at:.*", re.DOTALL)
72
+ # A query string or fragment, up to (not including) a stack frame's
73
+ # trailing :line:col, a space, a quote or a bracket.
74
+ _URL_QUERY = re.compile(
75
+ r"(\b[a-z][a-z0-9+.-]*://[^\s?#\"'()]+|(?<![\w/])/[^\s?#\"'()]*)"
76
+ r"[?#][^\s\"'()]*?(?=(?::\d+){1,2}(?=[\s\"'()]|$)|[\s\"'()]|$)",
77
+ re.IGNORECASE,
78
+ )
79
+
80
+
81
+ def scrub(text: str, limit: int = MAX_MESSAGE) -> str:
82
+ """Cuts what a message or stack must never carry: a database error's
83
+ SQL and bound parameters (which hold row values), and every query
84
+ string or fragment in a URL or path. Then caps the length."""
85
+ text = _SQL_TAIL.sub("", text)
86
+ text = _SQLA_BACKGROUND.sub("", text)
87
+ text = _URL_QUERY.sub(r"\1", text)
88
+ return text if len(text) <= limit else text[: limit - 1] + "…"
89
+
90
+
91
+ def from_exception(exc: BaseException) -> ReportedError:
92
+ frames = [
93
+ {"filename": frame.filename, "function": frame.name, "lineno": frame.lineno, "in_app": "/app/" in frame.filename.replace("\\", "/")}
94
+ for frame in traceback.extract_tb(exc.__traceback__)
95
+ ]
96
+ return ReportedError(type=type(exc).__name__, message=scrub(str(exc)), frames=frames, platform="python")
97
+
98
+
99
+ # Chrome/V8 " at fn (url:1:2)" or " at url:1:2"; Firefox/Safari "fn@url:1:2".
100
+ _V8_FRAME = re.compile(r"^\s*at (?:(?P<fn>.+?) \()?(?P<file>[^()\s]+?):(?P<line>\d+):(?P<col>\d+)\)?$")
101
+ _GECKO_FRAME = re.compile(r"^(?P<fn>[^@]*)@(?P<file>.+?):(?P<line>\d+):(?P<col>\d+)$")
102
+
103
+
104
+ def from_client(type_: str, message: str, stack: str | None) -> ReportedError:
105
+ stack = scrub(stack, MAX_STACK) if stack else None
106
+ frames: list[dict[str, Any]] = []
107
+ for line in (stack or "").splitlines():
108
+ match = _V8_FRAME.match(line) or _GECKO_FRAME.match(line.strip())
109
+ if match:
110
+ frames.append(
111
+ {
112
+ "filename": match["file"],
113
+ "function": (match["fn"] or "?").strip() or "?",
114
+ "lineno": int(match["line"]),
115
+ "colno": int(match["col"]),
116
+ }
117
+ )
118
+ # Sentry lists frames oldest first; a JS stack is newest first.
119
+ frames.reverse()
120
+ return ReportedError(type=type_, message=scrub(message), frames=frames, platform="javascript", stack=stack)
121
+
122
+
123
+ # ------------------------------------------------------------------- send
124
+
125
+
126
+ def parse_dsn(dsn: str) -> tuple[str, str]:
127
+ """`https://<key>@host[:port]/[path/]<project>` → (envelope URL, key)."""
128
+ parts = urlsplit(dsn)
129
+ if not parts.scheme or not parts.hostname or not parts.username or not parts.path.strip("/"):
130
+ raise ValueError("ERROR_REPORTING_DSN should look like https://<key>@<host>/<project id>")
131
+ path, _, project = parts.path.strip("/").rpartition("/")
132
+ host = parts.hostname + (f":{parts.port}" if parts.port else "")
133
+ prefix = f"/{path}" if path else ""
134
+ return f"{parts.scheme}://{host}{prefix}/api/{project}/envelope/", parts.username
135
+
136
+
137
+ def build_event(error: ReportedError, context: ErrorContext) -> dict[str, Any]:
138
+ tags = {"source": context.source, **context.tags}
139
+ if context.route:
140
+ tags["route"] = context.route
141
+ if context.method:
142
+ tags["method"] = context.method
143
+ if context.status is not None:
144
+ tags["status"] = str(context.status)
145
+ event: dict[str, Any] = {
146
+ "event_id": uuid.uuid4().hex,
147
+ "timestamp": datetime.now(timezone.utc).isoformat(),
148
+ "platform": error.platform,
149
+ "level": "error",
150
+ "logger": "app.errors",
151
+ "environment": APP_ENV,
152
+ "exception": {
153
+ "values": [
154
+ {
155
+ "type": error.type,
156
+ "value": error.message,
157
+ **({"stacktrace": {"frames": error.frames}} if error.frames else {}),
158
+ }
159
+ ]
160
+ },
161
+ "tags": tags,
162
+ }
163
+ release = context.release or RELEASE
164
+ if release:
165
+ event["release"] = release
166
+ if context.route:
167
+ event["transaction"] = context.route
168
+ if context.user_id is not None:
169
+ event["user"] = {"id": str(context.user_id)}
170
+ if error.stack and not error.frames:
171
+ # A stack the parser didn't recognise still reaches the report.
172
+ event["extra"] = {"stack": error.stack}
173
+ return event
174
+
175
+
176
+ def build_envelope(event: dict[str, Any], dsn: str) -> bytes:
177
+ payload = json.dumps(event, separators=(",", ":")).encode()
178
+ header = {"event_id": event["event_id"], "dsn": dsn, "sent_at": event["timestamp"]}
179
+ item = {"type": "event", "content_type": "application/json", "length": len(payload)}
180
+ return b"\n".join([json.dumps(header).encode(), json.dumps(item).encode(), payload]) + b"\n"
181
+
182
+
183
+ def _post(url: str, key: str, body: bytes) -> None:
184
+ request = urllib.request.Request(
185
+ url,
186
+ data=body,
187
+ method="POST",
188
+ headers={
189
+ "Content-Type": "application/x-sentry-envelope",
190
+ "X-Sentry-Auth": f"Sentry sentry_version=7, sentry_key={key}, sentry_client=ui-foundation/1.0",
191
+ },
192
+ )
193
+ with urllib.request.urlopen(request, timeout=SEND_TIMEOUT_SECONDS): # noqa: S310 — the DSN's own https URL
194
+ pass
195
+
196
+
197
+ def _send(dsn: str, event: dict[str, Any]) -> None:
198
+ try:
199
+ url, key = parse_dsn(dsn)
200
+ _post(url, key, build_envelope(event, dsn))
201
+ except Exception: # noqa: BLE001 — reporting must never take the app down
202
+ logger.warning("error reporting: could not send event %s", event["event_id"], exc_info=True)
203
+
204
+
205
+ def _dispatch(dsn: str, event: dict[str, Any]) -> None:
206
+ # A thread per report: the request that failed never waits on the
207
+ # destination. Tests replace this with a direct call.
208
+ threading.Thread(target=_send, args=(dsn, event), daemon=True).start()
209
+
210
+
211
+ def report(error: ReportedError, context: ErrorContext) -> None:
212
+ """Logs `error` and, with ERROR_REPORTING_DSN set, sends it in the
213
+ background: the request that failed never waits on the destination."""
214
+ event = build_event(error, context)
215
+ logger.error(
216
+ "%s: %s (source=%s route=%s status=%s user=%s)",
217
+ error.type,
218
+ error.message,
219
+ context.source,
220
+ context.route,
221
+ context.status,
222
+ context.user_id,
223
+ )
224
+ if ERROR_REPORTING_DSN:
225
+ _dispatch(ERROR_REPORTING_DSN, event)
226
+
227
+
228
+ def report_error(exc: BaseException, context: ErrorContext | None = None) -> None:
229
+ """The seam for Python exceptions: app code may call it too."""
230
+ report(from_exception(exc), context or ErrorContext())
@@ -0,0 +1,46 @@
1
+ """Exception handlers — pin FastAPI's default error bodies to the exact
2
+ shapes openapi.yaml declares (ValidationErrorBody, HTTPErrorBody), so the
3
+ frontend gateway's toAppError (src/api/gateway/errors.ts) needs no changes.
4
+ """
5
+
6
+ from fastapi import FastAPI, Request, status
7
+ from fastapi.exceptions import RequestValidationError
8
+ from fastapi.responses import JSONResponse
9
+ from starlette.exceptions import HTTPException as StarletteHTTPException
10
+
11
+ from foundation_backend.error_reporting import ErrorContext, report_error
12
+
13
+
14
+ def register_error_handlers(app: FastAPI) -> None:
15
+ @app.exception_handler(RequestValidationError)
16
+ async def validation_error_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
17
+ detail = [
18
+ {"loc": list(error["loc"]), "msg": error["msg"], "type": error["type"]}
19
+ for error in exc.errors()
20
+ ]
21
+ return JSONResponse(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, content={"detail": detail})
22
+
23
+ @app.exception_handler(StarletteHTTPException)
24
+ async def http_error_handler(_: Request, exc: StarletteHTTPException) -> JSONResponse:
25
+ # Headers kept: a 429's Retry-After is part of the contract.
26
+ return JSONResponse(
27
+ status_code=exc.status_code, content={"detail": str(exc.detail)}, headers=exc.headers
28
+ )
29
+
30
+ @app.exception_handler(Exception)
31
+ async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
32
+ # Every 500 is reported (error_reporting.py): only the route's
33
+ # pattern, the method and the user's id go with it, never anything
34
+ # else from the request.
35
+ route = request.scope.get("route")
36
+ report_error(
37
+ exc,
38
+ ErrorContext(
39
+ source="server",
40
+ route=getattr(route, "path", None),
41
+ method=request.method,
42
+ status=500,
43
+ user_id=getattr(request.state, "user_id", None),
44
+ ),
45
+ )
46
+ return JSONResponse(status_code=500, content={"detail": "Internal server error"})
@@ -0,0 +1,120 @@
1
+ """Failed sign-in limits: per client IP and per account, counted in the
2
+ database (`login_failures`) so they survive a restart and hold across
3
+ worker processes. Stdlib only.
4
+
5
+ The check runs before the password is checked, so an answer over the
6
+ limit says nothing about the password. A wrong TOTP code counts as a
7
+ failure too. A session starting clears that account's and that IP's
8
+ failures; a right password alone doesn't when the account has a second
9
+ step, or a known password would reset the count for guessing codes.
10
+
11
+ The per-account limit lets anyone lock an account out for its window by
12
+ failing on purpose. That's the usual trade-off, kept short by the
13
+ defaults (docs/deploy.md).
14
+ """
15
+
16
+ import hashlib
17
+ import math
18
+ from datetime import datetime, timedelta, timezone
19
+
20
+ from fastapi import HTTPException, Request
21
+ from sqlmodel import col, delete, or_, select
22
+ from sqlmodel.ext.asyncio.session import AsyncSession
23
+
24
+ from foundation_backend.config import (
25
+ CLIENT_IP_HEADER,
26
+ LOGIN_ACCOUNT_WINDOW_SECONDS,
27
+ LOGIN_IP_WINDOW_SECONDS,
28
+ LOGIN_MAX_FAILURES_PER_ACCOUNT,
29
+ LOGIN_MAX_FAILURES_PER_IP,
30
+ )
31
+ from foundation_backend.models import LoginFailure
32
+
33
+ IP = "ip"
34
+ ACCOUNT = "account"
35
+
36
+
37
+ def client_ip(request: Request) -> str:
38
+ # CLIENT_IP_HEADER, when set, is a header the proxy in front always
39
+ # overwrites (docs/deploy.md), so a client can't choose its own key.
40
+ if CLIENT_IP_HEADER:
41
+ value = request.headers.get(CLIENT_IP_HEADER, "").strip()
42
+ if value:
43
+ return value
44
+ # Otherwise right only behind a proxy uvicorn trusts (--proxy-headers,
45
+ # FORWARDED_ALLOW_IPS), as the template's Dockerfile runs it.
46
+ return request.client.host if request.client is not None else "unknown"
47
+
48
+
49
+ def account_key(email: str) -> str:
50
+ """sha256 of the normalized email: an unknown email counts the same as
51
+ a known one, and the table holds no addresses."""
52
+ return hashlib.sha256(email.strip().lower().encode()).hexdigest()
53
+
54
+
55
+ def _aware(moment: datetime) -> datetime:
56
+ # SQLite (the pytest engine) drops tzinfo on the way back; Postgres keeps it.
57
+ return moment if moment.tzinfo is not None else moment.replace(tzinfo=timezone.utc)
58
+
59
+
60
+ def _limits() -> list[tuple[str, int, int]]:
61
+ return [
62
+ (IP, LOGIN_MAX_FAILURES_PER_IP, LOGIN_IP_WINDOW_SECONDS),
63
+ (ACCOUNT, LOGIN_MAX_FAILURES_PER_ACCOUNT, LOGIN_ACCOUNT_WINDOW_SECONDS),
64
+ ]
65
+
66
+
67
+ async def retry_after(session: AsyncSession, ip: str, account: str) -> int | None:
68
+ """Seconds until another attempt is allowed, or None if it is now."""
69
+ now = datetime.now(timezone.utc)
70
+ keys = {IP: ip, ACCOUNT: account}
71
+ wait = 0.0
72
+ for kind, limit, window in _limits():
73
+ # Compared here, not in SQL: SQLite stores these without a zone.
74
+ result = await session.exec(
75
+ select(LoginFailure.failed_at).where(LoginFailure.kind == kind, LoginFailure.key == keys[kind])
76
+ )
77
+ cutoff = now - timedelta(seconds=window)
78
+ recent = sorted(at for at in map(_aware, result.all()) if at > cutoff)
79
+ if len(recent) >= limit:
80
+ # Allowed again once enough of them fall out of the window to
81
+ # leave one attempt.
82
+ frees_at = recent[len(recent) - limit] + timedelta(seconds=window)
83
+ wait = max(wait, (frees_at - now).total_seconds())
84
+ return max(1, math.ceil(wait)) if wait > 0 else None
85
+
86
+
87
+ async def refuse_if_limited(session: AsyncSession, ip: str, account: str) -> None:
88
+ wait = await retry_after(session, ip, account)
89
+ if wait is None:
90
+ return
91
+ minutes = max(1, math.ceil(wait / 60))
92
+ raise HTTPException(
93
+ status_code=429,
94
+ detail=f"Too many sign-in attempts. Try again in {minutes} minute{'s' if minutes != 1 else ''}.",
95
+ headers={"Retry-After": str(wait)},
96
+ )
97
+
98
+
99
+ async def record_failure(session: AsyncSession, ip: str, account: str) -> None:
100
+ """Adds one failure for each key and prunes what no window still needs.
101
+ Commits."""
102
+ now = datetime.now(timezone.utc)
103
+ oldest_needed = now - timedelta(seconds=max(window for _, _, window in _limits()))
104
+ await session.exec(delete(LoginFailure).where(col(LoginFailure.failed_at) < oldest_needed))
105
+ session.add(LoginFailure(kind=IP, key=ip, failed_at=now))
106
+ session.add(LoginFailure(kind=ACCOUNT, key=account, failed_at=now))
107
+ await session.commit()
108
+
109
+
110
+ async def clear_failures(session: AsyncSession, ip: str, account: str) -> None:
111
+ """Forgets this IP's and this account's failures. Doesn't commit: the
112
+ session that starts commits it."""
113
+ await session.exec(
114
+ delete(LoginFailure).where(
115
+ or_(
116
+ (col(LoginFailure.kind) == IP) & (col(LoginFailure.key) == ip),
117
+ (col(LoginFailure.kind) == ACCOUNT) & (col(LoginFailure.key) == account),
118
+ )
119
+ )
120
+ )