Use shared access for synthetic breast follow-up

This commit is contained in:
Angel Capetillo Zavala
2026-11-13 17:54:56 -06:00
parent 9c0e03f947
commit 46eb3dfc31
9 changed files with 35 additions and 71 deletions
+2 -2
View File
@@ -101,7 +101,7 @@ se omiten.
El lector usa la base configurada por `CAMA_DATABASE_URL` y publica el
`pac_id` de la plataforma como cadena decimal, con ámbito limitado a esa base
y dominio. El acceso a las rutas por paciente requiere el token configurado en
el servidor. Los parámetros de corte, ventana y selección, la revisión, la
y dominio. Las rutas por paciente usan el mismo acceso de la aplicación que
Seguimiento CaCu. Los parámetros de corte, ventana y selección, la revisión, la
supresión y los ejemplos de listado, ficha y exportación se describen en
[el contrato de cohorte](docs/cama-cohort-api.md).
+7 -13
View File
@@ -1,14 +1,10 @@
# Breast cohort: synthetic integration contract
This contract is for a synthetic source. Set `CAMA_COHORT_ACCESS_TOKEN` in
the server environment. The token must be at least 32 ASCII
letters, digits, underscores or hyphens. The application reads the configured CaMa database
and checks the `X-Cama-Cohort-Token` request header on patient routes. The
header must be supplied by a trusted server-side access boundary, never
embedded in browser code. Without an enabled reader the aggregate returns
503; without authorized access the patient routes return 403. This is not a
production access policy; authorization for real patient data has not been
implemented.
This contract is for a synthetic source. The application reads the configured
CaMa database through the shared persistence settings. Patient routes have
the same application access boundary as CaCu follow-up; an optional access
callback can apply an additional boundary. An unavailable reader returns 503.
Authorization for real patient data has not been implemented.
`GET /cama/analisis/indicadores?corte=2026-10-20` returns a descriptive count
by BI-RADS. It includes `cohorte`, `revision`, `escenario`, `corte`,
@@ -69,13 +65,11 @@ materializes the full cohort in memory and has not been sized for production.
The local example `examples/serve_cama_cohort.py` accepts an existing synthetic
SQLite file in `CAMA_SYNTHETIC_SQLITE`, opens it read-only, binds to loopback,
and requires `CAMA_COHORT_ACCESS_TOKEN` of at least 32 characters. Send it in
`X-Cama-Cohort-Token` for patient requests.
and does not require cohort-specific environment variables.
Other domain database URLs are set to isolated in-memory SQLite by the example.
The Windows-only `fcntl` shim raises if locking is attempted: this example does
not validate file-locking functionality.
`examples/serve_cama_integration.py` runs normal application configuration
against an existing disposable SQLite copy, with a temporary token injected by
its loopback-only test proxy. It is suitable only
against an existing disposable SQLite copy, bound to loopback. It is suitable only
for local synthetic integration and does not provide production authentication.
+1 -9
View File
@@ -1,6 +1,5 @@
"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file."""
import hmac
import os
from pathlib import Path
import sqlite3
@@ -24,9 +23,6 @@ if os.name == 'nt':
path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True)
token = os.environ['CAMA_COHORT_ACCESS_TOKEN']
if len(token) < 32:
raise ValueError('The access token must be at least 32 characters')
if not path.is_file():
raise ValueError('The synthetic SQLite database must already exist')
@@ -49,11 +45,7 @@ def read(cutoff):
return CamaCohort(session).rows(cutoff)
def authorized(request):
return hmac.compare_digest(request.headers.get('X-Cama-Cohort-Token', ''), token)
app.config.update(CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=authorized)
app.config['CAMA_COHORT_READER'] = read
if __name__ == '__main__':
app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False)
+2 -11
View File
@@ -3,7 +3,6 @@
import argparse
import os
from pathlib import Path
import secrets
import sys
import types
@@ -14,9 +13,8 @@ args = parser.parse_args()
database = Path(args.database).resolve(strict=True)
if not database.is_file():
raise ValueError('The synthetic database must be an existing file')
token = secrets.token_hex(32)
os.environ.update(CAMA_DATABASE_URL='sqlite:///' + database.as_posix(),
CAMA_COHORT_ACCESS_TOKEN=token, MLFLOW_DISABLE_AGENT_HINT='1',
MLFLOW_DISABLE_AGENT_HINT='1',
MLFLOW_DISABLE_TELEMETRY='true')
for domain in ('CACU', 'TEA', 'GOVERNANCE'):
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
@@ -32,12 +30,5 @@ from webapi import create_app
from werkzeug.serving import make_server
app = create_app()
application = app.wsgi_app
def test_proxy(environ, start_response):
# The harness is loopback-only and replaces any caller-supplied test token.
environ['HTTP_X_CAMA_COHORT_TOKEN'] = token
return application(environ, start_response)
print(f'Isolated synthetic test proxy: http://127.0.0.1:{args.port}', flush=True)
make_server('127.0.0.1', args.port, test_proxy, threaded=True).serve_forever()
make_server('127.0.0.1', args.port, app, threaded=True).serve_forever()
+1 -1
View File
@@ -97,7 +97,7 @@ def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403
assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400
assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409
client.application.config['CAMA_COHORT_ACCESS'] = None
client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
assert client.get('/cama/seguimiento' + selection).status_code == 403
assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403
assert client.get('/cama/pacientes/some-id' + selection).status_code == 403
+9 -22
View File
@@ -1,38 +1,25 @@
"""Exercise persistent cohort setup and its optional patient access boundary."""
"""Verify default persistent cohort setup with retained legacy configuration."""
from flask import Flask, request
from flask import Flask
from webapi.cama_runtime import configure_cama_cohort
def test_missing_or_invalid_token_does_not_prevent_startup(monkeypatch):
"""A malformed optional credential leaves the reader registered and access denied."""
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'short')
def test_default_reader_uses_shared_persistence(monkeypatch):
"""The reader is registered without special cohort environment variables."""
for key in ('CAMA_COHORT_SYNTHETIC', 'CAMA_COHORT_SECRET', 'CAMA_COHORT_ACCESS_TOKEN'):
monkeypatch.delenv(key, raising=False)
app = Flask(__name__)
configure_cama_cohort(app)
assert callable(app.config['CAMA_COHORT_READER'])
with app.test_request_context(headers={'X-Cama-Cohort-Token': 'short'}):
assert not app.config['CAMA_COHORT_ACCESS'](request)
def test_access_token_is_checked_on_the_server(monkeypatch):
"""The retained proxy credential gates patient routes until a shared boundary is available."""
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 't' * 32)
app = Flask(__name__)
configure_cama_cohort(app)
with app.test_request_context(headers={'X-Cama-Cohort-Token': 't' * 32}):
assert app.config['CAMA_COHORT_ACCESS'](request)
with app.test_request_context(headers={'X-Cama-Cohort-Token': 'incorrect'}):
assert not app.config['CAMA_COHORT_ACCESS'](request)
assert 'CAMA_COHORT_ACCESS' not in app.config
def test_application_starts_with_retained_obsolete_configuration(monkeypatch):
"""Old synthetic settings or a bad token cannot prevent the health endpoint starting."""
"""Retained synthetic settings cannot prevent the health endpoint starting."""
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
monkeypatch.delenv('CAMA_COHORT_SECRET', raising=False)
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'invalid')
from webapi import create_app
client = create_app().test_client()
assert client.get('/health').get_json() == {'status': 'ok'}
assert client.get('/cama/seguimiento').status_code == 403
assert create_app().test_client().get('/health').get_json() == {'status': 'ok'}
+11
View File
@@ -72,6 +72,17 @@ def test_a_scored_member_has_the_contracts_shape(client, seeded):
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
def test_follow_up_identity_resolves_scored_patient(client, seeded):
"""The patient selected from follow-up resolves to that patient's seeded risk."""
listing = client.get('/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200').get_json()
row = next(item for item in listing['items'] if item['pac_id'] == str(seeded[0]))
assert row['id_seudonimo'] == row['pac_id']
response = client.get(f"/cacu/pacientes/{row['pac_id']}/riesgo")
assert response.status_code == 200
assert response.get_json()['cohorte']['pap_0'] == 'ASC-US'
assert response.get_json()['riesgo']['horizontes'][0]['probabilidad'] == 0.1
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
null. Fails if either case errors or invents a risk."""
+1 -1
View File
@@ -45,7 +45,7 @@ def cutoff_arg(args):
def patient_access():
check = current_app.config.get('CAMA_COHORT_ACCESS')
if not callable(check) or not check(request):
if callable(check) and not check(request):
raise SelectionError('Acceso no autorizado', 403)
+1 -12
View File
@@ -1,23 +1,12 @@
"""Configure the breast cohort using the shared persistence settings."""
import hmac
import os
import re
from persistance.db import get_cama_session
from webapi.cama_cohort import CamaCohort
def configure_cama_cohort(app):
token = os.environ.get('CAMA_COHORT_ACCESS_TOKEN', '')
def read(cutoff):
with get_cama_session() as session:
return CamaCohort(session).rows(cutoff)
def access(req):
supplied = req.headers.get('X-Cama-Cohort-Token', '')
return bool(re.fullmatch(r'[A-Za-z0-9_-]{32,}', token)) and hmac.compare_digest(
supplied.encode('utf-8'), token.encode('utf-8'))
app.config.update(CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=access)
app.config['CAMA_COHORT_READER'] = read