diff --git a/packages/flow/openadapt_flow/byoc_veto_server.py b/packages/flow/openadapt_flow/byoc_veto_server.py new file mode 100644 index 0000000000..1dbd8b2d6e --- /dev/null +++ b/packages/flow/openadapt_flow/byoc_veto_server.py @@ -0,0 +1,990 @@ +"""Lightweight Shared BYOC Multi-LoRA Veto HTTP Server for zero-GPU laptops. + +Exposes a minimal stdlib ``ThreadingHTTPServer`` endpoint (``POST /v1/verify``, +``GET /healthz``) so zero-GPU laptops can route pre/post-submit visual veto +checks to a single customer-VPC GPU running :class:`MultiLoraVetoRouter` +(routing compact per-app LoRA adapters by server-authorized +``(tenant_id, app_id, workflow_id)``). + +Security & fail-closed invariants: +- **Mandatory tenant-key authentication & app allow-list:** Refuses to start + with an empty key table or without an explicit ``tenant_allowed_apps`` entry + for every tenant; compares bearer/header tokens in constant time + (``hmac.compare_digest``). +- **Mandatory server-issued run bindings (anti-steering & anti-replay):** + Every ``POST /v1/verify`` request MUST match a server-side :class:`RunBinding` + (issued via :meth:`ByocVetoServer.issue_run_binding` or pre-registered at + startup) that authoritatively binds ``(tenant_id, app_id, workflow_id, + domain, step_nonce, pre_submit_image_sha256, post_submit_image_sha256)``. + Each binding and ``step_nonce`` is strictly single-use, payload ``domain`` is + ignored, workflow-adapter downgrades (missing or unregistered ``workflow_id``) + are rejected, and fallback to ``default_base_adapter`` is disabled by default. +- **Server-side VPC HMAC enforcement:** Per-tenant HMAC keys stay strictly on + the VPC server. Any ``expected_field_hashes`` submitted on ``/v1/verify`` + must match server-bound keyed HMAC-SHA256 digests computed with the tenant's + VPC key; plain SHA-256 digests or digests without a configured key fail + closed with ``403 HALT_ESCALATE``. +- **Bounded TLS handshake, read timeout, and concurrency cap:** Wraps accepted + sockets inside worker threads with bounded handshake and request read + timeouts (never clearing socket timeouts to ``None``) and caps concurrent + connections with a semaphore so idle peers cannot exhaust threads. +- **Fail-closed ``ABSTAIN -> HALT_ESCALATE``:** Never allows DOM success claims + to override an abstained visual check; backend failures fail closed with + ``503`` and ``decision="HALT_ESCALATE"``. +""" + +from __future__ import annotations + +import hmac +import json +import secrets +import ssl +import threading +import urllib.error +import urllib.parse +import urllib.request +from collections.abc import Mapping +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator + +from openadapt_flow.multi_lora_veto import ( + _MIN_HMAC_KEY_BYTES, + _NONCE_RE, + MultiLoraVetoRouter, + VetoDecision, + VetoInferenceRequest, + VetoOutcome, + _validate_sha256_hex, + _validate_sha256_map, + hmac_field_value, +) + +DEFAULT_MAX_BODY_BYTES = 256 * 1024 +DEFAULT_TLS_HANDSHAKE_TIMEOUT_S = 5.0 +DEFAULT_REQUEST_TIMEOUT_S = 10.0 +DEFAULT_MAX_CONCURRENT_CONNECTIONS = 64 +_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) + + +class RunBinding(BaseModel): + """Server-side authoritative, single-use binding for one verification step. + + Binds the authenticated tenant, target ``app_id``, ``workflow_id``, + optional ``domain``, single-use ``step_nonce``, expected pre/post-submit + image SHA-256 digests, and optional server-computed keyed HMAC-SHA256 + ``expected_field_hashes``. + """ + + model_config = ConfigDict(extra="forbid") + + tenant_id: str = Field(min_length=1) + app_id: str = Field(min_length=1) + workflow_id: str | None = None + domain: str | None = None + step_nonce: str = Field(min_length=1) + pre_submit_image_sha256: str = Field(min_length=64, max_length=64) + post_submit_image_sha256: str = Field(min_length=64, max_length=64) + expected_field_hashes: dict[str, str] = Field(default_factory=dict) + + @field_validator("step_nonce") + @classmethod + def _check_step_nonce(cls, value: str) -> str: + if not _NONCE_RE.match(value): + raise ValueError(f"step_nonce must match {_NONCE_RE.pattern!r}.") + return value + + @field_validator("pre_submit_image_sha256") + @classmethod + def _check_pre_image_sha256(cls, value: str) -> str: + return _validate_sha256_hex(value, "pre_submit_image_sha256") + + @field_validator("post_submit_image_sha256") + @classmethod + def _check_post_image_sha256(cls, value: str) -> str: + return _validate_sha256_hex(value, "post_submit_image_sha256") + + @field_validator("expected_field_hashes") + @classmethod + def _check_expected_field_hashes(cls, value: dict[str, str]) -> dict[str, str]: + return _validate_sha256_map(value) + + +class IssuedRunBinding(BaseModel): + """Opaque server-issued token and single-use nonce returned to the caller.""" + + model_config = ConfigDict(extra="forbid") + + request_id: str = Field(min_length=1) + step_nonce: str = Field(min_length=1) + expected_field_hashes: dict[str, str] = Field(default_factory=dict) + + +class ByocVerifyPayload(BaseModel): + """Value-free HTTP request schema for ``POST /v1/verify``. + + Carries only the server-issued ``request_id``, single-use ``step_nonce``, + 64-hex SHA-256 image references (dereferenced from the customer-VPC + artifact store by the backend), and keyed HMAC-SHA256 field digests. + """ + + model_config = ConfigDict(extra="forbid") + + request_id: str = Field(min_length=1) + app_id: str = Field(min_length=1) + workflow_id: str | None = None + domain: str | None = None + tenant_id: str | None = None + step_nonce: str = Field(min_length=1) + requested_adapter_id: str | None = None + pre_submit_image_sha256: str = Field(min_length=64, max_length=64) + post_submit_image_sha256: str = Field(min_length=64, max_length=64) + expected_field_hashes: dict[str, str] = Field(default_factory=dict) + dom_claims_success: bool = False + + @field_validator("pre_submit_image_sha256") + @classmethod + def _check_pre_image_sha256(cls, value: str) -> str: + return _validate_sha256_hex(value, "pre_submit_image_sha256") + + @field_validator("post_submit_image_sha256") + @classmethod + def _check_post_image_sha256(cls, value: str) -> str: + return _validate_sha256_hex(value, "post_submit_image_sha256") + + @field_validator("step_nonce") + @classmethod + def _check_step_nonce(cls, value: str) -> str: + if not _NONCE_RE.match(value): + raise ValueError(f"step_nonce must match {_NONCE_RE.pattern!r}.") + return value + + @field_validator("expected_field_hashes") + @classmethod + def _check_expected_field_hashes(cls, value: dict[str, str]) -> dict[str, str]: + return _validate_sha256_map(value) + + +def _digests_equal(left: Mapping[str, str], right: Mapping[str, str]) -> bool: + if set(left.keys()) != set(right.keys()): + return False + matched = True + for key, expected in right.items(): + if not hmac.compare_digest(left[key], expected): + matched = False + return matched + + +class _ByocThreadingHTTPServer(ThreadingHTTPServer): + allow_reuse_address = True + daemon_threads = True + + def __init__( + self, + server_address: tuple[str, int], + *, + router: MultiLoraVetoRouter, + tenant_api_keys: dict[str, str], + tenant_allowed_apps: dict[str, frozenset[str]], + tenant_hmac_keys: dict[str, bytes], + run_bindings: dict[str, RunBinding], + allow_default_fallback: bool, + max_body_bytes: int, + ssl_context: ssl.SSLContext | None, + tls_handshake_timeout_s: float, + request_timeout_s: float, + max_concurrent_connections: int, + ) -> None: + self.router = router + self.tenant_api_keys = dict(tenant_api_keys) + self.tenant_allowed_apps = dict(tenant_allowed_apps) + self.tenant_hmac_keys = dict(tenant_hmac_keys) + self.run_bindings = dict(run_bindings) + self.consumed_bindings: set[str] = set() + self.consumed_nonces: set[tuple[str, str]] = set() + self.allow_default_fallback = allow_default_fallback + self.max_body_bytes = max_body_bytes + self.ssl_context = ssl_context + self.tls_handshake_timeout_s = tls_handshake_timeout_s + self.request_timeout_s = request_timeout_s + self.eval_lock = threading.Lock() + self.binding_lock = threading.Lock() + self._conn_semaphore = threading.BoundedSemaphore(max_concurrent_connections) + super().__init__(server_address, _ByocVetoRequestHandler) + + def process_request(self, request: Any, client_address: Any) -> None: + """Cap concurrent worker threads; drop excess connections immediately.""" + if not self._conn_semaphore.acquire(blocking=False): + self.shutdown_request(request) + return + try: + super().process_request(request, client_address) + except BaseException: + self._conn_semaphore.release() + raise + + def process_request_thread(self, request: Any, client_address: Any) -> None: + try: + super().process_request_thread(request, client_address) + finally: + self._conn_semaphore.release() + + def finish_request(self, request: Any, client_address: Any) -> None: + """Enforce bounded TLS handshake and post-handshake read timeouts.""" + if self.ssl_context is not None: + tls_sock: Any = None + try: + request.settimeout(self.tls_handshake_timeout_s) + tls_sock = self.ssl_context.wrap_socket( + request, + server_side=True, + do_handshake_on_connect=False, + ) + tls_sock.settimeout(self.tls_handshake_timeout_s) + tls_sock.do_handshake() + tls_sock.settimeout(self.request_timeout_s) + super().finish_request(tls_sock, client_address) + except (OSError, ssl.SSLError, TimeoutError): + return + finally: + if tls_sock is not None: + try: + tls_sock.close() + except OSError: + pass + return + try: + request.settimeout(self.request_timeout_s) + super().finish_request(request, client_address) + except (OSError, TimeoutError): + return + + +class _ByocVetoRequestHandler(BaseHTTPRequestHandler): + server: _ByocThreadingHTTPServer + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + # Suppress default stderr access logging to keep server output clean + # and avoid leaking request metadata. + return + + def _send_json(self, status: HTTPStatus, payload: dict[str, Any]) -> None: + body = json.dumps(payload, sort_keys=True).encode("utf-8") + self.send_response(int(status)) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def _extract_token(self) -> str | None: + auth = self.headers.get("Authorization", "").strip() + if auth.lower().startswith("bearer "): + token = auth[7:].strip() + if token: + return token + header_key = self.headers.get("X-OpenAdapt-Tenant-Key", "").strip() + return header_key or None + + def _authenticate_tenant(self) -> tuple[str | None, HTTPStatus | None, str | None]: + token = self._extract_token() + if not token: + return None, HTTPStatus.UNAUTHORIZED, "Missing tenant API key." + + matched_tenant: str | None = None + for tenant_id, expected_key in self.server.tenant_api_keys.items(): + if hmac.compare_digest(token, expected_key): + matched_tenant = tenant_id + break + if matched_tenant is None: + return None, HTTPStatus.UNAUTHORIZED, "Invalid tenant API key." + + header_tenant = self.headers.get("X-OpenAdapt-Tenant-Id") + if header_tenant is not None and header_tenant.strip() != matched_tenant: + return ( + None, + HTTPStatus.FORBIDDEN, + "X-OpenAdapt-Tenant-Id does not match authenticated tenant.", + ) + return matched_tenant, None, None + + def do_GET(self) -> None: # noqa: N802 + if self.path.split("?", 1)[0] != "/healthz": + self._send_json(HTTPStatus.NOT_FOUND, {"error": "Not found."}) + return + + # Unauthenticated liveness probe: never leak tenant adapter IDs or counters. + self._send_json(HTTPStatus.OK, {"status": "ok"}) + + def do_POST(self) -> None: # noqa: N802 + if self.path.split("?", 1)[0] != "/v1/verify": + self._send_json(HTTPStatus.NOT_FOUND, {"error": "Not found."}) + return + + tenant_id, err_status, err_msg = self._authenticate_tenant() + if err_status is not None or tenant_id is None: + self._send_json( + err_status or HTTPStatus.UNAUTHORIZED, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": err_msg or "Unauthorized.", + }, + ) + return + + try: + content_length = int(self.headers.get("Content-Length", "0")) + except ValueError: + self._send_json( + HTTPStatus.BAD_REQUEST, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": "Invalid Content-Length.", + }, + ) + return + + if content_length <= 0 or content_length > self.server.max_body_bytes: + self._send_json( + HTTPStatus.REQUEST_ENTITY_TOO_LARGE + if content_length > self.server.max_body_bytes + else HTTPStatus.BAD_REQUEST, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": f"Request body size must be between 1 and {self.server.max_body_bytes} bytes.", + }, + ) + return + + raw_body = self.rfile.read(content_length) + if len(raw_body) != content_length: + self._send_json( + HTTPStatus.BAD_REQUEST, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": "Incomplete request body.", + }, + ) + return + + try: + parsed = json.loads(raw_body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + self._send_json( + HTTPStatus.BAD_REQUEST, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": f"Invalid JSON: {exc}", + }, + ) + return + + try: + payload = ByocVerifyPayload.model_validate(parsed) + except ValidationError as exc: + # Strip raw `input` and `ctx` so bad requests never echo client values back. + sanitized_errors = [ + { + "loc": list(err.get("loc", ())), + "msg": str(err.get("msg", "validation error")), + "type": str(err.get("type", "value_error")), + } + for err in exc.errors() + ] + self._send_json( + HTTPStatus.UNPROCESSABLE_ENTITY, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": "Request schema validation failed.", + "details": sanitized_errors, + }, + ) + return + + if payload.tenant_id is not None and payload.tenant_id != tenant_id: + self._send_json( + HTTPStatus.FORBIDDEN, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": "Payload tenant_id does not match authenticated tenant.", + }, + ) + return + + # Mandatory server-side app allow-list per tenant (fail-closed). + allowed_apps = self.server.tenant_allowed_apps.get(tenant_id, frozenset()) + if payload.app_id not in allowed_apps: + self._send_json( + HTTPStatus.FORBIDDEN, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": f"Tenant {tenant_id!r} is not authorized for app_id {payload.app_id!r}.", + }, + ) + return + + # Mandatory server-side run binding + single-use step_nonce + image/HMAC verification. + with self.server.binding_lock: + binding = self.server.run_bindings.get(payload.request_id) + if binding is None: + self._send_json( + HTTPStatus.FORBIDDEN, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": ( + f"Unknown server-side run binding for request_id " + f"{payload.request_id!r}." + ), + }, + ) + return + + if ( + payload.request_id in self.server.consumed_bindings + or (tenant_id, payload.step_nonce) in self.server.consumed_nonces + ): + self._send_json( + HTTPStatus.CONFLICT, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": "Run binding or step_nonce already consumed (replay rejected).", + }, + ) + return + + if ( + binding.tenant_id != tenant_id + or binding.app_id != payload.app_id + or binding.workflow_id != payload.workflow_id + or not hmac.compare_digest(binding.step_nonce, payload.step_nonce) + or not hmac.compare_digest( + binding.pre_submit_image_sha256, payload.pre_submit_image_sha256 + ) + or not hmac.compare_digest( + binding.post_submit_image_sha256, payload.post_submit_image_sha256 + ) + ): + self._send_json( + HTTPStatus.FORBIDDEN, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": "Request parameters or image digests do not match server-side run binding.", + }, + ) + return + + # Server-side HMAC enforcement: laptops never hold tenant HMAC keys, + # and unkeyed SHA-256 digests are rejected. + if payload.expected_field_hashes or binding.expected_field_hashes: + if tenant_id not in self.server.tenant_hmac_keys: + self._send_json( + HTTPStatus.FORBIDDEN, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": ( + "expected_field_hashes cannot be verified without a " + "server-side tenant HMAC key." + ), + }, + ) + return + if not binding.expected_field_hashes or not _digests_equal( + payload.expected_field_hashes, binding.expected_field_hashes + ): + self._send_json( + HTTPStatus.FORBIDDEN, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": ( + "expected_field_hashes do not match server-bound " + "keyed HMAC-SHA256 digests." + ), + }, + ) + return + + # Mark binding & step_nonce consumed atomically before scoring. + self.server.consumed_bindings.add(payload.request_id) + self.server.consumed_nonces.add((tenant_id, binding.step_nonce)) + + # Resolve strictly from server-side binding; ignore caller-supplied payload.domain. + inference_req = VetoInferenceRequest( + request_id=payload.request_id, + app_id=binding.app_id, + workflow_id=binding.workflow_id, + domain=binding.domain, + tenant_id=tenant_id, + step_nonce=binding.step_nonce, + pre_submit_image_sha256=binding.pre_submit_image_sha256, + post_submit_image_sha256=binding.post_submit_image_sha256, + expected_field_hashes=dict(binding.expected_field_hashes), + dom_claims_success=payload.dom_claims_success, + ) + + try: + with self.server.eval_lock: + outcome = self.server.router.evaluate( + inference_req, + requested_adapter_id=payload.requested_adapter_id, + allow_default_fallback=self.server.allow_default_fallback, + require_exact_workflow=True, + ) + except PermissionError as exc: + self._send_json( + HTTPStatus.FORBIDDEN, + {"decision": VetoDecision.HALT_ESCALATE.value, "error": str(exc)}, + ) + return + except KeyError as exc: + self._send_json( + HTTPStatus.NOT_FOUND, + {"decision": VetoDecision.HALT_ESCALATE.value, "error": str(exc)}, + ) + return + except ValueError as exc: + self._send_json( + HTTPStatus.BAD_REQUEST, + {"decision": VetoDecision.HALT_ESCALATE.value, "error": str(exc)}, + ) + return + except ( + RuntimeError, + OSError, + TimeoutError, + LookupError, + TypeError, + ArithmeticError, + ValidationError, + ) as exc: + self._send_json( + HTTPStatus.SERVICE_UNAVAILABLE, + { + "decision": VetoDecision.HALT_ESCALATE.value, + "error": f"Fail-closed backend error: {type(exc).__name__}", + }, + ) + return + + # Defense-in-depth fail-closed invariant: ABSTAIN always yields HALT_ESCALATE. + if outcome.abstained and outcome.decision is not VetoDecision.HALT_ESCALATE: + outcome = outcome.model_copy( + update={ + "decision": VetoDecision.HALT_ESCALATE, + "dom_override_blocked": inference_req.dom_claims_success, + } + ) + + self._send_json(HTTPStatus.OK, outcome.model_dump(mode="json")) + + +class ByocVetoServer: + """Managed stdlib HTTP server fronting :class:`MultiLoraVetoRouter`.""" + + def __init__( + self, + *, + router: MultiLoraVetoRouter, + tenant_api_keys: Mapping[str, str], + tenant_allowed_apps: Mapping[str, frozenset[str] | set[str]], + tenant_hmac_keys: Mapping[str, bytes | str] | None = None, + run_bindings: Mapping[str, RunBinding] | None = None, + allow_default_fallback: bool = False, + host: str = "127.0.0.1", + port: int = 0, + max_body_bytes: int = DEFAULT_MAX_BODY_BYTES, + ssl_context: ssl.SSLContext | None = None, + tls_handshake_timeout_s: float = DEFAULT_TLS_HANDSHAKE_TIMEOUT_S, + request_timeout_s: float = DEFAULT_REQUEST_TIMEOUT_S, + max_concurrent_connections: int = DEFAULT_MAX_CONCURRENT_CONNECTIONS, + ) -> None: + if not tenant_api_keys: + raise ValueError("tenant_api_keys must contain at least one tenant key.") + if not tenant_allowed_apps: + raise ValueError( + "tenant_allowed_apps is required and must specify allowed apps per tenant." + ) + if host.strip().lower() not in _LOOPBACK_HOSTS and ssl_context is None: + raise ValueError( + f"Binding BYOC veto server to non-loopback host {host!r} requires ssl_context (TLS)." + ) + if request_timeout_s <= 0.0: + raise ValueError("request_timeout_s must be > 0.") + if max_concurrent_connections <= 0: + raise ValueError("max_concurrent_connections must be >= 1.") + + cleaned_keys: dict[str, str] = {} + seen_secrets: set[str] = set() + for tid, secret in tenant_api_keys.items(): + if not tid or not tid.strip(): + raise ValueError("Tenant IDs in tenant_api_keys must be non-empty.") + if not secret or not secret.strip(): + raise ValueError(f"API key for tenant {tid!r} must be non-empty.") + if secret in seen_secrets: + raise ValueError("Duplicate API keys across tenants are forbidden.") + seen_secrets.add(secret) + cleaned_keys[tid.strip()] = secret.strip() + + cleaned_allowed: dict[str, frozenset[str]] = {} + for tid in cleaned_keys: + apps = tenant_allowed_apps.get(tid) + if not apps: + raise ValueError( + f"tenant_allowed_apps must declare at least one allowed app for tenant {tid!r}." + ) + cleaned_allowed[tid] = frozenset( + str(a).strip() for a in apps if str(a).strip() + ) + if not cleaned_allowed[tid]: + raise ValueError( + f"tenant_allowed_apps for tenant {tid!r} cannot be empty." + ) + + cleaned_hmac_keys: dict[str, bytes] = {} + if tenant_hmac_keys is not None: + for tid, raw_key in tenant_hmac_keys.items(): + key_tid = tid.strip() + if key_tid not in cleaned_keys: + raise ValueError( + f"tenant_hmac_keys contains unknown tenant {tid!r}." + ) + key_bytes = ( + raw_key.encode("utf-8") + if isinstance(raw_key, str) + else bytes(raw_key) + ) + if len(key_bytes) < _MIN_HMAC_KEY_BYTES: + raise ValueError( + f"HMAC key for tenant {key_tid!r} must be at least " + f"{_MIN_HMAC_KEY_BYTES} bytes long." + ) + cleaned_hmac_keys[key_tid] = key_bytes + + cleaned_bindings: dict[str, RunBinding] = {} + if run_bindings is not None: + for rid, binding in run_bindings.items(): + if binding.tenant_id not in cleaned_keys: + raise ValueError( + f"RunBinding {rid!r} references unknown tenant {binding.tenant_id!r}." + ) + if binding.app_id not in cleaned_allowed[binding.tenant_id]: + raise ValueError( + f"RunBinding {rid!r} references unauthorized app_id {binding.app_id!r} " + f"for tenant {binding.tenant_id!r}." + ) + cleaned_bindings[rid] = binding + + self._use_tls = ssl_context is not None + self._httpd = _ByocThreadingHTTPServer( + (host, port), + router=router, + tenant_api_keys=cleaned_keys, + tenant_allowed_apps=cleaned_allowed, + tenant_hmac_keys=cleaned_hmac_keys, + run_bindings=cleaned_bindings, + allow_default_fallback=allow_default_fallback, + max_body_bytes=max_body_bytes, + ssl_context=ssl_context, + tls_handshake_timeout_s=tls_handshake_timeout_s, + request_timeout_s=request_timeout_s, + max_concurrent_connections=max_concurrent_connections, + ) + self._thread: threading.Thread | None = None + + def issue_run_binding( + self, + *, + tenant_id: str, + app_id: str, + pre_submit_image_sha256: str, + post_submit_image_sha256: str, + workflow_id: str | None = None, + domain: str | None = None, + expected_field_values: Mapping[str, str] | None = None, + ) -> IssuedRunBinding: + """Issue an opaque, single-use server-side run binding for one step. + + When ``expected_field_values`` is supplied, keyed HMAC-SHA256 digests + are computed strictly server-side using the tenant's VPC HMAC key so + laptops never need access to the key. + """ + if tenant_id not in self._httpd.tenant_api_keys: + raise PermissionError(f"Unknown tenant_id: {tenant_id!r}") + if app_id not in self._httpd.tenant_allowed_apps[tenant_id]: + raise PermissionError( + f"Tenant {tenant_id!r} is not authorized for app_id {app_id!r}." + ) + + field_hashes: dict[str, str] = {} + if expected_field_values: + hmac_key = self._httpd.tenant_hmac_keys.get(tenant_id) + if hmac_key is None: + raise PermissionError( + f"Tenant {tenant_id!r} has no server-side HMAC key configured." + ) + for slug, value in expected_field_values.items(): + field_hashes[slug] = hmac_field_value(hmac_key, slug, value) + + request_id = f"run-{secrets.token_urlsafe(18)}" + step_nonce = f"nonce-{secrets.token_urlsafe(16)}" + binding = RunBinding( + tenant_id=tenant_id, + app_id=app_id, + workflow_id=workflow_id, + domain=domain, + step_nonce=step_nonce, + pre_submit_image_sha256=pre_submit_image_sha256, + post_submit_image_sha256=post_submit_image_sha256, + expected_field_hashes=field_hashes, + ) + with self._httpd.binding_lock: + self._httpd.run_bindings[request_id] = binding + return IssuedRunBinding( + request_id=request_id, + step_nonce=step_nonce, + expected_field_hashes=dict(field_hashes), + ) + + def verify_field_hmac( + self, + *, + tenant_id: str, + field_slug: str, + observed_value: str, + expected_digest: str, + ) -> bool: + """Verify an observed screen field value against a server-side tenant HMAC digest. + + Fails closed (returns ``False``) if the tenant has no configured VPC + HMAC key or if the digest does not match in constant time. + """ + hmac_key = self._httpd.tenant_hmac_keys.get(tenant_id) + if hmac_key is None: + return False + computed = hmac_field_value(hmac_key, field_slug, observed_value) + return hmac.compare_digest(computed, expected_digest.strip().lower()) + + @property + def server_address(self) -> tuple[str, int]: + host, port = self._httpd.server_address[:2] + return str(host), int(port) + + @property + def base_url(self) -> str: + host, port = self.server_address + scheme = "https" if self._use_tls else "http" + return f"{scheme}://{host}:{port}" + + def start(self) -> None: + if self._thread is not None and self._thread.is_alive(): + return + self._thread = threading.Thread( + target=self._httpd.serve_forever, + kwargs={"poll_interval": 0.05}, + daemon=True, + name="openadapt-byoc-veto-server", + ) + self._thread.start() + + def stop(self) -> None: + self._httpd.shutdown() + self._httpd.server_close() + if self._thread is not None: + self._thread.join(timeout=5.0) + self._thread = None + + def __enter__(self) -> ByocVetoServer: + self.start() + return self + + def __exit__(self, *_exc: object) -> None: + self.stop() + + +def create_byoc_veto_server( + *, + router: MultiLoraVetoRouter, + tenant_api_keys: Mapping[str, str], + tenant_allowed_apps: Mapping[str, frozenset[str] | set[str]], + tenant_hmac_keys: Mapping[str, bytes | str] | None = None, + run_bindings: Mapping[str, RunBinding] | None = None, + allow_default_fallback: bool = False, + host: str = "127.0.0.1", + port: int = 0, + max_body_bytes: int = DEFAULT_MAX_BODY_BYTES, + ssl_context: ssl.SSLContext | None = None, + tls_handshake_timeout_s: float = DEFAULT_TLS_HANDSHAKE_TIMEOUT_S, + request_timeout_s: float = DEFAULT_REQUEST_TIMEOUT_S, + max_concurrent_connections: int = DEFAULT_MAX_CONCURRENT_CONNECTIONS, +) -> ByocVetoServer: + """Create a configured :class:`ByocVetoServer` ready to start.""" + return ByocVetoServer( + router=router, + tenant_api_keys=tenant_api_keys, + tenant_allowed_apps=tenant_allowed_apps, + tenant_hmac_keys=tenant_hmac_keys, + run_bindings=run_bindings, + allow_default_fallback=allow_default_fallback, + host=host, + port=port, + max_body_bytes=max_body_bytes, + ssl_context=ssl_context, + tls_handshake_timeout_s=tls_handshake_timeout_s, + request_timeout_s=request_timeout_s, + max_concurrent_connections=max_concurrent_connections, + ) + + +def _fail_closed_outcome( + payload: Mapping[str, Any] | Any, + *, + reason: str, +) -> VetoOutcome: + if isinstance(payload, Mapping): + req_id = str(payload.get("request_id") or "unknown") + dom_claims = bool(payload.get("dom_claims_success", False)) + else: + req_id = "unknown" + dom_claims = False + return VetoOutcome( + request_id=req_id, + adapter_id="unavailable", + base_model="unavailable", + decision=VetoDecision.HALT_ESCALATE, + calibrated_fault_prob=1.0, + calibrated_threshold=0.5, + temperature=1.0, + abstained=True, + dom_override_blocked=dom_claims, + reason=reason, + ) + + +def post_verify_request( + base_url: str, + *, + api_key: str, + payload: Mapping[str, Any], + tenant_id: str | None = None, + timeout_s: float = 10.0, + ssl_context: ssl.SSLContext | None = None, +) -> VetoOutcome: + """Send a ``POST /v1/verify`` request and fail closed to ``HALT_ESCALATE`` on any error. + + Validates payload type, non-empty ``request_id``, URL syntax, TLS for + non-loopback hosts, response ``request_id`` match, and fail-closed decision + invariants (never accepting ``ALLOW`` when ``abstained=True`` or + ``calibrated_fault_prob >= calibrated_threshold``). + """ + if not isinstance(payload, Mapping): + return _fail_closed_outcome( + {}, + reason=f"Fail-closed client payload error: expected Mapping, got {type(payload).__name__}", + ) + + raw_request_id = payload.get("request_id") + if not isinstance(raw_request_id, str) or not raw_request_id.strip(): + return _fail_closed_outcome( + payload, + reason="Fail-closed client request error: non-empty request_id is required.", + ) + + try: + if not isinstance(base_url, str) or not base_url.strip(): + raise ValueError("base_url must be a non-empty string") + parsed = urllib.parse.urlparse(base_url) + scheme = (parsed.scheme or "").lower() + host = (parsed.hostname or "").lower() + except (ValueError, TypeError, AttributeError) as exc: + return _fail_closed_outcome( + payload, + reason=f"Fail-closed client URL error: {type(exc).__name__}", + ) + + if scheme not in {"http", "https"}: + return _fail_closed_outcome( + payload, + reason=f"Fail-closed client scheme error: unsupported scheme {scheme!r}", + ) + if scheme == "http" and host not in _LOOPBACK_HOSTS: + return _fail_closed_outcome( + payload, + reason=f"Fail-closed client TLS error: refusing plaintext http:// to non-loopback host {host!r}", + ) + + url = base_url.rstrip("/") + "/v1/verify" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {api_key}", + } + if tenant_id is not None: + headers["X-OpenAdapt-Tenant-Id"] = tenant_id + expected_request_id = raw_request_id + try: + req = urllib.request.Request( + url, + data=json.dumps(dict(payload)).encode("utf-8"), + headers=headers, + method="POST", + ) + with urllib.request.urlopen( # noqa: S310 + req, timeout=timeout_s, context=ssl_context + ) as resp: + body = json.loads(resp.read().decode("utf-8")) + outcome = VetoOutcome.model_validate(body) + except urllib.error.HTTPError as exc: + return _fail_closed_outcome( + payload, reason=f"Fail-closed client HTTP error: {exc.code}" + ) + except ( + urllib.error.URLError, + OSError, + TimeoutError, + UnicodeDecodeError, + json.JSONDecodeError, + ValidationError, + ValueError, + TypeError, + ) as exc: + return _fail_closed_outcome( + payload, reason=f"Fail-closed client error: {type(exc).__name__}" + ) + + if outcome.request_id != expected_request_id: + return _fail_closed_outcome( + payload, + reason=( + "Fail-closed client response error: response request_id " + f"{outcome.request_id!r} != sent {expected_request_id!r}" + ), + ) + + # Enforce fail-closed invariants client-side so a compromised/buggy server + # cannot sneak ALLOW past abstained=True or prob >= threshold. + if outcome.decision is VetoDecision.ALLOW and ( + outcome.abstained + or outcome.calibrated_fault_prob >= outcome.calibrated_threshold + ): + return _fail_closed_outcome( + payload, + reason=( + "Fail-closed client invariant error: ALLOW rejected when " + "abstained=True or calibrated_fault_prob >= calibrated_threshold." + ), + ) + return outcome + + +__all__ = [ + "ByocVerifyPayload", + "ByocVetoServer", + "DEFAULT_MAX_BODY_BYTES", + "DEFAULT_MAX_CONCURRENT_CONNECTIONS", + "DEFAULT_REQUEST_TIMEOUT_S", + "DEFAULT_TLS_HANDSHAKE_TIMEOUT_S", + "IssuedRunBinding", + "RunBinding", + "create_byoc_veto_server", + "post_verify_request", +] diff --git a/packages/flow/openadapt_flow/calibration_collector.py b/packages/flow/openadapt_flow/calibration_collector.py new file mode 100644 index 0000000000..7b06dbfa74 --- /dev/null +++ b/packages/flow/openadapt_flow/calibration_collector.py @@ -0,0 +1,523 @@ +"""Online False-Pause Calibration Collector (value-free, opt-in local queue). + +Records operator override events from Exception Inbox or live-run pauses into +strictly tenant-scoped, value-free local JSONL queues for per-app LoRA +calibration. + +Security & privacy invariants: +- **Opt-in by default (off):** Refuses to write unless ``consent_enabled=True`` + is explicitly set by the operator/deployment. +- **Value-free:** Stores only SHA-256 screenshot hashes, structural metadata + from an explicit allowlist, and verdict labels. Never accepts or persists + raw form values, screenshots, DOM text, or free-text notes. +- **Fail-closed tenant isolation:** Refuses missing/invalid ``tenant_id`` and + rejects cross-tenant writes or reads when bound to a tenant. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import threading +from datetime import datetime, timezone +from enum import Enum +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from openadapt_flow.multi_lora_veto import VetoDecision + +CALIBRATION_RECORD_SCHEMA: Literal["openadapt.veto-calibration/v1"] = ( + "openadapt.veto-calibration/v1" +) + +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_SAFE_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") +_SAFE_STEP_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$") + +# Simple PII pattern guards for structural metadata string values. +_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}") +_SSN_RE = re.compile(r"\b\d{3}-\d{2}-\d{4}\b") +_PHONE_RE = re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b") + +ALLOWED_STRUCTURAL_METADATA_KEYS: frozenset[str] = frozenset( + { + "aria_error_count", + "device_scale_factor", + "dom_claims_success", + "dom_field_count", + "http_status", + "latency_ms", + "roi_crop_used", + "theme_hint", + "ui_framework_hint", + "viewport_height", + "viewport_width", + } +) + + +class CalibrationVerdict(str, Enum): + """Verdict labels accepted for online false-pause calibration records.""" + + ALLOW = "ALLOW" + VETO = "VETO" + HALT_ESCALATE = "HALT_ESCALATE" + ABSTAIN = "ABSTAIN" + + +class OverrideKind(str, Enum): + """Derived calibration signal comparing model prediction vs operator verdict.""" + + FALSE_PAUSE = "false_pause" + TRUE_FAULT = "true_fault" + MISSED_FAULT = "missed_fault" + CONFIRMED_ALLOW = "confirmed_allow" + + +def _coerce_verdict( + value: CalibrationVerdict | VetoDecision | str, +) -> CalibrationVerdict: + if isinstance(value, CalibrationVerdict): + return value + if isinstance(value, VetoDecision): + return CalibrationVerdict(value.value) + if isinstance(value, str): + normalized = value.strip().upper() + if normalized == "PASS": + return CalibrationVerdict.ALLOW + if normalized == "ACCEPT": + return CalibrationVerdict.ALLOW + return CalibrationVerdict(normalized) + raise ValueError(f"Unsupported verdict type: {type(value).__name__}") + + +def _derive_override_kind( + predicted: CalibrationVerdict, + operator: CalibrationVerdict, +) -> OverrideKind: + pred_paused = predicted is not CalibrationVerdict.ALLOW + op_allowed = operator is CalibrationVerdict.ALLOW + if pred_paused and op_allowed: + return OverrideKind.FALSE_PAUSE + if pred_paused and not op_allowed: + return OverrideKind.TRUE_FAULT + if not pred_paused and not op_allowed: + return OverrideKind.MISSED_FAULT + return OverrideKind.CONFIRMED_ALLOW + + +def _validate_slug(value: str, field_name: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError(f"{field_name} must be a non-empty string.") + cleaned = value.strip() + if ( + ".." in cleaned + or "/" in cleaned + or "\\" in cleaned + or not _SAFE_SLUG_RE.match(cleaned) + ): + raise ValueError(f"Invalid {field_name}: {value!r}") + return cleaned + + +def _validate_structural_metadata( + raw: dict[str, Any] | None, +) -> dict[str, str | int | float | bool]: + if not raw: + return {} + cleaned: dict[str, str | int | float | bool] = {} + for key, val in raw.items(): + if key not in ALLOWED_STRUCTURAL_METADATA_KEYS: + raise ValueError( + f"Value-free violation: disallowed structural_metadata key {key!r}. " + f"Allowed keys: {sorted(ALLOWED_STRUCTURAL_METADATA_KEYS)}" + ) + if isinstance(val, bool): + cleaned[key] = val + elif isinstance(val, (int, float)): + cleaned[key] = val + elif isinstance(val, str): + s = val.strip() + if len(s) > 64: + raise ValueError( + f"Value-free violation: structural_metadata[{key!r}] exceeds 64 characters." + ) + if _EMAIL_RE.search(s) or _SSN_RE.search(s) or _PHONE_RE.search(s): + raise ValueError( + f"Value-free violation: structural_metadata[{key!r}] matched a PII pattern." + ) + cleaned[key] = s + else: + raise ValueError( + f"Value-free violation: structural_metadata[{key!r}] must be a scalar " + f"(str, int, float, or bool), got {type(val).__name__}." + ) + return cleaned + + +class CalibrationOverrideRecord(BaseModel): + """Value-free operator override record for offline LoRA calibration.""" + + model_config = ConfigDict(extra="forbid") + + schema_version: Literal["openadapt.veto-calibration/v1"] = CALIBRATION_RECORD_SCHEMA + tenant_id: str = Field(min_length=1) + app_id: str = Field(min_length=1) + workflow_id: str = Field(min_length=1) + step_id: str = Field(min_length=1) + screenshot_hash: str + pre_submit_screenshot_hash: str | None = None + predicted_verdict: CalibrationVerdict + operator_verdict: CalibrationVerdict + override_kind: OverrideKind + adapter_id: str | None = None + calibrated_fault_prob: float | None = Field(default=None, ge=0.0, le=1.0) + structural_metadata: dict[str, str | int | float | bool] = Field( + default_factory=dict + ) + recorded_at: str = Field(min_length=1) + fingerprint: str + + @field_validator("tenant_id") + @classmethod + def _check_tenant_id(cls, value: str) -> str: + return _validate_slug(value, "tenant_id") + + @field_validator("app_id") + @classmethod + def _check_app_id(cls, value: str) -> str: + return _validate_slug(value, "app_id") + + @field_validator("workflow_id") + @classmethod + def _check_workflow_id(cls, value: str) -> str: + return _validate_slug(value, "workflow_id") + + @field_validator("step_id") + @classmethod + def _check_step_id(cls, value: str) -> str: + return _validate_slug(value, "step_id") + + @field_validator("adapter_id") + @classmethod + def _check_adapter_id(cls, value: str | None) -> str | None: + if value is None: + return None + return _validate_slug(value, "adapter_id") + + @field_validator("screenshot_hash") + @classmethod + def _check_screenshot_hash(cls, value: str) -> str: + normalized = value.strip().lower() + if not _SHA256_RE.match(normalized): + raise ValueError( + f"screenshot_hash must be 64 lowercase hex characters (got {value!r})" + ) + return normalized + + @field_validator("pre_submit_screenshot_hash") + @classmethod + def _check_pre_submit_hash(cls, value: str | None) -> str | None: + if value is None: + return None + normalized = value.strip().lower() + if not _SHA256_RE.match(normalized): + raise ValueError( + f"pre_submit_screenshot_hash must be 64 lowercase hex characters (got {value!r})" + ) + return normalized + + @field_validator("fingerprint") + @classmethod + def _check_fingerprint(cls, value: str) -> str: + normalized = value.strip().lower() + if not _SHA256_RE.match(normalized): + raise ValueError( + f"fingerprint must be 64 lowercase hex characters (got {value!r})" + ) + return normalized + + +class CalibrationReadinessSummary(BaseModel): + """Summary of queued calibration overrides for one ``(tenant_id, app_id)``.""" + + model_config = ConfigDict(extra="forbid") + + tenant_id: str + app_id: str + total_records: int = Field(ge=0) + false_pause_count: int = Field(ge=0) + true_fault_count: int = Field(ge=0) + missed_fault_count: int = Field(ge=0) + min_samples_required: int = Field(ge=1) + ready_for_calibration: bool + + +def _compute_fingerprint( + *, + tenant_id: str, + app_id: str, + workflow_id: str, + step_id: str, + screenshot_hash: str, + predicted_verdict: CalibrationVerdict, + operator_verdict: CalibrationVerdict, +) -> str: + canonical = json.dumps( + { + "tenant_id": tenant_id, + "app_id": app_id, + "workflow_id": workflow_id, + "step_id": step_id, + "screenshot_hash": screenshot_hash, + "predicted_verdict": predicted_verdict.value, + "operator_verdict": operator_verdict.value, + }, + sort_keys=True, + ) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +class CalibrationCollector: + """Tenant-isolated, value-free JSONL queue for offline per-app LoRA calibration. + + No trainer is wired in this module; records are queued locally for future + offline calibration workflows. + """ + + def __init__( + self, + queue_root: Path, + *, + bound_tenant_id: str | None = None, + consent_enabled: bool = False, + ) -> None: + self._queue_root = Path(queue_root).resolve() + self._bound_tenant_id = ( + _validate_slug(bound_tenant_id, "bound_tenant_id") + if bound_tenant_id is not None + else None + ) + self._consent_enabled = bool(consent_enabled) + self._lock = threading.Lock() + + @property + def consent_enabled(self) -> bool: + return self._consent_enabled + + @property + def queue_root(self) -> Path: + return self._queue_root + + @property + def bound_tenant_id(self) -> str | None: + return self._bound_tenant_id + + def _enforce_tenant_access(self, tenant_id: str) -> str: + validated = _validate_slug(tenant_id, "tenant_id") + if self._bound_tenant_id is not None and validated != self._bound_tenant_id: + raise PermissionError( + f"Cross-tenant calibration access denied: collector is bound to " + f"{self._bound_tenant_id!r}, got {validated!r}." + ) + return validated + + def queue_path_for(self, tenant_id: str, app_id: str) -> Path: + safe_tenant = self._enforce_tenant_access(tenant_id) + safe_app = _validate_slug(app_id, "app_id") + tenant_dir = (self._queue_root / safe_tenant).resolve() + if tenant_dir.parent != self._queue_root: + raise PermissionError("Resolved tenant queue directory escapes queue_root.") + target = (tenant_dir / f"{safe_app}.jsonl").resolve() + if target.parent != tenant_dir: + raise PermissionError( + "Resolved calibration queue file escapes tenant directory." + ) + return target + + def record_operator_override( + self, + *, + tenant_id: str, + app_id: str, + workflow_id: str, + step_id: str, + screenshot_hash: str, + predicted_verdict: CalibrationVerdict | VetoDecision | str, + operator_verdict: CalibrationVerdict | VetoDecision | str, + pre_submit_screenshot_hash: str | None = None, + adapter_id: str | None = None, + calibrated_fault_prob: float | None = None, + structural_metadata: dict[str, Any] | None = None, + recorded_at: str | None = None, + ) -> CalibrationOverrideRecord: + """Append one value-free calibration override record to the tenant queue.""" + if not self._consent_enabled: + raise PermissionError( + "Calibration collection is disabled by default; set consent_enabled=True to record." + ) + safe_tenant = self._enforce_tenant_access(tenant_id) + safe_app = _validate_slug(app_id, "app_id") + safe_workflow = _validate_slug(workflow_id, "workflow_id") + pred = _coerce_verdict(predicted_verdict) + op = _coerce_verdict(operator_verdict) + clean_meta = _validate_structural_metadata(structural_metadata) + norm_hash = screenshot_hash.strip().lower() + timestamp = recorded_at or datetime.now(timezone.utc).isoformat() + fp = _compute_fingerprint( + tenant_id=safe_tenant, + app_id=safe_app, + workflow_id=safe_workflow, + step_id=step_id.strip(), + screenshot_hash=norm_hash, + predicted_verdict=pred, + operator_verdict=op, + ) + record = CalibrationOverrideRecord( + tenant_id=safe_tenant, + app_id=safe_app, + workflow_id=safe_workflow, + step_id=step_id, + screenshot_hash=norm_hash, + pre_submit_screenshot_hash=pre_submit_screenshot_hash, + predicted_verdict=pred, + operator_verdict=op, + override_kind=_derive_override_kind(pred, op), + adapter_id=adapter_id, + calibrated_fault_prob=calibrated_fault_prob, + structural_metadata=clean_meta, + recorded_at=timestamp, + fingerprint=fp, + ) + + target = self.queue_path_for(safe_tenant, safe_app) + line = json.dumps(record.model_dump(mode="json"), sort_keys=True) + "\n" + with self._lock: + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("a", encoding="utf-8") as handle: + handle.write(line) + return record + + def read_tenant_queue( + self, + tenant_id: str, + *, + app_id: str | None = None, + deduplicate: bool = True, + ) -> list[CalibrationOverrideRecord]: + """Read value-free calibration records belonging strictly to ``tenant_id``.""" + safe_tenant = self._enforce_tenant_access(tenant_id) + tenant_dir = (self._queue_root / safe_tenant).resolve() + if not tenant_dir.is_dir(): + return [] + + files: list[Path] + if app_id is not None: + path = self.queue_path_for(safe_tenant, app_id) + files = [path] if path.is_file() else [] + else: + files = sorted(tenant_dir.glob("*.jsonl")) + + seen: set[str] = set() + records: list[CalibrationOverrideRecord] = [] + with self._lock: + for file_path in files: + for raw_line in file_path.read_text(encoding="utf-8").splitlines(): + stripped = raw_line.strip() + if not stripped: + continue + rec = CalibrationOverrideRecord.model_validate_json(stripped) + if rec.tenant_id != safe_tenant: + raise PermissionError( + f"Tenant isolation violation in {file_path}: expected " + f"{safe_tenant!r}, found {rec.tenant_id!r}." + ) + if deduplicate and rec.fingerprint in seen: + continue + seen.add(rec.fingerprint) + records.append(rec) + return records + + def calibration_readiness( + self, + tenant_id: str, + app_id: str, + *, + min_samples: int = 10, + ) -> CalibrationReadinessSummary: + """Report whether enough deduplicated overrides exist for offline LoRA calibration.""" + records = self.read_tenant_queue(tenant_id, app_id=app_id, deduplicate=True) + false_pauses = sum( + 1 for r in records if r.override_kind is OverrideKind.FALSE_PAUSE + ) + true_faults = sum( + 1 for r in records if r.override_kind is OverrideKind.TRUE_FAULT + ) + missed_faults = sum( + 1 for r in records if r.override_kind is OverrideKind.MISSED_FAULT + ) + return CalibrationReadinessSummary( + tenant_id=tenant_id, + app_id=app_id, + total_records=len(records), + false_pause_count=false_pauses, + true_fault_count=true_faults, + missed_fault_count=missed_faults, + min_samples_required=min_samples, + ready_for_calibration=len(records) >= min_samples, + ) + + +def record_operator_override( + tenant_id: str, + app_id: str, + workflow_id: str, + step_id: str, + screenshot_hash: str, + predicted_verdict: CalibrationVerdict | VetoDecision | str, + operator_verdict: CalibrationVerdict | VetoDecision | str, + *, + queue_root: Path, + consent_enabled: bool = False, + bound_tenant_id: str | None = None, + pre_submit_screenshot_hash: str | None = None, + adapter_id: str | None = None, + calibrated_fault_prob: float | None = None, + structural_metadata: dict[str, Any] | None = None, + recorded_at: str | None = None, +) -> CalibrationOverrideRecord: + """Convenience entry point for recording one value-free operator override.""" + collector = CalibrationCollector( + queue_root, + bound_tenant_id=bound_tenant_id, + consent_enabled=consent_enabled, + ) + return collector.record_operator_override( + tenant_id=tenant_id, + app_id=app_id, + workflow_id=workflow_id, + step_id=step_id, + screenshot_hash=screenshot_hash, + predicted_verdict=predicted_verdict, + operator_verdict=operator_verdict, + pre_submit_screenshot_hash=pre_submit_screenshot_hash, + adapter_id=adapter_id, + calibrated_fault_prob=calibrated_fault_prob, + structural_metadata=structural_metadata, + recorded_at=recorded_at, + ) + + +__all__ = [ + "ALLOWED_STRUCTURAL_METADATA_KEYS", + "CALIBRATION_RECORD_SCHEMA", + "CalibrationCollector", + "CalibrationOverrideRecord", + "CalibrationReadinessSummary", + "CalibrationVerdict", + "OverrideKind", + "record_operator_override", +] diff --git a/packages/flow/openadapt_flow/multi_lora_veto.py b/packages/flow/openadapt_flow/multi_lora_veto.py new file mode 100644 index 0000000000..77980fdd76 --- /dev/null +++ b/packages/flow/openadapt_flow/multi_lora_veto.py @@ -0,0 +1,798 @@ +"""Multi-LoRA app-adapter registry, veto router, and active-learning JSONL export contracts. + +Defines the control-plane registry, routing, temperature calibration, +fail-closed ``ABSTAIN -> HALT_ESCALATE`` semantics, and deduplicated QLoRA JSONL +export from resolved Exception Inbox items. No model weight loader or trainer is +wired in this module. +""" + +from __future__ import annotations + +import fnmatch +import hashlib +import hmac +import json +import math +import os +import re +import tempfile +from collections.abc import Sequence +from enum import Enum +from pathlib import Path +from typing import Any, Protocol + +import yaml +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +ADAPTER_REGISTRY_SCHEMA = "openadapt.adapter-registry/v1" + +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_SAFE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$") +_FIELD_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$") +_NONCE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +_MIN_HMAC_KEY_BYTES = 16 + + +class TenantScope(str, Enum): + """Visibility boundary of a registered LoRA adapter.""" + + PUBLIC = "public" + BYOC = "byoc" + + +class VetoDecision(str, Enum): + """Fail-closed decision emitted by the visual veto router. + + ``ALLOW`` means strictly **"no veto"** — it NEVER means ``VERIFIED`` and + NEVER proves that a write persisted in the system of record. + """ + + ALLOW = "ALLOW" + VETO = "VETO" + HALT_ESCALATE = "HALT_ESCALATE" + + +class InboxResolutionLabel(str, Enum): + """Human adjudication outcome from the Exception Inbox.""" + + TRUE_FAULT = "true_fault" + FALSE_ALARM = "false_alarm" + + +def hmac_field_value( + tenant_key: bytes | str, + field_slug: str, + value: str, +) -> str: + """Compute a keyed HMAC-SHA256 digest for a form field value. + + Design: ``tenant_key`` is a per-tenant secret (at least 16 bytes) that + stays strictly server-side inside the customer VPC (never distributed to + zero-GPU laptops and never written to training JSONL exports). When the + VPC orchestrator binds expected form fields for a run, it computes + ``hmac_field_value(tenant_key, field_slug, expected_value)`` server-side; + the VPC backend independently reads the rendered field from the screen, + computes ``hmac_field_value(tenant_key, field_slug, observed_value)``, + and compares the digests in constant time. + """ + if not _FIELD_SLUG_RE.match(field_slug): + raise ValueError( + f"field_slug must match {_FIELD_SLUG_RE.pattern!r} (got {field_slug!r})." + ) + key_bytes = ( + tenant_key.encode("utf-8") if isinstance(tenant_key, str) else bytes(tenant_key) + ) + if len(key_bytes) < _MIN_HMAC_KEY_BYTES: + raise ValueError( + f"tenant_key must be at least {_MIN_HMAC_KEY_BYTES} bytes long." + ) + msg = f"{field_slug}\x00{value}".encode("utf-8") + return hmac.new(key_bytes, msg, hashlib.sha256).hexdigest() + + +class AdapterSpec(BaseModel): + """Declarative specification for one hot-swappable LoRA veto adapter. + + Note: ``sha256`` is currently validated for format only (metadata-only / + unenforced in this control-plane module). Any weight loader wired to this + registry MUST verify ``sha256`` against the adapter bytes before load, + accept only ``.safetensors`` (never ``torch.load``/pickle), and restrict + ``adapter_uri`` to an allowlisted root. + """ + + model_config = ConfigDict(extra="forbid") + + adapter_id: str = Field(min_length=1) + base_model: str = Field(min_length=1) + adapter_uri: str = Field(min_length=1) + sha256: str + calibrated_threshold: float = Field(ge=0.0, le=1.0) + temperature: float = Field(default=1.0, gt=0.0) + tenant_scope: TenantScope = TenantScope.PUBLIC + tenant_id: str | None = None + app_id: str | None = None + workflow_id: str | None = None + domain_pattern: str | None = None + + @field_validator("adapter_id") + @classmethod + def _validate_adapter_id(cls, value: str) -> str: + if not _SAFE_ID_RE.match(value): + raise ValueError(f"Invalid adapter_id: {value!r}") + return value + + @field_validator("sha256") + @classmethod + def _validate_sha256(cls, value: str) -> str: + normalized = value.strip().lower() + if not _SHA256_RE.match(normalized): + raise ValueError( + f"sha256 must be 64 lowercase hex characters (got {value!r})" + ) + return normalized + + @model_validator(mode="after") + def _validate_tenant_scope(self) -> AdapterSpec: + if self.tenant_scope is TenantScope.BYOC: + if not self.tenant_id or not self.tenant_id.strip(): + raise ValueError("BYOC adapter requires a non-empty tenant_id.") + elif self.tenant_id is not None: + raise ValueError("Public adapter must not bind a private tenant_id.") + return self + + +def _validate_sha256_hex(value: str, field_name: str) -> str: + normalized = value.strip().lower() + if not _SHA256_RE.match(normalized): + raise ValueError(f"{field_name} must be 64 lowercase hex characters.") + return normalized + + +def _validate_sha256_map(values: dict[str, str]) -> dict[str, str]: + cleaned: dict[str, str] = {} + for key, digest in values.items(): + if not isinstance(key, str) or not _FIELD_SLUG_RE.match(key): + raise ValueError( + f"Field hash key must be a lowercase slug matching {_FIELD_SLUG_RE.pattern!r}." + ) + normalized = digest.strip().lower() + if not _SHA256_RE.match(normalized): + raise ValueError( + "expected_field_hashes values must be 64 lowercase hex HMAC-SHA256 digests " + "(raw form values are forbidden)." + ) + cleaned[key] = normalized + return cleaned + + +class VetoInferenceRequest(BaseModel): + """Value-free pre/post-submit visual veto request routed to an app adapter. + + Design: this control-plane request carries only 64-hex SHA-256 image + references and keyed HMAC-SHA256 field digests (computed via + :func:`hmac_field_value` with a customer-VPC per-tenant secret; no raw + form values, screenshots, or caller self-vouching booleans on the wire). + A real :class:`LoraBackend` dereferences ``pre_submit_image_sha256`` / + ``post_submit_image_sha256`` from a local or customer-VPC encrypted + artifact store, binds them to ``step_nonce`` when present, and MUST return + ``abstain=True`` if either image cannot be loaded or verified against its + SHA-256 digest. + """ + + model_config = ConfigDict(extra="forbid") + + request_id: str = Field(min_length=1) + app_id: str = Field(min_length=1) + workflow_id: str | None = None + domain: str | None = None + tenant_id: str | None = None + step_nonce: str | None = None + pre_submit_image_sha256: str = Field(min_length=64, max_length=64) + post_submit_image_sha256: str = Field(min_length=64, max_length=64) + expected_field_hashes: dict[str, str] = Field(default_factory=dict) + dom_claims_success: bool = False + + @field_validator("pre_submit_image_sha256") + @classmethod + def _check_pre_image_sha256(cls, value: str) -> str: + return _validate_sha256_hex(value, "pre_submit_image_sha256") + + @field_validator("post_submit_image_sha256") + @classmethod + def _check_post_image_sha256(cls, value: str) -> str: + return _validate_sha256_hex(value, "post_submit_image_sha256") + + @field_validator("step_nonce") + @classmethod + def _check_step_nonce(cls, value: str | None) -> str | None: + if value is None: + return None + if not _NONCE_RE.match(value): + raise ValueError(f"step_nonce must match {_NONCE_RE.pattern!r}.") + return value + + @field_validator("expected_field_hashes") + @classmethod + def _check_expected_field_hashes(cls, value: dict[str, str]) -> dict[str, str]: + return _validate_sha256_map(value) + + +class RawVetoScore(BaseModel): + """Unscaled backend score before per-adapter temperature calibration.""" + + model_config = ConfigDict(extra="forbid") + + fault_logit: float + abstain: bool = False + abstain_reason: str = "" + rationale: str = "" + + +class VetoOutcome(BaseModel): + """Calibrated, fail-closed veto outcome returned by ``MultiLoraVetoRouter``.""" + + model_config = ConfigDict(extra="forbid") + + request_id: str + adapter_id: str + base_model: str + decision: VetoDecision + calibrated_fault_prob: float = Field(ge=0.0, le=1.0) + calibrated_threshold: float = Field(ge=0.0, le=1.0) + temperature: float = Field(gt=0.0) + abstained: bool + dom_override_blocked: bool + reason: str + + +def calibrate_probability(fault_logit: float, temperature: float) -> float: + """Apply temperature scaling to a fault logit and return sigmoid probability.""" + if temperature <= 0.0: + raise ValueError(f"temperature must be > 0 (got {temperature})") + scaled = fault_logit / temperature + if scaled >= 0.0: + z = math.exp(-scaled) + return 1.0 / (1.0 + z) + z = math.exp(scaled) + return z / (1.0 + z) + + +def vllm_request_payload( + spec: AdapterSpec, + request: VetoInferenceRequest, +) -> dict[str, Any]: + """Build a value-free vLLM multi-LoRA inference request payload targeting ``spec.adapter_id``.""" + return { + "model": spec.adapter_id, + "metadata": { + "base_model": spec.base_model, + "request_id": request.request_id, + "app_id": request.app_id, + "workflow_id": request.workflow_id, + "step_nonce": request.step_nonce, + "pre_submit_image_sha256": request.pre_submit_image_sha256, + "post_submit_image_sha256": request.post_submit_image_sha256, + }, + "expected_field_hashes": dict(request.expected_field_hashes), + } + + +def ollama_model_tag(spec: AdapterSpec) -> str: + """Return the deterministic Ollama model tag for a base + adapter pair.""" + if spec.adapter_uri.startswith("ollama://"): + return spec.adapter_uri.removeprefix("ollama://") + return f"{spec.base_model}:{spec.adapter_id}" + + +class AppAdapterRegistry: + """Declarative registry mapping ``(tenant, app, workflow, domain)`` to ``AdapterSpec``.""" + + def __init__( + self, + *, + default_base_adapter: AdapterSpec, + adapters: Sequence[AdapterSpec] = (), + ) -> None: + if default_base_adapter.tenant_scope is not TenantScope.PUBLIC: + raise ValueError("default_base_adapter must have tenant_scope='public'.") + self._default_base = default_base_adapter + self._by_id: dict[str, AdapterSpec] = { + default_base_adapter.adapter_id: default_base_adapter + } + self._adapters: list[AdapterSpec] = [] + for spec in adapters: + self.register(spec) + + @property + def default_base_adapter(self) -> AdapterSpec: + return self._default_base + + def register(self, spec: AdapterSpec) -> None: + if spec.adapter_id in self._by_id: + raise ValueError(f"Duplicate adapter_id in registry: {spec.adapter_id!r}") + self._by_id[spec.adapter_id] = spec + self._adapters.append(spec) + + def get(self, adapter_id: str, *, tenant_id: str | None = None) -> AdapterSpec: + if adapter_id not in self._by_id: + raise KeyError(f"Unknown adapter_id: {adapter_id!r}") + spec = self._by_id[adapter_id] + if spec.tenant_scope is TenantScope.BYOC and spec.tenant_id != tenant_id: + raise PermissionError( + f"Cross-tenant access denied for BYOC adapter {adapter_id!r}." + ) + return spec + + def _is_accessible(self, spec: AdapterSpec, tenant_id: str | None) -> bool: + if spec.tenant_scope is TenantScope.PUBLIC: + return True + return tenant_id is not None and spec.tenant_id == tenant_id + + def has_workflow_adapters( + self, + *, + app_id: str, + tenant_id: str | None = None, + ) -> bool: + """Return True if any accessible workflow-specific adapter exists for ``app_id``.""" + return any( + self._is_accessible(spec, tenant_id) + and spec.app_id == app_id + and spec.workflow_id is not None + for spec in self._adapters + ) + + def resolve( + self, + *, + app_id: str, + workflow_id: str | None = None, + domain: str | None = None, + tenant_id: str | None = None, + requested_adapter_id: str | None = None, + allow_default_fallback: bool = True, + require_exact_workflow: bool = False, + ) -> AdapterSpec: + """Resolve the authoritative adapter from server-side bindings with strict BYOC isolation. + + Fallback chain: + 1. Exact BYOC ``(tenant_id, app_id, workflow_id)`` + 2. Exact BYOC ``(tenant_id, app_id)`` (no workflow binding) + 3. Public ``(app_id, workflow_id)`` + 4. Public ``(app_id)`` (no workflow binding) + 5. Matching ``domain_pattern`` (BYOC for ``tenant_id`` first, then public) + 6. Cold-start ``default_base_adapter`` (only when ``allow_default_fallback=True``) + + If ``require_exact_workflow=True`` and workflow-specific adapters exist + for ``app_id``, ``workflow_id`` MUST match a registered workflow adapter + (closing both missing-workflow and bogus-workflow downgrade bypasses). + + If ``requested_adapter_id`` is supplied by the caller, it is accepted + ONLY when it matches the server-resolved adapter; otherwise + ``PermissionError`` is raised so a caller can never steer scoring to a + more lenient adapter. + """ + resolved, used_default = self._resolve_authoritative( + app_id=app_id, + workflow_id=workflow_id, + domain=domain, + tenant_id=tenant_id, + ) + if used_default and not allow_default_fallback: + raise PermissionError( + f"No registered veto adapter for app_id={app_id!r} " + "(default adapter fallback is disabled)." + ) + if require_exact_workflow and self.has_workflow_adapters( + app_id=app_id, tenant_id=tenant_id + ): + if workflow_id is None or resolved.workflow_id != workflow_id: + raise PermissionError( + f"workflow_id {workflow_id!r} has no registered workflow veto adapter " + f"for app_id={app_id!r} (workflow downgrade rejected)." + ) + if ( + requested_adapter_id is not None + and requested_adapter_id != resolved.adapter_id + ): + raise PermissionError( + f"Caller-requested adapter {requested_adapter_id!r} does not match " + f"server-resolved adapter {resolved.adapter_id!r} for app_id={app_id!r}." + ) + return resolved + + def _resolve_authoritative( + self, + *, + app_id: str, + workflow_id: str | None = None, + domain: str | None = None, + tenant_id: str | None = None, + ) -> tuple[AdapterSpec, bool]: + accessible = [s for s in self._adapters if self._is_accessible(s, tenant_id)] + + if tenant_id is not None and workflow_id is not None: + for spec in accessible: + if ( + spec.tenant_scope is TenantScope.BYOC + and spec.tenant_id == tenant_id + and spec.app_id == app_id + and spec.workflow_id == workflow_id + ): + return spec, False + + if tenant_id is not None: + for spec in accessible: + if ( + spec.tenant_scope is TenantScope.BYOC + and spec.tenant_id == tenant_id + and spec.app_id == app_id + and spec.workflow_id is None + ): + return spec, False + + if workflow_id is not None: + for spec in accessible: + if ( + spec.tenant_scope is TenantScope.PUBLIC + and spec.app_id == app_id + and spec.workflow_id == workflow_id + ): + return spec, False + + for spec in accessible: + if ( + spec.tenant_scope is TenantScope.PUBLIC + and spec.app_id == app_id + and spec.workflow_id is None + ): + return spec, False + + if domain: + normalized_domain = domain.strip().lower() + for scope in (TenantScope.BYOC, TenantScope.PUBLIC): + for spec in accessible: + if ( + spec.tenant_scope is scope + and spec.domain_pattern + and fnmatch.fnmatch( + normalized_domain, spec.domain_pattern.lower() + ) + ): + return spec, False + + return self._default_base, True + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> AppAdapterRegistry: + schema = data.get("schema_version", ADAPTER_REGISTRY_SCHEMA) + if schema != ADAPTER_REGISTRY_SCHEMA: + raise ValueError(f"Unsupported registry schema_version: {schema!r}") + default_base = AdapterSpec.model_validate(data["default_base_adapter"]) + adapters = [ + AdapterSpec.model_validate(item) for item in data.get("adapters", []) + ] + return cls(default_base_adapter=default_base, adapters=adapters) + + @classmethod + def from_json(cls, source: str | Path) -> AppAdapterRegistry: + raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source + data = json.loads(raw) + if not isinstance(data, dict): + raise ValueError("Adapter registry JSON root must be an object.") + return cls.from_dict(data) + + @classmethod + def from_yaml(cls, source: str | Path) -> AppAdapterRegistry: + raw = source.read_text(encoding="utf-8") if isinstance(source, Path) else source + data = yaml.safe_load(raw) + if not isinstance(data, dict): + raise ValueError("Adapter registry YAML root must be a mapping.") + return cls.from_dict(data) + + +class LoraBackend(Protocol): + """Pluggable inference backend (PEFT ``set_adapter``, vLLM, or Ollama).""" + + @property + def active_adapter_id(self) -> str | None: ... + + def ensure_adapter(self, spec: AdapterSpec) -> bool: + """Activate ``spec`` on the loaded base model. Return True if swapped.""" + ... + + def score(self, spec: AdapterSpec, request: VetoInferenceRequest) -> RawVetoScore: + """Run visual veto scoring using ``spec``.""" + ... + + +class MultiLoraVetoRouter: + """Single-base, multi-LoRA router with fail-closed calibration.""" + + def __init__( + self, + *, + base_model: str, + registry: AppAdapterRegistry, + backend: LoraBackend, + ) -> None: + if not base_model.strip(): + raise ValueError("base_model must be non-empty.") + self._base_model = base_model + self._registry = registry + self._backend = backend + self.swap_count = 0 + self.request_count = 0 + + @property + def base_model(self) -> str: + return self._base_model + + @property + def registry(self) -> AppAdapterRegistry: + return self._registry + + @property + def active_adapter_id(self) -> str | None: + return self._backend.active_adapter_id + + def evaluate( + self, + request: VetoInferenceRequest, + *, + requested_adapter_id: str | None = None, + allow_default_fallback: bool = True, + require_exact_workflow: bool = False, + ) -> VetoOutcome: + spec = self._registry.resolve( + app_id=request.app_id, + workflow_id=request.workflow_id, + domain=request.domain, + tenant_id=request.tenant_id, + requested_adapter_id=requested_adapter_id, + allow_default_fallback=allow_default_fallback, + require_exact_workflow=require_exact_workflow, + ) + if spec.base_model != self._base_model: + raise ValueError( + f"Adapter {spec.adapter_id!r} targets base_model={spec.base_model!r}, " + f"expected {self._base_model!r}." + ) + if spec.app_id is not None and spec.app_id != request.app_id: + raise PermissionError( + f"Adapter {spec.adapter_id!r} is bound to app_id={spec.app_id!r}, " + f"not {request.app_id!r}." + ) + if spec.workflow_id is not None and spec.workflow_id != request.workflow_id: + raise PermissionError( + f"Adapter {spec.adapter_id!r} is bound to workflow_id={spec.workflow_id!r}, " + f"not {request.workflow_id!r}." + ) + + swapped = self._backend.ensure_adapter(spec) + if swapped: + self.swap_count += 1 + self.request_count += 1 + + raw = self._backend.score(spec, request) + prob = calibrate_probability(raw.fault_logit, spec.temperature) + + if raw.abstain: + reason = raw.abstain_reason.strip() or ( + "Visual veto abstained (occlusion or unreadable state); halting for human review." + ) + return VetoOutcome( + request_id=request.request_id, + adapter_id=spec.adapter_id, + base_model=spec.base_model, + decision=VetoDecision.HALT_ESCALATE, + calibrated_fault_prob=prob, + calibrated_threshold=spec.calibrated_threshold, + temperature=spec.temperature, + abstained=True, + dom_override_blocked=request.dom_claims_success, + reason=reason, + ) + + if prob >= spec.calibrated_threshold: + reason = raw.rationale.strip() or ( + f"Calibrated fault probability {prob:.4f} >= threshold " + f"{spec.calibrated_threshold:.4f}; commit vetoed." + ) + return VetoOutcome( + request_id=request.request_id, + adapter_id=spec.adapter_id, + base_model=spec.base_model, + decision=VetoDecision.VETO, + calibrated_fault_prob=prob, + calibrated_threshold=spec.calibrated_threshold, + temperature=spec.temperature, + abstained=False, + dom_override_blocked=request.dom_claims_success, + reason=reason, + ) + + reason = raw.rationale.strip() or ( + f"Calibrated fault probability {prob:.4f} < threshold " + f"{spec.calibrated_threshold:.4f}; visual veto did not fire (no veto)." + ) + return VetoOutcome( + request_id=request.request_id, + adapter_id=spec.adapter_id, + base_model=spec.base_model, + decision=VetoDecision.ALLOW, + calibrated_fault_prob=prob, + calibrated_threshold=spec.calibrated_threshold, + temperature=spec.temperature, + abstained=False, + dom_override_blocked=False, + reason=reason, + ) + + +class InboxResolutionItem(BaseModel): + """Value-free Exception Inbox resolution item eligible for QLoRA active learning. + + ``expected_field_hashes`` MUST contain per-tenant keyed HMAC-SHA256 digests + produced by :func:`hmac_field_value` (with the tenant key kept strictly + inside the customer VPC and never exported). + """ + + model_config = ConfigDict(extra="forbid") + + item_id: str = Field(min_length=1) + app_id: str = Field(min_length=1) + workflow_id: str | None = None + tenant_id: str = Field(min_length=1) + label: InboxResolutionLabel + pre_submit_image_ref: str = Field(min_length=64, max_length=64) + post_submit_image_ref: str = Field(min_length=64, max_length=64) + expected_field_hashes: dict[str, str] = Field(default_factory=dict) + resolved_at: str = Field(min_length=1) + + @field_validator("pre_submit_image_ref") + @classmethod + def _check_pre_image_ref(cls, value: str) -> str: + return _validate_sha256_hex(value, "pre_submit_image_ref") + + @field_validator("post_submit_image_ref") + @classmethod + def _check_post_image_ref(cls, value: str) -> str: + return _validate_sha256_hex(value, "post_submit_image_ref") + + @field_validator("expected_field_hashes") + @classmethod + def _check_expected_field_hashes(cls, value: dict[str, str]) -> dict[str, str]: + return _validate_sha256_map(value) + + +def _dedup_fingerprint(item: InboxResolutionItem) -> str: + canonical = json.dumps( + { + "tenant_id": item.tenant_id, + "app_id": item.app_id, + "workflow_id": item.workflow_id, + "pre_submit_image_ref": item.pre_submit_image_ref, + "post_submit_image_ref": item.post_submit_image_ref, + "label": item.label.value, + "expected_field_hashes": item.expected_field_hashes, + }, + sort_keys=True, + ) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def export_inbox_training_jsonl( + items: Sequence[InboxResolutionItem], + output_path: Path, + *, + tenant_id: str | None = None, + app_id: str | None = None, +) -> int: + """Export resolved Exception Inbox items into deduplicated, value-free QLoRA JSONL pairs. + + Never writes raw form values, tenant HMAC keys, or free-text reviewer notes + into training files. When ``tenant_id`` is provided, enforces strict + single-tenant VPC isolation by exporting only records belonging to that + tenant. + """ + seen: set[str] = set() + records: list[dict[str, Any]] = [] + + for item in items: + if tenant_id is not None and item.tenant_id != tenant_id: + continue + if app_id is not None and item.app_id != app_id: + continue + fp = _dedup_fingerprint(item) + if fp in seen: + continue + seen.add(fp) + + target_verdict = ( + "FAULT" if item.label is InboxResolutionLabel.TRUE_FAULT else "CLEAN" + ) + records.append( + { + "messages": [ + { + "role": "system", + "content": ( + "Compare the pre-submit and post-submit screens against expected " + "field digests. Output FAULT if any write failed or drifted, or CLEAN if " + "all fields persisted." + ), + }, + { + "role": "user", + "content": json.dumps( + { + "app_id": item.app_id, + "workflow_id": item.workflow_id, + "pre_submit_image_ref": item.pre_submit_image_ref, + "post_submit_image_ref": item.post_submit_image_ref, + "expected_field_hashes": item.expected_field_hashes, + }, + sort_keys=True, + ), + }, + { + "role": "assistant", + "content": json.dumps( + { + "verdict": target_verdict, + "label": item.label.value, + }, + sort_keys=True, + ), + }, + ], + "metadata": { + "item_id": item.item_id, + "app_id": item.app_id, + "workflow_id": item.workflow_id, + "tenant_id": item.tenant_id, + "label": item.label.value, + "resolved_at": item.resolved_at, + "fingerprint": fp, + }, + } + ) + + dest = Path(output_path).resolve() + dest.parent.mkdir(parents=True, exist_ok=True) + fd, tmp_name = tempfile.mkstemp( + dir=dest.parent, prefix=".lora-train-", suffix=".tmp" + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + for rec in records: + handle.write(json.dumps(rec, sort_keys=True) + "\n") + os.replace(tmp_name, dest) + except BaseException: + if os.path.exists(tmp_name): + os.unlink(tmp_name) + raise + + return len(records) + + +__all__ = [ + "ADAPTER_REGISTRY_SCHEMA", + "AdapterSpec", + "AppAdapterRegistry", + "InboxResolutionItem", + "InboxResolutionLabel", + "LoraBackend", + "MultiLoraVetoRouter", + "RawVetoScore", + "TenantScope", + "VetoDecision", + "VetoInferenceRequest", + "VetoOutcome", + "calibrate_probability", + "export_inbox_training_jsonl", + "hmac_field_value", + "ollama_model_tag", + "vllm_request_payload", +] diff --git a/packages/flow/tests/test_byoc_veto_server.py b/packages/flow/tests/test_byoc_veto_server.py new file mode 100644 index 0000000000..4c097d7082 --- /dev/null +++ b/packages/flow/tests/test_byoc_veto_server.py @@ -0,0 +1,795 @@ +"""Tests for Mitigation #4: Shared BYOC Multi-LoRA Veto HTTP Server.""" + +from __future__ import annotations + +import hashlib +import json +import socket +import time +import urllib.error +import urllib.request +from typing import Any + +import pytest + +from openadapt_flow.byoc_veto_server import ( + ByocVetoServer, + RunBinding, + create_byoc_veto_server, + post_verify_request, +) +from openadapt_flow.multi_lora_veto import ( + AdapterSpec, + AppAdapterRegistry, + MultiLoraVetoRouter, + RawVetoScore, + TenantScope, + VetoDecision, + VetoInferenceRequest, +) + +_BASE_MODEL = "Qwen/Qwen3.5-9B" +_SHA_BASE = "0" * 64 +_SHA_A = "1" * 64 +_SHA_B = "2" * 64 +_SHA_C = "3" * 64 +_IMG_PRE = "a" * 64 +_IMG_POST = "b" * 64 +_IMG_OTHER = "c" * 64 +_HMAC_KEY_A = b"clinic-a-vpc-only-hmac-key-00001" +_HMAC_KEY_B = b"clinic-b-vpc-only-hmac-key-00002" + + +class _StubLoraBackend: + """In-memory multi-LoRA backend for deterministic HTTP server tests.""" + + def __init__( + self, scores_by_request: dict[str, RawVetoScore] | None = None + ) -> None: + self._active: str | None = None + self._scores = dict(scores_by_request or {}) + self.fail_next = False + self.loaded_sequence: list[str] = [] + + @property + def active_adapter_id(self) -> str | None: + return self._active + + def ensure_adapter(self, spec: AdapterSpec) -> bool: + self.loaded_sequence.append(spec.adapter_id) + if self._active == spec.adapter_id: + return False + self._active = spec.adapter_id + return True + + def score(self, spec: AdapterSpec, request: VetoInferenceRequest) -> RawVetoScore: + if self.fail_next: + self.fail_next = False + raise RuntimeError("simulated GPU OOM") + return self._scores.get( + request.request_id, + RawVetoScore(fault_logit=-3.0, rationale=f"clean via {spec.adapter_id}"), + ) + + +def _build_router( + scores: dict[str, RawVetoScore] | None = None, +) -> tuple[MultiLoraVetoRouter, _StubLoraBackend]: + registry = AppAdapterRegistry( + default_base_adapter=AdapterSpec( + adapter_id="veto-base-9b-v4", + base_model=_BASE_MODEL, + adapter_uri="local:///adapters/veto-base-9b-v4", + sha256=_SHA_BASE, + calibrated_threshold=0.5, + temperature=0.95, + tenant_scope=TenantScope.PUBLIC, + ), + adapters=[ + AdapterSpec( + adapter_id="veto-clinic-a-ehr", + base_model=_BASE_MODEL, + adapter_uri="local:///adapters/clinic-a-ehr", + sha256=_SHA_A, + calibrated_threshold=0.5, + temperature=0.95, + tenant_scope=TenantScope.BYOC, + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + ), + AdapterSpec( + adapter_id="veto-clinic-a-ehr-app-fallback", + base_model=_BASE_MODEL, + adapter_uri="local:///adapters/clinic-a-ehr-app", + sha256=_SHA_C, + calibrated_threshold=0.95, + temperature=1.0, + tenant_scope=TenantScope.BYOC, + tenant_id="clinic-a", + app_id="ehr-portal", + ), + AdapterSpec( + adapter_id="veto-clinic-b-ehr", + base_model=_BASE_MODEL, + adapter_uri="local:///adapters/clinic-b-ehr", + sha256=_SHA_B, + calibrated_threshold=0.5, + temperature=0.95, + tenant_scope=TenantScope.BYOC, + tenant_id="clinic-b", + app_id="ehr-portal", + workflow_id="intake", + ), + AdapterSpec( + adapter_id="veto-lenient-domain", + base_model=_BASE_MODEL, + adapter_uri="local:///adapters/lenient-domain", + sha256=_SHA_C, + calibrated_threshold=0.99, + temperature=1.0, + tenant_scope=TenantScope.PUBLIC, + domain_pattern="*.lenient.example", + ), + ], + ) + backend = _StubLoraBackend(scores) + router = MultiLoraVetoRouter( + base_model=_BASE_MODEL, registry=registry, backend=backend + ) + return router, backend + + +def _raw_http( + url: str, + *, + method: str = "GET", + headers: dict[str, str] | None = None, + payload: dict[str, Any] | None = None, +) -> tuple[int, dict[str, Any]]: + data = json.dumps(payload).encode("utf-8") if payload is not None else None + req_headers = dict(headers or {}) + if data is not None: + req_headers.setdefault("Content-Type", "application/json") + req = urllib.request.Request(url, data=data, headers=req_headers, method=method) + try: + with urllib.request.urlopen(req, timeout=5.0) as resp: # noqa: S310 + return resp.status, json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as exc: + return exc.code, json.loads(exc.read().decode("utf-8")) + + +def test_server_refuses_unauthenticated_duplicate_key_or_missing_allowlist_startup() -> ( + None +): + router, _ = _build_router() + with pytest.raises(ValueError, match="at least one tenant key"): + ByocVetoServer(router=router, tenant_api_keys={}, tenant_allowed_apps={}) + with pytest.raises(ValueError, match="tenant_allowed_apps"): + ByocVetoServer( + router=router, + tenant_api_keys={"clinic-a": "secret-a"}, + tenant_allowed_apps={}, + ) + with pytest.raises(ValueError, match="Duplicate API keys"): + ByocVetoServer( + router=router, + tenant_api_keys={"clinic-a": "shared-secret", "clinic-b": "shared-secret"}, + tenant_allowed_apps={ + "clinic-a": {"ehr-portal"}, + "clinic-b": {"ehr-portal"}, + }, + ) + with pytest.raises(ValueError, match="at least 16 bytes"): + ByocVetoServer( + router=router, + tenant_api_keys={"clinic-a": "secret-a"}, + tenant_allowed_apps={"clinic-a": {"ehr-portal"}}, + tenant_hmac_keys={"clinic-a": b"too-short"}, + ) + + +def test_live_http_roundtrip_hotswap_and_abstain_halts() -> None: + router, backend = _build_router() + keys = {"clinic-a": "key-clinic-a-secret", "clinic-b": "key-clinic-b-secret"} + with create_byoc_veto_server( + router=router, + tenant_api_keys=keys, + tenant_allowed_apps={"clinic-a": {"ehr-portal"}, "clinic-b": {"ehr-portal"}}, + tenant_hmac_keys={"clinic-a": _HMAC_KEY_A, "clinic-b": _HMAC_KEY_B}, + ) as srv: + status, health = _raw_http(f"{srv.base_url}/healthz") + assert status == 200 + assert health == {"status": "ok"} + + # 1. Clinic A routes to its BYOC adapter -> ALLOW (with server-issued HMAC binding) + b_a = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + expected_field_values={"dob": "1980-02-14"}, + ) + assert srv.verify_field_hmac( + tenant_id="clinic-a", + field_slug="dob", + observed_value="1980-02-14", + expected_digest=b_a.expected_field_hashes["dob"], + ) + assert not srv.verify_field_hmac( + tenant_id="clinic-b", + field_slug="dob", + observed_value="1980-02-14", + expected_digest=b_a.expected_field_hashes["dob"], + ) + + out_a = post_verify_request( + srv.base_url, + api_key=keys["clinic-a"], + tenant_id="clinic-a", + payload={ + "request_id": b_a.request_id, + "step_nonce": b_a.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "expected_field_hashes": b_a.expected_field_hashes, + }, + ) + assert out_a.adapter_id == "veto-clinic-a-ehr" + assert out_a.decision is VetoDecision.ALLOW + + # Replaying the exact same binding/nonce -> 409 HALT_ESCALATE + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": b_a.request_id, + "step_nonce": b_a.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "expected_field_hashes": b_a.expected_field_hashes, + }, + ) + assert code == 409 + assert body["decision"] == "HALT_ESCALATE" + + # 2. Clinic B hot-swaps to its isolated BYOC adapter -> VETO + b_b = srv.issue_run_binding( + tenant_id="clinic-b", + app_id="ehr-portal", + workflow_id="intake", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + backend._scores[b_b.request_id] = RawVetoScore( + fault_logit=3.5, rationale="homoglyph mismatch O vs 0" + ) + out_b = post_verify_request( + srv.base_url, + api_key=keys["clinic-b"], + tenant_id="clinic-b", + payload={ + "request_id": b_b.request_id, + "step_nonce": b_b.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "dom_claims_success": True, + }, + ) + assert out_b.adapter_id == "veto-clinic-b-ehr" + assert out_b.decision is VetoDecision.VETO + assert out_b.dom_override_blocked is True + + # 3. ABSTAIN -> HALT_ESCALATE even when dom_claims_success=True + b_abs = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + backend._scores[b_abs.request_id] = RawVetoScore( + fault_logit=-4.0, + abstain=True, + abstain_reason="occluding toast over target field", + ) + out_abstain = post_verify_request( + srv.base_url, + api_key=keys["clinic-a"], + payload={ + "request_id": b_abs.request_id, + "step_nonce": b_abs.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "dom_claims_success": True, + }, + ) + assert out_abstain.decision is VetoDecision.HALT_ESCALATE + assert out_abstain.abstained is True + assert out_abstain.dom_override_blocked is True + + # 4. Healthz stays minimal (never leaks tenant adapter IDs or counters) + status, health2 = _raw_http(f"{srv.base_url}/healthz") + assert status == 200 + assert health2 == {"status": "ok"} + assert router.request_count == 3 + assert router.swap_count == 3 + assert backend.loaded_sequence == [ + "veto-clinic-a-ehr", + "veto-clinic-b-ehr", + "veto-clinic-a-ehr", + ] + + +def test_anti_steering_workflow_downgrade_default_fallback_and_hmac_enforcement() -> ( + None +): + router, _ = _build_router() + keys = {"clinic-a": "key-clinic-a-secret"} + with create_byoc_veto_server( + router=router, + tenant_api_keys=keys, + tenant_allowed_apps={"clinic-a": {"ehr-portal", "unadapted-app"}}, + tenant_hmac_keys={"clinic-a": _HMAC_KEY_A}, + ) as srv: + # 1. Caller-invented request_id with no server binding -> 403 HALT_ESCALATE + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": "caller-invented-id", + "step_nonce": "caller-nonce", + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + + # 2. Bogus workflow_id cannot downgrade from workflow adapter to looser app adapter + b_bogus = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="wf-bogus", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": b_bogus.request_id, + "step_nonce": b_bogus.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "wf-bogus", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + assert "workflow" in body["error"].lower() + + # 3. Allowed app with NO registered adapter does NOT fall back to default_base_adapter + # and caller-supplied payload.domain is ignored (cannot steer to lenient domain adapter) + b_unadapted = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="unadapted-app", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": b_unadapted.request_id, + "step_nonce": b_unadapted.step_nonce, + "app_id": "unadapted-app", + "domain": "evil.lenient.example", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + assert "default adapter fallback is disabled" in body["error"] + + # 4. Plain unkeyed sha256("1980-02-14") in expected_field_hashes is rejected + b_hmac = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + expected_field_values={"dob": "1980-02-14"}, + ) + plain_sha256 = hashlib.sha256(b"1980-02-14").hexdigest() + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": b_hmac.request_id, + "step_nonce": b_hmac.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "expected_field_hashes": {"dob": plain_sha256}, + }, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + assert "HMAC" in body["error"] + + # 5. Swapped image digest against server-side RunBinding -> 403 HALT_ESCALATE + b_img = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": b_img.request_id, + "step_nonce": b_img.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_OTHER, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + + +def test_non_loopback_requires_tls_and_client_fails_closed() -> None: + router, _ = _build_router() + keys = {"clinic-a": "key-clinic-a-secret"} + + # Non-loopback bind without ssl_context is refused + with pytest.raises(ValueError, match="requires ssl_context"): + ByocVetoServer( + router=router, + tenant_api_keys=keys, + tenant_allowed_apps={"clinic-a": {"ehr-portal"}}, + host="0.0.0.0", + ) + + # Client refuses plaintext http:// to non-loopback host (fail closed) + remote_plain = post_verify_request( + "http://veto.internal.example:8443", + api_key=keys["clinic-a"], + payload={ + "request_id": "req-plain", + "app_id": "ehr-portal", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert remote_plain.decision is VetoDecision.HALT_ESCALATE + assert "http://" in remote_plain.reason + + # Malformed URL fails closed instead of raising ValueError + bad_url = post_verify_request( + "http://[::1", + api_key=keys["clinic-a"], + payload={"request_id": "req-bad-url"}, + ) + assert bad_url.decision is VetoDecision.HALT_ESCALATE + assert "URL error" in bad_url.reason + + # Non-mapping payload fails closed instead of raising AttributeError + non_map = post_verify_request( + "http://127.0.0.1:9", + api_key=keys["clinic-a"], + payload=["not", "a", "mapping"], # type: ignore[arg-type] + ) + assert non_map.decision is VetoDecision.HALT_ESCALATE + assert "Mapping" in non_map.reason + + # Missing request_id fails closed + missing_rid = post_verify_request( + "http://127.0.0.1:9", + api_key=keys["clinic-a"], + payload={"app_id": "ehr-portal"}, + ) + assert missing_rid.decision is VetoDecision.HALT_ESCALATE + assert "request_id" in missing_rid.reason + + # Client catches TypeError (non-JSON-serializable payload) and fails closed + bad_ser = post_verify_request( + "http://127.0.0.1:9", + api_key=keys["clinic-a"], + payload={"request_id": "req-ser", "bad": object()}, + ) + assert bad_ser.decision is VetoDecision.HALT_ESCALATE + assert "TypeError" in bad_ser.reason + + # 422 response never echoes raw client input values + with create_byoc_veto_server( + router=router, + tenant_api_keys=keys, + tenant_allowed_apps={"clinic-a": {"ehr-portal"}}, + ) as srv: + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": "req-bad", + "step_nonce": "nonce-bad", + "app_id": "ehr-portal", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "expected_field_hashes": {"ssn": "123-45-6789"}, + }, + ) + assert code == 422 + assert "123-45-6789" not in json.dumps(body) + + # Unauthorized app_id for tenant -> 403 + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": "req-unauth-app", + "step_nonce": "nonce-unauth", + "app_id": "other-app", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + stopped_url = srv.base_url + + # Server is now stopped -> post_verify_request fails closed to HALT_ESCALATE + offline = post_verify_request( + stopped_url, + api_key=keys["clinic-a"], + payload={ + "request_id": "req-offline", + "step_nonce": "nonce-offline", + "app_id": "ehr-portal", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + "dom_claims_success": True, + }, + timeout_s=1.0, + ) + assert offline.decision is VetoDecision.HALT_ESCALATE + assert offline.abstained is True + assert offline.dom_override_blocked is True + + +def test_http_tenant_auth_cross_tenant_rejection_and_fail_closed_503() -> None: + router, backend = _build_router() + keys = {"clinic-a": "key-clinic-a-secret", "clinic-b": "key-clinic-b-secret"} + with create_byoc_veto_server( + router=router, + tenant_api_keys=keys, + tenant_allowed_apps={"clinic-a": {"ehr-portal"}, "clinic-b": {"ehr-portal"}}, + run_bindings={ + "req-1": RunBinding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + step_nonce="nonce-1", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + }, + ) as srv: + base_payload = { + "request_id": "req-1", + "step_nonce": "nonce-1", + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + } + # Mismatched step_nonce against server-side run binding -> 403 + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={**base_payload, "step_nonce": "replayed-nonce"}, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + + # Missing auth -> 401 + code, body = _raw_http( + f"{srv.base_url}/v1/verify", method="POST", payload=base_payload + ) + assert code == 401 + assert body["decision"] == "HALT_ESCALATE" + + # Invalid auth -> 401 + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": "Bearer wrong-key"}, + payload=base_payload, + ) + assert code == 401 + assert body["decision"] == "HALT_ESCALATE" + + # Cross-tenant payload tenant_id -> 403 + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"X-OpenAdapt-Tenant-Key": keys["clinic-a"]}, + payload={**base_payload, "tenant_id": "clinic-b"}, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + + # Cross-tenant requested_adapter_id -> 403 (consumes req-1) + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={**base_payload, "requested_adapter_id": "veto-clinic-b-ehr"}, + ) + assert code == 403 + assert body["decision"] == "HALT_ESCALATE" + + # Unexpected backend exception -> fail-closed 503 with HALT_ESCALATE + b_503 = srv.issue_run_binding( + tenant_id="clinic-a", + app_id="ehr-portal", + workflow_id="intake", + pre_submit_image_sha256=_IMG_PRE, + post_submit_image_sha256=_IMG_POST, + ) + backend.fail_next = True + code, body = _raw_http( + f"{srv.base_url}/v1/verify", + method="POST", + headers={"Authorization": f"Bearer {keys['clinic-a']}"}, + payload={ + "request_id": b_503.request_id, + "step_nonce": b_503.step_nonce, + "app_id": "ehr-portal", + "workflow_id": "intake", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert code == 503 + assert body["decision"] == "HALT_ESCALATE" + + # Unknown route -> 404 + code, _ = _raw_http(f"{srv.base_url}/v1/unknown") + assert code == 404 + + +def test_server_read_timeout_and_connection_cap() -> None: + router, _ = _build_router() + keys = {"clinic-a": "key-clinic-a-secret"} + with create_byoc_veto_server( + router=router, + tenant_api_keys=keys, + tenant_allowed_apps={"clinic-a": {"ehr-portal"}}, + request_timeout_s=0.25, + max_concurrent_connections=1, + ) as srv: + host, port = srv.server_address + # Hold the single connection slot open with an idle TCP peer. + idle = socket.create_connection((host, port), timeout=2.0) + try: + # Give the server a brief moment to accept the idle connection. + time.sleep(0.05) + # Second concurrent connection is dropped immediately when cap=1. + with pytest.raises((OSError, urllib.error.URLError)): + _raw_http(f"{srv.base_url}/healthz") + # After request_timeout_s elapses, the idle peer is timed out and + # the slot is released so subsequent requests succeed. + time.sleep(0.35) + status, health = _raw_http(f"{srv.base_url}/healthz") + assert status == 200 + assert health == {"status": "ok"} + finally: + idle.close() + + +@pytest.mark.parametrize( + "forged_body,expected_substr", + [ + ( + { + "request_id": "forged-other-req", + "adapter_id": "veto-clinic-a-ehr", + "base_model": _BASE_MODEL, + "decision": "ALLOW", + "calibrated_fault_prob": 0.01, + "calibrated_threshold": 0.5, + "temperature": 1.0, + "abstained": False, + "dom_override_blocked": False, + "reason": "replayed", + }, + "request_id", + ), + ( + { + "request_id": "expected-req-123", + "adapter_id": "veto-clinic-a-ehr", + "base_model": _BASE_MODEL, + "decision": "ALLOW", + "calibrated_fault_prob": 0.01, + "calibrated_threshold": 0.5, + "temperature": 1.0, + "abstained": True, + "dom_override_blocked": False, + "reason": "contradictory abstain+allow", + }, + "invariant", + ), + ( + { + "request_id": "expected-req-123", + "adapter_id": "veto-clinic-a-ehr", + "base_model": _BASE_MODEL, + "decision": "ALLOW", + "calibrated_fault_prob": 0.85, + "calibrated_threshold": 0.5, + "temperature": 1.0, + "abstained": False, + "dom_override_blocked": False, + "reason": "contradictory prob>=threshold+allow", + }, + "invariant", + ), + ], +) +def test_client_rejects_mismatched_request_id_and_contradictory_allow( + monkeypatch: pytest.MonkeyPatch, + forged_body: dict[str, Any], + expected_substr: str, +) -> None: + class _ForgedResponse: + def __enter__(self) -> _ForgedResponse: + return self + + def __exit__(self, *_args: object) -> None: + return None + + def read(self) -> bytes: + return json.dumps(forged_body).encode("utf-8") + + monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **kw: _ForgedResponse()) + res = post_verify_request( + "http://127.0.0.1:9999", + api_key="k", + payload={ + "request_id": "expected-req-123", + "app_id": "ehr-portal", + "pre_submit_image_sha256": _IMG_PRE, + "post_submit_image_sha256": _IMG_POST, + }, + ) + assert res.decision is VetoDecision.HALT_ESCALATE + assert expected_substr in res.reason diff --git a/packages/flow/tests/test_calibration_collector.py b/packages/flow/tests/test_calibration_collector.py new file mode 100644 index 0000000000..5134180010 --- /dev/null +++ b/packages/flow/tests/test_calibration_collector.py @@ -0,0 +1,257 @@ +"""Tests for Mitigation #1: Online False-Pause Calibration Collector (zero-PHI).""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from openadapt_flow.calibration_collector import ( + CALIBRATION_RECORD_SCHEMA, + CalibrationCollector, + CalibrationVerdict, + OverrideKind, + record_operator_override, +) +from openadapt_flow.multi_lora_veto import VetoDecision + +_HASH_A = "a" * 64 +_HASH_B = "b" * 64 + + +def test_record_operator_override_writes_zero_phi_tenant_jsonl(tmp_path: Path) -> None: + # Defaults strictly off without explicit consent_enabled=True + with pytest.raises(PermissionError, match="consent_enabled=True"): + record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="patient-intake", + step_id="step-submit-01", + screenshot_hash=_HASH_A, + predicted_verdict=VetoDecision.VETO, + operator_verdict=VetoDecision.ALLOW, + queue_root=tmp_path, + ) + + rec = record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="patient-intake", + step_id="step-submit-01", + screenshot_hash=_HASH_A, + predicted_verdict=VetoDecision.VETO, + operator_verdict=VetoDecision.ALLOW, + queue_root=tmp_path, + consent_enabled=True, + bound_tenant_id="clinic-north", + pre_submit_screenshot_hash=_HASH_B, + adapter_id="veto-ehr-v1", + calibrated_fault_prob=0.61, + structural_metadata={ + "viewport_width": 1280, + "viewport_height": 800, + "dom_field_count": 14, + "dom_claims_success": True, + "roi_crop_used": True, + "theme_hint": "light_enterprise", + }, + ) + assert rec.schema_version == CALIBRATION_RECORD_SCHEMA + assert rec.override_kind is OverrideKind.FALSE_PAUSE + assert rec.predicted_verdict is CalibrationVerdict.VETO + assert rec.operator_verdict is CalibrationVerdict.ALLOW + + queue_file = tmp_path / "clinic-north" / "ehr-portal.jsonl" + assert queue_file.is_file() + raw = json.loads(queue_file.read_text(encoding="utf-8").strip()) + assert raw["tenant_id"] == "clinic-north" + assert raw["screenshot_hash"] == _HASH_A + assert raw["override_kind"] == "false_pause" + assert "expected_fields" not in raw + assert "reviewer_note" not in raw + + +def test_zero_phi_rejects_disallowed_metadata_keys_and_pii_values( + tmp_path: Path, +) -> None: + collector = CalibrationCollector( + tmp_path, bound_tenant_id="clinic-north", consent_enabled=True + ) + + # Disallow slash/colon record-id-like strings in step_id and adapter_id + with pytest.raises(ValueError, match="step_id"): + collector.record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="intake", + step_id="patient/12345", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + ) + with pytest.raises(ValueError, match="adapter_id"): + collector.record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + adapter_id="bad/adapter:id", + ) + + for bad_key in ( + "expected_fields", + "patient_name", + "raw_text", + "reviewer_note", + "dom_html", + ): + with pytest.raises(ValueError, match="Value-free violation"): + collector.record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + structural_metadata={bad_key: "secret"}, + ) + + for pii_val in ("jane.doe@clinic.org", "123-45-6789", "555-234-5678", "x" * 65): + with pytest.raises(ValueError, match="Value-free violation"): + collector.record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + structural_metadata={"theme_hint": pii_val}, + ) + + with pytest.raises(ValueError, match="64 lowercase hex"): + collector.record_operator_override( + tenant_id="clinic-north", + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash="/tmp/patient_john_doe.png", + predicted_verdict="VETO", + operator_verdict="ALLOW", + ) + + +def test_fail_closed_tenant_isolation_on_write_and_read(tmp_path: Path) -> None: + collector = CalibrationCollector( + tmp_path, bound_tenant_id="clinic-north", consent_enabled=True + ) + + # Missing or path-traversal tenant IDs are rejected. + for bad_tenant in ("", " ", "../clinic-south", "clinic-north/sub"): + with pytest.raises(ValueError, match="tenant_id"): + collector.record_operator_override( + tenant_id=bad_tenant, + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + ) + + # Cross-tenant write is refused. + with pytest.raises(PermissionError, match="Cross-tenant"): + collector.record_operator_override( + tenant_id="clinic-south", + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + ) + + # Cross-tenant read is refused. + with pytest.raises(PermissionError, match="Cross-tenant"): + collector.read_tenant_queue("clinic-south") + + # Tampered JSONL containing another tenant's record fails closed on read. + tampered_dir = tmp_path / "clinic-north" + tampered_dir.mkdir(parents=True, exist_ok=True) + other_collector = CalibrationCollector(tmp_path, consent_enabled=True) + other_rec = other_collector.record_operator_override( + tenant_id="clinic-south", + app_id="ehr-portal", + workflow_id="intake", + step_id="step-1", + screenshot_hash=_HASH_A, + predicted_verdict="VETO", + operator_verdict="ALLOW", + ) + (tampered_dir / "ehr-portal.jsonl").write_text( + json.dumps(other_rec.model_dump(mode="json")) + "\n", + encoding="utf-8", + ) + with pytest.raises(PermissionError, match="Tenant isolation violation"): + collector.read_tenant_queue("clinic-north", app_id="ehr-portal") + + +def test_deduplication_and_calibration_readiness_flywheel(tmp_path: Path) -> None: + collector = CalibrationCollector( + tmp_path, bound_tenant_id="clinic-north", consent_enabled=True + ) + + # Record 10 unique overrides (8 false pauses, 1 true fault, 1 missed fault) + 1 duplicate. + for idx in range(8): + h = f"{idx:064x}" + collector.record_operator_override( + tenant_id="clinic-north", + app_id="billing-app", + workflow_id="claim-submit", + step_id=f"step-{idx}", + screenshot_hash=h, + predicted_verdict=VetoDecision.HALT_ESCALATE, + operator_verdict=VetoDecision.ALLOW, + ) + # Duplicate of step-0 should deduplicate cleanly. + collector.record_operator_override( + tenant_id="clinic-north", + app_id="billing-app", + workflow_id="claim-submit", + step_id="step-0", + screenshot_hash=f"{0:064x}", + predicted_verdict=VetoDecision.HALT_ESCALATE, + operator_verdict=VetoDecision.ALLOW, + ) + collector.record_operator_override( + tenant_id="clinic-north", + app_id="billing-app", + workflow_id="claim-submit", + step_id="step-fault", + screenshot_hash="c" * 64, + predicted_verdict=VetoDecision.VETO, + operator_verdict=VetoDecision.VETO, + ) + collector.record_operator_override( + tenant_id="clinic-north", + app_id="billing-app", + workflow_id="claim-submit", + step_id="step-missed", + screenshot_hash="d" * 64, + predicted_verdict=VetoDecision.ALLOW, + operator_verdict=VetoDecision.VETO, + ) + + summary = collector.calibration_readiness( + "clinic-north", "billing-app", min_samples=10 + ) + assert summary.total_records == 10 + assert summary.false_pause_count == 8 + assert summary.true_fault_count == 1 + assert summary.missed_fault_count == 1 + assert summary.ready_for_calibration is True diff --git a/packages/flow/tests/test_multi_lora_veto.py b/packages/flow/tests/test_multi_lora_veto.py new file mode 100644 index 0000000000..df41660b4f --- /dev/null +++ b/packages/flow/tests/test_multi_lora_veto.py @@ -0,0 +1,450 @@ +"""Unit tests for Multi-LoRA app-adapter registry, hot-swap router, and JSONL exporter.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +import yaml +from pydantic import ValidationError + +from openadapt_flow.multi_lora_veto import ( + ADAPTER_REGISTRY_SCHEMA, + AdapterSpec, + AppAdapterRegistry, + InboxResolutionItem, + InboxResolutionLabel, + MultiLoraVetoRouter, + RawVetoScore, + TenantScope, + VetoDecision, + VetoInferenceRequest, + calibrate_probability, + export_inbox_training_jsonl, + hmac_field_value, + ollama_model_tag, + vllm_request_payload, +) + +BASE_MODEL = "openadapt-veto-4b" +SHA_A = "a" * 64 +SHA_B = "b" * 64 +SHA_C = "c" * 64 +SHA_D = "d" * 64 +SHA_E = "e" * 64 + + +def _make_spec( + adapter_id: str, + *, + base_model: str = BASE_MODEL, + sha256: str = SHA_A, + threshold: float = 0.5, + temperature: float = 1.0, + tenant_scope: TenantScope = TenantScope.PUBLIC, + tenant_id: str | None = None, + app_id: str | None = None, + workflow_id: str | None = None, + domain_pattern: str | None = None, + adapter_uri: str | None = None, +) -> AdapterSpec: + return AdapterSpec( + adapter_id=adapter_id, + base_model=base_model, + adapter_uri=adapter_uri or f"s3://adapters/{adapter_id}", + sha256=sha256, + calibrated_threshold=threshold, + temperature=temperature, + tenant_scope=tenant_scope, + tenant_id=tenant_id, + app_id=app_id, + workflow_id=workflow_id, + domain_pattern=domain_pattern, + ) + + +def _sample_registry() -> AppAdapterRegistry: + base = _make_spec("veto-base", sha256=SHA_A, threshold=0.60, temperature=1.0) + adapters = [ + _make_spec( + "veto-app-alpha", + sha256=SHA_B, + threshold=0.55, + temperature=1.2, + app_id="app-alpha", + ), + _make_spec( + "veto-app-alpha-intake", + sha256=SHA_C, + threshold=0.45, + temperature=0.8, + app_id="app-alpha", + workflow_id="intake-v1", + ), + _make_spec( + "veto-tenant1-alpha-intake", + sha256=SHA_D, + threshold=0.35, + temperature=0.5, + tenant_scope=TenantScope.BYOC, + tenant_id="tenant-1", + app_id="app-alpha", + workflow_id="intake-v1", + ), + _make_spec( + "veto-tenant1-alpha", + sha256=SHA_E, + threshold=0.40, + temperature=0.75, + tenant_scope=TenantScope.BYOC, + tenant_id="tenant-1", + app_id="app-alpha", + ), + _make_spec( + "veto-portal-domain", + sha256=SHA_B, + threshold=0.50, + temperature=1.0, + domain_pattern="*.portal.example", + ), + ] + return AppAdapterRegistry(default_base_adapter=base, adapters=adapters) + + +class _MockHotSwapBackend: + """In-memory mock LoraBackend tracking adapter hot-swaps.""" + + def __init__(self, scores_by_request: dict[str, RawVetoScore]) -> None: + self._scores = scores_by_request + self._active: str | None = None + self.swap_history: list[str] = [] + + @property + def active_adapter_id(self) -> str | None: + return self._active + + def ensure_adapter(self, spec: AdapterSpec) -> bool: + if self._active == spec.adapter_id: + return False + self._active = spec.adapter_id + self.swap_history.append(spec.adapter_id) + return True + + def score(self, spec: AdapterSpec, request: VetoInferenceRequest) -> RawVetoScore: + return self._scores[request.request_id] + + +def test_registry_routing_fallback_chain() -> None: + reg = _sample_registry() + + # 1. Exact BYOC (tenant, app, workflow) + s1 = reg.resolve(app_id="app-alpha", workflow_id="intake-v1", tenant_id="tenant-1") + assert s1.adapter_id == "veto-tenant1-alpha-intake" + + # 2. Exact BYOC (tenant, app) when workflow has no BYOC override + s2 = reg.resolve(app_id="app-alpha", workflow_id="other-wf", tenant_id="tenant-1") + assert s2.adapter_id == "veto-tenant1-alpha" + + # 3. Public (app, workflow) for another tenant (never sees tenant-1 BYOC) + s3 = reg.resolve(app_id="app-alpha", workflow_id="intake-v1", tenant_id="tenant-2") + assert s3.adapter_id == "veto-app-alpha-intake" + + # 4. Public (app) fallback + s4 = reg.resolve(app_id="app-alpha", workflow_id="unknown-wf", tenant_id="tenant-2") + assert s4.adapter_id == "veto-app-alpha" + + # 5. Domain pattern fallback + s5 = reg.resolve(app_id="unseen-app", domain="claims.portal.example") + assert s5.adapter_id == "veto-portal-domain" + + # 6. Cold-start default fallback + s6 = reg.resolve(app_id="brand-new-app", domain="unknown.example") + assert s6.adapter_id == "veto-base" + + +def test_strict_byoc_tenant_isolation_raises_permission_error() -> None: + reg = _sample_registry() + + # Owner tenant can explicitly select its BYOC adapter + own = reg.resolve( + app_id="app-alpha", + tenant_id="tenant-1", + requested_adapter_id="veto-tenant1-alpha", + ) + assert own.adapter_id == "veto-tenant1-alpha" + + # Another tenant requesting tenant-1's BYOC adapter raises PermissionError + with pytest.raises(PermissionError, match="does not match server-resolved adapter"): + reg.resolve( + app_id="app-alpha", + tenant_id="tenant-2", + requested_adapter_id="veto-tenant1-alpha", + ) + + # Anonymous caller requesting BYOC adapter raises PermissionError + with pytest.raises(PermissionError, match="does not match server-resolved adapter"): + reg.resolve( + app_id="app-alpha", + tenant_id=None, + requested_adapter_id="veto-tenant1-alpha-intake", + ) + + # Caller cannot steer app-alpha to a more lenient public adapter + lenient_reg = AppAdapterRegistry( + default_base_adapter=_make_spec("veto-base", threshold=0.5), + adapters=[ + _make_spec("strict-a", app_id="app-a", threshold=0.5), + _make_spec("lenient-b", app_id="app-b", threshold=0.99), + ], + ) + with pytest.raises(PermissionError, match="does not match server-resolved adapter"): + lenient_reg.resolve(app_id="app-a", requested_adapter_id="lenient-b") + + +def test_registry_loads_from_json_and_yaml(tmp_path: Path) -> None: + payload = { + "schema_version": ADAPTER_REGISTRY_SCHEMA, + "default_base_adapter": _make_spec("veto-base").model_dump(mode="json"), + "adapters": [ + _make_spec("veto-app-beta", sha256=SHA_B, app_id="app-beta").model_dump( + mode="json" + ) + ], + } + + json_path = tmp_path / "registry.json" + json_path.write_text(json.dumps(payload), encoding="utf-8") + from_json = AppAdapterRegistry.from_json(json_path) + assert from_json.resolve(app_id="app-beta").adapter_id == "veto-app-beta" + + yaml_path = tmp_path / "registry.yaml" + yaml_path.write_text(yaml.safe_dump(payload), encoding="utf-8") + from_yaml = AppAdapterRegistry.from_yaml(yaml_path) + assert from_yaml.resolve(app_id="app-beta").adapter_id == "veto-app-beta" + + # Validation guard: BYOC without tenant_id fails + with pytest.raises(ValidationError): + _make_spec("bad-byoc", tenant_scope=TenantScope.BYOC, tenant_id=None) + + +def test_router_hot_swaps_temperature_calibration_and_abstain_halt() -> None: + reg = _sample_registry() + backend = _MockHotSwapBackend( + { + # logit=0.2, temp=0.5 -> sigmoid(0.4)=0.5987 >= threshold 0.35 -> VETO + "req-1": RawVetoScore( + fault_logit=0.2, rationale="Field blanked after submit." + ), + # Same adapter (no swap!), logit=-1.5 -> sigmoid(-3.0)=0.0474 < 0.35 -> ALLOW + "req-2": RawVetoScore(fault_logit=-1.5, rationale="All fields persisted."), + # Different adapter (swap!), abstain=True while dom_claims_success=True -> HALT_ESCALATE + "req-3": RawVetoScore( + fault_logit=-4.0, + abstain=True, + abstain_reason="Modal occluded target region during post-submit capture.", + ), + } + ) + router = MultiLoraVetoRouter(base_model=BASE_MODEL, registry=reg, backend=backend) + + r1 = router.evaluate( + VetoInferenceRequest( + request_id="req-1", + app_id="app-alpha", + workflow_id="intake-v1", + tenant_id="tenant-1", + pre_submit_image_sha256="1" * 64, + post_submit_image_sha256="2" * 64, + dom_claims_success=True, + ) + ) + assert r1.adapter_id == "veto-tenant1-alpha-intake" + assert r1.decision is VetoDecision.VETO + assert r1.dom_override_blocked is True + assert r1.calibrated_fault_prob == pytest.approx(calibrate_probability(0.2, 0.5)) + assert router.swap_count == 1 + + r2 = router.evaluate( + VetoInferenceRequest( + request_id="req-2", + app_id="app-alpha", + workflow_id="intake-v1", + tenant_id="tenant-1", + pre_submit_image_sha256="3" * 64, + post_submit_image_sha256="4" * 64, + dom_claims_success=True, + ) + ) + assert r2.adapter_id == "veto-tenant1-alpha-intake" + assert r2.decision is VetoDecision.ALLOW + assert r2.dom_override_blocked is False + # Reused active adapter without swapping + assert router.swap_count == 1 + + r3 = router.evaluate( + VetoInferenceRequest( + request_id="req-3", + app_id="brand-new-app", + pre_submit_image_sha256="5" * 64, + post_submit_image_sha256="6" * 64, + dom_claims_success=True, + ) + ) + assert r3.adapter_id == "veto-base" + assert r3.decision is VetoDecision.HALT_ESCALATE + assert r3.abstained is True + assert r3.dom_override_blocked is True + assert "occluded" in r3.reason + assert router.swap_count == 2 + assert router.request_count == 3 + assert backend.swap_history == ["veto-tenant1-alpha-intake", "veto-base"] + + +def test_router_refuses_mismatched_base_model_and_backend_helpers() -> None: + base = _make_spec("veto-base") + wrong_base = _make_spec("veto-other", base_model="other-model-7b", app_id="app-z") + reg = AppAdapterRegistry(default_base_adapter=base, adapters=[wrong_base]) + backend = _MockHotSwapBackend({}) + router = MultiLoraVetoRouter(base_model=BASE_MODEL, registry=reg, backend=backend) + + req = VetoInferenceRequest( + request_id="req-mismatch", + app_id="app-z", + step_nonce="run-42-step-3", + pre_submit_image_sha256="1" * 64, + post_submit_image_sha256="2" * 64, + ) + with pytest.raises(ValueError, match="targets base_model"): + router.evaluate(req) + + payload = vllm_request_payload(base, req) + assert payload["model"] == "veto-base" + assert payload["metadata"]["base_model"] == BASE_MODEL + assert payload["metadata"]["step_nonce"] == "run-42-step-3" + assert "expected_field_matches" not in payload + assert ollama_model_tag(base) == f"{BASE_MODEL}:veto-base" + ollama_spec = _make_spec("veto-oll", adapter_uri="ollama://openadapt/veto:v2") + assert ollama_model_tag(ollama_spec) == "openadapt/veto:v2" + + +def test_hmac_field_value_and_strict_schema_guards() -> None: + d1 = hmac_field_value("tenant-1-vpc-secret-key-0001", "dob", "1980-02-14") + d2 = hmac_field_value("tenant-2-vpc-secret-key-0002", "dob", "1980-02-14") + assert len(d1) == 64 and d1 != d2 + with pytest.raises(ValueError, match="16 bytes"): + hmac_field_value("short", "dob", "1980-02-14") + with pytest.raises(ValueError, match="field_slug"): + hmac_field_value("tenant-1-vpc-secret-key-0001", "Jane Doe DOB", "1980-02-14") + + # Free-text image reference is rejected (must be 64 lowercase hex) + with pytest.raises(ValidationError): + VetoInferenceRequest( + request_id="req-bad-img", + app_id="app-alpha", + pre_submit_image_sha256="Jane Doe MRN 0123456 screenshot", + post_submit_image_sha256=SHA_B, + ) + # Free-text field hash key is rejected + with pytest.raises(ValidationError): + VetoInferenceRequest( + request_id="req-bad-key", + app_id="app-alpha", + pre_submit_image_sha256=SHA_A, + post_submit_image_sha256=SHA_B, + expected_field_hashes={"Jane Doe DOB 1980-02-14": d1}, + ) + # Caller self-vouching field (expected_field_matches) is forbidden + with pytest.raises(ValidationError): + VetoInferenceRequest.model_validate( + { + "request_id": "req-self-vouch", + "app_id": "app-alpha", + "pre_submit_image_sha256": SHA_A, + "post_submit_image_sha256": SHA_B, + "expected_field_matches": {"dob": True}, + } + ) + + +def test_export_inbox_training_jsonl_dedup_and_tenant_isolation(tmp_path: Path) -> None: + hmac_a = hmac_field_value("tenant-1-vpc-secret-key-0001", "email", "a@example.com") + hmac_b = hmac_field_value("tenant-1-vpc-secret-key-0001", "email", "b@example.com") + hmac_c = hmac_field_value("tenant-2-vpc-secret-key-0002", "email", "c@example.com") + items = [ + InboxResolutionItem( + item_id="inbox-1", + app_id="app-alpha", + workflow_id="intake-v1", + tenant_id="tenant-1", + label=InboxResolutionLabel.TRUE_FAULT, + pre_submit_image_ref=SHA_A, + post_submit_image_ref=SHA_B, + expected_field_hashes={"email": hmac_a}, + resolved_at="2026-11-22T18:00:00Z", + ), + # Duplicate content fingerprint (different item_id) -> must deduplicate + InboxResolutionItem( + item_id="inbox-1-dup", + app_id="app-alpha", + workflow_id="intake-v1", + tenant_id="tenant-1", + label=InboxResolutionLabel.TRUE_FAULT, + pre_submit_image_ref=SHA_A, + post_submit_image_ref=SHA_B, + expected_field_hashes={"email": hmac_a}, + resolved_at="2026-11-22T18:05:00Z", + ), + InboxResolutionItem( + item_id="inbox-2", + app_id="app-alpha", + workflow_id="intake-v1", + tenant_id="tenant-1", + label=InboxResolutionLabel.FALSE_ALARM, + pre_submit_image_ref=SHA_C, + post_submit_image_ref=SHA_D, + expected_field_hashes={"email": hmac_b}, + resolved_at="2026-11-22T18:10:00Z", + ), + # Different tenant -> excluded when exporting tenant-1 VPC dataset + InboxResolutionItem( + item_id="inbox-3", + app_id="app-alpha", + workflow_id="intake-v1", + tenant_id="tenant-2", + label=InboxResolutionLabel.TRUE_FAULT, + pre_submit_image_ref=SHA_D, + post_submit_image_ref=SHA_E, + expected_field_hashes={"email": hmac_c}, + resolved_at="2026-11-22T18:15:00Z", + ), + ] + + # Raw form values are rejected by value-free schema + with pytest.raises(ValidationError): + InboxResolutionItem( + item_id="inbox-raw", + app_id="app-alpha", + tenant_id="tenant-1", + label=InboxResolutionLabel.TRUE_FAULT, + pre_submit_image_ref=SHA_A, + post_submit_image_ref=SHA_B, + expected_field_hashes={"email": "patient@example.com"}, + resolved_at="2026-11-22T18:00:00Z", + ) + + out_path = tmp_path / "byoc" / "tenant-1-train.jsonl" + count = export_inbox_training_jsonl( + items, out_path, tenant_id="tenant-1", app_id="app-alpha" + ) + assert count == 2 + + lines = [ + json.loads(line) for line in out_path.read_text(encoding="utf-8").splitlines() + ] + assert len(lines) == 2 + assert all(rec["metadata"]["tenant_id"] == "tenant-1" for rec in lines) + assert all(rec["metadata"]["app_id"] == "app-alpha" for rec in lines) + assert all("reviewer_note" not in rec["messages"][2]["content"] for rec in lines) + verdicts = [json.loads(rec["messages"][2]["content"])["verdict"] for rec in lines] + assert verdicts == ["FAULT", "CLEAN"]