- At the first interaction the session name locks and a personal folder is created under the workspace root (default ~/.strata-ctl/<slug>, configurable via workspace_root); slug is filesystem-safe and unique. Stored in sessions.folder (idempotent migration).
- build_request always prepends a structural identity reminder ('Il tuo nome è X. La tua cartella personale è Y.') before the session SP — not an editable setting; gives the agent awareness of its workspace. router_with_store takes the workspace root. 114 tests green; verified live (folder created, name locked).
355 lines
12 KiB
Rust
355 lines
12 KiB
Rust
//! The HTTP surface: routing, request extraction, and OpenAI-shaped errors.
|
|
//!
|
|
//! `POST /v1/chat/completions` (stream and non-stream) and `GET /v1/models`,
|
|
//! plus a tiny `/health`. The handlers are thin: they delegate all behaviour
|
|
//! to [`ChatService`] and only decide status codes and envelopes.
|
|
|
|
use axum::extract::State;
|
|
use axum::http::StatusCode;
|
|
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
|
|
use axum::routing::{get, post};
|
|
use axum::Router;
|
|
use serde::de::DeserializeOwned;
|
|
use std::sync::Arc;
|
|
|
|
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
|
|
use super::service::ChatService;
|
|
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
|
|
use super::{sessions, web};
|
|
use crate::store::Store;
|
|
|
|
/// Build the router. Mount this inside any axum `Router` or serve it directly.
|
|
pub fn router(service: ChatService) -> Router {
|
|
router_with_auth(service, AuthConfig::default())
|
|
}
|
|
|
|
/// Build the router with optional API-key auth and a Host allowlist (no GUI store).
|
|
pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
|
|
build_router(
|
|
AppState {
|
|
service,
|
|
store: None,
|
|
workspace_root: default_workspace_root(),
|
|
},
|
|
auth,
|
|
)
|
|
}
|
|
|
|
/// Build the router with the session store + web GUI enabled, plus auth.
|
|
/// `workspace_root` is the parent of the per-session personal folders.
|
|
pub fn router_with_store(
|
|
service: ChatService,
|
|
store: Arc<dyn Store>,
|
|
auth: AuthConfig,
|
|
workspace_root: std::path::PathBuf,
|
|
) -> Router {
|
|
build_router(
|
|
AppState {
|
|
service,
|
|
store: Some(store),
|
|
workspace_root,
|
|
},
|
|
auth,
|
|
)
|
|
}
|
|
|
|
/// Default parent of the per-session workspace folders: `~/.strata-ctl`.
|
|
fn default_workspace_root() -> std::path::PathBuf {
|
|
let home = std::env::var("HOME").unwrap_or_default();
|
|
std::path::PathBuf::from(home).join(".strata-ctl")
|
|
}
|
|
|
|
fn build_router(state: AppState, auth: AuthConfig) -> Router {
|
|
let mut r = Router::new()
|
|
.route("/health", get(health))
|
|
.route("/v1/models", get(models))
|
|
.route("/v1/chat/completions", post(chat_completions))
|
|
.route("/v1/messages", post(messages));
|
|
// The session-aware API and the web GUI exist only when a store is configured.
|
|
if state.store.is_some() {
|
|
r = r
|
|
.route(
|
|
"/api/sessions",
|
|
get(sessions::list_sessions).post(sessions::create_session),
|
|
)
|
|
.route(
|
|
"/api/sessions/{id}",
|
|
get(sessions::get_session)
|
|
.delete(sessions::delete_session)
|
|
.patch(sessions::patch_session),
|
|
)
|
|
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
|
|
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
|
|
.route(
|
|
"/api/settings/defaults",
|
|
get(sessions::get_defaults).put(sessions::put_defaults),
|
|
)
|
|
.route("/api/stats", get(sessions::stats))
|
|
.route("/", get(web::index))
|
|
.route("/assets/{*path}", get(web::asset));
|
|
}
|
|
r.with_state(state)
|
|
.layer(axum::middleware::from_fn_with_state(auth, auth_middleware))
|
|
}
|
|
|
|
/// Optional access control, read from the shared config. Default = open (no
|
|
/// key, any host), matching a loopback-only deployment.
|
|
#[derive(Clone, Default)]
|
|
pub struct AuthConfig {
|
|
/// When set, every request except `/health` must carry this key, either as
|
|
/// `Authorization: Bearer <key>` or `x-api-key: <key>`.
|
|
pub api_key: Option<String>,
|
|
/// Host-header allowlist. Empty or `["*"]` allows any host; otherwise the
|
|
/// request `Host` must match one of these (DNS-rebinding protection).
|
|
pub allowed_hosts: Vec<String>,
|
|
}
|
|
|
|
impl AuthConfig {
|
|
fn host_allowed(&self, headers: &axum::http::HeaderMap) -> bool {
|
|
if self.allowed_hosts.is_empty() || self.allowed_hosts.iter().any(|h| h == "*") {
|
|
return true;
|
|
}
|
|
let host = headers
|
|
.get(axum::http::header::HOST)
|
|
.and_then(|h| h.to_str().ok())
|
|
.unwrap_or("");
|
|
let host = host.rsplit_once(':').map(|(h, _)| h).unwrap_or(host);
|
|
self.allowed_hosts
|
|
.iter()
|
|
.any(|h| h.eq_ignore_ascii_case(host))
|
|
}
|
|
|
|
fn key_ok(&self, headers: &axum::http::HeaderMap) -> bool {
|
|
let Some(key) = self.api_key.as_deref() else {
|
|
return true;
|
|
};
|
|
if let Some(auth) = headers
|
|
.get(axum::http::header::AUTHORIZATION)
|
|
.and_then(|v| v.to_str().ok())
|
|
{
|
|
if auth.strip_prefix("Bearer ").is_some_and(|t| t == key) {
|
|
return true;
|
|
}
|
|
}
|
|
headers
|
|
.get("x-api-key")
|
|
.and_then(|v| v.to_str().ok())
|
|
.is_some_and(|k| k == key)
|
|
}
|
|
}
|
|
|
|
/// Enforces the Host allowlist and (except on `/health`) the API key before any
|
|
/// handler runs.
|
|
async fn auth_middleware(
|
|
State(auth): State<AuthConfig>,
|
|
req: axum::extract::Request,
|
|
next: axum::middleware::Next,
|
|
) -> axum::response::Response {
|
|
if !auth.host_allowed(req.headers()) {
|
|
return Error::new(
|
|
StatusCode::FORBIDDEN,
|
|
ApiErrorEnvelope::new(
|
|
"request Host is not in allowed_hosts",
|
|
"invalid_request_error",
|
|
Some("host_not_allowed".to_string()),
|
|
),
|
|
)
|
|
.into_response();
|
|
}
|
|
if req.uri().path() != "/health" && !auth.key_ok(req.headers()) {
|
|
return Error::new(
|
|
StatusCode::UNAUTHORIZED,
|
|
ApiErrorEnvelope::new(
|
|
"missing or invalid API key",
|
|
"invalid_request_error",
|
|
Some("invalid_api_key".to_string()),
|
|
),
|
|
)
|
|
.into_response();
|
|
}
|
|
next.run(req).await
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct AppState {
|
|
pub(crate) service: ChatService,
|
|
pub(crate) store: Option<Arc<dyn Store>>,
|
|
pub(crate) workspace_root: std::path::PathBuf,
|
|
}
|
|
|
|
/// An OpenAI error with the HTTP status the code implies.
|
|
pub struct Error {
|
|
status: StatusCode,
|
|
body: ApiErrorEnvelope,
|
|
}
|
|
|
|
impl Error {
|
|
pub(crate) fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
|
|
Self { status, body }
|
|
}
|
|
|
|
/// Choose a status from the error's `code`; unknown codes are client 400s.
|
|
pub(crate) fn from_envelope(env: ApiErrorEnvelope) -> Self {
|
|
let status = match env.error.code.as_deref() {
|
|
Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE,
|
|
Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT,
|
|
// engine_refused, and any client/parse error, is a 400
|
|
_ => StatusCode::BAD_REQUEST,
|
|
};
|
|
Self::new(status, env)
|
|
}
|
|
|
|
pub(crate) fn bad_request(msg: impl Into<String>) -> Self {
|
|
Self::new(
|
|
StatusCode::BAD_REQUEST,
|
|
ApiErrorEnvelope::new(msg, "invalid_request_error", None),
|
|
)
|
|
}
|
|
|
|
pub(crate) fn not_found(msg: impl Into<String>) -> Self {
|
|
Self::new(
|
|
StatusCode::NOT_FOUND,
|
|
ApiErrorEnvelope::new(msg, "invalid_request_error", Some("not_found".to_string())),
|
|
)
|
|
}
|
|
|
|
pub(crate) fn internal(msg: impl Into<String>) -> Self {
|
|
Self::new(
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
ApiErrorEnvelope::new(msg, "server_error", None),
|
|
)
|
|
}
|
|
}
|
|
|
|
impl IntoResponse for Error {
|
|
fn into_response(self) -> axum::response::Response {
|
|
(self.status, Json(self.body)).into_response()
|
|
}
|
|
}
|
|
|
|
async fn health() -> &'static str {
|
|
"ok"
|
|
}
|
|
|
|
async fn models(State(st): State<AppState>) -> Json<ModelList> {
|
|
Json(ModelList {
|
|
object: "list",
|
|
data: vec![ModelCard {
|
|
id: st.service.model_name().to_string(),
|
|
object: "model",
|
|
created: super::types::now_unix(),
|
|
owned_by: "strata-ctl".to_string(),
|
|
}],
|
|
})
|
|
}
|
|
|
|
async fn chat_completions(
|
|
State(st): State<AppState>,
|
|
raw: axum::extract::Request,
|
|
) -> axum::response::Response {
|
|
// Parse manually so a malformed body yields an OpenAI-shaped 400 rather
|
|
// than axum's default plain-text rejection.
|
|
let req: ChatRequest = match json_body(raw).await {
|
|
Ok(r) => r,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
|
|
if req.messages.is_empty() {
|
|
return Error::bad_request("`messages` must not be empty").into_response();
|
|
}
|
|
|
|
if req.stream {
|
|
match st.service.stream(&req).await {
|
|
Ok((stream, _prompt_len)) => {
|
|
use futures::StreamExt;
|
|
// Serialize each semantic chunk to an SSE event, then append the
|
|
// terminal [DONE] the OpenAI wire expects.
|
|
let events = stream
|
|
.map(|chunk| match Event::default().json_data(&chunk) {
|
|
Ok(ev) => Ok::<_, std::convert::Infallible>(ev),
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "failed to serialize SSE chunk");
|
|
Ok(Event::default().data("{}"))
|
|
}
|
|
})
|
|
.chain(futures::stream::once(async {
|
|
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
|
|
}));
|
|
Sse::new(events)
|
|
.keep_alive(
|
|
axum::response::sse::KeepAlive::new()
|
|
.interval(std::time::Duration::from_secs(10))
|
|
.text("ping"),
|
|
)
|
|
.into_response()
|
|
}
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
} else {
|
|
match st.service.complete(&req).await {
|
|
Ok(resp) => Json(resp).into_response(),
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `POST /v1/messages` — the Anthropic Messages surface, translated onto the
|
|
/// same service. Non-streaming returns one message; streaming emits the
|
|
/// Anthropic event sequence.
|
|
async fn messages(
|
|
State(st): State<AppState>,
|
|
raw: axum::extract::Request,
|
|
) -> axum::response::Response {
|
|
let areq: AnthropicRequest = match json_body(raw).await {
|
|
Ok(r) => r,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
let req = match areq.to_chat_request() {
|
|
Ok(r) => r,
|
|
Err(env) => return Error::from_envelope(env).into_response(),
|
|
};
|
|
if req.messages.is_empty() {
|
|
return Error::bad_request("`messages` must not be empty").into_response();
|
|
}
|
|
|
|
if req.stream {
|
|
match st.service.stream(&req).await {
|
|
Ok((stream, prompt_len)) => {
|
|
use futures::StreamExt;
|
|
let mut tr = AnthropicStream::new(req.model.clone(), prompt_len);
|
|
let start = tr.start();
|
|
let events =
|
|
futures::stream::once(async move { Ok::<_, std::convert::Infallible>(start) })
|
|
.chain(stream.flat_map(move |chunk| {
|
|
let evs = tr.on_chunk(&chunk);
|
|
futures::stream::iter(
|
|
evs.into_iter().map(Ok::<_, std::convert::Infallible>),
|
|
)
|
|
}));
|
|
Sse::new(events)
|
|
.keep_alive(
|
|
axum::response::sse::KeepAlive::new()
|
|
.interval(std::time::Duration::from_secs(10))
|
|
.text("ping"),
|
|
)
|
|
.into_response()
|
|
}
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
} else {
|
|
match st.service.complete(&req).await {
|
|
Ok(resp) => Json(anthropic::from_chat_response(&resp)).into_response(),
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Read and deserialize a JSON body, mapping any failure to our error type.
|
|
async fn json_body<T: DeserializeOwned>(req: axum::extract::Request) -> Result<T, Error> {
|
|
let bytes = axum::body::to_bytes(req.into_body(), 32 * 1024 * 1024)
|
|
.await
|
|
.map_err(|e| Error::bad_request(format!("failed to read body: {e}")))?;
|
|
serde_json::from_slice::<T>(&bytes)
|
|
.map_err(|e| Error::bad_request(format!("invalid JSON body: {e}")))
|
|
}
|