diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..21f67f3 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +.github +.venv +__pycache__ +.pytest_cache +.pytest-tmp +.env +backups +data/streaming +docs/images diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e9729ad --- /dev/null +++ b/.env.example @@ -0,0 +1,21 @@ +# Copy to .env for local use. Never commit real secrets. +APP_ENV=development +APP_VERSION=4.0.0 +LOG_LEVEL=INFO +LOG_JSON=true +REQUIRE_API_KEY=false +API_KEY=replace-with-at-least-16-random-characters +CORS_ORIGINS=http://localhost:8501 +TRUSTED_HOSTS=localhost,127.0.0.1,testserver +METRICS_ENABLED=true +MAX_REQUEST_BODY_BYTES=1048576 + +# Enable these for the optional PostgreSQL warehouse. +POSTGRES_DB=project_rising +POSTGRES_USER=rising_user +POSTGRES_PASSWORD=replace-with-a-strong-password +DATABASE_URL=postgresql+psycopg2://rising_user:replace-with-a-strong-password@postgres:5432/project_rising +DATABASE_REQUIRED=false +DATABASE_CONNECT_TIMEOUT_SECONDS=5 +DATABASE_MAX_RETRIES=3 + diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 66b2b39..5645c65 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,4 +1,4 @@ -name: Project RISING Tests +name: Project RISING CI on: push: @@ -9,7 +9,7 @@ permissions: jobs: test: - name: Pytest (Python 3.11) + name: Test and validate (Python 3.11) runs-on: ubuntu-latest steps: @@ -28,4 +28,24 @@ jobs: python -m pip install -r requirements.txt - name: Run tests - run: python -m pytest -v + run: python -m pytest -q + + - name: Compile Python modules + run: python -m compileall -q api config demo pipelines schemas streaming warehouse main.py + + - name: Validate production configuration + env: + APP_ENV: production + REQUIRE_API_KEY: "true" + API_KEY: ci-only-api-key-000000000000 + CORS_ORIGINS: https://pilot.example.org + TRUSTED_HOSTS: pilot.example.org + run: python -c "from config.config import get_settings; print(get_settings().environment)" + + container: + name: Build container + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build pilot image + run: docker build --tag project-rising:${{ github.sha }} . diff --git a/.gitignore b/.gitignore index fe33baa..63712fd 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,11 @@ __pycache__/ .pytest_cache/ .pytest-tmp/ data/streaming/ +.env +.venv*/ +.coverage +htmlcov/ +*.log +backups/ + +.pytest-vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..55ae088 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM python:3.11-slim AS runtime + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + PORT=8000 + +WORKDIR /app + +RUN addgroup --system rising && adduser --system --ingroup rising rising + +COPY requirements.txt . +RUN python -m pip install --upgrade pip && python -m pip install -r requirements.txt + +COPY --chown=rising:rising . . +USER rising + +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3)" + +CMD ["sh", "-c", "python -m uvicorn main:app --host 0.0.0.0 --port ${PORT} --proxy-headers --forwarded-allow-ips='*'"] diff --git a/README.md b/README.md index 3b873c6..81cbf17 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,11 @@ Open , or get a real sample prediction: curl http://127.0.0.1:8000/api/v1/disease-risk/sample ``` +For a pilot-like local deployment, copy `.env.example` to `.env`, replace all +placeholder secrets, then run `docker compose up --build -d`. Liveness is at +`/health`, dependency readiness at `/ready`, and API-key-protected Prometheus +metrics at `/metrics`. See the [pilot deployment runbook](docs/operations/pilot_runbook.md). + Start the dashboard in a second terminal: ```bash @@ -158,6 +163,8 @@ docker compose exec postgres psql -U rising_user -d project_rising -c "SELECT ev | Method | Endpoint | Purpose | |---|---|---| | `GET` | `/health` | Service health check | +| `GET` | `/ready` | Required data and dependency readiness | +| `GET` | `/metrics` | Prometheus metrics (protected when API keys are enabled) | | `GET` | `/api/v1/health-indicators` | Filter processed health indicators | | `GET` | `/api/v1/climate-events` | Read accepted climate events when configured | | `GET` | `/api/v1/pipeline/status` | Inspect pipeline readiness | diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6157f1f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security Policy + +Project RISING is a pilot decision-support prototype and does not accept +patient-level or other sensitive personal data. Report vulnerabilities +privately to the repository owner; do not include secrets or real health data +in an issue. + +Production pilots must use HTTPS, API-key protection, explicit CORS and trusted +hosts, managed secrets, least-privilege database credentials, encrypted +backups, centralized logs, dependency scanning, and a documented key-rotation +procedure. The single shared API key is suitable only for a small controlled +pilot. Multi-user identity, roles, audit-grade access records, regulatory +review, and independent penetration testing are required before broader use. diff --git a/api/logging.py b/api/logging.py new file mode 100644 index 0000000..af94777 --- /dev/null +++ b/api/logging.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import json +import logging +from datetime import datetime, timezone +from typing import Any + + +class JsonFormatter(logging.Formatter): + """Emit one machine-readable JSON object per log record.""" + + def format(self, record: logging.LogRecord) -> str: + payload: dict[str, Any] = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "level": record.levelname, + "logger": record.name, + "message": record.getMessage(), + } + for field in ( + "request_id", + "method", + "path", + "status_code", + "duration_ms", + "environment", + ): + value = getattr(record, field, None) + if value is not None: + payload[field] = value + if record.exc_info: + payload["exception"] = self.formatException(record.exc_info) + return json.dumps(payload, default=str) + + +def configure_logging(level: str = "INFO", json_logs: bool = True) -> None: + handler = logging.StreamHandler() + handler.setFormatter( + JsonFormatter() + if json_logs + else logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s") + ) + root_logger = logging.getLogger() + root_logger.handlers.clear() + root_logger.addHandler(handler) + root_logger.setLevel(level) diff --git a/api/observability.py b/api/observability.py new file mode 100644 index 0000000..3ce096d --- /dev/null +++ b/api/observability.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +import threading +from collections import Counter +from time import perf_counter + + +class Metrics: + """Small dependency-free Prometheus metrics registry for pilot operation.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._requests: Counter[tuple[str, str, int]] = Counter() + self._duration_seconds: Counter[tuple[str, str]] = Counter() + self._started = perf_counter() + + def observe(self, method: str, path: str, status_code: int, duration: float) -> None: + normalized_path = path if not path.startswith("/api/v1/countries/") else "/api/v1/countries/{country}/risk" + with self._lock: + self._requests[(method, normalized_path, status_code)] += 1 + self._duration_seconds[(method, normalized_path)] += duration + + def render(self) -> str: + lines = [ + "# HELP rising_uptime_seconds Process uptime in seconds.", + "# TYPE rising_uptime_seconds gauge", + f"rising_uptime_seconds {perf_counter() - self._started:.6f}", + "# HELP rising_http_requests_total HTTP requests by method, path, and status.", + "# TYPE rising_http_requests_total counter", + ] + with self._lock: + for (method, path, status), count in sorted(self._requests.items()): + lines.append( + f'rising_http_requests_total{{method="{method}",path="{path}",status="{status}"}} {count}' + ) + lines.extend( + [ + "# HELP rising_http_request_duration_seconds_total Cumulative request duration.", + "# TYPE rising_http_request_duration_seconds_total counter", + ] + ) + for (method, path), duration in sorted(self._duration_seconds.items()): + lines.append( + f'rising_http_request_duration_seconds_total{{method="{method}",path="{path}"}} {duration:.6f}' + ) + return "\n".join(lines) + "\n" + + +metrics = Metrics() diff --git a/api/routes/health.py b/api/routes/health.py index 296cb6f..dada39c 100644 --- a/api/routes/health.py +++ b/api/routes/health.py @@ -17,8 +17,8 @@ @router.get("") def list_health_indicators( - country: str | None = Query(default=None), - indicator: str | None = Query(default=None), + country: str | None = Query(default=None, min_length=2, max_length=100), + indicator: str | None = Query(default=None, min_length=2, max_length=150), year: int | None = Query( default=None, ge=1900, @@ -90,4 +90,4 @@ def list_indicators() -> dict[str, Any]: return { "count": len(indicators), "indicators": indicators, - } \ No newline at end of file + } diff --git a/api/routes/pipeline.py b/api/routes/pipeline.py index 7aa4e59..7e0b897 100644 --- a/api/routes/pipeline.py +++ b/api/routes/pipeline.py @@ -1,13 +1,15 @@ from typing import Any -from fastapi import APIRouter +from fastapi import APIRouter, Depends from api.services.data_service import get_pipeline_status +from api.security import verify_api_key router = APIRouter( prefix="/pipeline", tags=["Pipeline Monitoring"], + dependencies=[Depends(verify_api_key)], ) @@ -15,4 +17,4 @@ def pipeline_status() -> dict[str, Any]: """Return the current batch and streaming pipeline status.""" - return get_pipeline_status() \ No newline at end of file + return get_pipeline_status() diff --git a/api/routes/prediction.py b/api/routes/prediction.py index 9ba33f8..a56c77f 100644 --- a/api/routes/prediction.py +++ b/api/routes/prediction.py @@ -1,9 +1,10 @@ from typing import Any, Literal -from fastapi import APIRouter, HTTPException -from pydantic import BaseModel, Field +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel, ConfigDict, Field from api.services.disease_risk_service import predict_disease_risk +from api.security import verify_api_key router = APIRouter( @@ -13,7 +14,9 @@ class DiseaseRiskRequest(BaseModel): - country: str = Field(examples=["Philippines"]) + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + country: str = Field(min_length=2, max_length=100, examples=["Philippines"]) disease: Literal["dengue", "malaria", "mosquito_borne"] = "dengue" temperature_c: float = Field(ge=-10, le=55, examples=[29.0]) rainfall_mm: float = Field(ge=0, le=2000, examples=[180.0]) @@ -31,7 +34,7 @@ def _predict(payload: DiseaseRiskRequest) -> dict[str, Any]: raise HTTPException(status_code=503, detail=str(error)) from error -@router.post("/predict") +@router.post("/predict", dependencies=[Depends(verify_api_key)]) def disease_risk_prediction(payload: DiseaseRiskRequest) -> dict[str, Any]: """Predict explainable 14-day mosquito-borne disease risk.""" diff --git a/api/routes/risk.py b/api/routes/risk.py index e81a024..769af72 100644 --- a/api/routes/risk.py +++ b/api/routes/risk.py @@ -1,6 +1,6 @@ from typing import Any -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, HTTPException, Path from api.services.data_service import get_country_risk @@ -12,7 +12,9 @@ @router.get("/{country}/risk") -def country_risk(country: str) -> dict[str, Any]: +def country_risk( + country: str = Path(min_length=2, max_length=100), +) -> dict[str, Any]: """Return a transparent comparative country-risk score.""" try: @@ -31,4 +33,4 @@ def country_risk(country: str) -> dict[str, Any]: raise HTTPException( status_code=503, detail=str(error), - ) from error \ No newline at end of file + ) from error diff --git a/api/security.py b/api/security.py new file mode 100644 index 0000000..7ab98cc --- /dev/null +++ b/api/security.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import secrets + +from fastapi import HTTPException, Security, status +from fastapi.security import APIKeyHeader + +from config.config import get_settings + + +api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False) + + +def verify_api_key(provided_key: str | None = Security(api_key_header)) -> None: + """Require a configured API key for protected pilot operations.""" + + settings = get_settings() + if not settings.require_api_key: + return + + expected = settings.api_key.get_secret_value() if settings.api_key else "" + if not provided_key or not secrets.compare_digest(provided_key, expected): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="A valid API key is required", + headers={"WWW-Authenticate": "ApiKey"}, + ) diff --git a/config/config.py b/config/config.py index e69de29..03f819c 100644 --- a/config/config.py +++ b/config/config.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import os +from functools import lru_cache +from pathlib import Path +from typing import Literal + +from dotenv import load_dotenv +from pydantic import BaseModel, Field, SecretStr, model_validator + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +load_dotenv(PROJECT_ROOT / ".env") + + +def _boolean(name: str, default: bool) -> bool: + value = os.getenv(name) + if value is None: + return default + normalized = value.strip().lower() + if normalized in {"1", "true", "yes", "on"}: + return True + if normalized in {"0", "false", "no", "off"}: + return False + raise ValueError(f"{name} must be a boolean value") + + +def _csv(name: str, default: str) -> tuple[str, ...]: + return tuple( + item.strip() + for item in os.getenv(name, default).split(",") + if item.strip() + ) + + +class Settings(BaseModel): + """Validated runtime configuration loaded from environment variables.""" + + app_name: str = "Project RISING API" + app_version: str = "4.0.0" + environment: Literal["development", "test", "staging", "production"] = ( + "development" + ) + log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO" + log_json: bool = True + api_key: SecretStr | None = None + require_api_key: bool = False + cors_origins: tuple[str, ...] = ("http://localhost:8501",) + trusted_hosts: tuple[str, ...] = ("localhost", "127.0.0.1", "testserver") + metrics_enabled: bool = True + max_request_body_bytes: int = Field(default=1_048_576, ge=1_024, le=10_485_760) + health_dataset: Path = PROJECT_ROOT / "data/processed/asean_health_indicators.csv" + database_url: SecretStr | None = None + database_required: bool = False + database_connect_timeout_seconds: int = Field(default=5, ge=1, le=30) + database_max_retries: int = Field(default=3, ge=0, le=10) + + @model_validator(mode="after") + def validate_secure_configuration(self) -> "Settings": + if self.require_api_key and not self.api_key: + raise ValueError("API_KEY is required when REQUIRE_API_KEY=true") + if ( + self.require_api_key + and self.api_key + and len(self.api_key.get_secret_value()) < 16 + ): + raise ValueError("API_KEY must contain at least 16 characters") + if self.database_required and not self.database_url: + raise ValueError("DATABASE_URL is required when DATABASE_REQUIRED=true") + if self.environment == "production" and "*" in self.cors_origins: + raise ValueError("Wildcard CORS origins are not allowed in production") + return self + + @classmethod + def from_environment(cls) -> "Settings": + return cls( + app_name=os.getenv("APP_NAME", "Project RISING API"), + app_version=os.getenv("APP_VERSION", "4.0.0"), + environment=os.getenv("APP_ENV", "development").lower(), + log_level=os.getenv("LOG_LEVEL", "INFO").upper(), + log_json=_boolean("LOG_JSON", True), + api_key=os.getenv("API_KEY") or None, + require_api_key=_boolean("REQUIRE_API_KEY", False), + cors_origins=_csv("CORS_ORIGINS", "http://localhost:8501"), + trusted_hosts=_csv( + "TRUSTED_HOSTS", "localhost,127.0.0.1,testserver" + ), + metrics_enabled=_boolean("METRICS_ENABLED", True), + max_request_body_bytes=int(os.getenv("MAX_REQUEST_BODY_BYTES", "1048576")), + health_dataset=Path( + os.getenv( + "HEALTH_DATASET", + str(PROJECT_ROOT / "data/processed/asean_health_indicators.csv"), + ) + ), + database_url=os.getenv("DATABASE_URL") or None, + database_required=_boolean("DATABASE_REQUIRED", False), + database_connect_timeout_seconds=int( + os.getenv("DATABASE_CONNECT_TIMEOUT_SECONDS", "5") + ), + database_max_retries=int(os.getenv("DATABASE_MAX_RETRIES", "3")), + ) + + +@lru_cache +def get_settings() -> Settings: + return Settings.from_environment() + diff --git a/config/settings.yaml b/config/settings.yaml index e69de29..19b61f5 100644 --- a/config/settings.yaml +++ b/config/settings.yaml @@ -0,0 +1,15 @@ +# Non-secret reference defaults. Runtime values come from environment variables; +# see .env.example. This file is documentation, not a second config source. +application: + name: Project RISING API + version: 4.0.0 + environment: development +observability: + log_level: INFO + json_logs: true + metrics_enabled: true +limits: + max_request_body_bytes: 1048576 +persistence: + database_required: false + diff --git a/docker-compose.yml b/docker-compose.yml index b6e7146..8edbc96 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,25 +1,46 @@ services: + api: + build: . + environment: + APP_ENV: ${APP_ENV:-development} + API_KEY: ${API_KEY:-} + REQUIRE_API_KEY: ${REQUIRE_API_KEY:-false} + CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:8501} + TRUSTED_HOSTS: ${TRUSTED_HOSTS:-localhost,127.0.0.1,api} + DATABASE_URL: postgresql+psycopg2://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB} + DATABASE_REQUIRED: ${DATABASE_REQUIRED:-false} + ports: + - "8000:8000" + depends_on: + postgres: + condition: service_healthy + read_only: true + tmpfs: + - /tmp + security_opt: + - no-new-privileges:true + restart: unless-stopped + postgres: image: postgres:16-alpine - container_name: project-rising-postgres environment: - POSTGRES_DB: project_rising - POSTGRES_USER: rising_user - POSTGRES_PASSWORD: rising_password + POSTGRES_DB: ${POSTGRES_DB} + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} ports: - - "55432:5432" + - "127.0.0.1:55432:5432" volumes: - postgres_data:/var/lib/postgresql/data - ./sql:/docker-entrypoint-initdb.d:ro healthcheck: - test: ["CMD-SHELL", "pg_isready -U rising_user -d project_rising"] + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] interval: 10s timeout: 5s retries: 5 + restart: unless-stopped redpanda: image: redpandadata/redpanda:v24.2.8 - container_name: project-rising-redpanda command: - redpanda - start @@ -36,12 +57,13 @@ services: - --kafka-addr - PLAINTEXT://0.0.0.0:9092 - --advertise-kafka-addr - - PLAINTEXT://localhost:9092 + - PLAINTEXT://redpanda:9092 ports: - - "9092:9092" - - "9644:9644" + - "127.0.0.1:9092:9092" + - "127.0.0.1:9644:9644" volumes: - redpanda_data:/var/lib/redpanda/data + restart: unless-stopped volumes: postgres_data: diff --git a/docs/operations/pilot_runbook.md b/docs/operations/pilot_runbook.md new file mode 100644 index 0000000..b36683f --- /dev/null +++ b/docs/operations/pilot_runbook.md @@ -0,0 +1,74 @@ +# Pilot Deployment Runbook + +Project RISING Phase 5 is intended for a controlled, monitored pilot. It is +not clinically validated and must not be the sole basis for patient care, +national surveillance, or emergency-response decisions. + +## Required production configuration + +Set `APP_ENV=production`, `REQUIRE_API_KEY=true`, a random `API_KEY` of at +least 16 characters, explicit HTTPS dashboard origins in `CORS_ORIGINS`, and +the externally visible host names in `TRUSTED_HOSTS`. Keep secrets in the +deployment platform's secret manager, never in git or a container image. + +`DATABASE_REQUIRED=false` is correct while the checked-in CSV remains the API's +authoritative data source. Set it to `true` only after provisioning PostgreSQL +and setting `DATABASE_URL`; `/ready` will then fail closed when PostgreSQL is +unavailable. + +## Deploy and verify + +```bash +cp .env.example .env +# Edit every placeholder secret and origin before continuing. +docker compose up --build -d api postgres +curl --fail http://localhost:8000/health +curl --fail http://localhost:8000/ready +curl --fail -H "X-API-Key: $API_KEY" http://localhost:8000/metrics +docker compose logs --tail=100 api +``` + +Use the included `render.yaml` as a Render Blueprint. Configure +`CORS_ORIGINS` and `TRUSTED_HOSTS` in Render before traffic is enabled. TLS +must terminate at the managed load balancer or reverse proxy. + +## Monitoring and alert thresholds + +Scrape `/metrics` with the API key. Alert when `/ready` returns 503 for two +consecutive checks, any 5xx rate exceeds 1% for five minutes, p95 latency +exceeds two seconds, an ETL run produces no usable datasets, or DLQ volume +increases unexpectedly. Logs are JSON and correlate on `request_id`; do not +log API keys, database URLs, raw sensitive payloads, or personal data. + +## Backup and restore + +The repository's CSV sources must be versioned or copied to immutable object +storage after each approved data release. For PostgreSQL, take encrypted daily +logical backups and test restoration at least quarterly: + +```bash +docker compose exec -T postgres pg_dump -U rising_user -d project_rising -Fc > backups/project_rising.dump +docker compose exec -T postgres pg_restore -U rising_user -d project_rising --clean --if-exists < backups/project_rising.dump +``` + +Run restore drills against an isolated database, never the active pilot. +Document recovery time, row counts, checksums, and the operator who approved +the recovery. Volume snapshots are useful but do not replace tested logical +backups. + +## Incident and rollback procedure + +1. Remove pilot traffic or scale the API to zero if confidentiality or data + integrity may be affected. +2. Preserve JSON logs, request IDs, image digest, configuration version, and + database audit evidence without copying secrets. +3. Roll back to the last tested container digest and last approved dataset. +4. Verify `/health`, `/ready`, smoke queries, data counts, and metrics before + reopening access. +5. Record impact, root cause, corrective action, and validation evidence. + +Rotate the API key immediately after exposure or staff access changes. Apply +dependency and base-image security updates through reviewed pull requests. +External penetration testing, privacy review, epidemiological validation, +high availability, disaster-recovery exercises, and country-specific legal +approval remain Phase 6 prerequisites for mission-critical use. diff --git a/main.py b/main.py index b840504..c20e5a8 100644 --- a/main.py +++ b/main.py @@ -1,113 +1,233 @@ -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware +from __future__ import annotations -from api.config import API_VERSION +import logging +import uuid +from time import perf_counter -# Original Project RISING API routes. -# These routers receive /api/v1 from main.py. -from api.routes.climate import router as climate_router -from api.routes.health import router as base_health_router -from api.routes.pipeline import router as pipeline_router -from api.routes.prediction import router as prediction_router +from fastapi import Depends, FastAPI, HTTPException, Request +from fastapi.exceptions import RequestValidationError +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse, PlainTextResponse +from starlette.middleware.trustedhost import TrustedHostMiddleware -# Phase 3 Health Intelligence routes. -# These routers already contain their own /api/v1 prefixes. +from api.config import API_VERSION +from api.logging import configure_logging +from api.observability import metrics from api.routers.health import router as health_intelligence_router from api.routers.intelligence import router as intelligence_router +from api.routers.ml import router as ml_router from api.routers.monitoring import router as monitoring_router - -# Phase 4 Operations Intelligence routes. -# This router already contains its own operations prefix. +from api.routes.climate import router as climate_router +from api.routes.health import router as base_health_router from api.routes.operations import router as operations_router - - -from api.routers.ml import router as ml_router - -app = FastAPI( - title="Project RISING", - description=( - "ASEAN health intelligence, climate resilience, disease-risk " - "analysis, operational alerting, root-cause analysis, and forecasting." - ), - version=API_VERSION, - docs_url="/docs", - redoc_url="/redoc", -) - - -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=False, - allow_methods=["*"], - allow_headers=["*"], -) - - -# ------------------------------------------------------------------- -# Original API routes -# These routers need /api/v1 added here. -# ------------------------------------------------------------------- - -app.include_router( - climate_router, - prefix="/api/v1", -) - -app.include_router( - base_health_router, - prefix="/api/v1", -) - -app.include_router( - pipeline_router, - prefix="/api/v1", -) - -app.include_router( - prediction_router, - prefix="/api/v1", -) - - -# ------------------------------------------------------------------- -# Phase 3 Health Intelligence -# Do not add another /api/v1 prefix here. -# ------------------------------------------------------------------- - -app.include_router(health_intelligence_router) -app.include_router(intelligence_router) -app.include_router(monitoring_router) - - -# ------------------------------------------------------------------- -# Phase 4 Operations Intelligence -# Do not add another prefix here. -# ------------------------------------------------------------------- - -app.include_router(operations_router) - - -# ------------------------------------------------------------------- -# System endpoints -# ------------------------------------------------------------------- - -# Phase 4B trained ML endpoints -app.include_router(ml_router) - -@app.get("/", tags=["System"]) -def root() -> dict[str, str]: - return { - "project": "Project RISING", - "status": "running", - "version": API_VERSION, - "documentation": "/docs", - } - - -@app.get("/health", tags=["System"]) -def health_check() -> dict[str, str]: - return { - "status": "healthy", - "version": API_VERSION, - } \ No newline at end of file +from api.routes.pipeline import router as pipeline_router +from api.routes.prediction import router as prediction_router +from api.security import verify_api_key +from config.config import Settings, get_settings +from warehouse.db import check_database + + +logger = logging.getLogger("rising.api") + + +def create_app(settings: Settings | None = None) -> FastAPI: + """Create the complete Phase 4 intelligence API with Phase 5 controls.""" + runtime = settings or get_settings() + configure_logging(runtime.log_level, runtime.log_json) + + application = FastAPI( + title="Project RISING", + description=( + "Pilot-grade ASEAN health intelligence, climate resilience, " + "disease-risk analysis, operational alerting, root-cause analysis, " + "and forecasting. Not a clinical decision system." + ), + version=API_VERSION, + docs_url="/docs", + redoc_url="/redoc", + ) + + application.state.settings = runtime + application.add_middleware( + TrustedHostMiddleware, + allowed_hosts=list(runtime.trusted_hosts), + ) + application.add_middleware( + CORSMiddleware, + allow_origins=list(runtime.cors_origins), + allow_credentials=False, + allow_methods=["GET", "POST", "PATCH"], + allow_headers=["Accept", "Content-Type", "X-API-Key", "X-Request-ID"], + ) + + @application.middleware("http") + async def request_controls(request: Request, call_next): + request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4()) + request.state.request_id = request_id + started = perf_counter() + content_length = request.headers.get("content-length") + + if content_length: + try: + oversized = int(content_length) > runtime.max_request_body_bytes + except ValueError: + oversized = True + if oversized: + return JSONResponse( + status_code=413, + content={ + "error": "payload_too_large", + "message": "Request body exceeds the configured limit", + "request_id": request_id, + }, + ) + + if request.method in {"POST", "PUT", "PATCH"}: + body = await request.body() + if len(body) > runtime.max_request_body_bytes: + return JSONResponse( + status_code=413, + content={ + "error": "payload_too_large", + "message": "Request body exceeds the configured limit", + "request_id": request_id, + }, + ) + + response = await call_next(request) + duration = perf_counter() - started + metrics.observe(request.method, request.url.path, response.status_code, duration) + response.headers["X-Request-ID"] = request_id + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["X-Frame-Options"] = "DENY" + response.headers["Referrer-Policy"] = "no-referrer" + response.headers["Cache-Control"] = "no-store" + if runtime.environment == "production": + response.headers["Strict-Transport-Security"] = "max-age=31536000" + logger.info( + "request_completed", + extra={ + "request_id": request_id, + "method": request.method, + "path": request.url.path, + "status_code": response.status_code, + "duration_ms": round(duration * 1000, 2), + "environment": runtime.environment, + }, + ) + return response + + @application.exception_handler(RequestValidationError) + async def validation_error(request: Request, exc: RequestValidationError): + return JSONResponse( + status_code=422, + content={ + "error": "validation_error", + "message": "Request validation failed", + "details": exc.errors(), + "request_id": getattr(request.state, "request_id", None), + }, + ) + + @application.exception_handler(HTTPException) + async def http_error(request: Request, exc: HTTPException): + return JSONResponse( + status_code=exc.status_code, + content={ + "error": "http_error", + "message": exc.detail, + "request_id": getattr(request.state, "request_id", None), + }, + headers=exc.headers, + ) + + @application.exception_handler(Exception) + async def unhandled_error(request: Request, exc: Exception): + logger.exception( + "unhandled_request_error", + extra={"request_id": getattr(request.state, "request_id", None)}, + ) + return JSONResponse( + status_code=500, + content={ + "error": "internal_server_error", + "message": "An unexpected error occurred", + "request_id": getattr(request.state, "request_id", None), + }, + ) + + # Original routes receive their version prefix here. They are registered + # first to preserve their established payloads and Phase 5 API-key gates. + application.include_router(climate_router, prefix="/api/v1") + application.include_router(base_health_router, prefix="/api/v1") + application.include_router(pipeline_router, prefix="/api/v1") + application.include_router(prediction_router, prefix="/api/v1") + + # Phase 3 routers already include /api/v1. + application.include_router(health_intelligence_router) + application.include_router(intelligence_router) + application.include_router(monitoring_router) + + # Phase 4 operations declares /operations; Phase 4B ML includes /api/v1/ml. + application.include_router(operations_router, prefix="/api/v1") + application.include_router(ml_router) + + @application.get("/", tags=["System"]) + def root() -> dict[str, str]: + return { + "project": "Project RISING", + "status": "running", + "version": API_VERSION, + "maturity": "production-ready pilot", + "description": "Climate-resilient healthcare decision-support platform", + "documentation": "/docs", + "docs": "/docs", + } + + @application.get("/health", tags=["System"]) + def health() -> dict[str, str]: + """Liveness probe: the API process can serve requests.""" + return { + "status": "healthy", + "service": runtime.app_name, + "version": API_VERSION, + } + + @application.get("/ready", tags=["System"]) + def readiness(): + """Readiness probe: required data and configured dependencies work.""" + database_check = ( + check_database( + required=runtime.database_required, + database_url=runtime.database_url.get_secret_value(), + ) + if runtime.database_url + else { + "status": "fail" if runtime.database_required else "not_configured", + "required": runtime.database_required, + } + ) + checks = { + "health_dataset": { + "status": "pass" if runtime.health_dataset.is_file() else "fail", + "required": True, + }, + "database": database_check, + } + ready = all( + check["status"] in {"pass", "not_configured"} + for check in checks.values() + ) + payload = {"status": "ready" if ready else "not_ready", "checks": checks} + return JSONResponse(status_code=200 if ready else 503, content=payload) + + @application.get("/metrics", tags=["System"]) + def prometheus_metrics(_: None = Depends(verify_api_key)): + if not runtime.metrics_enabled: + raise HTTPException(status_code=404, detail="Metrics are disabled") + return PlainTextResponse(metrics.render(), media_type="text/plain; version=0.0.4") + + return application + + +app = create_app() diff --git a/pipelines/load.py b/pipelines/load.py index 30a1668..0489120 100644 --- a/pipelines/load.py +++ b/pipelines/load.py @@ -1,4 +1,6 @@ from pathlib import Path +import os +import tempfile import pandas as pd @@ -17,15 +19,22 @@ def load_processed_csv( exist_ok=True, ) - dataframe.to_csv( - path, - index=False, - encoding="utf-8", + # Write beside the destination, then atomically replace it. A failed ETL + # therefore cannot leave the API serving a partially written CSV. + file_descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".tmp", dir=path.parent ) + os.close(file_descriptor) + temporary_path = Path(temporary_name) + try: + dataframe.to_csv(temporary_path, index=False, encoding="utf-8") + temporary_path.replace(path) + finally: + temporary_path.unlink(missing_ok=True) print( f"Loaded {len(dataframe)} records " f"into {path}" ) - return path \ No newline at end of file + return path diff --git a/render.yaml b/render.yaml new file mode 100644 index 0000000..df9dcf1 --- /dev/null +++ b/render.yaml @@ -0,0 +1,22 @@ +services: + - type: web + name: project-rising-api + runtime: docker + dockerfilePath: ./Dockerfile + healthCheckPath: /ready + autoDeployTrigger: checksPass + envVars: + - key: APP_ENV + value: production + - key: LOG_JSON + value: "true" + - key: REQUIRE_API_KEY + value: "true" + - key: API_KEY + generateValue: true + - key: CORS_ORIGINS + sync: false + - key: TRUSTED_HOSTS + sync: false + - key: DATABASE_REQUIRED + value: "false" diff --git a/tests/test_production_hardening.py b/tests/test_production_hardening.py new file mode 100644 index 0000000..d28736c --- /dev/null +++ b/tests/test_production_hardening.py @@ -0,0 +1,88 @@ +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from config.config import Settings, get_settings +from main import create_app + + +def test_production_configuration_rejects_insecure_values() -> None: + with pytest.raises(ValidationError): + Settings(environment="production", cors_origins=("*",)) + + with pytest.raises(ValidationError): + Settings(require_api_key=True, api_key="short") + + +def test_readiness_reports_missing_required_dataset(tmp_path: Path) -> None: + application = create_app( + Settings(environment="test", health_dataset=tmp_path / "missing.csv") + ) + response = TestClient(application).get("/ready") + + assert response.status_code == 503 + assert response.json()["status"] == "not_ready" + assert response.json()["checks"]["health_dataset"]["status"] == "fail" + + +def test_security_headers_and_request_id_are_returned() -> None: + response = TestClient(create_app(Settings(environment="test"))).get( + "/health", headers={"X-Request-ID": "test-request-123"} + ) + + assert response.status_code == 200 + assert response.headers["x-request-id"] == "test-request-123" + assert response.headers["x-content-type-options"] == "nosniff" + assert response.headers["x-frame-options"] == "DENY" + + +def test_oversized_request_is_rejected() -> None: + client = TestClient( + create_app(Settings(environment="test", max_request_body_bytes=1024)) + ) + response = client.post( + "/api/v1/disease-risk/predict", + content=b"x" * 1025, + headers={"content-type": "application/json"}, + ) + + assert response.status_code == 413 + assert response.json()["error"] == "payload_too_large" + + +def test_api_key_protects_prediction_and_metrics(monkeypatch) -> None: + monkeypatch.setenv("APP_ENV", "test") + monkeypatch.setenv("REQUIRE_API_KEY", "true") + monkeypatch.setenv("API_KEY", "pilot-secret-key-123456") + get_settings.cache_clear() + try: + client = TestClient(create_app(get_settings())) + assert client.get("/metrics").status_code == 401 + assert client.post("/api/v1/disease-risk/predict", json={}).status_code == 401 + response = client.get( + "/metrics", headers={"X-API-Key": "pilot-secret-key-123456"} + ) + assert response.status_code == 200 + assert "rising_http_requests_total" in response.text + finally: + get_settings.cache_clear() + + +def test_validation_error_has_stable_error_envelope() -> None: + response = TestClient(create_app(Settings(environment="test"))).post( + "/api/v1/disease-risk/predict", + json={ + "country": "Philippines", + "disease": "dengue", + "temperature_c": 29, + "rainfall_mm": -1, + "humidity_pct": 85, + "unexpected": "rejected", + }, + ) + + assert response.status_code == 422 + assert response.json()["error"] == "validation_error" + assert response.json()["request_id"] diff --git a/warehouse/db.py b/warehouse/db.py index 8460be6..a48189b 100644 --- a/warehouse/db.py +++ b/warehouse/db.py @@ -1,33 +1,52 @@ from __future__ import annotations -import os +from sqlalchemy import Engine, create_engine, text +from sqlalchemy.exc import SQLAlchemyError -from sqlalchemy import Engine, create_engine - - -DEFAULT_DATABASE_URL = ( - "postgresql+psycopg2://" - "rising_user:rising_password@127.0.0.1:55432/project_rising" -) +from config.config import get_settings def get_database_url() -> str: - """ - Read the warehouse database URL from the environment. - """ - return os.getenv( - "DATABASE_URL", - DEFAULT_DATABASE_URL, + """Return the configured URL without embedding development credentials.""" + configured = get_settings().database_url + if configured is None: + raise RuntimeError("DATABASE_URL is not configured") + return configured.get_secret_value() + + +def get_engine(database_url: str | None = None) -> Engine: + settings = get_settings() + url = database_url or get_database_url() + connect_args = {} + if url.startswith("postgresql"): + connect_args["connect_timeout"] = settings.database_connect_timeout_seconds + return create_engine( + url, + pool_pre_ping=True, + pool_recycle=1800, + connect_args=connect_args, ) -def get_engine( +def check_database( + required: bool = False, database_url: str | None = None, -) -> Engine: - """ - Build a SQLAlchemy engine for the warehouse. - """ - return create_engine( - database_url or get_database_url(), - pool_pre_ping=True, +) -> dict[str, object]: + """Check the optional database without exposing connection details.""" + settings = get_settings() + configured_url = database_url or ( + settings.database_url.get_secret_value() if settings.database_url else None ) + if configured_url is None: + return { + "status": "fail" if required else "not_configured", + "required": required, + } + try: + engine = get_engine(configured_url) + with engine.connect() as connection: + connection.execute(text("SELECT 1")) + engine.dispose() + return {"status": "pass", "required": required} + except SQLAlchemyError: + return {"status": "fail", "required": required} diff --git a/warehouse/weather_loader.py b/warehouse/weather_loader.py index 6dab0d9..999aba6 100644 --- a/warehouse/weather_loader.py +++ b/warehouse/weather_loader.py @@ -1,12 +1,15 @@ from __future__ import annotations import json +import time from datetime import datetime from pathlib import Path from sqlalchemy import Engine, text from sqlalchemy.exc import OperationalError +from config.config import get_settings + from warehouse.db import get_engine @@ -278,25 +281,22 @@ def load_weather_events_jsonl( "duplicates": 0, } - try: - with warehouse_engine.begin() as connection: - for event in events: - inserted = load_weather_event( - connection=connection, - event=event, - ) - - if inserted: - counts["inserted"] += 1 - else: - counts["duplicates"] += 1 - except OperationalError as exc: - raise RuntimeError( - "Could not connect to the PostgreSQL warehouse. " - "Confirm Docker Postgres is running and that DATABASE_URL matches " - "the credentials in docker-compose.yml. If the Docker volume was " - "created with old credentials, recreate it with: " - "docker compose down -v; docker compose up -d postgres" - ) from exc + max_retries = get_settings().database_max_retries + for attempt in range(max_retries + 1): + try: + with warehouse_engine.begin() as connection: + for event in events: + inserted = load_weather_event(connection=connection, event=event) + counts["inserted" if inserted else "duplicates"] += 1 + break + except OperationalError as exc: + counts["inserted"] = 0 + counts["duplicates"] = 0 + if attempt >= max_retries: + raise RuntimeError( + "Could not connect to the PostgreSQL warehouse after retries. " + "Confirm the service is healthy and DATABASE_URL is correct." + ) from exc + time.sleep(min(2**attempt, 8)) return counts