okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-apikey: the API key is optional; serving without one warns, never refusescc500be1c

main
6.4 KiB143 linesraw
1"""Bounded, local API verification for a managed server instance.
2
3The ready file is only a hint that a port was bound.  This module asks that
4same instance for telemetry, then performs one one-token generation when the
5model is loaded.  Credentials stay in memory and no response text is saved.
6"""
7
8from __future__ import annotations
9
10import http.client
11import hmac
12import ipaddress
13import json
14import os
15import re
16import socket
17import time
18
19
20class ReadinessError(Exception):
21    pass
22
23
24def _address(ready: dict, expected_host: str) -> tuple[str, int]:
25    host = ready.get("bound_host")
26    port = ready.get("bound_port")
27    if host != expected_host or type(port) is not int or not 1 <= port <= 65535:
28        raise ReadinessError("ready_endpoint_mismatch")
29    if host in ("", "0.0.0.0"):
30        return "127.0.0.1", port
31    if host == "::":
32        return "::1", port
33    if host == "localhost":
34        return host, port
35    try:
36        ipaddress.ip_address(host)
37    except ValueError:
38        raise ReadinessError("ready_endpoint_not_numeric") from None
39    return host, port
40
41
42def _credential(source_bytes: bytes) -> str | None:
43    from serve.server import api_key_of, key_list
44
45    cfg = json.loads(source_bytes.decode("utf-8-sig"))
46    if not isinstance(cfg, dict):
47        raise ValueError("run config must be an object")
48    raw = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "")
49    if str(raw).strip().lower() == "none":               # "api_key": "none" = served without a key on purpose
50        return None
51    keys = key_list(api_key_of(raw))
52    return keys[0] if keys else None
53
54
55def _request(host: str, port: int, method: str, path: str, key: str | None,
56             timeout: float, body: dict | None = None) -> dict:
57    payload = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
58    headers = {"Accept": "application/json"}
59    if payload is not None:
60        headers["Content-Type"] = "application/json"
61    if key is not None:
62        headers["Authorization"] = "Bearer " + key
63    connection = http.client.HTTPConnection(host, port, timeout=max(0.1, timeout))
64    try:
65        connection.request(method, path, body=payload, headers=headers)
66        response = connection.getresponse()
67        raw = response.read(512 * 1024 + 1)
68        if len(raw) > 512 * 1024:
69            raise ReadinessError("probe_response_too_large")
70        if response.status != 200:
71            raise ReadinessError(f"probe_http_{response.status}")
72        result = json.loads(raw)
73        if not isinstance(result, dict):
74            raise ReadinessError("probe_invalid_response")
75        return result
76    except (OSError, socket.timeout, http.client.HTTPException):
77        raise ReadinessError("probe_transport_failed") from None
78    except (UnicodeError, ValueError):
79        raise ReadinessError("probe_invalid_response") from None
80    finally:
81        connection.close()
82
83
84def verify(ready: dict, source_bytes: bytes, *, expected_host: str,
85           expected_instance: str, expected_attestation: str,
86           timeout: float, force_load: bool = False) -> dict:
87    if not isinstance(expected_attestation, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_attestation):
88        raise ReadinessError("probe_launch_attestation_unavailable")
89    host, port = _address(ready, expected_host)
90    display_host = f"[{host}]" if ":" in host else host
91    api_url = f"http://{display_host}:{port}"
92    deadline = time.monotonic() + timeout
93    try:
94        cfg = json.loads(source_bytes.decode("utf-8-sig"))
95        key = _credential(source_bytes)
96    except (UnicodeError, ValueError, TypeError):
97        raise ReadinessError("probe_credential_invalid") from None
98    if not isinstance(cfg, dict) or not isinstance(ready.get("model_id"), str) or \
99            (cfg.get("model_name") is not None and ready["model_id"] != cfg["model_name"]):
100        raise ReadinessError("probe_model_mismatch")
101    telemetry = _request(host, port, "GET", "/v1/telemetry", key,
102                         max(0.1, deadline - time.monotonic()))
103    instance = telemetry.get("instance")
104    model = telemetry.get("model")
105    if not isinstance(instance, dict) or instance.get("id") != expected_instance:
106        raise ReadinessError("probe_instance_mismatch")
107    reported_attestation = instance.get("launch_attestation")
108    if not isinstance(reported_attestation, str) or not hmac.compare_digest(
109            reported_attestation, expected_attestation):
110        raise ReadinessError("probe_launch_attestation_mismatch")
111    if not isinstance(model, dict) or model.get("id") != ready.get("model_id"):
112        raise ReadinessError("probe_model_mismatch")
113    if ready.get("model_state") not in ("ready", "unloaded"):
114        raise ReadinessError("probe_model_state_invalid")
115    loaded = model.get("loaded")
116    if type(loaded) is not bool:
117        raise ReadinessError("probe_model_state_unavailable")
118    if not loaded and not force_load:
119        return {"api_identity_verified": True, "launch_attested": True, "generation_ready": False,
120                "readiness_state": "unloaded", "model_state": "unloaded", "api_url": api_url}
121    probe = {"model": ready.get("model_id"), "messages": [{"role": "user", "content": "hi"}],
122             "max_tokens": 1, "temperature": 0, "stream": False}
123    while True:
124        try:
125            result = _request(host, port, "POST", "/v1/chat/completions", key,
126                              max(0.1, deadline - time.monotonic()), probe)
127            break
128        except ReadinessError as exc:
129            if str(exc) not in ("probe_http_409", "probe_http_429", "probe_http_503") or \
130                    time.monotonic() + 0.25 >= deadline:
131                raise
132            time.sleep(0.25)
133    choices = result.get("choices")
134    if not isinstance(choices, list) or len(choices) != 1 or not isinstance(choices[0], dict) or \
135            not isinstance(choices[0].get("message"), dict) or \
136            not isinstance(choices[0].get("finish_reason"), str):
137        raise ReadinessError("probe_generation_invalid_response")
138    usage = result.get("usage")
139    if not isinstance(usage, dict) or type(usage.get("completion_tokens")) is not int or \
140            usage["completion_tokens"] < 1:
141        raise ReadinessError("probe_generation_no_tokens")
142    return {"api_identity_verified": True, "launch_attested": True, "generation_ready": True,
143            "readiness_state": "generation_ready", "model_state": "ready", "api_url": api_url}