Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
1fc3102
fix(deps): move httpx to main dependencies (required by app/auth.py)
raylim Jun 12, 2026
7c501bd
feat(annotation): Dockerfile volume, config settings, CORS, router wi…
raylim Jun 12, 2026
067d988
feat(annotation): add annotation CRUD router and Keycloak JWT auth
raylim Jun 12, 2026
5c7c518
fix: add aiosqlite, python-jose, rsa, ecdsa to uv.lock
raylim Jun 14, 2026
d824805
Wire annotations to Lakebase
raylim Jun 26, 2026
a84278b
Configure Lakebase annotation DSN
raylim Jun 26, 2026
4ba6866
Add Lakebase annotation bundle
raylim Jun 26, 2026
654635b
Add OncoKB proxy endpoints for WSI viewer
raylim Jul 7, 2026
25db43e
feat(annotations): accept scoped WSI capabilities
raylim Jul 23, 2026
cda00d4
test(annotations): cover CRUD and concurrency
raylim Aug 28, 2026
b76751f
security(annotations): require scoped capabilities
raylim Aug 28, 2026
db39b82
security(deps): remove vulnerable unused JWT client
raylim Aug 28, 2026
4ea15c7
feat(annotations): pool Lakebase connections and migrate schema
raylim Sep 21, 2026
85bdd79
Fix duplicate annotation compose settings
raylim Aug 31, 2026
1f71752
ci(tile-server): publish immutable manual build tags
raylim Sep 21, 2026
b77ba4d
feat(wsi): v3 slide capabilities with encrypted sources
raylim Oct 3, 2026
75dce4f
refactor(wsi): leave accession policy to the data provider
raylim Oct 5, 2026
ef8184c
feat(wsi): open sealed sources with WSI_SOURCE_SEAL_KEY (v4 capabilit…
raylim Oct 8, 2026
29bd512
feat(deid): validate data_wsi.txt format v4 rows
raylim Oct 8, 2026
4ed0200
deid: check timeline links by parameter, allowing opaque keys
raylim Oct 8, 2026
4e71588
security: bump fsspec, s3fs and multidict past known CVEs
raylim Oct 9, 2026
899a2a4
refactor(auth): decode the seal key once at startup; drop unreachable…
raylim Oct 9, 2026
defa854
refactor(deid): drop unused validate_artifact_uri params and duplicat…
raylim Oct 9, 2026
d94af08
refactor(auth): share sealed-source shape and base64url decoding with…
raylim Oct 9, 2026
44a4c02
test: collapse duplicated capability, source-binding and readiness tests
raylim Oct 9, 2026
9c7d923
Merge #44 (wsi-serving-v6) into the annotation service
raylim Oct 9, 2026
3b8142d
refactor(slides): delete unused _resolve_s3_location
raylim Oct 13, 2026
6802798
refactor(deid): drop the slideKey LINKOUT exemption
raylim Oct 13, 2026
9d57a7d
test: drop duplicate and default-only source, capability and config t…
raylim Oct 13, 2026
84da53b
refactor(ready): check the seal key decoded at startup
raylim Oct 13, 2026
810ec2f
docs(slide_store): the source URI comes from the sealed capability
raylim Oct 13, 2026
897e6c1
Merge codex/wsi-deid-slide-key-v3 (#44) 810ec2f into feature/wsi-nati…
raylim Oct 13, 2026
d3537b6
Merge origin/main into the native annotation backend
raylim Nov 3, 2026
398bb92
Update locked dependencies with published security fixes
raylim Nov 3, 2026
54cff49
Merge main into feature/wsi-native-annotation-backend
raylim Nov 12, 2026
129736e
Serve annotations from a companion app behind the proxy's identity
raylim Nov 12, 2026
c7774c6
Log in to Lakebase with a refreshed OAuth credential
raylim Nov 12, 2026
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
5 changes: 3 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ ENV PATH="/app/.venv/bin:$PATH"

RUN groupadd --gid 1000 appuser \
&& useradd --uid 1000 --gid 1000 --no-create-home --shell /bin/false appuser
# A fresh named volume mounted at this path inherits this ownership.
RUN mkdir -p /cache/slide-blocks /cache/prometheus && chown -R appuser:appuser /cache
# Fresh named volumes mounted at these paths inherit this ownership.
RUN mkdir -p /cache/slide-blocks /cache/prometheus /data \
&& chown -R appuser:appuser /cache /data
ENV PROMETHEUS_MULTIPROC_DIR=/cache/prometheus
USER appuser

Expand Down
213 changes: 208 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ cBioPortal frontend.
At MSK, cBioPortal uses this service to show H&E and IHC whole-slide images
alongside the patients and samples they were taken from.

The service only handles pixels. It does not know about patients, samples,
studies, slide hierarchy, or image IDs; cBioPortal owns that metadata, and
the ingress in front of this service authorizes every request against
cBioPortal (see [Request flow](#request-flow)).
The pixel service only handles pixels. It does not know about patients,
samples, studies, slide hierarchy, or image IDs; cBioPortal owns that
metadata, and the ingress in front of this service authorizes every request
against cBioPortal (see [Request flow](#request-flow)). Slide annotations run
as a separate application from the same image (see
[Companion service](#companion-service)).

## What it serves

Expand Down Expand Up @@ -365,6 +367,205 @@ This example caches nothing. To cache, add `proxy_cache` to the auth
location with `proxy_cache_key "$cookie_SESSION$http_authorization$wsi_study";`
and a short `proxy_cache_valid 200 30s;`, for the reason above.

## Companion service

The same image also runs a second, separate application, `app.companion`,
which serves slide annotations. The pixel application (`app.main`) serves
none of its routes.

| Application | Command | Routes |
|-------------|---------|--------|
| Pixels | `gunicorn -c python:app.gunicorn_conf app.main:app` (the image's default `CMD`) | `/tiles`, `/thumbnails`, `/health`, `/ready`, `/metrics` |
| Companion | `gunicorn -c python:app.gunicorn_conf app.companion:app` | `/annotations`, `/health`, `/ready` |

Both serve the same routes under `/wsi` as well. Run them as separate
deployments: override the container command for the companion.

### Identity from the proxy

The companion does not authenticate anyone itself. It trusts two request
headers that an authenticating reverse proxy sets:

1. For every companion request, the proxy makes an auth subrequest to the
portal's `GET /api/studies/{studyId}/access`, carrying the browser's
`Cookie` (and `Authorization`, if sent). `{studyId}` comes from the
request's `studyId` query parameter. The portal answers:
- `204` with `X-Auth-Request-User` (the signed-in user; absent when the
portal runs without login) and `X-Auth-Request-Study`;
- `401` when not signed in;
- `403` when the user may not read the study, or the study is unknown.
2. On `2xx`, the proxy copies `X-Auth-Request-User` and
`X-Auth-Request-Study` from the auth response onto the forwarded request,
**replacing any copy the client sent**. With ingress-nginx
`auth-response-headers` and nginx `auth_request_set` + `proxy_set_header`,
a header the portal did not return is sent empty, which drops the
client's copy too.

The companion then requires, on every route:

- `X-Auth-Request-Study` present and well formed, else `401`;
- `studyId` in the query string exactly once (names matched
case-insensitively, as nginx does) and equal to `X-Auth-Request-Study`,
else `403`;
- any study the request body names, and the stored row's study for an update
or delete, equal to `X-Auth-Request-Study`, else `403`;
- `X-Auth-Request-User` present, else `401`. Only when
`ANNOTATION_ALLOW_ANONYMOUS=true` (development stacks whose portal has no
login) does a request without it act as `ANNOTATION_ANONYMOUS_USER`.

An annotation's `created_by` is `X-Auth-Request-User`, and only that user may
update or delete it.

**Trusted-proxy requirement.** Anyone who can reach the companion without
going through that proxy can claim any user. Deploy it:

- on the pod network, never `hostNetwork`;
- behind a Service that a NetworkPolicy opens to the ingress controller's
namespace only (no other namespaces, no node ports);
- with no Ingress rule that reaches it without the auth subrequest. Probe
routes (`/health`, `/ready`) read no identity and may be routed without
auth.

A client that holds another credential the portal accepts in the auth
subrequest (HTTP basic, a data-access token) can use the companion as that
user; that is the portal's own authorization.

### Browser request rules

The portal's session cookie authorizes companion requests, so unsafe methods
(`POST`, `PUT`, `PATCH`, `DELETE`) must also:

- send `X-Requested-With: XMLHttpRequest`, else `403`;
- send `Content-Type: application/json` when there is a body, else `415`;
- send no `Origin`, or one that is the request's own host or is listed in
`COMPANION_ALLOWED_ORIGINS`, else `403`.

The companion sends no CORS headers, so a page on another site cannot send
the custom header. Request bodies are capped at `COMPANION_MAX_BODY_BYTES`
(`413` above it), and every response is `Cache-Control: private, no-store`.

### Companion routes

Every route except `/health` and `/ready` takes `?studyId=<study>`.

| Method | Path | Description |
|--------|------|-------------|
| GET | `/annotations?studyId=&slide_id=` | The slide's annotations in the study that the user may see |
| POST | `/annotations?studyId=` | Create; the body's `study_id` must be `studyId` |
| PUT | `/annotations/{id}?studyId=` | Update (creator only; `version` is an optimistic lock) |
| DELETE | `/annotations/{id}?studyId=` | Delete (creator only) |
| GET | `/health` | Liveness |
| GET | `/ready` | Readiness: annotation storage reachable |

### Companion configuration

| Variable | Default | Purpose |
|----------|---------|---------|
| `ANNOTATION_DATABASE_URL` | — | Postgres/Lakebase DSN; SQLite at `ANNOTATION_DB_PATH` when unset |
| `ANNOTATION_DB_PATH` | `/data/annotations.db` | SQLite path |
| `ANNOTATION_DB_POOL_MIN_SIZE` / `ANNOTATION_DB_POOL_MAX_SIZE` | `1` / `8` | Postgres pool size per worker |
| `ANNOTATION_DB_COMMAND_TIMEOUT` | `30` | Postgres statement timeout, seconds |
| `ANNOTATION_DB_MAX_INACTIVE_CONNECTION_LIFETIME` | `300` | Close a pooled Postgres connection idle this many seconds |
| `ANNOTATION_DB_MAX_CONNECTION_AGE_SECONDS` | `1800` | Replace every pooled connection once the pool's connections are this old (`0` = never); keep it below the credential lifetime |
| `ANNOTATION_DATABASE_PASSWORD_PROVIDER` | — | `databricks`: log in with a Lakebase database credential (an OAuth token, about 1 h) fetched for each new connection instead of the DSN's password |
| `ANNOTATION_LAKEBASE_INSTANCE` | — | Lakebase database instance name(s), comma-separated, for that credential |
| `DATABRICKS_HOST`, `DATABRICKS_CLIENT_ID`, `DATABRICKS_CLIENT_SECRET` | — | Workspace and service principal that request the credential (OAuth machine-to-machine); `DATABRICKS_TOKEN` instead of the client pair is accepted |
| `ANNOTATION_ALLOW_ANONYMOUS` | `false` | Development only: accept requests without `X-Auth-Request-User` |
| `ANNOTATION_ANONYMOUS_USER` | `anonymous` | The user those requests act as |
| `COMPANION_ALLOWED_ORIGINS` | — | Comma-separated origins, besides the request's own host, allowed to send unsafe requests |
| `COMPANION_MAX_BODY_BYTES` | `4194304` | Largest accepted request body |
| `N_WORKERS` | `4` | Gunicorn workers; use `1` for the first start on an empty SQLite database |

The companion needs none of the pixel settings (seal key, object storage,
Redis).

With the Lakebase provider, `ANNOTATION_DATABASE_URL` names the host,
database and the service principal's Postgres role (its client ID) with no
password, for example
`postgresql://<client-id>@<instance-host>:5432/<database>?sslmode=require`.
The credential is generated through the workspace REST API
(`POST /api/2.0/database/credentials`) and cached until five minutes before it
expires; neither it nor the client secret is logged.

### ingress-nginx

The `$wsi_study` map from [Ingress](#ingress) matches `studyId` on any path,
so the companion Ingress uses it unchanged:

```yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: wsi-companion
annotations:
nginx.ingress.kubernetes.io/auth-url: "http://cbioportal.<namespace>.svc.cluster.local:8080/api/studies/$wsi_study/access"
nginx.ingress.kubernetes.io/auth-method: GET
nginx.ingress.kubernetes.io/auth-response-headers: "X-Auth-Request-User,X-Auth-Request-Study"
# No auth cache: a write or logout must take effect at once.
nginx.ingress.kubernetes.io/proxy-body-size: "4m"
nginx.ingress.kubernetes.io/enable-access-log: "false"
spec:
ingressClassName: nginx
rules:
- host: cbioportal.example.org
http:
paths:
- path: /wsi/annotations
pathType: Prefix
backend: {service: {name: wsi-companion, port: {number: 8080}}}
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: wsi-companion
spec:
podSelector:
matchLabels: {app: wsi-companion}
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: ingress-nginx}
ports:
- port: 8080
```

Keep `underscores_in_headers` off (the controller default), so
`X_Auth_Request_User` cannot stand in for the real header.

### Plain nginx

```nginx
location ~ ^/wsi/annotations(/.*)?$ {
if ($wsi_study = "!") {
return 400;
}
auth_request /_wsi_companion_access;
auth_request_set $wsi_auth_user $upstream_http_x_auth_request_user;
auth_request_set $wsi_auth_study $upstream_http_x_auth_request_study;
proxy_pass http://companion:8080;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $remote_addr;
# Always set both, so a client's copy never passes through.
proxy_set_header X-Auth-Request-User $wsi_auth_user;
proxy_set_header X-Auth-Request-Study $wsi_auth_study;
proxy_set_header Cookie "";
client_max_body_size 4m;
}

location = /_wsi_companion_access {
internal;
proxy_pass http://portal/api/studies/$wsi_study/access;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header Cookie $http_cookie;
proxy_set_header Host $http_host;
}
```

A location that sets any `proxy_set_header` inherits none from the server
block, so each companion location sets both identity headers itself.

## Runtime configuration

The service needs only pixel storage, the source seal key, and an optional
Expand Down Expand Up @@ -444,7 +645,9 @@ docker compose up --build
```

The compose file is a local rehearsal with no ingress in front of the
service, so it performs no study authorization; do not expose it. Use the
service, so it performs no study authorization; do not expose it. Its
`companion` service listens on `127.0.0.1:${COMPANION_PORT:-8081}` and expects
the identity headers a proxy would set; send them yourself to try it. Use the
same `WSI_SOURCE_SEAL_KEY` here and wherever the study's sealed sources were
produced.

Expand Down
140 changes: 140 additions & 0 deletions app/annotation_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""Shared annotation database lifecycle and versioned schema migrations.

The Postgres/Lakebase pool takes its password from the DSN, or, with
a password provider (``ANNOTATION_DATABASE_PASSWORD_PROVIDER``), from a short-lived
Lakebase credential fetched for each new connection
(``app.lakebase_credentials``). Idle connections close after
``ANNOTATION_DB_MAX_INACTIVE_CONNECTION_LIFETIME`` seconds and every
connection is replaced once it is ``ANNOTATION_DB_MAX_CONNECTION_AGE_SECONDS``
old, so none outlives the credential it logged in with by much.
"""

from __future__ import annotations

import os
import time
from contextlib import asynccontextmanager
from typing import AsyncIterator

import asyncpg

from . import lakebase_credentials

_pool: asyncpg.Pool | None = None
_pool_dsn = ""
_pool_generation_started = 0.0


def _pool_size(name: str, default: int) -> int:
try:
return max(1, int(os.environ.get(name, str(default))))
except ValueError:
return default


def _seconds(name: str, default: float) -> float:
try:
return max(0.0, float(os.environ.get(name, str(default))))
except ValueError:
return default


def max_connection_age() -> float:
"""Seconds after which every pooled connection is replaced (0 = never)."""
return _seconds("ANNOTATION_DB_MAX_CONNECTION_AGE_SECONDS", 1800)


async def open_pool(dsn: str) -> asyncpg.Pool:
"""Open one process-local pool for the shared Postgres/Lakebase database."""
global _pool, _pool_dsn, _pool_generation_started
if _pool is not None and _pool_dsn == dsn:
return _pool
await close_pool()
_pool = await asyncpg.create_pool(
dsn,
password=lakebase_credentials.password_option(),
min_size=_pool_size("ANNOTATION_DB_POOL_MIN_SIZE", 1),
max_size=_pool_size("ANNOTATION_DB_POOL_MAX_SIZE", 8),
max_inactive_connection_lifetime=_seconds(
"ANNOTATION_DB_MAX_INACTIVE_CONNECTION_LIFETIME", 300
),
command_timeout=float(
os.environ.get("ANNOTATION_DB_COMMAND_TIMEOUT", "30")
),
)
_pool_dsn = dsn
_pool_generation_started = time.monotonic()
return _pool


async def _expire_aged_connections(pool: asyncpg.Pool) -> None:
"""Replace every pooled connection once the current set is too old."""
global _pool_generation_started
age = max_connection_age()
now = time.monotonic()
if age and now - _pool_generation_started >= age:
_pool_generation_started = now
await pool.expire_connections()


async def close_pool() -> None:
global _pool, _pool_dsn
if _pool is not None:
await _pool.close()
_pool = None
_pool_dsn = ""


@asynccontextmanager
async def connection(dsn: str) -> AsyncIterator[asyncpg.Connection]:
pool = await open_pool(dsn)
await _expire_aged_connections(pool)
async with pool.acquire() as conn:
yield conn


async def migrate(conn: asyncpg.Connection) -> None:
"""Apply idempotent schema version 1 without destructive table rewrites."""
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS annotation_schema_migrations (
component TEXT PRIMARY KEY,
version INTEGER NOT NULL,
applied_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now())
)
"""
)
current = await conn.fetchval(
"SELECT version FROM annotation_schema_migrations WHERE component = 'annotations'"
)
if current is not None and int(current) >= 1:
return

await conn.execute(
"""
CREATE TABLE IF NOT EXISTS annotations (
id TEXT PRIMARY KEY,
slide_id TEXT NOT NULL,
study_id TEXT NOT NULL,
body TEXT NOT NULL,
target TEXT NOT NULL,
created_by TEXT NOT NULL,
visible_to TEXT,
version INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now()),
updated_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now())
)
"""
)
await conn.execute(
"CREATE INDEX IF NOT EXISTS idx_ann_slide_study ON annotations(slide_id, study_id)"
)
await conn.execute("CREATE INDEX IF NOT EXISTS idx_ann_slide ON annotations(slide_id)")
await conn.execute(
"""
INSERT INTO annotation_schema_migrations(component, version)
VALUES ('annotations', 1)
ON CONFLICT (component) DO UPDATE SET version = EXCLUDED.version,
applied_at = timezone('utc', now())
"""
)
Loading
Loading