真机联调(CubeSandbox 沙箱当异地站点端 → 海光真机 192.168.1.102)暴露并修掉
三个真缺口,并把「否定式判据恒为真」这个探针自指坑彻底堵上。
① hostd 服务端**完全没有鉴权**(真缺口)
原来 client.rs 只在客户端拼 Authorization 头,服务端根本不验 ——
之所以没出事只因默认只听回环。新增 crates/mpc-hostd/src/auth.rs:
- 回环信任(未配密钥)/ 凭据模式(已配)两档;服务端只存 sha256(secret),
摘要不能反向当 token 用;最低 32 字节,启动期硬拒;ct_eq 常量时间比对;
- 对外不区分「没带」与「带错了」,细分只进日志;
- 鉴权先于路由(含 /health),业务端点 POST /sandboxes 同样受保护;
- 非回环必须「共享密钥 + --allow-remote」两者齐备,互为兜底。
共享密钥是静态的,不是站点端签发的短期 token(那一层仍未落地)。
② DELETE /sandboxes/{id} 只停不删(真缺口)
api.rs 注释写着「显式删除」,实现却只调 stop() ⇒ 删完仍在 GET /sandboxes 里。
症状极静默:204 看着成功,列表越积越多。
新增 runtime.remove()(先 stop 收进程、再删记录与子进程句柄,顺序反了会留僵尸)。
③ guest 边界探针的否定式判据可能是空判据
实测 release+strip+LTO 后:eth_sendRawTransaction / 1234567812345678 在 musl
host 产物里**也找不到**(host 不含 chain)⇒ 拿它们判 guest 必然恒为真;
而 mpc-hostd / allow-remote 在 guest 产物里**也会有**(那是 main.rs 帮助文本)。
改法:标识串按归属分五组,binary 子命令同时吃 guest + host 两份产物做交叉对照 ——
先用 host 证明「这些串确实会进二进制」,再据此在 guest 上跑否定判据;
host 里找不到 ⇒ 探针失效 ⇒ 直接 FAIL,不安静跳过。
配套:
- 两种 musl 产物正式化:guest(--no-default-features) 与
host(--no-default-features --features host-only)。真机无 Rust 工具链,
hostd 必须以自包含静态二进制跑在真机上;openssl 仍禁入 musl 依赖图
(否则 pkg-config 会抢先于 compile_error! 守卫,守卫就成假判据)。
- 修 Request::header 大小写敏感(手写 Request 时带对 Authorization 头却被判没带)。
- 主门禁第 4 条改交叉对照(deps 30 + guard 3 + binary 39 条);
第 12 条 hostd 自测补 DELETE 真删判据。
- 文档:docs/REAL_MACHINE_FINDINGS.md 第 5 节(沙箱→真机闭环)+ CLAUDE.md 铁律。
真机实测全绿:沙箱经 e2b 兼容 HTTP 面 up/ps/attest/down 跨机跑通,
鉴权矩阵(正向 200 / 缺凭据 401 / 错凭据 401 且两响应体逐字节相同)全绿。
诚实边界:沙箱起的是真机上的普通进程不是真 TEE enclave(四布尔必然全 false),
这验证的是控制面编排而非证明链;hostd 仍是明文 HTTP;只连了海光一台。
381 lines
14 KiB
Rust
381 lines
14 KiB
Rust
//! 宿主控制面的 HTTP 层 —— 由 **axum / hyper** 承担。
|
||
//!
|
||
//! # 为什么不再自研
|
||
//!
|
||
//! 上一版自己解析 HTTP/1.1(请求行、头、`Content-Length`、chunked、keep-alive)。
|
||
//! 那是纯粹的协议活,不是本项目的业务:一旦出现「响应头和 body 分两次写、
|
||
//! 客户端只读一次」这类流语义细节,测试就会偶发红,而排查成本全落在自己身上。
|
||
//! 现在这些全部交给 hyper,`api.rs` 的业务判定与它的契约测试**一行不动**。
|
||
//!
|
||
//! # 隔离带
|
||
//!
|
||
//! `protocol.rs` 里的 `Request`/`Response` 是协议无关的中间表示。
|
||
//! 本文件只做两件事:把 axum 的请求**转成**它,再把它的响应**转回** axum。
|
||
//! 换协议栈不换业务判定 —— 这是刻意保留的边界。
|
||
//!
|
||
//! # 仍然由我们把守的边界
|
||
//!
|
||
//! hyper 的默认行为不等于我们要的契约。以下三条在 handler 里显式判定:
|
||
//!
|
||
//! - `Transfer-Encoding: chunked` → **400 + 关连接**(控制面只收定长体);
|
||
//! - **重复 `Content-Length`** → 400(请求走私入口);
|
||
//! - body 超过 4 MiB → 413。
|
||
//!
|
||
//! 其它(超时、半开连接、头部大小、keep-alive、请求行语法)由 hyper 负责。
|
||
|
||
use std::collections::HashMap;
|
||
use std::sync::Arc;
|
||
|
||
use axum::body::{to_bytes, Body};
|
||
use axum::extract::{Request as AxumRequest, State};
|
||
use axum::http::{StatusCode, Uri};
|
||
use axum::response::Response as AxumResponse;
|
||
use axum::Router;
|
||
|
||
use crate::api;
|
||
use crate::protocol::{body_str, Request, Response, Status, MAX_BODY};
|
||
use crate::runtime::TeeRuntime;
|
||
|
||
/// 构造路由。
|
||
///
|
||
/// 用 `fallback` 而不是逐条 `route`:e2b 兼容面的路径分段规则
|
||
/// (`/sandboxes/{id}/{pause,resume,attestation,connect,timeout}`)已经集中在
|
||
/// `api::dispatch` 里,路由层再写一遍就是把同一份判定拆到两处 —— 会分叉。
|
||
pub fn router(rt: Arc<TeeRuntime>) -> Router {
|
||
router_with_auth(rt, crate::auth::Authenticator::unconfigured())
|
||
}
|
||
|
||
/// 带鉴权的路由。
|
||
///
|
||
/// `auth` 传进 handler 的 State 里,**每个请求都过一次判定**。
|
||
pub fn router_with_auth(rt: Arc<TeeRuntime>, auth: crate::auth::Authenticator) -> Router {
|
||
Router::new()
|
||
.fallback(handler)
|
||
.with_state((rt, auth))
|
||
}
|
||
|
||
/// handler 的 State。
|
||
type HandlerState = (Arc<TeeRuntime>, crate::auth::Authenticator);
|
||
|
||
/// 单个请求的处理。
|
||
async fn handler(State((rt, auth)): State<HandlerState>, req: AxumRequest) -> AxumResponse {
|
||
let (parts, body) = req.into_parts();
|
||
|
||
// ★ 边界一:chunked 一律不收。hyper 会透明解码 chunked,
|
||
// 所以必须在它把 body 交给我们之前拦下。
|
||
if let Some(te) = parts.headers.get("transfer-encoding") {
|
||
if te.to_str().unwrap_or("").to_ascii_lowercase().contains("chunked") {
|
||
return close(Response::error(Status::BadRequest, "不支持 chunked 请求体"));
|
||
}
|
||
}
|
||
|
||
// ★ 边界二:重复 Content-Length 是请求走私的经典入口。
|
||
// hyper 可能自己在解析层就拒了;这里再兜一次,保证行为可判。
|
||
let cl_values: Vec<_> = parts.headers.get_all("content-length").iter().collect();
|
||
if cl_values.len() > 1
|
||
|| cl_values
|
||
.iter()
|
||
.any(|v| v.to_str().unwrap_or("").contains(','))
|
||
{
|
||
return close(Response::error(
|
||
Status::BadRequest,
|
||
"重复的 Content-Length 不合法",
|
||
));
|
||
}
|
||
|
||
let bytes = match to_bytes(body, MAX_BODY).await {
|
||
Ok(b) => b,
|
||
Err(_) => {
|
||
return close(Response::error(Status::PayloadTooLarge, "请求体过大"));
|
||
}
|
||
};
|
||
|
||
let mut headers = HashMap::new();
|
||
for (k, v) in parts.headers.iter() {
|
||
if let Ok(s) = v.to_str() {
|
||
headers.insert(k.as_str().to_ascii_lowercase(), s.to_string());
|
||
}
|
||
}
|
||
|
||
let (path, query) = split_uri(&parts.uri);
|
||
let ours = Request {
|
||
method: parts.method.as_str().to_ascii_uppercase(),
|
||
path,
|
||
query,
|
||
headers,
|
||
body: bytes.to_vec(),
|
||
};
|
||
|
||
to_axum(api::dispatch_with_auth(&rt, &ours, &auth))
|
||
}
|
||
|
||
fn split_uri(uri: &Uri) -> (String, String) {
|
||
let path = uri.path().to_string();
|
||
let query = uri.query().unwrap_or("").to_string();
|
||
(path, query)
|
||
}
|
||
|
||
/// 把协议无关的响应转成 axum 响应。
|
||
///
|
||
/// **204 必须是空体** —— e2b 兼容面硬要求,`DELETE /sandboxes/{id}` 就走这条。
|
||
fn to_axum(resp: Response) -> AxumResponse {
|
||
let status =
|
||
StatusCode::from_u16(resp.status.code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||
let mut builder = AxumResponse::builder().status(status);
|
||
for (k, v) in &resp.extra_headers {
|
||
builder = builder.header(k.as_str(), v.as_str());
|
||
}
|
||
let body = if resp.status == Status::NoContent {
|
||
Vec::new()
|
||
} else {
|
||
resp.body
|
||
};
|
||
// Body::from(Vec) 带准确 size_hint,hyper 会写准确的 Content-Length。
|
||
builder.body(Body::from(body)).unwrap_or_else(|_| {
|
||
AxumResponse::builder()
|
||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||
.body(Body::empty())
|
||
.expect("空响应一定能构造")
|
||
})
|
||
}
|
||
|
||
/// 畸形请求之后不能继续复用同一条流。
|
||
fn close(resp: Response) -> AxumResponse {
|
||
let mut a = to_axum(resp);
|
||
a.headers_mut().insert(
|
||
axum::http::header::CONNECTION,
|
||
axum::http::HeaderValue::from_static("close"),
|
||
);
|
||
a
|
||
}
|
||
|
||
/// 业务逻辑入口(保留给单元测试直接调用,不必起 socket)。
|
||
pub fn handle_request(rt: &TeeRuntime, req: &Request) -> Response {
|
||
api::dispatch(rt, req)
|
||
}
|
||
|
||
/// 业务逻辑入口(带鉴权)。
|
||
pub fn handle_request_with_auth(
|
||
rt: &TeeRuntime,
|
||
req: &Request,
|
||
auth: &crate::auth::Authenticator,
|
||
) -> Response {
|
||
api::dispatch_with_auth(rt, req, auth)
|
||
}
|
||
|
||
/// 便捷:把请求体当 UTF-8 文本。
|
||
pub fn request_body(req: &Request) -> Result<&str, String> {
|
||
body_str(req)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use std::io::{Read, Write};
|
||
use std::net::{TcpListener, TcpStream};
|
||
use std::time::Duration;
|
||
|
||
fn req(method: &str, path: &str) -> Request {
|
||
Request {
|
||
method: String::from(method),
|
||
path: String::from(path),
|
||
query: String::new(),
|
||
headers: HashMap::new(),
|
||
body: Vec::new(),
|
||
}
|
||
}
|
||
|
||
fn serve_on_background(rt: Arc<TeeRuntime>) -> std::net::SocketAddr {
|
||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||
listener.set_nonblocking(true).unwrap();
|
||
let addr = listener.local_addr().unwrap();
|
||
std::thread::spawn(move || {
|
||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||
.enable_all()
|
||
.build()
|
||
.unwrap();
|
||
runtime.block_on(async {
|
||
let l = tokio::net::TcpListener::from_std(listener).unwrap();
|
||
axum::serve(l, router(rt)).await.unwrap();
|
||
});
|
||
});
|
||
addr
|
||
}
|
||
|
||
#[test]
|
||
fn dispatch_reaches_api_layer() {
|
||
let rt = TeeRuntime::new();
|
||
let resp = handle_request(&rt, &req("GET", "/health"));
|
||
assert_eq!(resp.status, Status::Ok);
|
||
}
|
||
|
||
#[test]
|
||
fn unknown_path_is_404_not_500() {
|
||
let rt = TeeRuntime::new();
|
||
let resp = handle_request(&rt, &req("GET", "/wat"));
|
||
assert_eq!(resp.status, Status::NotFound);
|
||
}
|
||
|
||
/// 端到端:真 socket → axum → dispatch → 真响应。
|
||
///
|
||
/// ★ 读响应必须**带 `Connection: close` 读到 EOF**,不能只读一次。
|
||
/// TCP 是流:一次 read 可能只拿到响应头,body 还在缓冲区里。
|
||
/// 上一版自研 HTTP 就是栽在这里(25 轮门禁偶发 2 次红)。
|
||
#[test]
|
||
fn serves_over_real_socket() {
|
||
let addr = serve_on_background(Arc::new(TeeRuntime::new()));
|
||
let mut s = TcpStream::connect(addr).unwrap();
|
||
s.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||
s.write_all(b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
|
||
.unwrap();
|
||
s.flush().unwrap();
|
||
|
||
let mut raw = Vec::new();
|
||
s.read_to_end(&mut raw).unwrap();
|
||
let got = String::from_utf8_lossy(&raw).to_string();
|
||
assert!(got.contains("200 OK"), "got {got}");
|
||
assert!(got.contains("ok"), "got {got}");
|
||
}
|
||
|
||
/// 畸形请求(chunked)必须被拒,且连接关闭。
|
||
#[test]
|
||
fn chunked_request_gets_400_and_closes() {
|
||
let addr = serve_on_background(Arc::new(TeeRuntime::new()));
|
||
let mut s = TcpStream::connect(addr).unwrap();
|
||
s.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||
s.write_all(
|
||
b"POST /sandboxes HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n0\r\n\r\n",
|
||
)
|
||
.unwrap();
|
||
s.flush().unwrap();
|
||
let mut raw = Vec::new();
|
||
let _ = s.read_to_end(&mut raw);
|
||
let got = String::from_utf8_lossy(&raw).to_string();
|
||
assert!(got.contains("400"), "got {got}");
|
||
assert!(got.contains("chunked"), "应说明拒绝原因: {got}");
|
||
}
|
||
|
||
#[test]
|
||
fn response_204_has_empty_body() {
|
||
let a = to_axum(Response::empty(Status::NoContent));
|
||
assert_eq!(a.status(), StatusCode::NO_CONTENT);
|
||
}
|
||
|
||
// ---- 鉴权:端到端(真 socket → axum → 鉴权 → dispatch)------------
|
||
|
||
/// 起一个带鉴权的真服务。
|
||
fn serve_auth_on_background(
|
||
rt: Arc<TeeRuntime>,
|
||
auth: crate::auth::Authenticator,
|
||
) -> std::net::SocketAddr {
|
||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||
listener.set_nonblocking(true).unwrap();
|
||
let addr = listener.local_addr().unwrap();
|
||
std::thread::spawn(move || {
|
||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||
.enable_all()
|
||
.build()
|
||
.unwrap();
|
||
runtime.block_on(async {
|
||
let l = tokio::net::TcpListener::from_std(listener).unwrap();
|
||
axum::serve(l, router_with_auth(rt, auth)).await.unwrap();
|
||
});
|
||
});
|
||
addr
|
||
}
|
||
|
||
/// 发一个原始 HTTP 请求并读满响应。
|
||
fn raw_request(addr: std::net::SocketAddr, req_bytes: &[u8]) -> String {
|
||
let mut s = TcpStream::connect(addr).unwrap();
|
||
s.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||
s.write_all(req_bytes).unwrap();
|
||
s.flush().unwrap();
|
||
let mut raw = Vec::new();
|
||
// ★ 必须读到 EOF:TCP 是流,一次 read 可能只拿到头。
|
||
let _ = s.read_to_end(&mut raw);
|
||
String::from_utf8_lossy(&raw).to_string()
|
||
}
|
||
|
||
const TEST_SECRET: &str = "0123456789abcdef0123456789abcdef";
|
||
|
||
/// ★ 正向:带正确 token 必须放行。
|
||
#[test]
|
||
fn correct_bearer_token_is_accepted_over_socket() {
|
||
let auth = crate::auth::Authenticator::from_secret(TEST_SECRET.as_bytes()).unwrap();
|
||
let addr = serve_auth_on_background(Arc::new(TeeRuntime::new()), auth);
|
||
let req = format!(
|
||
"GET /health HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer {TEST_SECRET}\r\nConnection: close\r\n\r\n"
|
||
);
|
||
let got = raw_request(addr, req.as_bytes());
|
||
assert!(got.contains("200 OK"), "got {got}");
|
||
}
|
||
|
||
/// ★ 负向:**不带 token** 必须 401。
|
||
#[test]
|
||
fn missing_token_over_socket_gets_401() {
|
||
let auth = crate::auth::Authenticator::from_secret(TEST_SECRET.as_bytes()).unwrap();
|
||
let addr = serve_auth_on_background(Arc::new(TeeRuntime::new()), auth);
|
||
let got = raw_request(
|
||
addr,
|
||
b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n",
|
||
);
|
||
assert!(got.contains("401"), "缺 token 必须 401: {got}");
|
||
}
|
||
|
||
/// ★ 负向:**错 token** 必须 401。
|
||
#[test]
|
||
fn wrong_token_over_socket_gets_401() {
|
||
let auth = crate::auth::Authenticator::from_secret(TEST_SECRET.as_bytes()).unwrap();
|
||
let addr = serve_auth_on_background(Arc::new(TeeRuntime::new()), auth);
|
||
let req = "GET /health HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer wrongwrongwrongwrongwrongwrongwrong123\r\nConnection: close\r\n\r\n";
|
||
let got = raw_request(addr, req.as_bytes());
|
||
assert!(got.contains("401"), "错 token 必须 401: {got}");
|
||
}
|
||
|
||
/// ★ ★ 关键:**业务端点也必须受鉴权保护**。
|
||
///
|
||
/// 只保护 `/health` 而放过 `POST /sandboxes` 是假安全 ——
|
||
/// 那正是「能起 guest、读远程证明」的那条路。
|
||
#[test]
|
||
fn sandbox_endpoints_are_also_protected() {
|
||
let auth = crate::auth::Authenticator::from_secret(TEST_SECRET.as_bytes()).unwrap();
|
||
let addr = serve_auth_on_background(Arc::new(TeeRuntime::new()), auth);
|
||
// POST /sandboxes 不带 token —— 必须 401,绝不能 201。
|
||
let got = raw_request(
|
||
addr,
|
||
b"POST /sandboxes HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}",
|
||
);
|
||
assert!(got.contains("401"), "业务端点也必须鉴权: {got}");
|
||
assert!(!got.contains("201"), "不该创建实例: {got}");
|
||
}
|
||
|
||
/// ★ 回环信任模式(未配置密钥):不带凭据放行。
|
||
#[test]
|
||
fn unconfigured_mode_allows_bare_request() {
|
||
let addr = serve_auth_on_background(
|
||
Arc::new(TeeRuntime::new()),
|
||
crate::auth::Authenticator::unconfigured(),
|
||
);
|
||
let got = raw_request(
|
||
addr,
|
||
b"GET /health HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n",
|
||
);
|
||
assert!(got.contains("200 OK"), "回环模式应放行: {got}");
|
||
}
|
||
|
||
/// ★ 回环信任模式:**带凭据仍必须拒** ——
|
||
/// 没配密钥时没有基准值,放行等于「接受任意 token」。
|
||
#[test]
|
||
fn unconfigured_mode_rejects_any_credential() {
|
||
let addr = serve_auth_on_background(
|
||
Arc::new(TeeRuntime::new()),
|
||
crate::auth::Authenticator::unconfigured(),
|
||
);
|
||
let got = raw_request(
|
||
addr,
|
||
b"GET /health HTTP/1.1\r\nHost: x\r\nAuthorization: Bearer whatever\r\nConnection: close\r\n\r\n",
|
||
);
|
||
assert!(got.contains("401"), "回环模式带凭据必须拒: {got}");
|
||
}
|
||
}
|