diff --git a/CHANGELOG.md b/CHANGELOG.md index aca225b..08687d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable public-facing changes to TaskSignal are recorded here. ## Unreleased +## 1.0.0a5 - 2026-11-21 + +### Security + +- Tightened `CORSMiddleware` to explicit HTTP methods (`GET`, `POST`, `PUT`, + `PATCH`, `DELETE`, `OPTIONS`) and explicit request headers (`Content-Type`, + `X-Operator-Scan-Token`, `Authorization`, `Accept`) instead of wildcards. +- Added configurable sliding-window rate limiting (`RATE_LIMIT_REQUESTS_PER_MINUTE`, + defaulting to `60/min` outside `ENVIRONMENT=local`) on high-load endpoints + (`POST /api/scans`, `POST /api/process/demo`, `POST /api/search/semantic`). +- Redacted internal runtime configuration (`llm_provider`, `embedding_model`) + from unauthenticated `/health` responses outside `ENVIRONMENT=local`. +- Added strict SQL identifier validation before executing hardcoded SQLite + compatibility `ALTER TABLE` / `CREATE INDEX` statements. + ## 1.0.0a4 - 2026-11-21 ### Added diff --git a/apps/api/app/core/config.py b/apps/api/app/core/config.py index 98d36fc..7c9aeb4 100644 --- a/apps/api/app/core/config.py +++ b/apps/api/app/core/config.py @@ -70,9 +70,27 @@ class Settings(BaseSettings): require_operator_token_for_writes: bool = False public_scan_sources: str = "fixture,hackernews" cors_allowed_origins: str = "http://localhost:3000,http://127.0.0.1:3000" + rate_limit_requests_per_minute: int | None = None model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore") + @field_validator("rate_limit_requests_per_minute") + @classmethod + def validate_rate_limit(cls, value: int | None) -> int | None: + if value is not None and value < 0: + raise ValueError("RATE_LIMIT_REQUESTS_PER_MINUTE must be >= 0.") + return value + + @property + def is_local_environment(self) -> bool: + return self.environment.strip().lower() == "local" + + @property + def effective_rate_limit_per_minute(self) -> int: + if self.rate_limit_requests_per_minute is not None: + return self.rate_limit_requests_per_minute + return 0 if self.is_local_environment else 60 + @field_validator("database_url", mode="before") @classmethod def select_psycopg3_driver(cls, value: object) -> object: diff --git a/apps/api/app/core/version.py b/apps/api/app/core/version.py index 20d7054..6b0545a 100644 --- a/apps/api/app/core/version.py +++ b/apps/api/app/core/version.py @@ -11,7 +11,7 @@ def installed_tasksignal_version() -> str: return version(distribution) except PackageNotFoundError: continue - return "1.0.0a4" + return "1.0.0a5" TASKSIGNAL_VERSION = installed_tasksignal_version() diff --git a/apps/api/app/db/session.py b/apps/api/app/db/session.py index 34d5d0f..9ba3cbb 100644 --- a/apps/api/app/db/session.py +++ b/apps/api/app/db/session.py @@ -1,3 +1,4 @@ +import re from collections.abc import Generator from sqlalchemy import Engine, create_engine, event, inspect, text @@ -5,6 +6,14 @@ from app.core.config import settings +_SQLITE_IDENT_RE = re.compile(r"^[a-z_][a-z0-9_]*$") + + +def _validate_sqlite_identifier(name: str, kind: str) -> str: + if not _SQLITE_IDENT_RE.fullmatch(name): + raise ValueError(f"Unsafe SQLite {kind} identifier: {name!r}") + return name + connect_args = ( {"check_same_thread": False, "timeout": 30} if settings.database_url.startswith("sqlite") @@ -24,6 +33,8 @@ def enable_sqlite_foreign_keys(dbapi_connection, _connection_record) -> None: SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False) +# Security invariant: SQLITE_COMPAT_COLUMNS and SQLITE_COMPAT_INDEXES are strictly +# hardcoded static migration definitions and must never be populated from external input. SQLITE_COMPAT_COLUMNS = { "scan_jobs": [ ("signals_detected", "INTEGER NOT NULL DEFAULT 0"), @@ -62,24 +73,29 @@ def ensure_sqlite_schema_compatibility(target_engine: Engine = engine) -> None: for table_name, columns in SQLITE_COMPAT_COLUMNS.items(): if table_name not in tables: continue - existing_columns = {column["name"] for column in inspector.get_columns(table_name)} + safe_table = _validate_sqlite_identifier(table_name, "table") + existing_columns = {column["name"] for column in inspector.get_columns(safe_table)} for column_name, column_sql in columns: if column_name in existing_columns: continue + safe_column = _validate_sqlite_identifier(column_name, "column") connection.execute( - text(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_sql}") + text(f"ALTER TABLE {safe_table} ADD COLUMN {safe_column} {column_sql}") ) for table_name, indexes in SQLITE_COMPAT_INDEXES.items(): if table_name not in tables: continue + safe_table = _validate_sqlite_identifier(table_name, "table") existing_indexes = { - index["name"] for index in inspect(target_engine).get_indexes(table_name) + index["name"] for index in inspect(target_engine).get_indexes(safe_table) } for index_name, column_name in indexes: if index_name in existing_indexes: continue + safe_index = _validate_sqlite_identifier(index_name, "index") + safe_column = _validate_sqlite_identifier(column_name, "column") connection.execute( - text(f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({column_name})") + text(f"CREATE INDEX IF NOT EXISTS {safe_index} ON {safe_table} ({safe_column})") ) diff --git a/apps/api/app/main.py b/apps/api/app/main.py index 39e53f9..dd51b02 100644 --- a/apps/api/app/main.py +++ b/apps/api/app/main.py @@ -1,10 +1,12 @@ import os +import time +from collections import deque from collections.abc import AsyncIterator from contextlib import asynccontextmanager os.environ.setdefault("DISABLE_SQLALCHEMY_CEXT_RUNTIME", "1") -from fastapi import FastAPI, Request, status +from fastapi import FastAPI, Header, Request, status from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse @@ -16,6 +18,38 @@ from app.db.session import engine, ensure_sqlite_schema_compatibility from app.models import all_models # noqa: F401 +CORS_ALLOWED_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] +CORS_ALLOWED_HEADERS = ["Content-Type", "X-Operator-Scan-Token", "Authorization", "Accept"] +RATE_LIMITED_POST_PATHS = frozenset({"/scans", "/process/demo", "/search/semantic"}) +_RATE_LIMIT_WINDOW_SECONDS = 60.0 +_MAX_RATE_LIMIT_BUCKETS = 4096 + + +def _is_local_environment() -> bool: + if hasattr(settings, "is_local_environment"): + return bool(settings.is_local_environment) + return str(getattr(settings, "environment", "local")).strip().lower() == "local" + + +def _effective_rate_limit_per_minute() -> int: + if hasattr(settings, "effective_rate_limit_per_minute"): + return int(settings.effective_rate_limit_per_minute) + configured = getattr(settings, "rate_limit_requests_per_minute", None) + if configured is not None: + return int(configured) + return 0 if _is_local_environment() else 60 + + +def _normalize_rate_limit_path(path: str) -> str | None: + if path.startswith("/api/v1/"): + suffix = path[len("/api/v1") :] + elif path.startswith("/api/"): + suffix = path[len("/api") :] + else: + return None + normalized = suffix.rstrip("/") + return normalized if normalized in RATE_LIMITED_POST_PATHS else None + def cors_allowed_origins() -> list[str]: origins = [ @@ -70,18 +104,56 @@ async def protect_hosted_api(request: Request, call_next): ) return await call_next(request) + rate_limit_buckets: dict[tuple[str, str], deque[float]] = {} + + @app.middleware("http") + async def enforce_high_load_rate_limit(request: Request, call_next): + limit = _effective_rate_limit_per_minute() + if limit > 0 and request.method.upper() == "POST": + route_key = _normalize_rate_limit_path(request.url.path) + if route_key is not None: + now = time.monotonic() + cutoff = now - _RATE_LIMIT_WINDOW_SECONDS + if len(rate_limit_buckets) >= _MAX_RATE_LIMIT_BUCKETS: + stale_keys = [ + key + for key, hits in rate_limit_buckets.items() + if not hits or hits[-1] <= cutoff + ] + for key in stale_keys: + del rate_limit_buckets[key] + client_host = request.client.host if request.client else "unknown" + bucket = rate_limit_buckets.setdefault((client_host, route_key), deque()) + while bucket and bucket[0] <= cutoff: + bucket.popleft() + if len(bucket) >= limit: + retry_after = max(1, int(_RATE_LIMIT_WINDOW_SECONDS - (now - bucket[0])) + 1) + return JSONResponse( + status_code=status.HTTP_429_TOO_MANY_REQUESTS, + content={"detail": "Rate limit exceeded for this endpoint. Retry later."}, + headers={"Retry-After": str(retry_after)}, + ) + bucket.append(now) + return await call_next(request) + app.add_middleware( CORSMiddleware, allow_origins=cors_allowed_origins(), allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], + allow_methods=CORS_ALLOWED_METHODS, + allow_headers=CORS_ALLOWED_HEADERS, ) app.include_router(router, prefix="/api/v1") app.include_router(router, prefix="/api", include_in_schema=False) @app.get("/health") - def health() -> dict: + def health( + x_operator_scan_token: str | None = Header(default=None), + ) -> dict[str, object]: + if not _is_local_environment() and not operator_token_matches( + x_operator_scan_token, settings.operator_scan_token + ): + return {"status": "ok"} return { "status": "ok", "llm_provider": settings.llm_provider, diff --git a/apps/api/pyproject.toml b/apps/api/pyproject.toml index 2731996..9d93ed1 100644 --- a/apps/api/pyproject.toml +++ b/apps/api/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "tasksignal" -version = "1.0.0a4" +version = "1.0.0a5" description = "FastAPI backend for TaskSignal, an AI-assisted problem discovery engine." readme = "README.md" requires-python = ">=3.11,<3.15" diff --git a/apps/api/tests/test_security_hardening.py b/apps/api/tests/test_security_hardening.py new file mode 100644 index 0000000..15a8135 --- /dev/null +++ b/apps/api/tests/test_security_hardening.py @@ -0,0 +1,82 @@ +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy import create_engine + +from app.core.config import Settings, settings +from app.db.session import ( + SQLITE_COMPAT_COLUMNS, + _validate_sqlite_identifier, + ensure_sqlite_schema_compatibility, +) +from app.main import CORS_ALLOWED_HEADERS, CORS_ALLOWED_METHODS, create_app + + +def test_cors_uses_explicit_methods_and_headers(client) -> None: + assert "*" not in CORS_ALLOWED_METHODS + assert "*" not in CORS_ALLOWED_HEADERS + response = client.options( + "/api/readiness", + headers={ + "Origin": "http://localhost:3000", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "X-Operator-Scan-Token, Content-Type", + }, + ) + + assert response.status_code == 200 + assert response.headers["access-control-allow-origin"] == "http://localhost:3000" + assert "POST" in response.headers["access-control-allow-methods"] + + +def test_health_redacts_internal_runtime_outside_local(client, monkeypatch) -> None: + monkeypatch.setattr(settings, "environment", "production") + monkeypatch.setattr(settings, "operator_scan_token", "prod-health-secret") + + unauthenticated = client.get("/health") + assert unauthenticated.status_code == 200 + assert unauthenticated.json() == {"status": "ok"} + + authenticated = client.get("/health", headers={"X-Operator-Scan-Token": "prod-health-secret"}) + assert authenticated.status_code == 200 + body = authenticated.json() + assert body["status"] == "ok" + assert "llm_provider" in body + assert "embedding_model" in body + + +def test_high_load_endpoints_enforce_rate_limit(monkeypatch) -> None: + monkeypatch.setattr(settings, "rate_limit_requests_per_minute", 2) + app = create_app() + with TestClient(app) as limited_client: + first = limited_client.post("/api/search/semantic", json={"query": "rate limit test"}) + second = limited_client.post("/api/search/semantic", json={"query": "rate limit test"}) + third = limited_client.post("/api/search/semantic", json={"query": "rate limit test"}) + + assert first.status_code == 200 + assert second.status_code == 200 + assert third.status_code == 429 + assert int(third.headers["Retry-After"]) >= 1 + + +def test_settings_default_rate_limit_enables_outside_local() -> None: + local_cfg = Settings(environment="local", author_hash_salt="change-me") + prod_cfg = Settings(environment="production", author_hash_salt="unique-prod-salt-123") + + assert local_cfg.effective_rate_limit_per_minute == 0 + assert prod_cfg.effective_rate_limit_per_minute == 60 + + +def test_sqlite_compat_rejects_unsafe_identifiers(tmp_path: Path, monkeypatch) -> None: + with pytest.raises(ValueError, match="Unsafe SQLite"): + _validate_sqlite_identifier("scan_jobs; DROP TABLE scan_jobs", "table") + + db_file = tmp_path / "compat.db" + test_engine = create_engine(f"sqlite:///{db_file}") + with test_engine.begin() as conn: + conn.exec_driver_sql("CREATE TABLE safe_tbl (id INTEGER PRIMARY KEY)") + monkeypatch.setitem(SQLITE_COMPAT_COLUMNS, "safe_tbl", [("bad;col", "TEXT")]) + with pytest.raises(ValueError, match="Unsafe SQLite column identifier"): + ensure_sqlite_schema_compatibility(test_engine) + test_engine.dispose() diff --git a/apps/api/tests/test_version.py b/apps/api/tests/test_version.py index 2281bf0..dbc08bc 100644 --- a/apps/api/tests/test_version.py +++ b/apps/api/tests/test_version.py @@ -9,4 +9,4 @@ def missing_distribution(_distribution: str) -> str: monkeypatch.setattr(version_module, "version", missing_distribution) - assert version_module.installed_tasksignal_version() == "1.0.0a4" + assert version_module.installed_tasksignal_version() == "1.0.0a5" diff --git a/apps/api/uv.lock b/apps/api/uv.lock index 4d6ca93..f14cb00 100644 --- a/apps/api/uv.lock +++ b/apps/api/uv.lock @@ -2243,7 +2243,7 @@ wheels = [ [[package]] name = "tasksignal" -version = "1.0.0a4" +version = "1.0.0a5" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/apps/web/package-lock.json b/apps/web/package-lock.json index 377e4e6..43d45c6 100644 --- a/apps/web/package-lock.json +++ b/apps/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "tasksignal-web", - "version": "1.0.0-alpha.4", + "version": "1.0.0-alpha.5", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "tasksignal-web", - "version": "1.0.0-alpha.4", + "version": "1.0.0-alpha.5", "dependencies": { "@tanstack/react-query": "^5.108.0", "clsx": "^2.1.1", diff --git a/apps/web/package.json b/apps/web/package.json index dcff14a..27f2f83 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "tasksignal-web", - "version": "1.0.0-alpha.4", + "version": "1.0.0-alpha.5", "private": true, "scripts": { "dev": "next dev -H 127.0.0.1",