mpc-tee 新增四层:scheduler / dispatch / reconciler / probe; mpc-hostd 与 mpc-cli 落集群面与单机面。 - 集群面(mpc control-plane,:3020)与单机面(mpc hostd,:3010) 两个命令、两个端口、两套暴露面,故意不合并。 - 节点自报格式复用 TeeNode::descriptor()/parse() 这一份 fail-closed 口径, 不自写 JSON schema;JSON 只是外壳。 - 探针只答「文件在不在」这种客观事实,拿不到就 false,不猜; 默认不自报(没 --node-platform 就不宣称有 TEE 能力)。 - 证明漂移必须立刻把旧记录从 placed 移除:只 destroy 不 remove 会让 proven_endpoints() 继续公布证明已不通过的旧端点(真 fail-open)。 - DesiredSession.binding 优先于全局绑定,防芯片报告 user_data 跨会话重放。 - probe/reconciler 只在 std 下存在;scheduler/dispatch 是 no_std。 门禁:新增判据并入既有 gate 12(门禁仍 22 条),用假 hostd 补正向对照 (真 socket、create 成功、attestation 四布尔可控):证明 ok ⇒ 端点出现、 证明 bad ⇒ 端点收回、再 ok ⇒ 能恢复。否定式判据在「create 恒失败」链路上 恒为真(空集通过),所以必须有正向对照,否则是假绿。
638 lines
24 KiB
Rust
638 lines
24 KiB
Rust
//! 集群控制面(对应 CubeSandbox 的 CubeMaster 本体)。
|
||
//!
|
||
//! # 它站在哪
|
||
//!
|
||
//! ```text
|
||
//! hostd (Cubelet) 控制面(本模块)
|
||
//! ┌──────────────────┐ ┌────────────────────────┐
|
||
//! │ 探针 → 自报 │ POST /registry │ NodeRegistry (Redis 等价)│
|
||
//! │ 周期推送 ────────▶│ ──────────────▶ │ ↓ │
|
||
//! └──────────────────┘ │ TeeReconciler 选节点 │
|
||
//! │ ↓ │
|
||
//! │ 下发 create/attest │
|
||
//! └────────────────────────┘
|
||
//! ```
|
||
//!
|
||
//! # 为什么要有这一层
|
||
//!
|
||
//! [`crate::scheduler::NodeRegistry`] 与 [`crate::reconciler::TeeReconciler`]
|
||
//! 此前**只有单测在用** —— 生产路径上没有任何进程持有它们,
|
||
//! 于是「自报」推过去也没有人收、「对账」也跑不起来。
|
||
//! 本模块把两者接起来,是那两段之间**唯一**的桥。
|
||
//!
|
||
//! ★ **不另起一套**:注册表就是 [`NodeRegistry`],对账就是 [`TeeReconciler`],
|
||
//! 判据([`crate::schedule::node_satisfies`] / [`crate::schedule::admit`])
|
||
//! 一个都不重写。控制面只做**编排**。
|
||
//!
|
||
//! # fail-closed
|
||
//!
|
||
//! - 注册表为空 ⇒ 选址必然失败 ⇒ 会话被标 `failed`(**绝不**硬塞一台)。
|
||
//! - 自报解析失败 ⇒ **拒收**,不写注册表(半条记录比没有更危险)。
|
||
//! - 对账器只在拿到**确定的**结论时才把端点交给计算面。
|
||
//!
|
||
//! # 依赖边界
|
||
//!
|
||
//! 本模块只在 `std` 下存在:它要跑长循环、要落盘注册表。
|
||
//! `no_std`(TA)构建不编译到这里,不污染 enclave 产物。
|
||
|
||
use crate::probe::{NodeReport, NodeReporter};
|
||
use crate::reconciler::{DesiredSession, ReconcileReport, TeeReconciler};
|
||
use crate::scheduler::{NodeRegistry, RegisteredNode};
|
||
use crate::schedule::TeeNode;
|
||
use crate::session::SessionBinding;
|
||
use crate::TeeError;
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
use std::sync::{Arc, Mutex};
|
||
use std::time::Duration;
|
||
/// 控制面配置。
|
||
#[derive(Debug, Clone)]
|
||
pub struct ControlPlaneConfig {
|
||
/// 节点心跳 TTL(秒)。超过则该节点被 [`NodeRegistry::prune_stale`] 剔除。
|
||
///
|
||
/// ★ 必须**大于** hostd 的自报推送间隔,否则节点会在两次自报之间被剔除,
|
||
/// 表现为「注册表里节点时有时无」���— 那种抖动看起来像网络问题,
|
||
/// 实际是配置自相矛盾。
|
||
pub node_ttl_secs: u64,
|
||
/// 对账周期(秒)。
|
||
pub reconcile_period_secs: u64,
|
||
/// 节点 `host` 上的 hostd 监听端口(拼 endpoint 用)。
|
||
pub hostd_port: u16,
|
||
/// 注册表落盘路径(`None` = 不落盘)。
|
||
pub registry_file: Option<String>,
|
||
/// ★ 公布会话端点时是否要求 `chip_sig=true`(真芯片验签通过)。
|
||
///
|
||
/// 默认 `true` —— 用户的目标是「**真 KBS 验签后**的会话端点」。
|
||
/// 只验结构 + 绑定意味着「报告里那串 user_data 对得上」,
|
||
/// 而报告签名本身没人验过,那只是一段自述数据。
|
||
///
|
||
/// 关掉它只在**明确知道**宿主侧没配验签器、
|
||
/// 且接受「结构 + 绑定」这一层时才合理。
|
||
pub require_chip_sig: bool,
|
||
}
|
||
|
||
impl Default for ControlPlaneConfig {
|
||
fn default() -> Self {
|
||
Self {
|
||
node_ttl_secs: 90,
|
||
reconcile_period_secs: 10,
|
||
hostd_port: 3010,
|
||
registry_file: None,
|
||
require_chip_sig: true,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 集群控制面:持有节点注册表,驱动对账器。
|
||
///
|
||
/// `D` 是下发实现(生产走 `mpc_hostd::client::HostClient`,单测走内存 mock)。
|
||
pub struct ControlPlane<D: crate::dispatch::TeeHostDispatch> {
|
||
config: ControlPlaneConfig,
|
||
registry: Arc<NodeRegistry>,
|
||
/// 对账器(放在 Mutex 里:它有可变状态,且要被长循环与查询同时访问)。
|
||
reconciler: Mutex<TeeReconciler<D>>,
|
||
/// 本轮会话绑定(`place` 用它校验度量 pin / 会话绑定)。
|
||
binding: SessionBinding,
|
||
/// 期望态(可被外部更新:HTTP 端点 / CLI 都能改)。
|
||
///
|
||
/// ★ 放在 `Mutex` 里而不是长循环的局部变量里,是因为期望态**要能变**:
|
||
/// 一个静态的期望态等于「一轮跑完就再也不动」——那不是对账,
|
||
/// 那是启动脚本。
|
||
desired: Mutex<Vec<DesiredSession>>,
|
||
/// 最近一轮对账的结论(给 HTTP 查询用)。
|
||
last_report: Mutex<ReconcileReport>,
|
||
stop: AtomicBool,
|
||
}
|
||
|
||
impl<D: crate::dispatch::TeeHostDispatch> ControlPlane<D> {
|
||
/// 构造控制面。
|
||
pub fn new(
|
||
config: ControlPlaneConfig,
|
||
dispatch: D,
|
||
binding: SessionBinding,
|
||
) -> Self {
|
||
let registry = Arc::new(NodeRegistry::new(config.node_ttl_secs));
|
||
let mut reconciler = TeeReconciler::new(
|
||
registry.clone(),
|
||
dispatch,
|
||
binding.clone(),
|
||
config.hostd_port,
|
||
);
|
||
// 发布策略从配置透传给对账器(默认要求真芯片验签)。
|
||
reconciler.set_require_chip_sig(config.require_chip_sig);
|
||
Self {
|
||
config,
|
||
registry,
|
||
reconciler: Mutex::new(reconciler),
|
||
binding,
|
||
desired: Mutex::new(Vec::new()),
|
||
last_report: Mutex::new(ReconcileReport::default()),
|
||
stop: AtomicBool::new(false),
|
||
}
|
||
}
|
||
|
||
/// 节点注册表句柄(给 HTTP handler 收自报用)。
|
||
pub fn registry(&self) -> Arc<NodeRegistry> {
|
||
self.registry.clone()
|
||
}
|
||
|
||
/// 本轮会话绑定。
|
||
pub fn binding(&self) -> &SessionBinding {
|
||
&self.binding
|
||
}
|
||
|
||
/// 设置期望态(不立刻对账)。
|
||
///
|
||
/// 长循环下一轮会取到新期望态;想立刻生效请调 [`Self::reconcile`]。
|
||
pub fn set_desired(&self, desired: Vec<DesiredSession>) {
|
||
match self.desired.lock() {
|
||
Ok(mut d) => *d = desired,
|
||
Err(_) => {}
|
||
}
|
||
}
|
||
|
||
/// 当前期望态。
|
||
pub fn desired(&self) -> Vec<DesiredSession> {
|
||
self.desired
|
||
.lock()
|
||
.map(|d| d.clone())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
/// 收一份自报并写入注册表。
|
||
///
|
||
/// 失败返回 [`TeeError`],**不**写注册表 —— 半条记录会让调度器
|
||
/// 选中一台「能力不明」的机器,比没有这台更危险。
|
||
pub fn accept_report(&self, report: &NodeReport) -> Result<(), TeeError> {
|
||
self.registry.register(report.node.clone(), report.capacity);
|
||
Ok(())
|
||
}
|
||
|
||
/// 从节点描述文本收一份自报(走 [`TeeNode::parse`] 的 fail-closed 解析)。
|
||
pub fn accept_report_text(&self, text: &str, capacity: usize) -> Result<(), TeeError> {
|
||
let node = TeeNode::parse(text)?;
|
||
self.registry.register(node, capacity);
|
||
Ok(())
|
||
}
|
||
|
||
/// 设置期望态(一组会话需求)并跑一次对账。
|
||
///
|
||
/// 期望态与真实态的对齐由 [`TeeReconciler`] 负责,本方法只是接线。
|
||
pub fn reconcile(&self, desired: Vec<DesiredSession>) -> Result<ReconcileReport, TeeError> {
|
||
self.set_desired(desired.clone());
|
||
let mut r = self
|
||
.reconciler
|
||
.lock()
|
||
.map_err(|_| TeeError::Io(String::from("对账器锁中毒")))?;
|
||
r.set_desired(desired);
|
||
let report = r.reconcile_once()?;
|
||
// 记住最近一轮结论(给查询用);锁中毒时保持旧值。
|
||
if let Ok(mut lr) = self.last_report.lock() {
|
||
*lr = report.clone();
|
||
}
|
||
Ok(report)
|
||
}
|
||
|
||
/// 按**当前**期望态跑一次对账(长循环用)。
|
||
pub fn reconcile_current(&self) -> Result<ReconcileReport, TeeError> {
|
||
self.reconcile(self.desired())
|
||
}
|
||
|
||
/// 最近一轮对账的结论。
|
||
pub fn last_report(&self) -> ReconcileReport {
|
||
self.last_report
|
||
.lock()
|
||
.map(|r| r.clone())
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
/// 当前已证明可用的会话端点(供计算面消费)。
|
||
pub fn proven_endpoints(&self) -> Vec<(String, String)> {
|
||
match self.reconciler.lock() {
|
||
Ok(r) => r.proven_endpoints(),
|
||
// 锁中毒 ⇒ 交不出端点(fail-closed:宁可算不了,不给不确定的端点)。
|
||
Err(_) => Vec::new(),
|
||
}
|
||
}
|
||
|
||
/// 注册表全量列表(给 HTTP 查询用)。
|
||
pub fn nodes(&self) -> Vec<RegisteredNode> {
|
||
self.registry.list()
|
||
}
|
||
|
||
/// 剔除超过 TTL 未心跳的节点。
|
||
pub fn prune_stale(&self) {
|
||
self.registry.prune_stale(None);
|
||
}
|
||
|
||
/// 把注册表落盘(若配了路径)。
|
||
pub fn save_registry(&self) -> Result<(), TeeError> {
|
||
match &self.config.registry_file {
|
||
Some(p) => self.registry.save(p),
|
||
None => Ok(()),
|
||
}
|
||
}
|
||
|
||
/// 请求停止长循环。
|
||
pub fn stop(&self) {
|
||
self.stop.store(true, Ordering::Relaxed);
|
||
}
|
||
|
||
/// 是否已被要求停止。
|
||
pub fn is_stopped(&self) -> bool {
|
||
self.stop.load(Ordering::Relaxed)
|
||
}
|
||
|
||
/// 长循环:周期性对账 + 剔除过期节点 + 落盘注册表。
|
||
///
|
||
/// `stop` 置位即退出(最多多跑一个周期的尾巴)。
|
||
///
|
||
/// ★ 每轮都从共享槽里取一次期望态 —— 期望态在长循环运行期间被改,
|
||
/// 下一轮就生效。
|
||
pub fn run(&self) {
|
||
let period = Duration::from_secs(self.config.reconcile_period_secs.max(1));
|
||
while !self.is_stopped() {
|
||
// 对账:拿不到结论就让 reconciler 自己标失败(fail-closed)。
|
||
let _ = self.reconcile_current();
|
||
self.prune_stale();
|
||
let _ = self.save_registry();
|
||
std::thread::sleep(period);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 自报接收端(HTTP 侧)的实现体,供组合根挂到路由上。
|
||
///
|
||
/// 刻意做成**独立于 [`ControlPlane`] 泛型**的类型:接收自报不需要下发实现,
|
||
/// 而把控制面泛型化会让 HTTP 层也带上 `TeeHostDispatch` 的类型参数,
|
||
/// 徒增组合复杂度。
|
||
#[derive(Clone)]
|
||
pub struct ReportInbox {
|
||
registry: Arc<NodeRegistry>,
|
||
}
|
||
|
||
impl ReportInbox {
|
||
/// 构造收件箱。
|
||
pub fn new(registry: Arc<NodeRegistry>) -> Self {
|
||
Self { registry }
|
||
}
|
||
|
||
/// 收一份自报。
|
||
pub fn accept(&self, report: &NodeReport) -> Result<(), TeeError> {
|
||
self.registry.register(report.node.clone(), report.capacity);
|
||
Ok(())
|
||
}
|
||
|
||
/// 注册表句柄。
|
||
pub fn registry(&self) -> Arc<NodeRegistry> {
|
||
self.registry.clone()
|
||
}
|
||
}
|
||
|
||
/// 一个把自报**写进**控制面注册表的推送端(生产用 HTTP 实装)。
|
||
///
|
||
/// 与 [`crate::probe::NodeReporter`] 的区别:那个是「推给远端控制面」,
|
||
/// 这个是「就地写进本进程的控制面」—— 单测与单机联调用。
|
||
pub struct LocalReporter {
|
||
inbox: ReportInbox,
|
||
}
|
||
|
||
impl LocalReporter {
|
||
/// 构造。
|
||
pub fn new(inbox: ReportInbox) -> Self {
|
||
Self { inbox }
|
||
}
|
||
}
|
||
|
||
impl NodeReporter for LocalReporter {
|
||
fn report(&self, report: &NodeReport) -> Result<(), TeeError> {
|
||
self.inbox.accept(report)
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::dispatch::{AttestationSummary, TeeHostDispatch};
|
||
use crate::platform::KbcMode;
|
||
use crate::schedule::{LaunchSpec, TeeRequirement};
|
||
use crate::PlatformKind;
|
||
use alloc::vec;
|
||
use std::collections::HashSet;
|
||
use std::sync::Mutex as StdMutex;
|
||
|
||
/// 内存 mock 宿主。
|
||
struct MockHost {
|
||
up: StdMutex<HashSet<String>>,
|
||
attest_ok: bool,
|
||
created: StdMutex<Vec<(String, String)>>,
|
||
}
|
||
|
||
impl MockHost {
|
||
fn new(up: &[&str], attest_ok: bool) -> Self {
|
||
Self {
|
||
up: StdMutex::new(up.iter().map(|s| s.to_string()).collect()),
|
||
attest_ok,
|
||
created: StdMutex::new(Vec::new()),
|
||
}
|
||
}
|
||
fn created_len(&self) -> usize {
|
||
self.created.lock().unwrap().len()
|
||
}
|
||
}
|
||
|
||
impl TeeHostDispatch for Arc<MockHost> {
|
||
fn create(
|
||
&self,
|
||
endpoint: &str,
|
||
_site: &str,
|
||
_sid: &str,
|
||
_launch: &LaunchSpec,
|
||
) -> Result<String, TeeError> {
|
||
if !self.up.lock().unwrap().contains(endpoint) {
|
||
return Err(TeeError::Io(format!("hostd {endpoint} 不可达")));
|
||
}
|
||
let n = self.created.lock().unwrap().len();
|
||
let id = format!("sbx-{n}");
|
||
self.created
|
||
.lock()
|
||
.unwrap()
|
||
.push((endpoint.to_string(), id.clone()));
|
||
Ok(id)
|
||
}
|
||
fn attest(
|
||
&self,
|
||
endpoint: &str,
|
||
_sid: &str,
|
||
) -> Result<AttestationSummary, TeeError> {
|
||
if !self.up.lock().unwrap().contains(endpoint) {
|
||
return Err(TeeError::Io(format!("hostd {endpoint} 不可达")));
|
||
}
|
||
Ok(AttestationSummary {
|
||
user_data_ok: self.attest_ok,
|
||
meas_ok: self.attest_ok,
|
||
tcb_ok: self.attest_ok,
|
||
// ★ `chip_sig = true`:这个 mock 的 `attest_ok=true` 表示
|
||
// 「证据成立**且**芯片验签通过」—— 与真机上一致。
|
||
// 控制面默认要求 `chip_sig=true` 才公布端点,
|
||
// 这里若填 false,mock 就会退化成「证据成立但不可公布」,
|
||
// 既有测试会因端点不公布而红,且原因与被测逻辑无关。
|
||
chip_sig: self.attest_ok,
|
||
chip_sig_failed: false,
|
||
status: if self.attest_ok {
|
||
crate::dispatch::AttestationStatus::Verified
|
||
} else {
|
||
crate::dispatch::AttestationStatus::Rejected
|
||
},
|
||
})
|
||
}
|
||
fn destroy(&self, _endpoint: &str, _sid: &str) -> Result<(), TeeError> {
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
/// 构造一个**通过 admit** 的 SNP 节点(能力位齐 + 度量已 pin)。
|
||
fn snp_node(site: &str, host: &str) -> TeeNode {
|
||
let mut n = TeeNode::new(site, host, PlatformKind::SevSnp, 5);
|
||
n.device_present = true;
|
||
n.qemu_present = true;
|
||
n.firmware_present = true;
|
||
n.image_present = true;
|
||
n.measurement = [9u8; 32];
|
||
n.kbc = KbcMode::Offline;
|
||
n.qemu_bin = String::from("/usr/bin/qemu-system-x86_64");
|
||
n.firmware = String::from("/srv/tee/AMDSEV.fd");
|
||
n.kernel = String::from("/srv/tee/vmlinuz");
|
||
n.initrd = String::from("/srv/tee/initrd.img");
|
||
n
|
||
}
|
||
|
||
fn binding() -> SessionBinding {
|
||
SessionBinding::new([1u8; 32], "alice", [2u8; 32], [9u8; 32])
|
||
}
|
||
|
||
fn req() -> TeeRequirement {
|
||
TeeRequirement::new(PlatformKind::SevSnp, 3)
|
||
}
|
||
|
||
/// ★ 闭环正向:自报 → 注册表 → 对账选址 → 下发 → 证明通过。
|
||
///
|
||
/// 这条是 Phase 3b 的核心判据:**自报进来的节点必须能被真的选中并下发**。
|
||
#[test]
|
||
fn self_report_feeds_registry_then_reconciler_places_session() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
|
||
// 1) 自报进来。
|
||
let node = snp_node("alice", "192.168.1.7");
|
||
let report = NodeReport {
|
||
node,
|
||
capacity: 2,
|
||
};
|
||
cp.accept_report(&report).unwrap();
|
||
|
||
// 2) 注册表里有了。
|
||
assert_eq!(cp.nodes().len(), 1, "自报必须落到注册表");
|
||
assert_eq!(cp.nodes()[0].capacity, 2, "容量必须跟着自报一起进注册表");
|
||
|
||
// 3) 对账选址 + 下发 + 证明 ⇒ 健康。
|
||
let rep = cp
|
||
.reconcile(vec![DesiredSession::new("s1", req())])
|
||
.unwrap();
|
||
assert_eq!(rep.healthy, vec!["s1".to_string()], "自报节点必须能被选中");
|
||
assert!(rep.failed.is_empty());
|
||
assert_eq!(host.created_len(), 1, "必须真下发了一次");
|
||
assert_eq!(
|
||
cp.proven_endpoints(),
|
||
vec![("s1".to_string(), "192.168.1.7:3010".to_string())]
|
||
);
|
||
}
|
||
|
||
/// ★ 负向:自报里的节点能力不合格(设备节点缺失)⇒ 选址必须失败。
|
||
///
|
||
/// 这条钉死「注册表收下了不代表它合格」—— 准入判据不能因为
|
||
/// 「是自报来的」就放水。
|
||
#[test]
|
||
fn incapable_self_report_is_registered_but_not_selectable() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
|
||
// 设备节点缺失(探针在没 /dev/sev 的机器上就是这样报的)。
|
||
let mut node = snp_node("alice", "192.168.1.7");
|
||
node.device_present = false;
|
||
cp.accept_report(&NodeReport {
|
||
node,
|
||
capacity: 2,
|
||
})
|
||
.unwrap();
|
||
|
||
// 注册表收了(自报本身是合法的),但**选不出来**。
|
||
assert_eq!(cp.nodes().len(), 1);
|
||
let rep = cp
|
||
.reconcile(vec![DesiredSession::new("s1", req())])
|
||
.unwrap();
|
||
assert!(rep.healthy.is_empty(), "能力不合格绝不能被选中");
|
||
assert_eq!(rep.failed.len(), 1);
|
||
assert!(rep.failed[0].1.contains("无合格节点"));
|
||
assert_eq!(host.created_len(), 0, "不许下发");
|
||
assert!(cp.proven_endpoints().is_empty());
|
||
}
|
||
|
||
/// ★ 负向:注册表为空 ⇒ 对账必然失败(fail-closed)。
|
||
#[test]
|
||
fn empty_registry_fails_closed() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
let rep = cp
|
||
.reconcile(vec![DesiredSession::new("s1", req())])
|
||
.unwrap();
|
||
assert!(rep.healthy.is_empty());
|
||
assert!(rep.failed[0].1.contains("无合格节点"));
|
||
assert_eq!(host.created_len(), 0);
|
||
}
|
||
|
||
/// ★ 自报解析失败 ⇒ **拒收**,不写注册表。
|
||
#[test]
|
||
fn malformed_report_text_is_rejected() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
// 缺必填字段(site/host/kind/tcb/measurement)。
|
||
let e = cp
|
||
.accept_report_text("site=alice\nhost=192.168.1.7\n", 1)
|
||
.unwrap_err();
|
||
assert!(!e.to_string().is_empty(), "必须给出拒绝原因");
|
||
assert_eq!(cp.nodes().len(), 0, "坏自报绝不能污染注册表");
|
||
}
|
||
|
||
/// ★ 自报重复推送(心跳)⇒ 注册表**不重复**计数。
|
||
#[test]
|
||
fn repeated_self_report_updates_in_place() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
let node = snp_node("alice", "192.168.1.7");
|
||
for _ in 0..5 {
|
||
cp.accept_report(&NodeReport {
|
||
node: node.clone(),
|
||
capacity: 2,
|
||
})
|
||
.unwrap();
|
||
}
|
||
assert_eq!(cp.nodes().len(), 1, "同一节点反复自报只占一条");
|
||
}
|
||
|
||
/// ★ 本地推送端(单机联调)写进的就是控制面的注册表。
|
||
#[test]
|
||
fn local_reporter_writes_into_control_plane_registry() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
let reporter = LocalReporter::new(ReportInbox::new(cp.registry()));
|
||
reporter
|
||
.report(&NodeReport {
|
||
node: snp_node("alice", "192.168.1.7"),
|
||
capacity: 4,
|
||
})
|
||
.unwrap();
|
||
assert_eq!(cp.nodes().len(), 1);
|
||
assert_eq!(cp.nodes()[0].capacity, 4);
|
||
}
|
||
|
||
/// ★ TTL 过期 ⇒ 节点被剔除,不再参与选址。
|
||
///
|
||
/// 用 `prune_stale(now)` 的显式时间参数,避免依赖真实时钟(免得慢 CI 抖)。
|
||
#[test]
|
||
fn stale_node_is_pruned_and_becomes_unselectable() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let mut cfg = ControlPlaneConfig::default();
|
||
cfg.node_ttl_secs = 10;
|
||
let cp = ControlPlane::new(cfg, host.clone(), binding());
|
||
cp.accept_report(&NodeReport {
|
||
node: snp_node("alice", "192.168.1.7"),
|
||
capacity: 2,
|
||
})
|
||
.unwrap();
|
||
|
||
// 推进到 TTL 之后(用显式 now)。
|
||
cp.registry().prune_stale(Some(u64::MAX));
|
||
assert_eq!(cp.nodes().len(), 0, "过期节点必须被剔除");
|
||
|
||
let rep = cp
|
||
.reconcile(vec![DesiredSession::new("s1", req())])
|
||
.unwrap();
|
||
assert!(rep.healthy.is_empty(), "过期节点不许被选中");
|
||
}
|
||
|
||
/// ★ 期望态可以在长循环运行期间被改 —— 下一轮就生效。
|
||
///
|
||
/// 这条钉死「期望态不是启动时的常量」:静态期望态等于「一轮跑完就再也不动」,
|
||
/// 那不是对账,是启动脚本。
|
||
#[test]
|
||
fn desired_state_can_change_between_rounds() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
cp.accept_report(&NodeReport {
|
||
node: snp_node("alice", "192.168.1.7"),
|
||
capacity: 2,
|
||
})
|
||
.unwrap();
|
||
|
||
// 第一轮:没有期望态 ⇒ 什么都不该建。
|
||
let rep = cp.reconcile_current().unwrap();
|
||
assert!(rep.healthy.is_empty());
|
||
assert!(rep.failed.is_empty(), "没有期望就没有失败项");
|
||
assert_eq!(host.created_len(), 0);
|
||
|
||
// 改期望态 ⇒ 下一轮生效。
|
||
cp.set_desired(vec![DesiredSession::new("s1", req())]);
|
||
assert_eq!(cp.desired().len(), 1, "期望态要能被外部读到");
|
||
let rep = cp.reconcile_current().unwrap();
|
||
assert_eq!(rep.healthy, vec!["s1".to_string()]);
|
||
assert_eq!(host.created_len(), 1);
|
||
}
|
||
|
||
/// ★ 最近一轮对账结论可查(HTTP 查询端点要靠它)。
|
||
#[test]
|
||
fn last_report_reflects_the_latest_round() {
|
||
let host = Arc::new(MockHost::new(&[], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
// 第一轮:注册表为空 ⇒ 失败。
|
||
let rep = cp.reconcile(vec![DesiredSession::new("s1", req())]).unwrap();
|
||
assert_eq!(rep.failed.len(), 1);
|
||
let last = cp.last_report();
|
||
assert_eq!(last.failed.len(), 1, "最近一轮结论必须能被查到");
|
||
assert_eq!(last.failed[0].0, "s1".to_string());
|
||
}
|
||
|
||
/// ★ 每个会话可以带**自己的**绑定材料。
|
||
///
|
||
/// 绑定值要写进芯片报告的 `user_data`;两个会话共用一份绑定,
|
||
/// 等于两个会话的报告可以互相冒用 —— 那正是重放攻击要利用的性质。
|
||
#[test]
|
||
fn per_session_binding_overrides_the_global_one() {
|
||
let host = Arc::new(MockHost::new(&["192.168.1.7:3010"], true));
|
||
let cp = ControlPlane::new(ControlPlaneConfig::default(), host.clone(), binding());
|
||
cp.accept_report(&NodeReport {
|
||
node: snp_node("alice", "192.168.1.7"),
|
||
capacity: 2,
|
||
})
|
||
.unwrap();
|
||
|
||
// 专属绑定的度量与节点度量**不一致** ⇒ 该会话必须被拒。
|
||
let mut wrong = binding();
|
||
wrong.code_measurement = [8u8; 32];
|
||
let rep = cp
|
||
.reconcile(vec![DesiredSession::with_binding("s1", req(), wrong)])
|
||
.unwrap();
|
||
assert!(rep.healthy.is_empty(), "绑定不符绝不能被选中");
|
||
assert!(rep.failed[0].1.contains("无合格节点"), "got {:?}", rep.failed);
|
||
|
||
// 换成与节点一致的绑定 ⇒ 通过。
|
||
let rep = cp
|
||
.reconcile(vec![DesiredSession::with_binding(
|
||
"s1",
|
||
req(),
|
||
binding(),
|
||
)])
|
||
.unwrap();
|
||
assert_eq!(rep.healthy, vec!["s1".to_string()]);
|
||
}
|
||
}
|