Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions bases/lif/control_plane_restapi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# `control_plane_restapi` — Base

FastAPI base for the LIF **control plane** (EPIC #1041, ADR 0002 and ADR 0006): the service that will own developer keys, and later identity and admin, outside MDR.

So far it's the service and its own database, without the key endpoints (#1182). The developer-key table and endpoints wait on #1190.

## Endpoints

| Path | Auth | What it does |
|---|---|---|
| `/health-check` | public | `200 {"status": "ok"}` when the control plane's database answers `SELECT 1`, otherwise `503` |
| `/docs`, `/openapi.json` | public | FastAPI docs |

## Auth
Cognito JWTs only, through `lif.auth`'s `AuthMiddleware` with `cognito_strategy` (configured with `CONTROL_PLANE_AUTH__USER_POOL_ID` / `__REGION` / `__CLIENT_ID`). **It fails closed:** if the user pool or the client ID isn't configured, the middleware has no strategies, so every non-public path returns `401`. The service never tries to verify a token against an empty pool, and never accepts one without checking its client ID (with no client ID, `decode_cognito_jwt` would accept a token from any app client in the pool).

## Config
- `CONTROL_PLANE__DATABASE_URL` (required): an async SQLAlchemy URL, e.g. `postgresql+asyncpg://user:pass@host:5432/db`. Startup fails, naming the variable, if it's missing (#1179).
- `CONTROL_PLANE_AUTH__*`: see Auth.

Nothing from the MDR domain is imported or configured.

## Composes
- `auth` — `AuthMiddleware` and the Cognito strategy (`lif.auth.cognito`)
- `logging` — `get_logger`

## Deployed as
`projects/lif_control_plane_api/` (API, port 8014) + `projects/lif_control_plane_database/` (its migrations). Local compose only for now; the dev/demo deploy is the AWS half of #1182.
3 changes: 3 additions & 0 deletions bases/lif/control_plane_restapi/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from lif.control_plane_restapi import core

__all__ = ["core"]
69 changes: 69 additions & 0 deletions bases/lif/control_plane_restapi/core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""LIF control-plane API (EPIC #1041, ADR 0002 / ADR 0006).

The service and its own database, without the developer-key endpoints yet (#1182). The key table
waits on the workspace and owner questions in #1190.

Config: ``CONTROL_PLANE__DATABASE_URL`` (required) and Cognito via ``CONTROL_PLANE_AUTH__*``
(``lif.auth.cognito``). Nothing from the MDR domain is imported or configured here.
"""

import os

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine

from lif.auth import AuthMiddleware
from lif.auth.cognito import CognitoAuthConfig, cognito_strategy
from lif.logging import get_logger

logger = get_logger(__name__)

DATABASE_URL_VAR = "CONTROL_PLANE__DATABASE_URL"


def require_env(name: str) -> str:
"""Return a required setting, failing fast with the variable's name if it is missing (#1179)."""
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"{name} is not set; the control-plane API cannot start without it")
return value


def create_app(engine: AsyncEngine, cognito_config: CognitoAuthConfig) -> FastAPI:
app = FastAPI(title="LIF Control Plane API", description="LIF control-plane service", version="0.1.0")

# Fail closed: without a user pool nobody can be authenticated, and without a client ID
# decode_cognito_jwt skips the aud/client_id check, so a token from any app client in the pool
# would pass. Either way there are no strategies, so every non-public path is refused. An empty
# pool is never handed to cognito_strategy, which would try to fetch JWKS for it on every
# request that carries a token.
missing = [
name
for name, value in (("USER_POOL_ID", cognito_config.user_pool_id), ("CLIENT_ID", cognito_config.client_id))
if not value
]
if missing:
unset = ", ".join(f"CONTROL_PLANE_AUTH__{name}" for name in missing)
logger.warning(f"Cognito auth NOT configured ({unset} unset): non-public paths return 401")
strategies = [] if missing else [cognito_strategy(cognito_config)]
app.add_middleware(AuthMiddleware, strategies=strategies)

@app.get("/health-check")
async def health_check():
"""Healthy only when the control plane's own database answers."""
try:
async with engine.connect() as conn:
await conn.execute(text("SELECT 1"))
except Exception:
logger.exception("Control-plane database is unreachable")
return JSONResponse(status_code=503, content={"status": "unavailable"})
return {"status": "ok"}

return app


app = create_app(
create_async_engine(require_env(DATABASE_URL_VAR)), CognitoAuthConfig.from_environment(prefix="CONTROL_PLANE_AUTH")
)
43 changes: 43 additions & 0 deletions deployments/advisor-demo-docker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,48 @@ services:
depends_on:
- lif-advisor-api

lif-control-plane-database:
image: postgres
command: postgres
environment:
POSTGRES_USER: ${LIF_CONTROL_PLANE__DATABASE__USER:-control_plane}
POSTGRES_PASSWORD: ${LIF_CONTROL_PLANE__DATABASE__PASSWORD:-control_plane}
POSTGRES_DB: ${LIF_CONTROL_PLANE__DATABASE__DBNAME:-control_plane}
volumes:
- ../../projects/lif_control_plane_database/migrations:/docker-entrypoint-initdb.d:ro
networks:
- lif-net-control-plane-db
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10

lif-control-plane-api:
build:
context: ../../
dockerfile: projects/lif_control_plane_api/Dockerfile2
container_name: lif-control-plane-api
environment:
CONTROL_PLANE__DATABASE_URL: postgresql+asyncpg://${LIF_CONTROL_PLANE__DATABASE__USER:-control_plane}:${LIF_CONTROL_PLANE__DATABASE__PASSWORD:-control_plane}@lif-control-plane-database:5432/${LIF_CONTROL_PLANE__DATABASE__DBNAME:-control_plane}
CONTROL_PLANE_AUTH__USER_POOL_ID: ${CONTROL_PLANE_AUTH__USER_POOL_ID:-}
CONTROL_PLANE_AUTH__REGION: ${CONTROL_PLANE_AUTH__REGION:-us-east-1}
CONTROL_PLANE_AUTH__CLIENT_ID: ${CONTROL_PLANE_AUTH__CLIENT_ID:-}
ports:
- "8014:8014"
depends_on:
lif-control-plane-database:
condition: service_healthy
networks:
- lif-net-org1
- lif-net-control-plane-db
healthcheck:
test: ["CMD", "python", "-c", "import sys,urllib.request; sys.exit(0) if urllib.request.urlopen('http://localhost:8014/health-check').status==200 else sys.exit(1)"]
interval: 15s
timeout: 10s
retries: 3
start_period: 10s

lif-mdr-database:
image: postgres
command: postgres
Expand Down Expand Up @@ -718,6 +760,7 @@ networks:
lif-net-org2:
lif-net-org3:
lif-net-mdr-db:
lif-net-control-plane-db:

# ----------- VOLUMES -----------

Expand Down
1 change: 1 addition & 0 deletions projects/lif_control_plane_api/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.venv
2 changes: 2 additions & 0 deletions projects/lif_control_plane_api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
requirements.txt
18 changes: 18 additions & 0 deletions projects/lif_control_plane_api/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM python:3.13-slim

ARG wheel=lif_control_plane_api-0.1.0-py3-none-any.whl

ARG deps=requirements.txt

RUN python -m pip install --upgrade pip

WORKDIR /code

COPY ./dist/$wheel /code/$wheel
COPY ./$deps /code/$deps

# This is adjusted to install third-party dependencies separately (the --no-deps) and install from requirements
RUN pip install --no-cache-dir --upgrade --no-deps /code/$wheel
RUN pip install -r /code/$deps

CMD ["uvicorn", "lif.control_plane_restapi.core:app", "--host", "0.0.0.0", "--port", "8014"]
52 changes: 52 additions & 0 deletions projects/lif_control_plane_api/Dockerfile2
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Stage 1: Builder stage
FROM python:3.13-slim AS builder

# Build arguments for project configuration
ARG PROJECT_NAME=lif_control_plane_api

# Install uv
RUN pip install --no-cache-dir uv

# Set UV environment variables for optimal caching and behavior
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy

# Set working directory in the container
WORKDIR /code

# Copy the entire monorepo structure needed for polylith
COPY projects/${PROJECT_NAME}/ /code/projects/${PROJECT_NAME}/
COPY bases/ /code/bases/
COPY components/ /code/components/

# Change to the specific project directory
WORKDIR /code/projects/${PROJECT_NAME}

# Sync dependencies and build the project wheel
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync --locked --no-dev && \
uv export --locked --no-dev --no-emit-project --no-hashes -o /code/constraints.txt && \
uv build --wheel

# Stage 2: Final runtime image
FROM python:3.13-slim AS runtime

# Inherit build arguments in runtime stage
ARG PROJECT_NAME=lif_control_plane_api

# Install uv in runtime for faster package installation
RUN pip install --no-cache-dir uv

# Copy the built wheel from the builder stage
COPY --from=builder /code/projects/${PROJECT_NAME}/dist/*.whl /tmp/
COPY --from=builder /code/constraints.txt /tmp/constraints.txt

# Install the wheel in the final image, pinned to the versions in uv.lock
RUN uv pip install --system --constraint /tmp/constraints.txt /tmp/*.whl && \
rm /tmp/*.whl /tmp/constraints.txt

# Set working directory
WORKDIR /code

# Use uvicorn to run the FastAPI application
CMD ["uvicorn", "lif.control_plane_restapi.core:app", "--host", "0.0.0.0", "--port", "8014"]
41 changes: 41 additions & 0 deletions projects/lif_control_plane_api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Control Plane API

The **Control Plane API** is the LIF service that will own developer keys, and later identity and admin, outside MDR (EPIC #1041). So far it's the service and its own database, with a health check and Cognito auth; the key endpoints come next (#1182, #1190). See [`bases/lif/control_plane_restapi/README.md`](../../bases/lif/control_plane_restapi/README.md).

# Example usage

## Build the project
Navigate to this folder (where the `pyproject.toml` file is)

1. Export the dependencies from the project lock:
``` shell
uv export --frozen --no-emit-project --output-file requirements.txt
```

2. Build a wheel:
``` shell
uv build --out-dir ./dist
```

## Build a docker image from root

``` shell
./build-docker.sh
```

## Run it with its database (local compose)

``` shell
cd deployments/advisor-demo-docker
docker compose up -d lif-control-plane-api # also starts lif-control-plane-database
```

## Example calls

``` shell
curl http://localhost:8014/health-check
# {"status":"ok"} (503 {"status":"unavailable"} if the database is down)

curl -H "Authorization: Bearer <token>" http://localhost:8014/anything
# 401 {"detail":"Cognito auth is not configured"} without CONTROL_PLANE_AUTH__USER_POOL_ID
```
15 changes: 15 additions & 0 deletions projects/lif_control_plane_api/build-docker.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

set -e

# Configuration
IMAGE_TAG=${1:-lif-control-plane-api}
PROJ_DIR=${2:-lif_control_plane_api}

# Change to repo root
cd "$(dirname "$0")/../.."

echo "Building ${IMAGE_TAG} from repo root..."
docker build -f projects/${PROJ_DIR}/Dockerfile2 -t ${IMAGE_TAG} .

echo "Build complete!"
3 changes: 3 additions & 0 deletions projects/lif_control_plane_api/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/bash
uv export --frozen --no-emit-project --output-file requirements.txt
uv build --out-dir ./dist
29 changes: 29 additions & 0 deletions projects/lif_control_plane_api/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[build-system]
requires = ["hatchling", "hatch-polylith-bricks"]
build-backend = "hatchling.build"

[project]
name = "lif_control_plane_api"
version = "0.1.0"

requires-python = ">=3.13,<3.14"

dependencies = [
"asyncpg~=0.30",
"fastapi~=0.115",
"pyjwt[crypto]~=2.10",
"sqlalchemy[asyncio]~=2.0.0",
"uvicorn~=0.34",
]

# This section is needed for the Hatchling build backend, to activate the polylith build hook.
[tool.hatch.build.hooks.polylith-bricks]

# This section is needed for building
[tool.hatch.build.targets.wheel]
packages = ["lif"]

[tool.polylith.bricks]
"../../bases/lif/control_plane_restapi" = "lif/control_plane_restapi"
"../../components/lif/auth" = "lif/auth"
"../../components/lif/logging" = "lif/logging"
Loading
Loading