Skip to main content

qualia_core_db/services/
poet_llm_authority.rs

1//! Trusted product setup for the existing authenticated Webizen HTTP transport.
2//! Request DID fields are labels; they cannot select the authenticated actor.
3use super::webizen_server::WebizenState;
4use crate::llm_agent::{native_request::NativeProductSession, LocalLlmAgent};
5use axum::{
6    http::{HeaderMap, StatusCode},
7    response::{IntoResponse, Response},
8    Json,
9};
10use std::sync::{Arc, Mutex, OnceLock};
11
12static SESSION: OnceLock<Mutex<Option<Arc<NativeProductSession>>>> = OnceLock::new();
13
14/// Privileged LOCAL setup only. Do not register as an HTTP/MCP signing endpoint.
15/// The session has already proved possession under signed native admission and
16/// retains the configured host's shared revocation state and file leases.
17pub fn configure(session: Arc<NativeProductSession>) {
18    super::poet_llm_jobs::cancel_all();
19    *SESSION
20        .get_or_init(|| Mutex::new(None))
21        .lock()
22        .unwrap_or_else(|e| e.into_inner()) = Some(session);
23}
24
25pub fn disconnect() {
26    super::poet_llm_jobs::cancel_all();
27    if let Some(slot) = SESSION.get() {
28        *slot.lock().unwrap_or_else(|e| e.into_inner()) = None;
29    }
30}
31
32/// No development bypass: a local server token is transport authentication,
33/// separate from the independently installed actor/policy authorization.
34pub(super) fn authenticate(
35    state: &WebizenState,
36    headers: &HeaderMap,
37) -> Result<Arc<NativeProductSession>, Response> {
38    let token = headers.get("x-qualia-token").and_then(|v| v.to_str().ok());
39    if !state
40        .token
41        .as_deref()
42        .is_some_and(|expected| !expected.is_empty() && Some(expected) == token)
43    {
44        return Err((
45            StatusCode::UNAUTHORIZED,
46            Json(serde_json::json!({
47                "ok": false, "code": "inference_transport_authentication",
48                "diagnostic": "Authenticated native Webizen transport is required"
49            })),
50        )
51            .into_response());
52    }
53    let session = SESSION.get().and_then(|slot| slot.lock().ok().and_then(|s| s.clone()))
54        .ok_or_else(|| (StatusCode::SERVICE_UNAVAILABLE, Json(serde_json::json!({
55            "ok": false, "code": "inference_host_not_configured",
56            "diagnostic": "Native host must bind an authenticated actor, installed policy and model preparation budgets"
57        }))).into_response())?;
58    // Recheck the actual session for history/cancellation as well as decode.
59    // Strings in requests cannot restore an expired or disconnected owner.
60    session.bind().map_err(|_| {
61        (
62            StatusCode::FORBIDDEN,
63            Json(serde_json::json!({
64                "ok": false, "code": "inference_session_expired",
65                "diagnostic": "Native inference session expired or was disconnected"
66            })),
67        )
68            .into_response()
69    })?;
70    Ok(session)
71}
72
73pub(super) fn bind(agent: &LocalLlmAgent, session: &NativeProductSession) -> Result<(), String> {
74    agent
75        .bind_native_governed_request(session.bind().map_err(|e| e.to_string())?)
76        .map_err(|e| e.to_string())
77}