feat: server foundation (phase 1 core) — state, auth, healthz/decoy, gateway dispatch, HttpAdapter

Tasks completed: server-core-types, server-auth, server-healthz-decoy,
gateway-dispatch, server-adapter (5 of 17).

- src/server/state.rs: DecoyConfig + RouterState (alkcall type paths,
  6-endpoint reserved-path docs)
- src/server/auth.rs: bearer middleware + ResolvedIdentity extractor
  (10 tests: missing/malformed/basic/failed-resolution matrix)
- src/server/healthz.rs + decoy.rs: raw healthz; nginx-style 404,
  static site (path-traversal guarded), redirect decoys
- src/gateway/dispatch.rs: GatewayDispatch invoke/invoke_streaming
  (internal:false, forwarded_for:None, bounded deadline) +
  src/gateway/error.rs: CallError→HTTP status mapping (HTTP_<status>
  passthrough, retryable→Retry-After)
- src/server/adapter.rs: HttpAdapter ProtocolHandler — accept_bi →
  BiStream → TokioIo → hyper auto builder (h2 CONNECT enabled);
  integration tests over DuplexStream (request/response cycle, healthz,
  decoy 404)

Verified: cargo test (46 lib tests), clippy -D warnings, fmt,
test --all-features.
This commit is contained in:
2026-08-28 07:35:02 +00:00
parent a85500d3d9
commit d070e548ad
15 changed files with 1669 additions and 31 deletions
+361
View File
@@ -0,0 +1,361 @@
//! `HttpAdapter` — `ProtocolHandler` for `h2`/`http/1.1` (axum over a
//! `BiStream`).
//!
//! Wires the axum `Router` (gateway endpoints + `/healthz` +
//! `/openapi.json` + MCP + custom routes + decoy fallback) and drives
//! hyper's HTTP/1.1 or HTTP/2 connection driver over a single
//! bidirectional stream yielded by `Connection::accept_bi()`. The WS
//! upgrade route lands with the websocket subsystem; until then the
//! router reserves `/alk/channels` for it.
use std::sync::Arc;
use alkcall::core::auth::AuthContext;
use alkcall::core::types::{Connection, HandlerError, StreamError};
use alkcall::registry::registration::OperationRegistry;
use async_trait::async_trait;
use axum::routing::get;
use axum::Router;
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder as HyperBuilder;
use hyper_util::service::TowerToHyperService;
use tracing::error;
use super::auth::bearer_auth_middleware;
use super::decoy::decoy_fallback;
use super::healthz::healthz;
use super::state::{DecoyConfig, RouterState};
pub const ALPN_HTTP1: &[u8] = b"http/1.1";
pub const ALPN_H2: &[u8] = b"h2";
/// The WS upgrade path (ADR-067). Reserved in the default surface; the
/// handler is wired by the websocket subsystem task.
pub const WS_UPGRADE_PATH: &str = "/alk/channels";
/// Reserved default-surface paths (ADR-046 collision rule). Custom
/// routes must not collide with these; the default surface wins.
pub const RESERVED_PATHS: &[&str] = &[
"/search",
"/schema",
"/call",
"/batch",
"/subscribe",
"/publish",
"/healthz",
"/openapi.json",
"/mcp",
WS_UPGRADE_PATH,
];
pub struct HttpAdapter {
identity_provider: Arc<dyn alkcall::core::auth::IdentityProvider>,
registry: Arc<OperationRegistry>,
decoy: DecoyConfig,
extra_routes: Option<Router>,
alpn: &'static [u8],
router: Router,
}
impl HttpAdapter {
pub fn new(
identity_provider: Arc<dyn alkcall::core::auth::IdentityProvider>,
registry: Arc<OperationRegistry>,
) -> Self {
Self::for_alpn(identity_provider, registry, ALPN_HTTP1)
}
pub fn h2(
identity_provider: Arc<dyn alkcall::core::auth::IdentityProvider>,
registry: Arc<OperationRegistry>,
) -> Self {
Self::for_alpn(identity_provider, registry, ALPN_H2)
}
fn for_alpn(
identity_provider: Arc<dyn alkcall::core::auth::IdentityProvider>,
registry: Arc<OperationRegistry>,
alpn: &'static [u8],
) -> Self {
let decoy = DecoyConfig::default();
let state = RouterState {
registry: Arc::clone(&registry),
identity_provider: Arc::clone(&identity_provider),
decoy: decoy.clone(),
};
let router = build_router(state, None);
Self {
identity_provider,
registry,
decoy,
extra_routes: None,
alpn,
router,
}
}
pub fn with_decoy(mut self, decoy: DecoyConfig) -> Self {
self.decoy = decoy.clone();
let state = RouterState {
registry: Arc::clone(&self.registry),
identity_provider: Arc::clone(&self.identity_provider),
decoy,
};
self.router = build_router(state, self.extra_routes.take());
self
}
pub fn with_extra_routes(mut self, routes: Router) -> Self {
let state = RouterState {
registry: Arc::clone(&self.registry),
identity_provider: Arc::clone(&self.identity_provider),
decoy: self.decoy.clone(),
};
self.router = build_router(state, Some(routes.clone()));
self.extra_routes = Some(routes);
self
}
pub fn decoy(&self) -> &DecoyConfig {
&self.decoy
}
pub fn alpn(&self) -> &'static [u8] {
self.alpn
}
pub fn router(&self) -> &Router {
&self.router
}
}
fn build_router(state: RouterState, extra_routes: Option<Router>) -> Router {
let auth_state = Arc::clone(&state.identity_provider);
let default: Router<RouterState> = Router::new()
.route("/healthz", get(healthz))
.route_layer(from_fn_with_state(
auth_state.clone(),
bearer_auth_middleware,
))
.fallback(decoy_fallback);
let with_extras = match extra_routes {
Some(extra) => {
let extra: Router<RouterState> = extra.with_state(());
default.merge(extra)
}
None => default,
};
with_extras.with_state(state)
}
use axum::middleware::from_fn_with_state;
#[async_trait]
impl alkcall::core::types::ProtocolHandler for HttpAdapter {
fn alpn(&self) -> &'static [u8] {
self.alpn
}
async fn handle(&self, connection: Connection, auth: &AuthContext) -> Result<(), HandlerError> {
if let Some(identity) = auth.identity.clone() {
let _ = connection.set_identity(identity);
}
let stream = connection
.accept_bi()
.await
.map_err(stream_error_to_handler)?;
self.serve_io(stream).await
}
}
impl HttpAdapter {
async fn serve_io<I>(&self, io: I) -> Result<(), HandlerError>
where
I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin + 'static,
{
let io = TokioIo::new(io);
let service = TowerToHyperService::new(self.router.clone());
#[cfg_attr(not(feature = "h2"), allow(unused_mut))]
let mut builder = HyperBuilder::new(TokioExecutor::new());
#[cfg(feature = "h2")]
{
builder.http2().enable_connect_protocol();
}
let conn = builder.serve_connection_with_upgrades(io, service);
tokio::pin!(conn);
let result = (&mut conn).await;
if let Err(e) = result {
error!("http adapter: connection closed with error: {e}");
}
Ok(())
}
}
fn stream_error_to_handler(e: StreamError) -> HandlerError {
HandlerError::from(e)
}
#[cfg(test)]
mod tests {
use super::*;
use alkcall::core::auth::IdentityProvider;
use alkcall::core::types::ProtocolHandler;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
struct NoopProvider;
impl IdentityProvider for NoopProvider {
fn resolve_from_fingerprint(&self, _: &str) -> Option<alkcall::core::auth::Identity> {
None
}
fn resolve_from_token(
&self,
_: &alkcall::core::auth::AuthToken,
) -> Option<alkcall::core::auth::Identity> {
None
}
}
fn empty_registry() -> Arc<OperationRegistry> {
Arc::new(OperationRegistry::new())
}
fn provider() -> Arc<dyn IdentityProvider> {
Arc::new(NoopProvider)
}
#[test]
fn alpn_returns_http1_for_default_new() {
let adapter = HttpAdapter::new(provider(), empty_registry());
assert_eq!(adapter.alpn(), ALPN_HTTP1);
assert_eq!(adapter.alpn(), b"http/1.1");
}
#[test]
fn alpn_returns_h2_for_h2_constructor() {
let adapter = HttpAdapter::h2(provider(), empty_registry());
assert_eq!(adapter.alpn(), ALPN_H2);
assert_eq!(adapter.alpn(), b"h2");
}
#[test]
fn decoy_config_default_is_not_found() {
assert!(matches!(DecoyConfig::default(), DecoyConfig::NotFound));
}
#[test]
fn with_decoy_updates_decoy() {
let adapter = HttpAdapter::new(provider(), empty_registry());
let adapter = adapter.with_decoy(DecoyConfig::Redirect {
to: "https://example.com".to_string(),
});
assert!(matches!(adapter.decoy(), DecoyConfig::Redirect { .. }));
}
#[tokio::test]
async fn full_http_request_response_cycle_over_duplex() {
let extra = Router::new().route("/v1/ping", get(|| async { "pong" }));
let adapter = HttpAdapter::new(provider(), empty_registry()).with_extra_routes(extra);
let (client, server) = tokio::io::duplex(64 * 1024);
let conn = Connection::from_bidi(server, b"http/1.1".to_vec(), None);
let auth = AuthContext::anonymous(b"http/1.1");
let server_task =
tokio::spawn(async move { ProtocolHandler::handle(&adapter, conn, &auth).await });
let mut client = client;
client
.write_all(b"GET /v1/ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
.await
.unwrap();
let mut response = Vec::new();
let _ = tokio::time::timeout(
std::time::Duration::from_secs(5),
client.read_to_end(&mut response),
)
.await
.expect("read timed out")
.unwrap();
let text = String::from_utf8_lossy(&response);
assert!(text.starts_with("HTTP/1.1 200 OK"), "got: {text}");
assert!(text.contains("pong"), "got: {text}");
let _ = server_task.await;
}
#[tokio::test]
async fn healthz_served_by_the_adapter_over_duplex() {
let adapter = HttpAdapter::new(provider(), empty_registry());
let (client, server) = tokio::io::duplex(64 * 1024);
let conn = Connection::from_bidi(server, b"http/1.1".to_vec(), None);
let auth = AuthContext::anonymous(b"http/1.1");
let server_task = tokio::spawn(async move {
let _ = ProtocolHandler::handle(&adapter, conn, &auth).await;
});
let mut client = client;
client
.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
.await
.unwrap();
let mut response = Vec::new();
let _ = tokio::time::timeout(
std::time::Duration::from_secs(5),
client.read_to_end(&mut response),
)
.await
.expect("read timed out")
.unwrap();
let text = String::from_utf8_lossy(&response);
assert!(text.starts_with("HTTP/1.1 200 OK"), "got: {text}");
assert!(text.contains("ok"), "got: {text}");
let _ = server_task.await;
}
#[tokio::test]
async fn unknown_path_serves_decoy_404_over_duplex() {
let adapter = HttpAdapter::new(provider(), empty_registry());
let (client, server) = tokio::io::duplex(64 * 1024);
let conn = Connection::from_bidi(server, b"http/1.1".to_vec(), None);
let auth = AuthContext::anonymous(b"http/1.1");
let server_task = tokio::spawn(async move {
let _ = ProtocolHandler::handle(&adapter, conn, &auth).await;
});
let mut client = client;
client
.write_all(b"GET /nowhere HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
.await
.unwrap();
let mut response = Vec::new();
let _ = tokio::time::timeout(
std::time::Duration::from_secs(5),
client.read_to_end(&mut response),
)
.await
.expect("read timed out")
.unwrap();
let text = String::from_utf8_lossy(&response);
assert!(text.starts_with("HTTP/1.1 404 Not Found"), "got: {text}");
assert!(
text.contains("nginx"),
"decoy should look like nginx: {text}"
);
let _ = server_task.await;
}
}
+305
View File
@@ -0,0 +1,305 @@
//! Shared Bearer auth axum middleware ([ADR-004]).
//!
//! Resolves the `Authorization: Bearer` header via
//! `IdentityProvider::resolve_from_token()` and stashes the resolved
//! `Option<Identity>` in request extensions. Shared by the HTTP gateway
//! endpoints and the `to_mcp` service.
//!
//! Resolution semantics:
//! - No `Authorization` header → `None` (request proceeds; the route
//! handler / `AccessControl` decides whether to reject).
//! - Malformed `Authorization` header (not `Bearer <token>`) → `None`
//! (treated as no-token, not an error — Bearer-only is the auth
//! mechanism).
//! - Token present but resolution fails → `None` (treat as
//! unauthenticated, matching the call protocol's per-request identity
//! resolution behavior).
//!
//! This middleware resolves identity and stashes it; it does NOT enforce
//! `AccessControl` (the route handlers / `GatewayDispatch::invoke()` do)
//! or map `CallError` codes to HTTP status (the error mapping does).
//!
//! [ADR-004]: crate::docs
use std::convert::Infallible;
use std::sync::Arc;
use alkcall::core::auth::{AuthToken, Identity, IdentityProvider};
use axum::extract::{FromRequestParts, Request, State};
use axum::http::header::AUTHORIZATION;
use axum::middleware::Next;
use axum::response::Response;
use http::request::Parts;
/// Axum middleware that resolves the `Authorization: Bearer` header via
/// `IdentityProvider::resolve_from_token()` and stashes the resolved
/// `Option<Identity>` in request extensions.
///
/// The state is `Arc<dyn IdentityProvider>` so the middleware can be applied
/// via `middleware::from_fn_with_state(idp.clone(), bearer_auth_middleware)`
/// around both HTTP routes and a nested service.
pub async fn bearer_auth_middleware(
State(identity_provider): State<Arc<dyn IdentityProvider>>,
mut request: Request,
next: Next,
) -> Response {
let identity = extract_bearer_identity(&request, identity_provider.as_ref());
request.extensions_mut().insert(identity);
next.run(request).await
}
/// Extract the `Authorization: Bearer <token>` header and resolve it to
/// an `Option<Identity>`. Returns `None` if no token is present (the
/// request proceeds unauthenticated; the route handler / `AccessControl`
/// decides whether to reject). Returns `None` if the token is present
/// but resolution fails (treat as unauthenticated, not as an error —
/// matches the call protocol's per-request identity resolution behavior).
pub fn extract_bearer_identity(
request: &Request,
identity_provider: &dyn IdentityProvider,
) -> Option<Identity> {
let header = request.headers().get(AUTHORIZATION)?;
let token_str = header.to_str().ok()?.strip_prefix("Bearer ")?;
let token = AuthToken {
raw: token_str.as_bytes().to_vec(),
};
identity_provider.resolve_from_token(&token)
}
/// Axum extractor: the resolved bearer identity (or `None` if
/// unauthenticated). Read from request extensions (stashed by
/// `bearer_auth_middleware`).
#[derive(Clone, Debug)]
pub struct ResolvedIdentity(pub Option<Identity>);
impl<S> FromRequestParts<S> for ResolvedIdentity
where
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let identity = parts
.extensions
.get::<Option<Identity>>()
.cloned()
.flatten();
Ok(ResolvedIdentity(identity))
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::{Request as AxumRequest, StatusCode};
use axum::middleware::from_fn_with_state;
use axum::routing::get;
use axum::Router;
use std::collections::HashMap;
use tower::ServiceExt;
fn sample_identity() -> Identity {
Identity {
id: "worker-a".to_string(),
scopes: vec!["relay:connect".to_string()],
resources: HashMap::new(),
}
}
struct StaticProvider {
identity: Option<Identity>,
}
impl IdentityProvider for StaticProvider {
fn resolve_from_fingerprint(&self, _: &str) -> Option<Identity> {
None
}
fn resolve_from_token(&self, _: &AuthToken) -> Option<Identity> {
self.identity.clone()
}
}
fn provider(identity: Option<Identity>) -> Arc<dyn IdentityProvider> {
Arc::new(StaticProvider { identity })
}
fn request_with_authorization(value: Option<&str>) -> Request {
let mut builder = AxumRequest::builder();
if let Some(v) = value {
builder = builder.header(AUTHORIZATION, v);
}
builder.body(Body::empty()).unwrap()
}
#[test]
fn extract_returns_some_for_valid_bearer_when_provider_resolves() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(Some("Bearer alk_testsecret"));
let identity = extract_bearer_identity(&req, idp.as_ref());
assert!(identity.is_some());
assert_eq!(identity.unwrap().id, "worker-a");
}
#[test]
fn extract_returns_none_for_missing_authorization_header() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(None);
let identity = extract_bearer_identity(&req, idp.as_ref());
assert!(identity.is_none());
}
#[test]
fn extract_returns_none_for_malformed_authorization_header() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(Some("not-a-bearer-scheme"));
let identity = extract_bearer_identity(&req, idp.as_ref());
assert!(identity.is_none());
}
#[test]
fn extract_returns_none_for_basic_auth_bearer_only() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(Some("Basic dXNlcjpwYXNz"));
let identity = extract_bearer_identity(&req, idp.as_ref());
assert!(identity.is_none());
}
#[test]
fn extract_returns_none_when_token_present_but_resolution_fails() {
let idp = provider(None);
let req = request_with_authorization(Some("Bearer alk_unknown"));
let identity = extract_bearer_identity(&req, idp.as_ref());
assert!(identity.is_none());
}
async fn run_middleware(idp: Arc<dyn IdentityProvider>, request: Request) -> Response {
let app: Router<()> = Router::new()
.route(
"/",
get(|req: Request| async move {
let identity = req
.extensions()
.get::<Option<Identity>>()
.cloned()
.flatten();
if let Some(id) = identity {
(StatusCode::OK, id.id)
} else {
(StatusCode::OK, "none".to_string())
}
}),
)
.layer(from_fn_with_state(idp, bearer_auth_middleware));
app.oneshot(request).await.unwrap()
}
#[tokio::test]
async fn middleware_stashes_some_identity_for_valid_bearer() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(Some("Bearer alk_testsecret"));
let response = run_middleware(idp, req).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"worker-a");
}
#[tokio::test]
async fn middleware_stashes_none_when_no_authorization_header() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(None);
let response = run_middleware(idp, req).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"none");
}
#[tokio::test]
async fn middleware_stashes_none_for_malformed_authorization() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(Some("garbage"));
let response = run_middleware(idp, req).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"none");
}
#[tokio::test]
async fn middleware_stashes_none_for_basic_auth() {
let idp = provider(Some(sample_identity()));
let req = request_with_authorization(Some("Basic dXNlcjpwYXNz"));
let response = run_middleware(idp, req).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"none");
}
#[tokio::test]
async fn middleware_stashes_none_when_resolution_fails() {
let idp = provider(None);
let req = request_with_authorization(Some("Bearer alk_unknown"));
let response = run_middleware(idp, req).await;
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"none");
}
#[tokio::test]
async fn resolved_identity_extractor_retrieves_stashed_some() {
let idp = provider(Some(sample_identity()));
let app: Router<()> = Router::new()
.route(
"/",
get(|ResolvedIdentity(identity): ResolvedIdentity| async move {
match identity {
Some(id) => (StatusCode::OK, id.id),
None => (StatusCode::OK, "none".to_string()),
}
}),
)
.layer(from_fn_with_state(idp, bearer_auth_middleware));
let req = request_with_authorization(Some("Bearer alk_testsecret"));
let response = app.oneshot(req).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"worker-a");
}
#[tokio::test]
async fn resolved_identity_extractor_retrieves_stashed_none() {
let idp = provider(Some(sample_identity()));
let app: Router<()> = Router::new()
.route(
"/",
get(|ResolvedIdentity(identity): ResolvedIdentity| async move {
match identity {
Some(id) => (StatusCode::OK, id.id),
None => (StatusCode::OK, "none".to_string()),
}
}),
)
.layer(from_fn_with_state(idp, bearer_auth_middleware));
let req = request_with_authorization(None);
let response = app.oneshot(req).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
assert_eq!(&bytes[..], b"none");
}
}
+290
View File
@@ -0,0 +1,290 @@
//! Stealth decoy fallback for unknown paths ([ADR-010], [ADR-036]).
//!
//! For paths not matched by the default surface (the 6 gateway
//! endpoints, `/healthz`, `/openapi.json`, the MCP route, the WS
//! upgrade) nor by a custom route ([ADR-046]), the HTTP handler serves
//! a configurable decoy ([`DecoyConfig`]): a fake nginx-style 404 (the
//! default), a static site served from a directory, or a redirect. The
//! decoy must not leak alk presence — no alk-specific headers, no alk
//! error format.
//!
//! [ADR-010]: crate::docs
//! [ADR-036]: crate::docs
//! [ADR-046]: crate::docs
use std::path::{Component, Path, PathBuf};
use axum::body::Body;
use axum::extract::{Request, State};
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::Response;
use super::DecoyConfig;
pub async fn decoy_fallback(State(decoy): State<DecoyConfig>, request: Request) -> Response {
match decoy {
DecoyConfig::NotFound => fake_nginx_404(),
DecoyConfig::StaticSite { root } => serve_static(&root, request).await,
DecoyConfig::Redirect { to } => redirect(&to),
}
}
pub fn fake_nginx_404() -> Response {
let body = nginx_404_body();
let mut resp = Response::new(Body::from(body));
*resp.status_mut() = StatusCode::NOT_FOUND;
resp.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"),
);
resp.headers_mut()
.insert(header::SERVER, HeaderValue::from_static("nginx"));
resp
}
pub fn redirect(to: &str) -> Response {
let mut resp = Response::new(Body::empty());
*resp.status_mut() = StatusCode::FOUND;
if let Ok(value) = HeaderValue::from_str(to) {
resp.headers_mut().insert(header::LOCATION, value);
}
resp
}
pub async fn serve_static(root: &Path, request: Request) -> Response {
let path = request.uri().path();
let resolved = match resolve_static_path(root, path) {
Some(p) => p,
None => return fake_nginx_404(),
};
match tokio::fs::read(&resolved).await {
Ok(bytes) => {
let content_type = mime_for_path(&resolved);
let mut resp = Response::new(Body::from(bytes));
*resp.status_mut() = StatusCode::OK;
resp.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
resp
}
Err(_) => fake_nginx_404(),
}
}
fn resolve_static_path(root: &Path, request_path: &str) -> Option<PathBuf> {
let trimmed = request_path.trim_start_matches('/');
let relative = if trimmed.is_empty() {
PathBuf::from("index.html")
} else {
let decoded = percent_decode(trimmed);
PathBuf::from(decoded)
};
let mut safe = PathBuf::new();
for component in relative.components() {
match component {
Component::Normal(part) => safe.push(part),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
}
}
if safe.as_os_str().is_empty() {
return None;
}
let full = root.join(&safe);
if full.is_dir() {
return Some(full.join("index.html"));
}
if full.is_file() {
return Some(full);
}
None
}
fn percent_decode(input: &str) -> String {
let mut out = String::with_capacity(input.len());
let bytes = input.as_bytes();
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if b == b'%' && i + 2 < bytes.len() {
if let (Some(h), Some(l)) = (hex_digit(bytes[i + 1]), hex_digit(bytes[i + 2])) {
out.push(((h << 4) | l) as char);
i += 3;
continue;
}
} else if b == b'+' {
out.push(' ');
i += 1;
continue;
}
out.push(b as char);
i += 1;
}
out
}
fn hex_digit(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn mime_for_path(path: &Path) -> &'static str {
match path.extension().and_then(|e| e.to_str()) {
Some("html") | Some("htm") => "text/html; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("js") => "application/javascript",
Some("json") => "application/json",
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("svg") => "image/svg+xml",
Some("txt") => "text/plain; charset=utf-8",
Some("ico") => "image/x-icon",
Some("woff") => "font/woff",
Some("woff2") => "font/woff2",
_ => "application/octet-stream",
}
}
fn nginx_404_body() -> String {
"<html>\r\n<head><title>404 Not Found</title></head>\r\n<body>\r\n<center><h1>404 Not Found</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n".to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
fn decoy_router(decoy: DecoyConfig) -> axum::Router {
axum::Router::new()
.fallback(decoy_fallback)
.with_state(decoy)
}
async fn send(router: axum::Router, uri: &str) -> axum::response::Response {
tower::ServiceExt::<Request<Body>>::oneshot(
router,
Request::builder().uri(uri).body(Body::empty()).unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn unknown_path_with_not_found_decoy_returns_404() {
let resp = send(decoy_router(DecoyConfig::NotFound), "/nonexistent").await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let server = resp
.headers()
.get(header::SERVER)
.map(|v| v.to_str().unwrap().to_string());
assert_eq!(server.as_deref(), Some("nginx"));
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let body = String::from_utf8_lossy(&bytes);
assert!(!body.contains("alk"));
assert!(body.contains("404 Not Found"));
}
#[tokio::test]
async fn unknown_path_with_redirect_decoy_returns_redirect() {
let decoy = DecoyConfig::Redirect {
to: "https://example.com".to_string(),
};
let resp = send(decoy_router(decoy), "/anything").await;
assert_eq!(resp.status(), StatusCode::FOUND);
let location = resp
.headers()
.get(header::LOCATION)
.map(|v| v.to_str().unwrap().to_string());
assert_eq!(location.as_deref(), Some("https://example.com"));
}
#[tokio::test]
async fn unknown_path_with_static_site_decoy_serves_file() {
let dir = tempfile_dir();
let file = dir.join("index.html");
tokio::fs::write(&file, "<h1>hello</h1>").await.unwrap();
let decoy = DecoyConfig::StaticSite { root: dir.clone() };
let resp = send(decoy_router(decoy), "/").await;
assert_eq!(resp.status(), StatusCode::OK);
let ctype = resp
.headers()
.get(header::CONTENT_TYPE)
.map(|v| v.to_str().unwrap().to_string());
assert!(ctype.as_deref().unwrap_or("").starts_with("text/html"));
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&bytes[..], b"<h1>hello</h1>");
}
#[tokio::test]
async fn static_site_decoy_serves_named_file() {
let dir = tempfile_dir();
tokio::fs::write(dir.join("about.html"), "<p>about</p>")
.await
.unwrap();
let decoy = DecoyConfig::StaticSite { root: dir };
let resp = send(decoy_router(decoy), "/about.html").await;
assert_eq!(resp.status(), StatusCode::OK);
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&bytes[..], b"<p>about</p>");
}
#[tokio::test]
async fn static_site_decoy_missing_file_returns_fake_404() {
let dir = tempfile_dir();
let decoy = DecoyConfig::StaticSite { root: dir };
let resp = send(decoy_router(decoy), "/missing.txt").await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let server = resp
.headers()
.get(header::SERVER)
.map(|v| v.to_str().unwrap().to_string());
assert_eq!(server.as_deref(), Some("nginx"));
}
#[tokio::test]
async fn static_site_decoy_path_traversal_is_blocked() {
let dir = tempfile_dir();
tokio::fs::write(dir.join("index.html"), "ok")
.await
.unwrap();
tokio::fs::write(dir.join("secret.txt"), "secret")
.await
.unwrap();
let decoy = DecoyConfig::StaticSite { root: dir };
let resp = send(decoy_router(decoy), "/../secret.txt").await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn not_found_decoy_does_not_leak_alk_headers() {
let resp = send(decoy_router(DecoyConfig::NotFound), "/whatever").await;
for (name, value) in resp.headers().iter() {
let name = name.as_str().to_lowercase();
let value = value.to_str().unwrap_or("");
assert!(
!name.contains("alkhttp") && !value.contains("alkhttp"),
"decoy leaked alkhttp: {name}={value}"
);
}
}
fn tempfile_dir() -> PathBuf {
let dir =
PathBuf::from("/tmp").join(format!("alkhttp-decoy-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
}
+61
View File
@@ -0,0 +1,61 @@
//! `GET /healthz` — the one raw HTTP route (ADR-036).
//!
//! No auth, no call protocol, no `OperationContext`. Returns `200 OK`
//! with a plain-text body (`"ok"`). The infrastructure endpoint load
//! balancers and orchestrators call; it must work before identity is
//! resolvable.
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::IntoResponse;
const HEALTHZ_BODY: &str = "ok";
pub async fn healthz() -> impl IntoResponse {
(
StatusCode::OK,
[(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"))],
HEALTHZ_BODY,
)
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
async fn call_healthz(req: Request<Body>) -> axum::response::Response {
let app = axum::Router::new().route("/healthz", axum::routing::get(healthz));
tower::ServiceExt::<Request<Body>>::oneshot(app, req)
.await
.unwrap()
}
#[tokio::test]
async fn healthz_handler_returns_200_with_plain_text_ok() {
let req = Request::builder()
.uri("/healthz")
.body(Body::empty())
.unwrap();
let resp = call_healthz(req).await;
assert_eq!(resp.status(), StatusCode::OK);
let ctype = resp
.headers()
.get(header::CONTENT_TYPE)
.map(|v| v.to_str().unwrap().to_string());
assert_eq!(ctype.as_deref(), Some("text/plain"));
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&bytes[..], b"ok");
}
#[tokio::test]
async fn healthz_works_with_no_authorization_header() {
let req = Request::builder()
.uri("/healthz")
.body(Body::empty())
.unwrap();
let resp = call_healthz(req).await;
assert_eq!(resp.status(), StatusCode::OK);
}
}
+10
View File
@@ -1 +1,11 @@
pub mod adapter;
pub mod auth;
pub mod decoy;
pub mod healthz;
pub mod state;
pub use adapter::{HttpAdapter, RESERVED_PATHS, WS_UPGRADE_PATH};
pub use auth::{bearer_auth_middleware, extract_bearer_identity, ResolvedIdentity};
pub use decoy::decoy_fallback;
pub use healthz::healthz;
pub use state::DecoyConfig;
+88
View File
@@ -0,0 +1,88 @@
//! Shared server state and configuration for the `HttpAdapter` router.
use std::path::PathBuf;
use std::sync::Arc;
use alkcall::core::auth::IdentityProvider;
use alkcall::registry::registration::OperationRegistry;
/// The stealth decoy surface for paths that are not registered
/// operations and not part of the reserved default surface (the 6
/// gateway endpoints, `/healthz`, `/openapi.json`, the MCP route, the
/// WS upgrade path). Set by the assembly layer at `HttpAdapter`
/// construction. The existence of the decoy path is fixed by ADR-010;
/// the variant is a two-way-door config default.
#[derive(Clone, Default, Debug)]
pub enum DecoyConfig {
/// Serve a fake `404 Not Found` (the default — a fake nginx 404).
#[default]
NotFound,
/// Serve a static site from a configured directory.
StaticSite { root: PathBuf },
/// Redirect to a configured URL.
Redirect { to: String },
}
/// State embedded in the axum `Router`: the registry and identity
/// provider every request handler reaches through the router state, plus
/// the decoy config for the fallback.
#[derive(Clone)]
pub(crate) struct RouterState {
pub(crate) registry: Arc<OperationRegistry>,
pub(crate) identity_provider: Arc<dyn IdentityProvider>,
pub(crate) decoy: DecoyConfig,
}
impl axum::extract::FromRef<RouterState> for DecoyConfig {
fn from_ref(state: &RouterState) -> Self {
state.decoy.clone()
}
}
impl axum::extract::FromRef<RouterState> for Arc<OperationRegistry> {
fn from_ref(state: &RouterState) -> Self {
Arc::clone(&state.registry)
}
}
impl axum::extract::FromRef<RouterState> for Arc<dyn IdentityProvider> {
fn from_ref(state: &RouterState) -> Self {
Arc::clone(&state.identity_provider)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decoy_config_default_is_not_found() {
assert!(matches!(DecoyConfig::default(), DecoyConfig::NotFound));
}
#[test]
fn router_state_from_ref_extracts_decoy() {
let state = RouterState {
registry: Arc::new(OperationRegistry::new()),
identity_provider: Arc::new(NoopProvider),
decoy: DecoyConfig::Redirect {
to: "https://example.com".to_string(),
},
};
let extracted: DecoyConfig = axum::extract::FromRef::from_ref(&state);
assert!(matches!(extracted, DecoyConfig::Redirect { .. }));
}
struct NoopProvider;
impl IdentityProvider for NoopProvider {
fn resolve_from_fingerprint(&self, _: &str) -> Option<alkcall::core::auth::Identity> {
None
}
fn resolve_from_token(
&self,
_: &alkcall::core::auth::AuthToken,
) -> Option<alkcall::core::auth::Identity> {
None
}
}
}