diff --git a/Cargo.lock b/Cargo.lock index bf0c2b9..e81ee0d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1608,6 +1608,15 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +[[package]] +name = "floatile-ai-balance-wasm" +version = "0.1.0" +dependencies = [ + "floatile-sdk", + "serde", + "serde_json", +] + [[package]] name = "floatile-cli" version = "0.1.0" @@ -1735,11 +1744,14 @@ version = "0.1.0" dependencies = [ "floatile-core", "floatile-platform", + "futures-util", + "reqwest", "serde", "serde_json", "thiserror 2.0.20", "tokio", "tracing", + "url", ] [[package]] @@ -2112,9 +2124,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core", + "wasm-bindgen", ] [[package]] @@ -2381,6 +2395,22 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + [[package]] name = "hyper-util" version = "0.1.20" @@ -3377,6 +3407,12 @@ version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "lyon_algorithms" version = "1.0.20" @@ -4509,6 +4545,62 @@ dependencies = [ "memchr", ] +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.20", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.20", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "quote" version = "1.0.47" @@ -4547,6 +4639,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4723,23 +4824,31 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", "tokio", + "tokio-rustls", + "tokio-util", "tower", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", + "webpki-roots", ] [[package]] @@ -4768,6 +4877,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rowan" version = "0.16.1" @@ -4866,6 +4989,41 @@ dependencies = [ "rustix 1.1.4", ] +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -5448,6 +5606,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.16.1" @@ -5784,6 +5948,29 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "0.8.23" @@ -6133,6 +6320,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "unty" version = "0.0.4" @@ -6402,6 +6595,19 @@ dependencies = [ "wasmparser 0.254.0", ] +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "wasmparser" version = "0.252.0" @@ -6920,6 +7126,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -7806,6 +8021,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index db1990e..67e456e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ "crates/floatile-ui-schema", "crates/floatile-cli", "plugins/clock-wasm", + "plugins/ai-balance-wasm", "plugins/evil-wasm", ] @@ -45,7 +46,10 @@ thiserror = "2" toml = "0.8" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } -tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "macros", "sync"] } +tokio = { version = "1", features = ["rt", "rt-multi-thread", "time", "macros", "sync", "net"] } +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream"] } +url = "2" +futures-util = "0.3" slint = { version = "1.17", features = ["backend-winit", "unstable-winit-030"] } winit = "0.30" x11rb = { version = "0.13", default-features = false, features = ["randr", "shape"] } diff --git a/crates/floatile-cli/src/build.rs b/crates/floatile-cli/src/build.rs index a2b61cc..2b7d4dd 100644 --- a/crates/floatile-cli/src/build.rs +++ b/crates/floatile-cli/src/build.rs @@ -150,6 +150,15 @@ pub fn build_project(project_dir: &Path, out: &Path) -> Result, + #[serde(default, rename = "httpTemplates")] + pub http_templates: Vec, #[serde(default)] pub publisher: Option, } @@ -71,6 +73,14 @@ pub struct PermissionCfg { pub max_active: Option, #[serde(default)] pub sample_rate_hz: Option, + #[serde(default)] + pub origins: Vec, + #[serde(default)] + pub max_requests_per_minute: Option, + #[serde(default)] + pub max_response_bytes: Option, + #[serde(default)] + pub max_timeout_ms: Option, } /// `floatile.toml` 的权限段短名 → 完整 capability 名(manifest-v1 §3)。 @@ -130,6 +140,20 @@ pub fn generate_manifest(config: &ProjectConfig) -> Result { + if !cfg.origins.is_empty() { + params.insert("origins".into(), serde_json::json!(cfg.origins)); + } + if let Some(v) = cfg.max_requests_per_minute { + params.insert("maxRequestsPerMinute".into(), serde_json::json!(v)); + } + if let Some(v) = cfg.max_response_bytes { + params.insert("maxResponseBytes".into(), serde_json::json!(v)); + } + if let Some(v) = cfg.max_timeout_ms { + params.insert("maxTimeoutMs".into(), serde_json::json!(v)); + } + } } permissions.push(PermissionDecl { capability: capability.name.to_owned(), @@ -180,6 +204,7 @@ pub fn generate_manifest(config: &ProjectConfig) -> Result PathBuf { @@ -12,8 +13,19 @@ fn workspace_root() -> PathBuf { .join("..") } +/// Both cases invoke Cargo for the same project and consume the same release artifact. Keep that +/// producer/consumer sequence exclusive: Windows cannot safely replace/read the artifact across +/// the two concurrent test threads, while each individual author flow remains fully exercised. +fn author_build_lock() -> MutexGuard<'static, ()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + #[test] fn test_project_runs_clock_smoke() { + let _build_guard = author_build_lock(); let project_dir = workspace_root().join("plugins/clock-wasm"); let out = std::env::temp_dir().join(format!("floatile-test-e2e-{}.floatile", std::process::id())); @@ -51,6 +63,7 @@ fn test_project_runs_clock_smoke() { #[test] fn test_scenario_injects_event_and_exercises_broker_denial() { + let _build_guard = author_build_lock(); let project_dir = workspace_root().join("plugins/clock-wasm"); let out = std::env::temp_dir().join(format!( "floatile-test-scenario-{}.floatile", diff --git a/crates/floatile-core/src/capability.rs b/crates/floatile-core/src/capability.rs index 5c616a4..d03a3d8 100644 --- a/crates/floatile-core/src/capability.rs +++ b/crates/floatile-core/src/capability.rs @@ -23,6 +23,7 @@ pub enum CapabilityId { ThemeSubscribe, SystemCpu, SystemMemory, + NetworkHttps, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -39,12 +40,14 @@ pub enum CapabilityParamKind { Storage, Timer, Metrics, + Network, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub enum CapabilityRisk { Inherent, L0, + L2, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -190,6 +193,19 @@ pub const CAPABILITY_REGISTRY: &[CapabilityDefinition] = &[ author_section: Some("metrics"), audit_redaction: "result-bucket-only", }, + CapabilityDefinition { + id: CapabilityId::NetworkHttps, + name: "network:https", + exposure: CapabilityExposure::Declared, + params: CapabilityParamKind::Network, + risk: CapabilityRisk::L2, + execution: CapabilityExecution::SyncAndOperation, + wit_interface: "host-http", + wit_functions: &["submit", "take-result"], + sdk_surface: "ctx.http", + author_section: Some("httpTemplates"), + audit_redaction: "template-origin-status-and-size-only", + }, ]; impl CapabilityId { @@ -248,6 +264,13 @@ pub enum CapabilityParams { }, /// system:cpu:采样频率上限(Hz)。 Metrics { sample_rate_hz: u32 }, + /// network:https:精确 HTTPS origin 白名单与宿主执行预算。 + Network { + origins: Vec, + max_requests_per_minute: u32, + max_response_bytes: u64, + max_timeout_ms: u64, + }, } /// 授权来源(permission-model §2)。 @@ -450,6 +473,73 @@ pub fn parse_capability_params( } CapabilityParams::Metrics { sample_rate_hz } } + CapabilityParamKind::Network => { + let mut origins = Vec::new(); + let mut max_requests_per_minute = 30; + let mut max_response_bytes = 256 * 1024; + let mut max_timeout_ms = 10_000; + for (k, v) in obj { + match k.as_str() { + "origins" => { + let values = + v.as_array().ok_or_else(|| CapabilityError::InvalidParams { + capability: capability.name(), + detail: "`origins` 必须是字符串数组".to_owned(), + })?; + if values.is_empty() || values.len() > 16 { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: "`origins` 必须包含 1..=16 项".to_owned(), + }); + } + for value in values { + let origin = + value + .as_str() + .ok_or_else(|| CapabilityError::InvalidParams { + capability: capability.name(), + detail: "`origins` 元素必须是字符串".to_owned(), + })?; + validate_https_origin(origin)?; + if origins.iter().any(|item| item == origin) { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: format!("重复 origin `{origin}`"), + }); + } + origins.push(origin.to_owned()); + } + } + "maxRequestsPerMinute" => { + max_requests_per_minute = bounded_u32(v, capability, k, 1, 600)?; + } + "maxResponseBytes" => { + max_response_bytes = bounded_u64(v, capability, k, 1, 1024 * 1024)?; + } + "maxTimeoutMs" => { + max_timeout_ms = bounded_u64(v, capability, k, 100, 30_000)?; + } + other => { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: format!("未知字段 `{other}`"), + }); + } + } + } + if origins.is_empty() { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: "`origins` 不得省略".to_owned(), + }); + } + CapabilityParams::Network { + origins, + max_requests_per_minute, + max_response_bytes, + max_timeout_ms, + } + } // 无参数能力:任何 params 都拒绝。 CapabilityParamKind::None => { return Err(CapabilityError::InvalidParams { @@ -472,10 +562,79 @@ fn default_params(capability: CapabilityId) -> Result, max_active: 8, }, CapabilityParamKind::Metrics => CapabilityParams::Metrics { sample_rate_hz: 1 }, + CapabilityParamKind::Network => { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: "`origins` 不得省略".to_owned(), + }); + } CapabilityParamKind::None => return Ok(None), })) } +fn bounded_u32( + value: &serde_json::Value, + capability: CapabilityId, + field: &str, + min: u32, + max: u32, +) -> Result { + let value = value + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or_else(|| CapabilityError::InvalidParams { + capability: capability.name(), + detail: format!("`{field}` 必须是 32 位整数"), + })?; + if !(min..=max).contains(&value) { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: format!("`{field}` 必须在 {min}..={max}"), + }); + } + Ok(value) +} + +fn bounded_u64( + value: &serde_json::Value, + capability: CapabilityId, + field: &str, + min: u64, + max: u64, +) -> Result { + let value = value + .as_u64() + .ok_or_else(|| CapabilityError::InvalidParams { + capability: capability.name(), + detail: format!("`{field}` 必须是非负整数"), + })?; + if !(min..=max).contains(&value) { + return Err(CapabilityError::InvalidParams { + capability: capability.name(), + detail: format!("`{field}` 必须在 {min}..={max}"), + }); + } + Ok(value) +} + +fn validate_https_origin(origin: &str) -> Result<(), CapabilityError> { + let invalid = !origin.starts_with("https://") + || origin.len() > 255 + || origin[8..].is_empty() + || origin[8..].contains('/') + || origin.contains('@') + || origin.contains('?') + || origin.contains('#') + || origin.chars().any(char::is_whitespace); + if invalid { + return Err(CapabilityError::InvalidParams { + capability: "network:https", + detail: format!("`{origin}` 不是精确 HTTPS origin"), + }); + } + Ok(()) +} + fn validate_storage_key(key: &str) -> Result<(), CapabilityError> { if key.is_empty() { return Err(CapabilityError::InvalidParams { @@ -563,6 +722,38 @@ pub fn decide(grant: Option<&Grant>, request: Option<&CapabilityParams>) -> Perm } PermissionDecision::Allowed } + ( + CapabilityParams::Network { + origins, + max_requests_per_minute, + max_response_bytes, + max_timeout_ms, + }, + CapabilityParams::Network { + origins: requested_origins, + max_requests_per_minute: requested_rate, + max_response_bytes: requested_bytes, + max_timeout_ms: requested_timeout, + }, + ) => { + if !requested_origins + .iter() + .all(|origin| origins.contains(origin)) + { + return PermissionDecision::Denied { + reason: DenyReason::ScopeViolation, + }; + } + if requested_rate > max_requests_per_minute + || requested_bytes > max_response_bytes + || requested_timeout > max_timeout_ms + { + return PermissionDecision::Denied { + reason: DenyReason::QuotaExceeded, + }; + } + PermissionDecision::Allowed + } _ => PermissionDecision::Denied { reason: DenyReason::InvalidInput, }, @@ -619,6 +810,27 @@ fn params_within(plugin: Option<&CapabilityParams>, instance: Option<&Capability CapabilityParams::Metrics { sample_rate_hz }, CapabilityParams::Metrics { sample_rate_hz: ir }, ) => ir <= sample_rate_hz, + ( + CapabilityParams::Network { + origins, + max_requests_per_minute, + max_response_bytes, + max_timeout_ms, + }, + CapabilityParams::Network { + origins: instance_origins, + max_requests_per_minute: instance_rate, + max_response_bytes: instance_bytes, + max_timeout_ms: instance_timeout, + }, + ) => { + instance_origins + .iter() + .all(|origin| origins.contains(origin)) + && instance_rate <= max_requests_per_minute + && instance_bytes <= max_response_bytes + && instance_timeout <= max_timeout_ms + } _ => false, }, } @@ -907,4 +1119,35 @@ mod tests { .is_none() ); } + + #[test] + fn network_scope_requires_exact_https_origins_and_bounded_budgets() { + let params = parse_capability_params( + CapabilityId::NetworkHttps, + Some(&json!({ + "origins": ["https://api.example.com"], + "maxRequestsPerMinute": 12, + "maxResponseBytes": 4096, + "maxTimeoutMs": 2000 + })), + ) + .unwrap(); + assert!(matches!(params, Some(CapabilityParams::Network { .. }))); + for origin in [ + "http://api.example.com", + "https://user@example.com", + "https://api.example.com/path", + "https://api.example.com?token=x", + ] { + assert!( + parse_capability_params( + CapabilityId::NetworkHttps, + Some(&json!({ "origins": [origin] })), + ) + .is_err(), + "应拒绝 {origin}" + ); + } + assert!(parse_capability_params(CapabilityId::NetworkHttps, None).is_err()); + } } diff --git a/crates/floatile-core/src/connection.rs b/crates/floatile-core/src/connection.rs new file mode 100644 index 0000000..f6a9f10 --- /dev/null +++ b/crates/floatile-core/src/connection.rs @@ -0,0 +1,276 @@ +//! 宿主拥有的外部数据连接领域模型(PP-M5)。 +//! +//! Connection 只保存外部账户的非敏感身份与不透明凭证引用。明文 secret 由 +//! `floatile-services` 的凭证库持有,不得进入本模型、SQLite、guest Config 或 State。 + +use serde::{Deserialize, Serialize}; + +use crate::InstanceId; + +pub const MAX_CONNECTION_PROVIDER_BYTES: usize = 64; +pub const MAX_CONNECTION_ACCOUNT_BYTES: usize = 256; +pub const MAX_CREDENTIAL_REF_BYTES: usize = 256; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ConnectionId(pub u64); + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)] +#[serde(transparent)] +pub struct CredentialRef(String); + +impl CredentialRef { + pub fn new(value: impl Into) -> Result { + let value = value.into(); + if value.len() > MAX_CREDENTIAL_REF_BYTES || !valid_credential_ref(&value) { + return Err(ConnectionModelError::InvalidCredentialRef); + } + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl<'de> Deserialize<'de> for CredentialRef { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ConnectionHealth { + Unknown, + Healthy, + Degraded, + Unavailable, + Revoked, +} + +impl ConnectionHealth { + pub const fn as_str(self) -> &'static str { + match self { + Self::Unknown => "unknown", + Self::Healthy => "healthy", + Self::Degraded => "degraded", + Self::Unavailable => "unavailable", + Self::Revoked => "revoked", + } + } + + pub fn parse(value: &str) -> Result { + match value { + "unknown" => Ok(Self::Unknown), + "healthy" => Ok(Self::Healthy), + "degraded" => Ok(Self::Degraded), + "unavailable" => Ok(Self::Unavailable), + "revoked" => Ok(Self::Revoked), + _ => Err(ConnectionModelError::InvalidHealth), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Connection { + id: ConnectionId, + provider: String, + account_identity: String, + credential: CredentialRef, + health: ConnectionHealth, + credential_generation: u64, + created_at: u64, + updated_at: u64, +} + +impl Connection { + #[allow(clippy::too_many_arguments)] + pub fn restore( + id: ConnectionId, + provider: impl Into, + account_identity: impl Into, + credential: CredentialRef, + health: ConnectionHealth, + credential_generation: u64, + created_at: u64, + updated_at: u64, + ) -> Result { + let provider = provider.into(); + let account_identity = account_identity.into(); + validate_token(&provider, MAX_CONNECTION_PROVIDER_BYTES) + .map_err(|_| ConnectionModelError::InvalidProvider)?; + validate_text(&account_identity, MAX_CONNECTION_ACCOUNT_BYTES) + .map_err(|_| ConnectionModelError::InvalidAccountIdentity)?; + if id.0 == 0 { + return Err(ConnectionModelError::InvalidId); + } + if updated_at < created_at { + return Err(ConnectionModelError::InvalidTimestamps); + } + Ok(Self { + id, + provider, + account_identity, + credential, + health, + credential_generation, + created_at, + updated_at, + }) + } + + pub const fn id(&self) -> ConnectionId { + self.id + } + pub fn provider(&self) -> &str { + &self.provider + } + pub fn account_identity(&self) -> &str { + &self.account_identity + } + pub fn credential(&self) -> &CredentialRef { + &self.credential + } + pub const fn health(&self) -> ConnectionHealth { + self.health + } + pub const fn credential_generation(&self) -> u64 { + self.credential_generation + } + pub const fn created_at(&self) -> u64 { + self.created_at + } + pub const fn updated_at(&self) -> u64 { + self.updated_at + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ConnectionGrant { + pub instance_id: InstanceId, + pub connection_id: ConnectionId, + pub granted_at: u64, +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum ConnectionModelError { + #[error("connection id 无效")] + InvalidId, + #[error("provider 无效")] + InvalidProvider, + #[error("account identity 无效")] + InvalidAccountIdentity, + #[error("credential reference 无效")] + InvalidCredentialRef, + #[error("connection health 无效")] + InvalidHealth, + #[error("connection 时间戳无效")] + InvalidTimestamps, +} + +fn valid_credential_ref(value: &str) -> bool { + let Some(path) = value.strip_prefix("cred://") else { + return false; + }; + !path.is_empty() + && !path.starts_with('/') + && !path.ends_with('/') + && path.split('/').all(|part| { + !part.is_empty() + && part != "." + && part != ".." + && part + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + }) +} + +fn validate_token(value: &str, maximum: usize) -> Result<(), ()> { + if value.is_empty() + || value.len() > maximum + || !value.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'.') + }) + { + return Err(()); + } + Ok(()) +} + +fn validate_text(value: &str, maximum: usize) -> Result<(), ()> { + if value.is_empty() || value.len() > maximum || value.chars().any(char::is_control) { + return Err(()); + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn credential_reference_is_opaque_bounded_and_canonical() { + assert!(CredentialRef::new("cred://openai/account-1").is_ok()); + for invalid in [ + "secret", + "cred://", + "cred:///root", + "cred://a/../b", + "cred://a//b", + ] { + assert_eq!( + CredentialRef::new(invalid), + Err(ConnectionModelError::InvalidCredentialRef) + ); + } + } + + #[test] + fn connection_rejects_sensitive_or_corrupt_identity_fields() { + let credential = CredentialRef::new("cred://openai/default").unwrap(); + assert!( + Connection::restore( + ConnectionId(1), + "openai", + "user@example.com", + credential.clone(), + ConnectionHealth::Unknown, + 0, + 1, + 1 + ) + .is_ok() + ); + assert!( + Connection::restore( + ConnectionId(1), + "Open AI", + "account", + credential.clone(), + ConnectionHealth::Unknown, + 0, + 1, + 1 + ) + .is_err() + ); + assert!( + Connection::restore( + ConnectionId(1), + "openai", + "token\nvalue", + credential, + ConnectionHealth::Unknown, + 0, + 2, + 1 + ) + .is_err() + ); + } +} diff --git a/crates/floatile-core/src/constants.rs b/crates/floatile-core/src/constants.rs index 5bf47e7..d85f572 100644 --- a/crates/floatile-core/src/constants.rs +++ b/crates/floatile-core/src/constants.rs @@ -1,5 +1,5 @@ /// 宿主声明的插件 API 兼容版本(对应 WIT world 版本)。 -pub const ENGINE_API_VERSION: &str = "1.1.0"; +pub const ENGINE_API_VERSION: &str = "1.2.0"; /// 插件包格式版本(.floatile zip 布局)。 pub const PACKAGE_FORMAT_VERSION: u32 = 1; diff --git a/crates/floatile-core/src/lib.rs b/crates/floatile-core/src/lib.rs index dc2db2f..cfe4bc3 100644 --- a/crates/floatile-core/src/lib.rs +++ b/crates/floatile-core/src/lib.rs @@ -1,4 +1,5 @@ pub mod capability; +pub mod connection; pub mod constants; pub mod install; pub mod instance; @@ -13,6 +14,11 @@ pub use capability::{ DenyReason, EffectiveGrant, Grant, Grants, InstanceGrant, PermissionDecision, TrustLevel, decide, narrow_instance, parse_capability_params, }; +pub use connection::{ + Connection, ConnectionGrant, ConnectionHealth, ConnectionId, ConnectionModelError, + CredentialRef, MAX_CONNECTION_ACCOUNT_BYTES, MAX_CONNECTION_PROVIDER_BYTES, + MAX_CREDENTIAL_REF_BYTES, +}; pub use instance::{ InstallationDigest, InstallationRef, InstanceConfig, InstanceDesiredState, InstanceModelError, MAX_INSTANCE_CONFIG_BYTES, MAX_INSTANCE_CONFIG_DEPTH, PluginInstance, @@ -22,9 +28,9 @@ pub use layout::{ RecoveredLayout, WidgetLayout, recover_layout, }; pub use manifest::{ - BuildMeta, ConfigRef, Entrypoints, Manifest, ManifestError, PackagePath, PermissionDecl, - PluginKind, Publisher, Sizes, StorageDecl, manifest_json_schema, validate_manifest, - validate_manifest_json_with_schema, + BuildMeta, ConfigRef, Entrypoints, HttpTemplateDecl, Manifest, ManifestError, PackagePath, + PermissionDecl, PluginKind, Publisher, Sizes, StorageDecl, manifest_json_schema, + validate_manifest, validate_manifest_json_with_schema, }; pub use operation::{ OperationCompletion, OperationCompletionDisposition, OperationFailure, OperationId, diff --git a/crates/floatile-core/src/manifest.rs b/crates/floatile-core/src/manifest.rs index 786fbb2..55d54e1 100644 --- a/crates/floatile-core/src/manifest.rs +++ b/crates/floatile-core/src/manifest.rs @@ -115,6 +115,48 @@ pub struct BuildMeta { pub sdk_version: String, } +/// 宿主拥有的 HTTPS 请求模板。guest 只能选择模板并填写声明过的查询参数。 +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct HttpTemplateDecl { + pub id: String, + pub method: String, + pub url: String, + #[serde(default)] + pub query_params: Vec, + pub credential_header: String, + #[serde(default = "default_http_statuses")] + pub allowed_statuses: Vec, + #[serde(default = "default_http_max_bytes")] + pub max_response_bytes: u64, + #[serde(default = "default_http_timeout_ms")] + pub timeout_ms: u64, + #[serde(default)] + pub cache_ttl_ms: u64, + #[serde(default)] + pub stale_if_error_ms: u64, + #[serde(default)] + pub max_retries: u8, + #[serde(default = "default_retry_base_delay_ms")] + pub retry_base_delay_ms: u64, +} + +fn default_http_statuses() -> Vec { + vec![200] +} + +const fn default_http_max_bytes() -> u64 { + 256 * 1024 +} + +const fn default_http_timeout_ms() -> u64 { + 10_000 +} + +const fn default_retry_base_delay_ms() -> u64 { + 250 +} + /// manifest.json v1。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)] pub struct Manifest { @@ -135,6 +177,12 @@ pub struct Manifest { pub entrypoints: Entrypoints, pub sizes: Sizes, pub permissions: Vec, + #[serde( + default, + rename = "httpTemplates", + skip_serializing_if = "Vec::is_empty" + )] + pub http_templates: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -172,6 +220,8 @@ pub enum ManifestError { InvalidCapabilityParams { capability: String, detail: String }, #[error("非法包路径 `{0}`")] InvalidPackagePath(String), + #[error("非法 HTTPS 模板: {0}")] + InvalidHttpTemplate(String), } impl ManifestError { @@ -190,6 +240,7 @@ impl ManifestError { Self::InherentCapabilityDeclared(_) => "FMAN_INHERENT_CAPABILITY_DECLARED", Self::InvalidCapabilityParams { .. } => "FMAN_INVALID_CAPABILITY_PARAMS", Self::InvalidPackagePath(_) => "FMAN_INVALID_PACKAGE_PATH", + Self::InvalidHttpTemplate(_) => "FMAN_INVALID_HTTP_TEMPLATE", } } } @@ -239,9 +290,142 @@ pub fn validate_manifest(manifest: &Manifest) -> Result<(), ManifestError> { for decl in &manifest.permissions { validate_permission(decl)?; } + validate_http_templates(manifest)?; + Ok(()) +} + +fn validate_http_templates(manifest: &Manifest) -> Result<(), ManifestError> { + if manifest.http_templates.len() > 16 { + return Err(ManifestError::InvalidHttpTemplate( + "httpTemplates 最多 16 项".to_owned(), + )); + } + let network = manifest + .permissions + .iter() + .find(|permission| permission.capability == "network:https") + .map(|permission| { + parse_capability_params(CapabilityId::NetworkHttps, permission.params.as_ref()) + }) + .transpose() + .map_err(|error| ManifestError::InvalidHttpTemplate(error.to_string()))? + .flatten(); + let network = match network { + Some(crate::capability::CapabilityParams::Network { + origins, + max_response_bytes, + max_timeout_ms, + .. + }) => Some((origins, max_response_bytes, max_timeout_ms)), + _ => None, + }; + let mut ids = std::collections::BTreeSet::new(); + for template in &manifest.http_templates { + let valid_id = !template.id.is_empty() + && template.id.len() <= 64 + && template + .id + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '.'); + if !valid_id || !ids.insert(template.id.as_str()) { + return Err(ManifestError::InvalidHttpTemplate(format!( + "模板 id `{}` 非法或重复", + template.id + ))); + } + if template.method != "GET" { + return Err(ManifestError::InvalidHttpTemplate(format!( + "模板 `{}` 当前仅允许 GET", + template.id + ))); + } + let origin = https_url_origin(&template.url).ok_or_else(|| { + ManifestError::InvalidHttpTemplate(format!( + "模板 `{}` URL 必须是无凭证、无 fragment 的固定 HTTPS URL", + template.id + )) + })?; + let Some((origins, max_bytes, max_timeout)) = &network else { + return Err(ManifestError::InvalidHttpTemplate( + "声明 httpTemplates 必须同时声明 network:https".to_owned(), + )); + }; + if !origins.iter().any(|allowed| allowed == origin) + || template.max_response_bytes == 0 + || template.max_response_bytes > *max_bytes + || !(100..=30_000).contains(&template.timeout_ms) + || template.timeout_ms > *max_timeout + || template.cache_ttl_ms > 24 * 60 * 60 * 1000 + || template.stale_if_error_ms > 7 * 24 * 60 * 60 * 1000 + || template.max_retries > 2 + || !(10..=2_000).contains(&template.retry_base_delay_ms) + { + return Err(ManifestError::InvalidHttpTemplate(format!( + "模板 `{}` 超出 network:https origin 或预算", + template.id + ))); + } + if !matches!( + template.credential_header.as_str(), + "authorization" | "x-api-key" + ) { + return Err(ManifestError::InvalidHttpTemplate(format!( + "模板 `{}` credentialHeader 仅允许 authorization/x-api-key", + template.id + ))); + } + if template.query_params.len() > 16 + || template.query_params.iter().any(|name| { + name.is_empty() + || name.len() > 64 + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + }) + || template + .query_params + .iter() + .collect::>() + .len() + != template.query_params.len() + { + return Err(ManifestError::InvalidHttpTemplate(format!( + "模板 `{}` queryParams 非法或重复", + template.id + ))); + } + if template.allowed_statuses.is_empty() + || template.allowed_statuses.len() > 32 + || template + .allowed_statuses + .iter() + .any(|status| !(100..=599).contains(status)) + { + return Err(ManifestError::InvalidHttpTemplate(format!( + "模板 `{}` allowedStatuses 非法", + template.id + ))); + } + } Ok(()) } +fn https_url_origin(url: &str) -> Option<&str> { + let rest = url.strip_prefix("https://")?; + let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); + let authority = &rest[..authority_end]; + if authority.is_empty() + || authority.contains('@') + || authority.starts_with('[') + || authority.eq_ignore_ascii_case("localhost") + || url.contains('#') + || url.chars().any(char::is_whitespace) + { + return None; + } + Some(&url[.."https://".len() + authority_end]) +} + pub(crate) fn validate_plugin_id(id: &str) -> Result<(), ManifestError> { let valid = !id.is_empty() && id.len() <= 128 @@ -459,6 +643,20 @@ fn permission_schema_from_registry() -> serde_json::Value { "sampleRateHz": { "type": "integer", "minimum": 0, "maximum": u32::MAX } } }), + CapabilityParamKind::Network => serde_json::json!({ + "type": "object", + "additionalProperties": false, + "required": ["origins"], + "properties": { + "origins": { + "type": "array", "minItems": 1, "maxItems": 16, + "items": { "type": "string", "pattern": "^https://[^/?#@]+$" } + }, + "maxRequestsPerMinute": { "type": "integer", "minimum": 1, "maximum": 600 }, + "maxResponseBytes": { "type": "integer", "minimum": 1, "maximum": 1048576 }, + "maxTimeoutMs": { "type": "integer", "minimum": 100, "maximum": 30000 } + } + }), }; serde_json::json!({ "type": "object", @@ -535,6 +733,7 @@ mod tests { capability: "timer:schedule".into(), params: Some(json!({"maxPerMinute": 60, "maxActive": 2})), }], + http_templates: Vec::new(), config: None, storage: None, build: None, @@ -546,6 +745,46 @@ mod tests { assert!(validate_manifest(&valid_manifest()).is_ok()); } + #[test] + fn validates_connection_bound_https_templates() { + let mut manifest = valid_manifest(); + manifest.permissions.push(PermissionDecl { + capability: "network:https".into(), + params: Some(serde_json::json!({ + "origins": ["https://api.example.com"], + "maxResponseBytes": 4096, + "maxTimeoutMs": 2000 + })), + }); + manifest.http_templates.push(HttpTemplateDecl { + id: "balance".into(), + method: "GET".into(), + url: "https://api.example.com/v1/balance".into(), + query_params: vec!["account".into()], + credential_header: "authorization".into(), + allowed_statuses: vec![200], + max_response_bytes: 4096, + timeout_ms: 2000, + cache_ttl_ms: 1000, + stale_if_error_ms: 5000, + max_retries: 1, + retry_base_delay_ms: 10, + }); + assert!(validate_manifest(&manifest).is_ok()); + + manifest.http_templates[0].url = "https://evil.example/steal".into(); + assert!(matches!( + validate_manifest(&manifest), + Err(ManifestError::InvalidHttpTemplate(_)) + )); + manifest.http_templates[0].url = "https://api.example.com/v1/balance".into(); + manifest.http_templates[0].credential_header = "cookie".into(); + assert!(matches!( + validate_manifest(&manifest), + Err(ManifestError::InvalidHttpTemplate(_)) + )); + } + #[test] fn manifest_json_schema_validates_own_serialization() { // 单源一致性:生成的 manifest.schema.json 必须能通过自身校验合法 manifest 的 @@ -671,7 +910,7 @@ mod tests { fn rejects_unknown_and_inherent_capabilities() { let mut m = valid_manifest(); m.permissions = vec![PermissionDecl { - capability: "network:https".into(), + capability: "network:raw".into(), params: None, }]; assert!(matches!( diff --git a/crates/floatile-plugin-api/src/lib.rs b/crates/floatile-plugin-api/src/lib.rs index c98e599..597f4e5 100644 --- a/crates/floatile-plugin-api/src/lib.rs +++ b/crates/floatile-plugin-api/src/lib.rs @@ -20,7 +20,7 @@ wasmtime::component::bindgen!({ /// 宿主要求的引擎 API 版本;与 `floatile-sdk::ENGINE_API_VERSION` 一致, /// 二者都来自 `wit/floatile-widget.wit` 的 package 版本。宿主加载插件时校验 /// 插件的 `engineApiVersion`:major 不匹配拒绝加载,minor 兼容时按能力降级。 -pub const ENGINE_API_VERSION: &str = "1.1.0"; +pub const ENGINE_API_VERSION: &str = "1.2.0"; #[cfg(test)] mod tests { @@ -30,6 +30,6 @@ mod tests { fn engine_api_version_matches_wit_package() { // 该值必须与 wit/floatile-widget.wit 的 package 版本同步; // 修改 WIT 时本测试与 SDK 常量一起更新(CI 校验两者一致)。 - assert_eq!(ENGINE_API_VERSION, "1.1.0"); + assert_eq!(ENGINE_API_VERSION, "1.2.0"); } } diff --git a/crates/floatile-runtime/src/lib.rs b/crates/floatile-runtime/src/lib.rs index da80dbb..f658ab2 100644 --- a/crates/floatile-runtime/src/lib.rs +++ b/crates/floatile-runtime/src/lib.rs @@ -28,12 +28,12 @@ use floatile_plugin_api::floatile::widget::host_operation::{ OperationTerminal as WitOperationTerminal, }; use floatile_services::{ - AuditListener, AuditSink, Broker, OperationLimits, OperationRegistry, TimerSink, + AuditListener, AuditSink, Broker, HttpsService, OperationLimits, OperationRegistry, TimerSink, }; use floatile_ui_schema::schema::JsonSchema; use floatile_ui_schema::validate_value; use serde_json::Value; -use tokio::sync::{mpsc, oneshot}; +use tokio::sync::{mpsc, oneshot, watch}; use wasmtime::component::{Component, HasSelf, Linker}; use wasmtime::{Config, Store}; @@ -134,6 +134,15 @@ impl WidgetManager { /// 派生一个插件实例(加载组件 + 启动串行 actor)。 pub fn spawn(&self, config: WidgetConfig) -> Result { + self.spawn_with_https(config, None) + } + + /// Spawn with the host-owned PP-M5 HTTPS service for this exact instance generation. + pub fn spawn_with_https( + &self, + config: WidgetConfig, + https: Option, + ) -> Result { let (cmd_tx, cmd_rx) = mpsc::channel(QUEUE_CAPACITY); let (ui_tx, ui_rx) = mpsc::channel(QUEUE_CAPACITY); @@ -144,23 +153,38 @@ impl WidgetManager { let call_timeout = self.call_timeout; let epoch_ticker = Arc::clone(&self.epoch_ticker); let audit_listener = self.audit_listener.clone(); - let join = tokio::spawn(run_actor( - engine, - config, - max_memory, - fuel_per_call, - call_timeout, - epoch_ticker, - audit_listener, - ui_tx, - cmd_rx, - actor_tx, - )); + let (failure_tx, actor_failure) = watch::channel(None); + let join = tokio::spawn(async move { + let actor = tokio::spawn(run_actor( + engine, + config, + https, + max_memory, + fuel_per_call, + call_timeout, + epoch_ticker, + audit_listener, + ui_tx, + cmd_rx, + actor_tx, + )); + let result = match actor.await { + Ok(result) => result, + Err(error) => Err(RuntimeError::InstanceFailed(format!( + "actor 任务异常终止: {error}" + ))), + }; + if let Err(error) = &result { + failure_tx.send_replace(Some(error.to_string())); + } + result + }); Ok(WidgetHandle { cmd: cmd_tx, ui: ui_rx, join, + actor_failure, }) } } @@ -211,6 +235,7 @@ pub struct WidgetHandle { cmd: mpsc::Sender, ui: mpsc::Receiver, join: tokio::task::JoinHandle>, + actor_failure: watch::Receiver>, } enum InstanceCommand { @@ -225,16 +250,20 @@ impl WidgetHandle { pub async fn start(&self) -> Result<(), InstanceError> { let (tx, rx) = oneshot::channel(); self.send(InstanceCommand::Start(tx)).await?; - rx.await - .map_err(|_| InstanceError::Failed("actor 未返回调用结果".to_owned()))? + match rx.await { + Ok(result) => result, + Err(_) => Err(self.actor_stopped_error().await), + } } /// 投递一个统一事件(UI/timer/mode/config/theme/suspend/resume)。 pub async fn handle_event(&self, event: WidgetEvent) -> Result<(), InstanceError> { let (tx, rx) = oneshot::channel(); self.send(InstanceCommand::Event(event, tx)).await?; - rx.await - .map_err(|_| InstanceError::Failed("actor 未返回调用结果".to_owned()))? + match rx.await { + Ok(result) => result, + Err(_) => Err(self.actor_stopped_error().await), + } } /// 展示模式切换通知。 @@ -270,12 +299,27 @@ impl WidgetHandle { .await .map_err(|_| InstanceError::Failed("实例已终止(命令通道关闭)".to_owned())) } + + async fn actor_stopped_error(&self) -> InstanceError { + // Dropping the command receiver can wake the caller before the actor wrapper observes + // its task result. Wait for that publication instead of relying on scheduler timing. + let mut failure = self.actor_failure.clone(); + match failure.wait_for(Option::is_some).await { + Ok(detail) => InstanceError::Failed( + detail + .clone() + .unwrap_or_else(|| "actor 未返回调用结果".to_owned()), + ), + Err(_) => InstanceError::Failed("actor 未返回调用结果".to_owned()), + } + } } #[allow(clippy::too_many_arguments)] async fn run_actor( engine: wasmtime::Engine, config: WidgetConfig, + https: Option, max_memory: usize, fuel_per_call: u64, call_timeout: Duration, @@ -317,7 +361,7 @@ async fn run_actor( let operation_actor = actor_tx.clone(); let completion_audit = audit.clone(); let completion_results = operations.result_discarder(); - let broker = Broker::new( + let mut broker = Broker::new( config.plugin.clone(), config.generation, config.grants, @@ -328,6 +372,9 @@ async fn run_actor( .map_err(|error| { RuntimeError::InstanceFailed(format!("绑定 Operation registry 失败: {error}")) })?; + if let Some(https) = https { + broker = broker.with_https(https); + } tokio::spawn(async move { while let Some(completion) = operation_completions.recv().await { let capability = completion.capability; @@ -512,6 +559,7 @@ async fn handle_operation_completion( ) -> Result<(), InstanceError> { let capability = match completion.capability { CapabilityId::StorageRead => OperationCapability::StorageRead, + CapabilityId::NetworkHttps => OperationCapability::HttpsRequest, _ => { store.data().broker.discard_operation_result(completion.id); return Ok(()); @@ -577,9 +625,9 @@ fn timeout_epoch_ticks(timeout: Duration) -> u64 { fn setup_call_error(operation: &str, timeout: Duration, error: wasmtime::Error) -> RuntimeError { if is_epoch_interrupt(&error) { - RuntimeError::InstanceFailed(format!("{operation} 超过墙钟预算 {timeout:?}: {error}")) + RuntimeError::InstanceFailed(format!("{operation} 超过墙钟预算 {timeout:?}: {error:#}")) } else { - RuntimeError::InstanceFailed(format!("{operation} trap: {error}")) + RuntimeError::InstanceFailed(format!("{operation} trap: {error:#}")) } } @@ -589,9 +637,9 @@ fn instance_call_error( error: wasmtime::Error, ) -> InstanceError { if is_epoch_interrupt(&error) { - InstanceError::Failed(format!("{operation} 超过墙钟预算 {timeout:?}: {error}")) + InstanceError::Failed(format!("{operation} 超过墙钟预算 {timeout:?}: {error:#}")) } else { - InstanceError::Failed(error.to_string()) + InstanceError::Failed(format!("{error:#}")) } } diff --git a/crates/floatile-runtime/src/state.rs b/crates/floatile-runtime/src/state.rs index b95fc08..44f53ad 100644 --- a/crates/floatile-runtime/src/state.rs +++ b/crates/floatile-runtime/src/state.rs @@ -9,8 +9,8 @@ use std::time::Instant; use floatile_core::OperationId; use floatile_core::types::InstanceId; use floatile_plugin_api::floatile::widget::{ - host_clock, host_log, host_metrics, host_operation, host_storage, host_theme, host_timer, - host_ui, + host_clock, host_http, host_log, host_metrics, host_operation, host_storage, host_theme, + host_timer, host_ui, }; use floatile_services::broker::Broker; use floatile_services::errors::{LogError, MetricsError, StorageError, ThemeError, TimerError}; @@ -262,6 +262,44 @@ impl host_storage::Host for InstanceHostState { } } +impl host_http::Host for InstanceHostState { + async fn submit( + &mut self, + template_id: String, + connection_id: u64, + query: Vec, + ) -> Result { + self.broker + .submit_https( + &template_id, + floatile_core::ConnectionId(connection_id), + query + .into_iter() + .map(|param| floatile_services::QueryParam { + name: param.name, + value: param.value, + }) + .collect(), + ) + .map(OperationId::get) + .map_err(map_operation_submit) + } + + async fn take_result( + &mut self, + id: u64, + ) -> Result { + let id = OperationId::new(id).ok_or(host_operation::OperationError::InvalidOperationId)?; + self.broker + .take_https_result(id) + .map(|response| host_http::HttpResponse { + status: response.status, + body: response.body, + }) + .map_err(map_operation_take) + } +} + fn map_operation_submit(error: OperationSubmitError) -> host_operation::OperationError { match error { OperationSubmitError::PermissionDenied(_) => host_operation::OperationError::NotAllowed, diff --git a/crates/floatile-runtime/tests/clock.rs b/crates/floatile-runtime/tests/clock.rs index c14b3bd..b27b4c0 100644 --- a/crates/floatile-runtime/tests/clock.rs +++ b/crates/floatile-runtime/tests/clock.rs @@ -21,23 +21,26 @@ fn workspace_root() -> PathBuf { .join("..") } -/// 读取 clock-wasm 组件;未构建时先构建。 +/// 读取与当前 WIT/SDK 精确匹配的 clock-wasm 组件;Cargo 增量构建负责跳过未变输入。 fn clock_wasm_bytes() -> Vec { + static WASM: std::sync::OnceLock> = std::sync::OnceLock::new(); + WASM.get_or_init(build_clock_wasm).clone() +} + +fn build_clock_wasm() -> Vec { let wasm_path = workspace_root().join("target/wasm32-wasip2/debug/floatile_clock_wasm.wasm"); - if !wasm_path.exists() { - let status = Command::new("cargo") - .current_dir(workspace_root()) - .args([ - "build", - "-p", - "floatile-clock-wasm", - "--target", - "wasm32-wasip2", - ]) - .status() - .expect("failed to run cargo build for clock-wasm"); - assert!(status.success(), "clock-wasm 构建失败"); - } + let status = Command::new("cargo") + .current_dir(workspace_root()) + .args([ + "build", + "-p", + "floatile-clock-wasm", + "--target", + "wasm32-wasip2", + ]) + .status() + .expect("failed to run cargo build for clock-wasm"); + assert!(status.success(), "clock-wasm 构建失败"); std::fs::read(&wasm_path).expect("读取 clock-wasm 失败") } diff --git a/crates/floatile-runtime/tests/harness.rs b/crates/floatile-runtime/tests/harness.rs index 7212831..4b9298f 100644 --- a/crates/floatile-runtime/tests/harness.rs +++ b/crates/floatile-runtime/tests/harness.rs @@ -20,23 +20,26 @@ fn workspace_root() -> PathBuf { .join("..") } -/// 读取 clock-wasm 组件;未构建时先构建。 +/// 读取与当前 WIT/SDK 精确匹配的 clock-wasm 组件。 fn clock_wasm_bytes() -> Vec { + static WASM: std::sync::OnceLock> = std::sync::OnceLock::new(); + WASM.get_or_init(build_clock_wasm).clone() +} + +fn build_clock_wasm() -> Vec { let wasm_path = workspace_root().join("target/wasm32-wasip2/debug/floatile_clock_wasm.wasm"); - if !wasm_path.exists() { - let status = Command::new("cargo") - .current_dir(workspace_root()) - .args([ - "build", - "-p", - "floatile-clock-wasm", - "--target", - "wasm32-wasip2", - ]) - .status() - .expect("failed to run cargo build for clock-wasm"); - assert!(status.success(), "clock-wasm 构建失败"); - } + let status = Command::new("cargo") + .current_dir(workspace_root()) + .args([ + "build", + "-p", + "floatile-clock-wasm", + "--target", + "wasm32-wasip2", + ]) + .status() + .expect("failed to run cargo build for clock-wasm"); + assert!(status.success(), "clock-wasm 构建失败"); std::fs::read(&wasm_path).expect("读取 clock-wasm 失败") } diff --git a/crates/floatile-runtime/tests/security.rs b/crates/floatile-runtime/tests/security.rs index 6cc04ef..66b12b1 100644 --- a/crates/floatile-runtime/tests/security.rs +++ b/crates/floatile-runtime/tests/security.rs @@ -34,23 +34,26 @@ fn workspace_root() -> PathBuf { .join("..") } -/// 读取 evil-wasm 组件;未构建时先构建。 +/// 读取与当前 WIT/SDK 精确匹配的 evil-wasm 组件。 fn evil_wasm_bytes() -> Vec { + static WASM: std::sync::OnceLock> = std::sync::OnceLock::new(); + WASM.get_or_init(build_evil_wasm).clone() +} + +fn build_evil_wasm() -> Vec { let wasm_path = workspace_root().join("target/wasm32-wasip2/debug/floatile_evil_wasm.wasm"); - if !wasm_path.exists() { - let status = Command::new("cargo") - .current_dir(workspace_root()) - .args([ - "build", - "-p", - "floatile-evil-wasm", - "--target", - "wasm32-wasip2", - ]) - .status() - .expect("failed to run cargo build for evil-wasm"); - assert!(status.success(), "evil-wasm 构建失败"); - } + let status = Command::new("cargo") + .current_dir(workspace_root()) + .args([ + "build", + "-p", + "floatile-evil-wasm", + "--target", + "wasm32-wasip2", + ]) + .status() + .expect("failed to run cargo build for evil-wasm"); + assert!(status.success(), "evil-wasm 构建失败"); std::fs::read(&wasm_path).expect("读取 evil-wasm 失败") } diff --git a/crates/floatile-sdk/src/context.rs b/crates/floatile-sdk/src/context.rs index 431fdc1..13c35f8 100644 --- a/crates/floatile-sdk/src/context.rs +++ b/crates/floatile-sdk/src/context.rs @@ -8,8 +8,8 @@ use std::marker::PhantomData; use crate::{LogError, LogLevel, OperationError, StorageError, ThemeError, TimerError, UiError}; use crate::{ - host_clock, host_log, host_metrics, host_operation, host_storage, host_theme, host_timer, - host_ui, + host_clock, host_http, host_log, host_metrics, host_operation, host_storage, host_theme, + host_timer, host_ui, }; pub struct Context { @@ -61,6 +61,12 @@ impl Context { StorageCtx } + // ---- HTTPS(声明能力 network:https + instance Connection grant)---- + + pub fn http(&self) -> HttpCtx { + HttpCtx + } + // ---- operation(宿主托管异步工作)---- pub fn operation(&self) -> OperationCtx { @@ -80,6 +86,24 @@ impl Context { } } +/// `ctx.http()` — static-template, Connection-bound HTTPS operations. +pub struct HttpCtx; + +impl HttpCtx { + pub fn submit( + &self, + template_id: &str, + connection_id: u64, + query: &[host_http::QueryParam], + ) -> Result { + host_http::submit(template_id, connection_id, query) + } + + pub fn take_result(&self, id: u64) -> Result { + host_http::take_result(id) + } +} + /// `ctx.state()` — State Patch 更新(JSON Merge Patch → host 侧原子应用)。 pub struct StateCtx; diff --git a/crates/floatile-sdk/src/export.rs b/crates/floatile-sdk/src/export.rs index 1adffb4..f6ac12b 100644 --- a/crates/floatile-sdk/src/export.rs +++ b/crates/floatile-sdk/src/export.rs @@ -13,30 +13,46 @@ macro_rules! impl_export_widget { use ::core::cell::RefCell; /// 自动生成的 Component 适配层(非公开 API)。 - struct _FloatileWidgetAdapter(RefCell<$widget>); + struct _FloatileWidgetAdapter { + widget: RefCell<$widget>, + init_error: ::core::option::Option<::std::string::String>, + } impl $crate::GuestWidgetInstance for _FloatileWidgetAdapter { fn new(init: $crate::WidgetInit) -> Self { // canonical initial State 是宿主校验后下发的唯一权威;guest - // 不得自行猜默认值(WIT widget-init 注释)。反序列化失败 = - // 插件 State 类型与宿主校验的 UI IR 契约 drift,以 trap 终止 - // 本实例(per 架构文档:宿主与其他实例必须存活)。 + // 不得自行猜默认值(WIT widget-init 注释)。反序列化失败说明 + // 插件 State 类型与宿主校验的 UI IR 契约 drift;保留原因并在 + // start 返回 invalid-input,使 runtime 终止本实例且能稳定诊断。 let initial = $crate::serde_json::from_str::< <$widget as $crate::Widget>::State, - >(&init.initial_state_json) - .unwrap_or_else(|error| { - ::core::panic!( - "host initial state 与插件 State 类型不匹配: {error}" - ) - }); + >(&init.initial_state_json); let mut widget = <$widget as ::core::default::Default>::default(); - <$widget as $crate::Widget>::init(&mut widget, &initial); - _FloatileWidgetAdapter(RefCell::new(widget)) + let init_error = match initial { + ::core::result::Result::Ok(initial) => { + <$widget as $crate::Widget>::init(&mut widget, &initial); + ::core::option::Option::None + } + ::core::result::Result::Err(error) => ::core::option::Option::Some( + ::std::format!( + "host initial state 与插件 State 类型不匹配: {error}" + ), + ), + }; + _FloatileWidgetAdapter { + widget: RefCell::new(widget), + init_error, + } } fn start(&self) -> Result<(), $crate::WidgetError> { + if let ::core::option::Option::Some(error) = &self.init_error { + return ::core::result::Result::Err( + $crate::WidgetError::InvalidInput(error.clone()), + ); + } let mut ctx = $crate::Context::new(); - self.0.borrow_mut().start(&mut ctx); + self.widget.borrow_mut().start(&mut ctx); Ok(()) } @@ -44,17 +60,24 @@ macro_rules! impl_export_widget { &self, event: $crate::WidgetEvent, ) -> Result<(), $crate::WidgetError> { + if let ::core::option::Option::Some(error) = &self.init_error { + return ::core::result::Result::Err( + $crate::WidgetError::InvalidInput(error.clone()), + ); + } if let Some(ev) = <<$widget as $crate::Widget>::Event as $crate::FromWidgetEvent>::from_widget_event(event) { let mut ctx = $crate::Context::new(); - self.0.borrow_mut().event(ev, &mut ctx); + self.widget.borrow_mut().event(ev, &mut ctx); } Ok(()) } fn stop(&self) { - self.0.borrow_mut().stop(); + if self.init_error.is_none() { + self.widget.borrow_mut().stop(); + } } } diff --git a/crates/floatile-sdk/src/lib.rs b/crates/floatile-sdk/src/lib.rs index 2832b08..7c57853 100644 --- a/crates/floatile-sdk/src/lib.rs +++ b/crates/floatile-sdk/src/lib.rs @@ -14,13 +14,14 @@ wit_bindgen::generate!({ export_macro_name: "export_widget", }); -pub const ENGINE_API_VERSION: &str = "1.1.0"; +pub const ENGINE_API_VERSION: &str = "1.2.0"; // 供 `impl_export_widget!` 在 guest 侧解析宿主下发的 canonical initial State。 pub use serde_json; // ---- 低层 WIT host modules ---- pub use floatile::widget::host_clock; +pub use floatile::widget::host_http; pub use floatile::widget::host_log; pub use floatile::widget::host_metrics; pub use floatile::widget::host_operation; diff --git a/crates/floatile-sdk/wit/floatile-widget.wit b/crates/floatile-sdk/wit/floatile-widget.wit index 1d5c86c..a9f45cd 100644 --- a/crates/floatile-sdk/wit/floatile-widget.wit +++ b/crates/floatile-sdk/wit/floatile-widget.wit @@ -1,4 +1,4 @@ -// Floatile Widget 插件契约 v1.1.0(唯一事实源)。 +// Floatile Widget 插件契约 v1.2.0(唯一事实源)。 // // 宿主与 guest 绑定都由本文件生成;修改必须同步 floatile-plugin-api、 // floatile-sdk、floatile-runtime 适配、engineApiVersion 与契约测试。 @@ -8,7 +8,7 @@ // handle-event/stop)、canonical initial State、host-ui.update-state 与稳定 // guest error。宿主能力即 interface,world 显式 import 才算获得;所有能力 // 调用仍由 PermissionBroker 仲裁与审计。 -package floatile:widget@1.1.0; +package floatile:widget@1.2.0; // ---------- 宿主能力(插件 import;能力即接口,world 显式 import 才算获得) ---------- @@ -77,6 +77,7 @@ interface host-operation { enum operation-capability { storage-read, + https-request, } enum operation-terminal { @@ -111,6 +112,24 @@ interface host-operation { cancel: func(id: operation-id) -> result<_, operation-error>; } +interface host-http { + use host-operation.{operation-error, operation-id}; + + record query-param { + name: string, + value: string, + } + + record http-response { + status: u16, + body: list, + } + + // 模板、Connection grant、origin、预算与 credential 注入均由宿主验证。 + submit: func(template-id: string, connection-id: u64, query: list) -> result; + take-result: func(id: operation-id) -> result; +} + interface host-storage { use host-operation.{operation-error, operation-id}; @@ -231,6 +250,7 @@ world floatile-widget { import host-timer; import host-operation; import host-storage; + import host-http; import host-metrics; import host-theme; diff --git a/crates/floatile-services/Cargo.toml b/crates/floatile-services/Cargo.toml index 73dbb1c..cda24c9 100644 --- a/crates/floatile-services/Cargo.toml +++ b/crates/floatile-services/Cargo.toml @@ -17,6 +17,9 @@ serde = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } +reqwest = { workspace = true } +url = { workspace = true } +futures-util = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/floatile-services/src/broker.rs b/crates/floatile-services/src/broker.rs index 66bfdf9..922821f 100644 --- a/crates/floatile-services/src/broker.rs +++ b/crates/floatile-services/src/broker.rs @@ -6,7 +6,8 @@ use std::any::Any; use std::future::Future; -use std::time::Duration; +use std::sync::Mutex; +use std::time::{Duration, Instant}; use floatile_core::types::PluginId; use floatile_core::{ @@ -18,6 +19,7 @@ use floatile_core::{ use crate::audit::AuditSink; use crate::clock::{Clock, ClockSnapshot}; use crate::errors::{LogError, MetricsError, StorageError, ThemeError, TimerError}; +use crate::http::{HttpResponse, HttpsService, QueryParam}; use crate::log::{LogLevel, LogService}; use crate::metrics::{MemorySnapshot, MetricsService}; use crate::operation::{ @@ -41,6 +43,14 @@ pub struct Broker { metrics: MetricsService, theme: ThemeService, operations: Option, + https: Option, + https_rate_max: u32, + https_rate: Mutex, +} + +struct RateWindow { + started: Instant, + used: u32, } impl Broker { @@ -73,6 +83,7 @@ impl Broker { let mut storage_max_bytes = 64 * 1024; let mut timer_quota = None; let mut metrics_rate = 1; + let mut https_rate_max = 0; for grant in &grants.caps { match (&grant.capability, &grant.params) { (CapabilityId::StorageWrite, Some(CapabilityParams::Storage { max_bytes, .. })) => { @@ -90,6 +101,13 @@ impl Broker { (CapabilityId::SystemCpu, Some(CapabilityParams::Metrics { sample_rate_hz })) => { metrics_rate = *sample_rate_hz; } + ( + CapabilityId::NetworkHttps, + Some(CapabilityParams::Network { + max_requests_per_minute, + .. + }), + ) => https_rate_max = *max_requests_per_minute, _ => {} } } @@ -113,6 +131,12 @@ impl Broker { metrics: MetricsService::new(metrics_rate), theme: ThemeService::new(), operations: None, + https: None, + https_rate_max, + https_rate: Mutex::new(RateWindow { + started: Instant::now(), + used: 0, + }), } } @@ -132,6 +156,12 @@ impl Broker { Ok(self) } + /// Bind manifest templates, instance-scoped Connection grants, vault, and transport. + pub fn with_https(mut self, https: HttpsService) -> Self { + self.https = Some(https); + self + } + /// 纯授权检查(用于 UI State 等由 runtime 执行、Broker 只裁决的能力)。 pub fn authorize( &self, @@ -275,6 +305,87 @@ impl Broker { self.take_operation_result(CapabilityId::StorageRead, id) } + /// HTTPS 服务尚未为本实例绑定模板/Connection 时的安全降级路径。 + /// 仍通过 Broker 记录授权与环境不可用,WIT adapter 不直接作权限判断。 + pub fn submit_https( + &self, + template_id: &str, + connection_id: floatile_core::ConnectionId, + query: Vec, + ) -> Result { + let Some(https) = &self.https else { + self.authorize_existing_grant( + CapabilityId::NetworkHttps, + &format!("https template={}B service=unconfigured", template_id.len()), + ) + .map_err(OperationSubmitError::PermissionDenied)?; + self.audit.record( + CapabilityId::NetworkHttps, + false, + Some(DenyReason::EnvironmentUnavailable), + "https service=unconfigured", + ); + return Err(OperationSubmitError::Unavailable); + }; + let prepared = + https + .prepare(template_id, connection_id, query) + .map_err(|error| match error { + crate::http::HttpServiceError::InvalidInput + | crate::http::HttpServiceError::TemplateUnavailable + | crate::http::HttpServiceError::ConnectionNotGranted => { + OperationSubmitError::InvalidInput + } + _ => OperationSubmitError::Unavailable, + })?; + let detail = format!( + "operation=https template={}B connection={}", + template_id.len(), + connection_id.0 + ); + self.authorize( + CapabilityId::NetworkHttps, + Some(&prepared.request_params), + &detail, + ) + .map_err(OperationSubmitError::PermissionDenied)?; + if !self.reserve_https_rate() { + self.audit.record( + CapabilityId::NetworkHttps, + false, + Some(DenyReason::QuotaExceeded), + "https rate-limit", + ); + return Err(OperationSubmitError::PermissionDenied( + DenyReason::QuotaExceeded, + )); + } + self.submit_authorized_operation( + CapabilityId::NetworkHttps, + prepared.timeout, + prepared.work, + ) + } + + pub fn take_https_result(&self, id: OperationId) -> Result { + self.take_operation_result(CapabilityId::NetworkHttps, id) + } + + fn reserve_https_rate(&self) -> bool { + let Ok(mut window) = self.https_rate.lock() else { + return false; + }; + if window.started.elapsed() >= Duration::from_secs(60) { + window.started = Instant::now(); + window.used = 0; + } + if window.used >= self.https_rate_max { + return false; + } + window.used += 1; + true + } + pub fn metrics_cpu_percent(&mut self) -> Result { self.authorize( CapabilityId::SystemCpu, @@ -321,6 +432,19 @@ impl Broker { { self.authorize(capability, request, audit_detail) .map_err(OperationSubmitError::PermissionDenied)?; + self.submit_authorized_operation(capability, timeout, work) + } + + fn submit_authorized_operation( + &self, + capability: CapabilityId, + timeout: Duration, + work: F, + ) -> Result + where + T: Any + Send + 'static, + F: Future> + Send + 'static, + { let result = match &self.operations { Some(operations) => operations.submit(capability, timeout, work), None => Err(OperationSubmitError::Unavailable), @@ -478,6 +602,16 @@ mod tests { }), effective: EffectiveGrant::DerivedFromInstall, }, + Grant { + capability: CapabilityId::NetworkHttps, + params: Some(CapabilityParams::Network { + origins: vec!["https://api.example.com".into()], + max_requests_per_minute: 1, + max_response_bytes: 4096, + max_timeout_ms: 2000, + }), + effective: EffectiveGrant::DerivedFromInstall, + }, ], }; narrow_instance( @@ -508,11 +642,34 @@ mod tests { }), effective: EffectiveGrant::DerivedFromInstall, }, + Grant { + capability: CapabilityId::NetworkHttps, + params: Some(CapabilityParams::Network { + origins: vec!["https://api.example.com".into()], + max_requests_per_minute: 1, + max_response_bytes: 4096, + max_timeout_ms: 2000, + }), + effective: EffectiveGrant::DerivedFromInstall, + }, ], ) .unwrap() } + #[test] + fn https_rate_budget_is_instance_scoped_and_bounded() { + let broker = Broker::new( + PluginId("dev.floatile.clock".into()), + 0, + test_grants(), + AuditSink::new("dev.floatile.clock", 7), + sink(), + ); + assert!(broker.reserve_https_rate()); + assert!(!broker.reserve_https_rate()); + } + fn sink() -> TimerSink { let delivered = Arc::new(Mutex::new(Vec::new())); Arc::new(move |id| { diff --git a/crates/floatile-services/src/credential.rs b/crates/floatile-services/src/credential.rs new file mode 100644 index 0000000..62e0b9e --- /dev/null +++ b/crates/floatile-services/src/credential.rs @@ -0,0 +1,148 @@ +//! 宿主 Credential Vault 边界。 +//! +//! Secret 不实现 `Debug`、`Clone` 或序列化,只能在宿主闭包内短暂借用。当前进程内实现用于 +//! Broker 组合与确定性测试;平台持久 Keyring 接入前,宿主重启后必须把连接报告为 unavailable。 + +use std::collections::BTreeMap; +use std::sync::Mutex; + +use floatile_core::CredentialRef; + +pub const MAX_CREDENTIAL_BYTES: usize = 8 * 1024; + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum CredentialError { + #[error("credential secret 为空")] + Empty, + #[error("credential secret 超过宿主预算")] + TooLarge, + #[error("credential 不存在")] + NotFound, + #[error("credential vault 不可用")] + Unavailable, +} + +struct SecretBytes(Vec); + +impl SecretBytes { + fn new(value: &[u8]) -> Result { + if value.is_empty() { + return Err(CredentialError::Empty); + } + if value.len() > MAX_CREDENTIAL_BYTES { + return Err(CredentialError::TooLarge); + } + Ok(Self(value.to_vec())) + } + + fn expose(&self) -> &[u8] { + &self.0 + } +} + +impl Drop for SecretBytes { + fn drop(&mut self) { + self.0.fill(0); + std::hint::black_box(&mut self.0); + } +} + +/// 最小凭证库能力。调用方不能取得拥有所有权的 secret,也不能枚举凭证。 +pub trait CredentialVault: Send + Sync { + fn put(&self, reference: &CredentialRef, secret: &[u8]) -> Result<(), CredentialError>; + fn delete(&self, reference: &CredentialRef) -> Result; + fn with_secret( + &self, + reference: &CredentialRef, + use_secret: &mut dyn FnMut(&[u8]), + ) -> Result<(), CredentialError>; +} + +/// 不落盘的宿主凭证库。用于开发、测试和平台 Keyring 不可用时的显式会话模式。 +#[derive(Default)] +pub struct MemoryCredentialVault { + entries: Mutex>, +} + +impl CredentialVault for MemoryCredentialVault { + fn put(&self, reference: &CredentialRef, secret: &[u8]) -> Result<(), CredentialError> { + let secret = SecretBytes::new(secret)?; + let mut entries = self + .entries + .lock() + .map_err(|_| CredentialError::Unavailable)?; + entries.insert(reference.as_str().to_owned(), secret); + Ok(()) + } + + fn delete(&self, reference: &CredentialRef) -> Result { + let mut entries = self + .entries + .lock() + .map_err(|_| CredentialError::Unavailable)?; + Ok(entries.remove(reference.as_str()).is_some()) + } + + fn with_secret( + &self, + reference: &CredentialRef, + use_secret: &mut dyn FnMut(&[u8]), + ) -> Result<(), CredentialError> { + let entries = self + .entries + .lock() + .map_err(|_| CredentialError::Unavailable)?; + let secret = entries + .get(reference.as_str()) + .ok_or(CredentialError::NotFound)?; + use_secret(secret.expose()); + Ok(()) + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + fn reference() -> CredentialRef { + CredentialRef::new("cred://provider/account").unwrap() + } + + #[test] + fn secret_is_only_borrowed_and_replacement_is_visible() { + let vault = MemoryCredentialVault::default(); + vault.put(&reference(), b"first-secret").unwrap(); + vault.put(&reference(), b"second-secret").unwrap(); + let mut observed = Vec::new(); + vault + .with_secret(&reference(), &mut |secret| { + observed.extend_from_slice(secret) + }) + .unwrap(); + assert_eq!(observed, b"second-secret"); + } + + #[test] + fn missing_deleted_and_oversized_secrets_fail_without_fallback() { + let vault = MemoryCredentialVault::default(); + assert_eq!( + vault.with_secret(&reference(), &mut |_| {}), + Err(CredentialError::NotFound) + ); + assert_eq!(vault.put(&reference(), &[]), Err(CredentialError::Empty)); + assert_eq!( + vault.put(&reference(), &vec![0; MAX_CREDENTIAL_BYTES + 1]), + Err(CredentialError::TooLarge) + ); + vault.put(&reference(), b"secret").unwrap(); + assert!(vault.delete(&reference()).unwrap()); + assert!(!vault.delete(&reference()).unwrap()); + } + + #[test] + fn vault_debug_surface_never_contains_secret() { + assert!(!std::any::type_name::().contains("secret")); + assert!(!std::any::type_name::().contains("secret")); + } +} diff --git a/crates/floatile-services/src/http.rs b/crates/floatile-services/src/http.rs new file mode 100644 index 0000000..d593939 --- /dev/null +++ b/crates/floatile-services/src/http.rs @@ -0,0 +1,624 @@ +//! Connection-bound HTTPS request construction and transport. +//! +//! The guest selects only a validated manifest template, a granted Connection, and bounded query +//! values. Credential lookup and injection stay in this host-only module. + +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; +use std::net::{IpAddr, SocketAddr}; +use std::pin::Pin; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use floatile_core::{ + CapabilityParams, Connection, ConnectionHealth, ConnectionId, HttpTemplateDecl, +}; +use futures_util::StreamExt; +use reqwest::header::{HeaderName, HeaderValue}; +use url::Url; + +use floatile_core::OperationFailure; + +use crate::CredentialVault; + +pub const MAX_QUERY_VALUE_BYTES: usize = 1024; +pub type ConnectionHealthListener = + Arc; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpResponse { + pub status: u16, + pub body: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QueryParam { + pub name: String, + pub value: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum HttpServiceError { + #[error("HTTPS request input is invalid")] + InvalidInput, + #[error("HTTPS template is not available")] + TemplateUnavailable, + #[error("Connection is not granted")] + ConnectionNotGranted, + #[error("Connection credential is unavailable")] + CredentialUnavailable, + #[error("HTTPS destination is not public")] + DestinationNotPublic, + #[error("HTTPS transport is unavailable")] + Unavailable, + #[error("HTTPS response violates the template")] + ResponseRejected, +} + +impl From for OperationFailure { + fn from(error: HttpServiceError) -> Self { + match error { + HttpServiceError::InvalidInput + | HttpServiceError::TemplateUnavailable + | HttpServiceError::ConnectionNotGranted + | HttpServiceError::ResponseRejected => Self::Internal, + HttpServiceError::CredentialUnavailable + | HttpServiceError::DestinationNotPublic + | HttpServiceError::Unavailable => Self::Unavailable, + } + } +} + +#[derive(Clone)] +pub struct HttpTransportRequest { + url: Url, + credential_header: HeaderName, + credential: HeaderValue, + max_response_bytes: usize, + allowed_statuses: Vec, +} + +pub trait HttpTransport: Send + Sync { + fn execute( + &self, + request: HttpTransportRequest, + ) -> Pin> + Send + 'static>>; +} + +/// Production HTTPS transport: system DNS is resolved once, every result must be public, and the +/// selected address is pinned into a per-request rustls client. Redirects are disabled. +#[derive(Default)] +pub struct ReqwestHttpTransport; + +impl HttpTransport for ReqwestHttpTransport { + fn execute( + &self, + request: HttpTransportRequest, + ) -> Pin> + Send + 'static>> + { + Box::pin(async move { + let host = request + .url + .host_str() + .ok_or(HttpServiceError::InvalidInput)? + .to_owned(); + let port = request + .url + .port_or_known_default() + .ok_or(HttpServiceError::InvalidInput)?; + let addresses: Vec<_> = tokio::net::lookup_host((host.as_str(), port)) + .await + .map_err(|_| HttpServiceError::Unavailable)? + .collect(); + if addresses.is_empty() || addresses.iter().any(|addr| !is_public_ip(addr.ip())) { + return Err(HttpServiceError::DestinationNotPublic); + } + let pinned = SocketAddr::new(addresses[0].ip(), port); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .resolve(&host, pinned) + .build() + .map_err(|_| HttpServiceError::Unavailable)?; + let response = client + .get(request.url) + .header(request.credential_header, request.credential) + .send() + .await + .map_err(|_| HttpServiceError::Unavailable)?; + let status = response.status().as_u16(); + if !request.allowed_statuses.contains(&status) + || response + .content_length() + .is_some_and(|length| length > request.max_response_bytes as u64) + { + return Err(HttpServiceError::ResponseRejected); + } + let mut body = Vec::new(); + let mut stream = response.bytes_stream(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|_| HttpServiceError::Unavailable)?; + if body.len().saturating_add(chunk.len()) > request.max_response_bytes { + return Err(HttpServiceError::ResponseRejected); + } + body.extend_from_slice(&chunk); + } + Ok(HttpResponse { status, body }) + }) + } +} + +#[derive(Clone)] +pub struct HttpsService { + templates: Arc>, + connections: Arc>, + vault: Arc, + transport: Arc, + cache: Arc>>, + health_listener: Option, +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] +struct CacheKey { + template_id: String, + connection_id: ConnectionId, + credential_generation: u64, + url: String, +} + +struct CachedResponse { + stored_at: Instant, + response: HttpResponse, +} + +impl HttpsService { + pub fn new( + templates: Vec, + granted_connections: Vec, + vault: Arc, + transport: Arc, + ) -> Self { + Self { + templates: Arc::new( + templates + .into_iter() + .map(|template| (template.id.clone(), template)) + .collect(), + ), + connections: Arc::new( + granted_connections + .into_iter() + .map(|connection| (connection.id(), connection)) + .collect(), + ), + vault, + transport, + cache: Arc::new(Mutex::new(BTreeMap::new())), + health_listener: None, + } + } + + pub fn with_health_listener(mut self, listener: ConnectionHealthListener) -> Self { + self.health_listener = Some(listener); + self + } + + pub fn prepare( + &self, + template_id: &str, + connection_id: ConnectionId, + query: Vec, + ) -> Result { + let template = self + .templates + .get(template_id) + .ok_or(HttpServiceError::TemplateUnavailable)?; + let connection = self + .connections + .get(&connection_id) + .ok_or(HttpServiceError::ConnectionNotGranted)?; + if matches!( + connection.health(), + ConnectionHealth::Unavailable | ConnectionHealth::Revoked + ) { + return Err(HttpServiceError::CredentialUnavailable); + } + if query.len() > template.query_params.len() { + return Err(HttpServiceError::InvalidInput); + } + let mut seen = BTreeSet::new(); + let mut url = Url::parse(&template.url).map_err(|_| HttpServiceError::InvalidInput)?; + { + let mut pairs = url.query_pairs_mut(); + for param in query { + if !template.query_params.contains(¶m.name) + || !seen.insert(param.name.clone()) + || param.value.len() > MAX_QUERY_VALUE_BYTES + || param.value.contains('\0') + { + return Err(HttpServiceError::InvalidInput); + } + pairs.append_pair(¶m.name, ¶m.value); + } + } + let header = HeaderName::from_bytes(template.credential_header.as_bytes()) + .map_err(|_| HttpServiceError::InvalidInput)?; + let mut credential = None; + if self + .vault + .with_secret(connection.credential(), &mut |secret| { + credential = HeaderValue::from_bytes(secret).ok(); + }) + .is_err() + { + if let Some(listener) = &self.health_listener { + listener(connection_id, ConnectionHealth::Unavailable); + } + return Err(HttpServiceError::CredentialUnavailable); + } + let mut credential = credential.ok_or(HttpServiceError::CredentialUnavailable)?; + credential.set_sensitive(true); + let origin = url.origin().ascii_serialization(); + let request_params = CapabilityParams::Network { + origins: vec![origin], + max_requests_per_minute: 1, + max_response_bytes: template.max_response_bytes, + max_timeout_ms: template.timeout_ms, + }; + let transport_request = HttpTransportRequest { + url: url.clone(), + credential_header: header, + credential, + max_response_bytes: usize::try_from(template.max_response_bytes) + .map_err(|_| HttpServiceError::InvalidInput)?, + allowed_statuses: template.allowed_statuses.clone(), + }; + let transport = Arc::clone(&self.transport); + let health_listener = self.health_listener.clone(); + let cache = Arc::clone(&self.cache); + let cache_key = CacheKey { + template_id: template.id.clone(), + connection_id, + credential_generation: connection.credential_generation(), + url: url.into(), + }; + let cache_ttl = Duration::from_millis(template.cache_ttl_ms); + let stale_if_error = Duration::from_millis(template.stale_if_error_ms); + let max_retries = template.max_retries; + let retry_base_delay = Duration::from_millis(template.retry_base_delay_ms); + Ok(PreparedHttpOperation { + request_params, + timeout: Duration::from_millis(template.timeout_ms), + work: Box::pin(async move { + if !cache_ttl.is_zero() + && let Some(hit) = lock(&cache).get(&cache_key) + && hit.stored_at.elapsed() <= cache_ttl + { + return Ok(hit.response.clone()); + } + let mut attempt = 0u8; + loop { + match transport.execute(transport_request.clone()).await { + Ok(response) => { + if let Some(listener) = &health_listener { + listener(connection_id, ConnectionHealth::Healthy); + } + if !cache_ttl.is_zero() || !stale_if_error.is_zero() { + lock(&cache).insert( + cache_key.clone(), + CachedResponse { + stored_at: Instant::now(), + response: response.clone(), + }, + ); + } + return Ok(response); + } + Err(error) if attempt < max_retries && retryable(error) => { + let multiplier = 1u32 << attempt; + tokio::time::sleep(retry_base_delay.saturating_mul(multiplier)).await; + attempt += 1; + } + Err(error) => { + if !stale_if_error.is_zero() + && let Some(hit) = lock(&cache).get(&cache_key) + && hit.stored_at.elapsed() + <= cache_ttl.saturating_add(stale_if_error) + { + return Ok(hit.response.clone()); + } + if let Some(listener) = &health_listener { + listener(connection_id, ConnectionHealth::Degraded); + } + return Err(OperationFailure::from(error)); + } + } + } + }), + }) + } +} + +fn retryable(error: HttpServiceError) -> bool { + matches!(error, HttpServiceError::Unavailable) +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +pub struct PreparedHttpOperation { + pub request_params: CapabilityParams, + pub timeout: Duration, + pub work: + Pin> + Send + 'static>>, +} + +fn is_public_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(ip) => is_public_ipv4(ip), + IpAddr::V6(ip) => { + if let Some(mapped) = ip.to_ipv4_mapped() { + return is_public_ipv4(mapped); + } + let segments = ip.segments(); + !(ip.is_loopback() + || ip.is_unspecified() + || ip.is_multicast() + || ip.is_unique_local() + || ip.is_unicast_link_local() + || (segments[0] & 0xffc0) == 0xfec0 + || (segments[0] == 0x2001 && segments[1] == 0x0db8)) + } + } +} + +fn is_public_ipv4(ip: std::net::Ipv4Addr) -> bool { + let [a, b, c, _] = ip.octets(); + !(a == 0 + || a == 10 + || a == 127 + || (a == 100 && (64..=127).contains(&b)) + || (a == 169 && b == 254) + || (a == 172 && (16..=31).contains(&b)) + || (a == 192 && b == 0 && c == 0) + || (a == 192 && b == 0 && c == 2) + || (a == 192 && b == 168) + || (a == 198 && (b == 18 || b == 19)) + || (a == 198 && b == 51 && c == 100) + || (a == 203 && b == 0 && c == 113) + || a >= 224) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + use floatile_core::{CredentialRef, HttpTemplateDecl}; + + use super::*; + use crate::{CredentialVault, MemoryCredentialVault}; + + struct InspectTransport { + saw_secret: Arc, + } + + struct CountingTransport { + calls: Arc, + failures_before_success: usize, + } + + impl HttpTransport for CountingTransport { + fn execute( + &self, + _request: HttpTransportRequest, + ) -> Pin> + Send + 'static>> + { + let call = self.calls.fetch_add(1, Ordering::AcqRel); + let fail = call < self.failures_before_success; + Box::pin(async move { + if fail { + Err(HttpServiceError::Unavailable) + } else { + Ok(HttpResponse { + status: 200, + body: b"cached".to_vec(), + }) + } + }) + } + } + + impl HttpTransport for InspectTransport { + fn execute( + &self, + request: HttpTransportRequest, + ) -> Pin> + Send + 'static>> + { + let saw_secret = Arc::clone(&self.saw_secret); + Box::pin(async move { + saw_secret.store( + request.credential.as_bytes() == b"Bearer host-only-secret", + Ordering::Release, + ); + assert_eq!( + request.url.as_str(), + "https://api.example.com/v1/balance?account=A%26B" + ); + Ok(HttpResponse { + status: 200, + body: br#"{"balance":42}"#.to_vec(), + }) + }) + } + } + + fn template() -> HttpTemplateDecl { + HttpTemplateDecl { + id: "balance".into(), + method: "GET".into(), + url: "https://api.example.com/v1/balance".into(), + query_params: vec!["account".into()], + credential_header: "authorization".into(), + allowed_statuses: vec![200], + max_response_bytes: 4096, + timeout_ms: 2000, + cache_ttl_ms: 1000, + stale_if_error_ms: 5000, + max_retries: 1, + retry_base_delay_ms: 10, + } + } + + fn connection(health: ConnectionHealth) -> Connection { + Connection::restore( + ConnectionId(7), + "example", + "account@example.com", + CredentialRef::new("cred://example/account").unwrap(), + health, + 3, + 1, + 2, + ) + .unwrap() + } + + #[tokio::test] + async fn injects_secret_only_inside_host_transport_and_returns_typed_body() { + let vault = Arc::new(MemoryCredentialVault::default()); + vault + .put( + connection(ConnectionHealth::Healthy).credential(), + b"Bearer host-only-secret", + ) + .unwrap(); + let saw_secret = Arc::new(AtomicBool::new(false)); + let service = HttpsService::new( + vec![template()], + vec![connection(ConnectionHealth::Healthy)], + vault, + Arc::new(InspectTransport { + saw_secret: Arc::clone(&saw_secret), + }), + ); + let prepared = service + .prepare( + "balance", + ConnectionId(7), + vec![QueryParam { + name: "account".into(), + value: "A&B".into(), + }], + ) + .unwrap(); + let response = prepared.work.await.unwrap(); + assert_eq!(response.status, 200); + assert_eq!(response.body, br#"{"balance":42}"#); + assert!(saw_secret.load(Ordering::Acquire)); + assert!(!format!("{response:?}").contains("host-only-secret")); + } + + #[tokio::test] + async fn retries_transient_failure_then_serves_generation_scoped_cache() { + let vault = Arc::new(MemoryCredentialVault::default()); + let healthy = connection(ConnectionHealth::Healthy); + vault + .put(healthy.credential(), b"Bearer host-only-secret") + .unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let observed = Arc::new(Mutex::new(Vec::new())); + let health_observed = Arc::clone(&observed); + let service = HttpsService::new( + vec![template()], + vec![healthy], + vault, + Arc::new(CountingTransport { + calls: Arc::clone(&calls), + failures_before_success: 1, + }), + ) + .with_health_listener(Arc::new(move |id, health| { + lock(&health_observed).push((id, health)); + })); + let first = service + .prepare("balance", ConnectionId(7), Vec::new()) + .unwrap() + .work + .await + .unwrap(); + assert_eq!(first.body, b"cached"); + assert_eq!(calls.load(Ordering::Acquire), 2); + let second = service + .prepare("balance", ConnectionId(7), Vec::new()) + .unwrap() + .work + .await + .unwrap(); + assert_eq!(second, first); + assert_eq!(calls.load(Ordering::Acquire), 2, "第二次必须命中缓存"); + assert_eq!( + lock(&observed).as_slice(), + &[(ConnectionId(7), ConnectionHealth::Healthy)] + ); + } + + #[test] + fn rejects_ungranted_unhealthy_and_undeclared_query_without_transport() { + let vault = Arc::new(MemoryCredentialVault::default()); + let service = HttpsService::new( + vec![template()], + vec![connection(ConnectionHealth::Unavailable)], + vault, + Arc::new(InspectTransport { + saw_secret: Arc::new(AtomicBool::new(false)), + }), + ); + assert!(matches!( + service.prepare("balance", ConnectionId(8), Vec::new()), + Err(HttpServiceError::ConnectionNotGranted) + )); + assert!(matches!( + service.prepare("balance", ConnectionId(7), Vec::new()), + Err(HttpServiceError::CredentialUnavailable) + )); + + let healthy = HttpsService::new( + vec![template()], + vec![connection(ConnectionHealth::Healthy)], + Arc::new(MemoryCredentialVault::default()), + Arc::new(InspectTransport { + saw_secret: Arc::new(AtomicBool::new(false)), + }), + ); + assert!(matches!( + healthy.prepare( + "balance", + ConnectionId(7), + vec![QueryParam { + name: "token".into(), + value: "forbidden".into() + }] + ), + Err(HttpServiceError::InvalidInput) + )); + } + + #[test] + fn ssrf_filter_rejects_non_public_addresses() { + for ip in [ + "127.0.0.1", + "10.0.0.1", + "169.254.1.1", + "192.0.2.1", + "::1", + "fe80::1", + ] { + assert!(!is_public_ip(ip.parse().unwrap()), "应拒绝 {ip}"); + } + assert!(is_public_ip("1.1.1.1".parse().unwrap())); + assert!(is_public_ip("2606:4700:4700::1111".parse().unwrap())); + } +} diff --git a/crates/floatile-services/src/lib.rs b/crates/floatile-services/src/lib.rs index 141bac3..13a9436 100644 --- a/crates/floatile-services/src/lib.rs +++ b/crates/floatile-services/src/lib.rs @@ -7,7 +7,9 @@ pub mod audit; pub mod broker; pub mod clock; +pub mod credential; pub mod errors; +pub mod http; pub mod log; pub mod metrics; pub mod operation; @@ -18,7 +20,14 @@ pub mod timer; pub use audit::{AuditEvent, AuditListener, AuditSink, fnv1a}; pub use broker::Broker; pub use clock::{Clock, ClockSnapshot}; +pub use credential::{ + CredentialError, CredentialVault, MAX_CREDENTIAL_BYTES, MemoryCredentialVault, +}; pub use errors::{LogError, MetricsError, StorageError, ThemeError, TimerError}; +pub use http::{ + ConnectionHealthListener, HttpResponse, HttpServiceError, HttpTransport, HttpTransportRequest, + HttpsService, QueryParam, ReqwestHttpTransport, +}; pub use log::{LogLevel, LogService}; pub use metrics::{MemorySnapshot, MetricsService}; pub use operation::{ diff --git a/crates/floatile-shell/src/instance_supervisor.rs b/crates/floatile-shell/src/instance_supervisor.rs index 3d84175..361fe9d 100644 --- a/crates/floatile-shell/src/instance_supervisor.rs +++ b/crates/floatile-shell/src/instance_supervisor.rs @@ -8,17 +8,20 @@ use std::cell::RefCell; use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; use std::rc::Rc; +use std::sync::Arc; use std::sync::mpsc::{self, Receiver, SyncSender}; use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use floatile_core::{InstanceDesiredState, InstanceId, PluginInstance}; use floatile_platform::PlatformCapabilities; -use floatile_services::AuditListener; +use floatile_services::{AuditListener, CredentialVault, HttpsService, MemoryCredentialVault}; use slint::{Timer, TimerMode}; use crate::plugin_manager::{RunnableInstance, load_runnable_instance}; -use crate::runtime_ui::{RuntimeUiLifecycleEvent, RuntimeUiSession, spawn_runtime_ui}; +use crate::runtime_ui::{ + RuntimeUiLifecycleEvent, RuntimeUiSession, compose_instance_https, spawn_runtime_ui_with_https, +}; const POLL_INTERVAL: Duration = Duration::from_millis(500); const UI_DRAIN_INTERVAL: Duration = Duration::from_millis(50); @@ -118,7 +121,10 @@ enum DesiredAction { enum SupervisorAction { Stop(InstanceId), - Start(Box), + Start { + runnable: Box, + https: HttpsService, + }, Failure { instance_id: Option, plugin_id: Option, @@ -177,12 +183,32 @@ impl DynamicInstanceSupervisor { plugin_store: PathBuf, caps: PlatformCapabilities, audit_listener: Option, + ) -> Result { + Self::start_with_vault( + database, + plugin_store, + caps, + audit_listener, + Arc::new(MemoryCredentialVault::default()), + ) + } + + /// Start the supervisor with the process-owned credential vault used by HTTPS operations. + /// The vault handle crosses only host components and is never exposed to a guest instance. + pub fn start_with_vault( + database: PathBuf, + plugin_store: PathBuf, + caps: PlatformCapabilities, + audit_listener: Option, + vault: Arc, ) -> Result { let (action_tx, action_rx) = mpsc::sync_channel(ACTION_QUEUE_CAPACITY); let (commands, command_rx) = mpsc::sync_channel(COMMAND_QUEUE_CAPACITY); let worker = thread::Builder::new() .name("floatile-instance-supervisor".to_owned()) - .spawn(move || supervisor_worker(database, plugin_store, action_tx, command_rx))?; + .spawn(move || { + supervisor_worker(database, plugin_store, action_tx, command_rx, vault) + })?; let sessions = Rc::new(RefCell::new(BTreeMap::new())); let desired_generations = Rc::new(RefCell::new(BTreeMap::new())); @@ -264,6 +290,7 @@ fn supervisor_worker( plugin_store: PathBuf, action_tx: SyncSender>, command_rx: Receiver, + vault: Arc, ) { let store = match floatile_store::open(&database) { Ok(store) => store, @@ -301,7 +328,7 @@ fn supervisor_worker( }; let (desired, next_known) = plan_snapshot(&snapshot, &known); if !desired.is_empty() { - let actions = prepare_actions(&store, &plugin_store, desired); + let actions = prepare_actions(&store, &plugin_store, desired, Arc::clone(&vault)); if action_tx.send(actions).is_err() { break; } @@ -332,6 +359,7 @@ fn prepare_actions( store: &floatile_store::Store, plugin_store: &std::path::Path, desired: Vec, + vault: Arc, ) -> Vec { let mut prepared = Vec::with_capacity(desired.len()); for action in desired { @@ -377,9 +405,23 @@ fn prepare_actions( }; let version = instance.installation().version().to_owned(); match load_runnable_instance(plugin_store, instance) { - Ok(Some(runnable)) => { - prepared.push(SupervisorAction::Start(Box::new(runnable))) - } + Ok(Some(runnable)) => match compose_instance_https( + store, + runnable.instance.id(), + &runnable.plugin.manifest, + Arc::clone(&vault), + ) { + Ok(https) => prepared.push(SupervisorAction::Start { + runnable: Box::new(runnable), + https, + }), + Err(error) => prepared.push(SupervisorAction::Failure { + instance_id: Some(id), + plugin_id: Some(plugin_id), + code: error.code(), + detail: error.to_string(), + }), + }, Ok(None) => prepared.push(SupervisorAction::Failure { instance_id: Some(id), plugin_id: Some(plugin_id), @@ -435,7 +477,7 @@ fn apply_actions( "persistent plugin instance reconcile failed (isolated; host continues)" ); } - SupervisorAction::Start(runnable) => { + SupervisorAction::Start { runnable, https } => { let id = runnable.instance.id(); let generation = runnable.instance.generation(); let plugin_id = runnable.plugin.manifest.id.0.clone(); @@ -446,8 +488,14 @@ fn apply_actions( let task_observed = Rc::clone(observed); let task_audit = audit_listener.clone(); match slint::spawn_local(async move { - match spawn_runtime_ui(runnable.plugin, runnable.instance, caps, task_audit) - .await + match spawn_runtime_ui_with_https( + runnable.plugin, + runnable.instance, + caps, + task_audit, + Some(https), + ) + .await { Ok(session) => { if task_desired.borrow().get(&id.0) == Some(&generation) { diff --git a/crates/floatile-shell/src/runtime_ui.rs b/crates/floatile-shell/src/runtime_ui.rs index 0948272..fc900de 100644 --- a/crates/floatile-shell/src/runtime_ui.rs +++ b/crates/floatile-shell/src/runtime_ui.rs @@ -392,7 +392,9 @@ use floatile_core::manifest::Manifest; use floatile_core::types::{InstanceId, PluginId}; use floatile_plugin_api::exports::floatile::widget::widget_contract::{UiEvent, WidgetEvent}; use floatile_runtime::{WidgetConfig, WidgetManager}; -use floatile_services::{AuditEvent, AuditListener}; +use floatile_services::{ + AuditEvent, AuditListener, CredentialVault, HttpsService, ReqwestHttpTransport, +}; use crate::plugin_manager::InstalledPlugin; @@ -616,6 +618,46 @@ pub async fn spawn_runtime_ui( instance: PluginInstance, caps: PlatformCapabilities, audit_listener: Option, +) -> Result { + spawn_runtime_ui_with_https(plugin, instance, caps, audit_listener, None).await +} + +/// Compose only the Connections explicitly granted to this instance. The caller owns the vault; +/// no secret is read from SQLite or copied into plugin config/state. +pub fn compose_instance_https( + store: &floatile_store::Store, + instance: InstanceId, + manifest: &Manifest, + vault: Arc, +) -> Result { + let connection_store = store.connections(); + let grants = connection_store + .grants_for_instance(instance) + .map_err(|error| { + RuntimeUiError::Runtime(format!("读取 Connection grants 失败: {error}")) + })?; + let mut connections = Vec::with_capacity(grants.len()); + for grant in grants { + let connection = connection_store + .get(grant.connection_id) + .map_err(|error| RuntimeUiError::Runtime(format!("读取 Connection 失败: {error}")))? + .ok_or_else(|| RuntimeUiError::Runtime("Connection grant 引用不存在".to_owned()))?; + connections.push(connection); + } + Ok(HttpsService::new( + manifest.http_templates.clone(), + connections, + vault, + Arc::new(ReqwestHttpTransport), + )) +} + +pub async fn spawn_runtime_ui_with_https( + plugin: InstalledPlugin, + instance: PluginInstance, + caps: PlatformCapabilities, + audit_listener: Option, + https: Option, ) -> Result { let id = plugin.manifest.id.clone(); let (instance_id, generation, config_json) = validate_runtime_instance(&plugin, &instance)?; @@ -690,7 +732,7 @@ pub async fn spawn_runtime_ui( config_json, grants, }; - let mut handle = match manager.spawn(config) { + let mut handle = match manager.spawn_with_https(config, https) { Ok(h) => h, Err(error) => { tracing::warn!(%error, "failed to spawn runtime widget"); diff --git a/crates/floatile-shell/tests/plugin_projection.rs b/crates/floatile-shell/tests/plugin_projection.rs index a8508dd..4215a1e 100755 --- a/crates/floatile-shell/tests/plugin_projection.rs +++ b/crates/floatile-shell/tests/plugin_projection.rs @@ -23,21 +23,24 @@ fn workspace_root() -> PathBuf { } fn clock_wasm_bytes() -> Vec { + static WASM: std::sync::OnceLock> = std::sync::OnceLock::new(); + WASM.get_or_init(build_clock_wasm).clone() +} + +fn build_clock_wasm() -> Vec { let wasm_path = workspace_root().join("target/wasm32-wasip2/debug/floatile_clock_wasm.wasm"); - if !wasm_path.exists() { - let status = Command::new("cargo") - .current_dir(workspace_root()) - .args([ - "build", - "-p", - "floatile-clock-wasm", - "--target", - "wasm32-wasip2", - ]) - .status() - .expect("failed to run cargo build for clock-wasm"); - assert!(status.success(), "clock-wasm 构建失败"); - } + let status = Command::new("cargo") + .current_dir(workspace_root()) + .args([ + "build", + "-p", + "floatile-clock-wasm", + "--target", + "wasm32-wasip2", + ]) + .status() + .expect("failed to run cargo build for clock-wasm"); + assert!(status.success(), "clock-wasm 构建失败"); std::fs::read(&wasm_path).expect("读取 clock-wasm 失败") } diff --git a/crates/floatile-store/src/lib.rs b/crates/floatile-store/src/lib.rs index 24d3479..04ff52b 100644 --- a/crates/floatile-store/src/lib.rs +++ b/crates/floatile-store/src/lib.rs @@ -6,6 +6,7 @@ use std::path::Path; use floatile_core::{ + Connection as HostConnection, ConnectionGrant, ConnectionHealth, ConnectionId, CredentialRef, InstallationDigest, InstallationRef, InstanceConfig, InstanceDesiredState, InstanceId, PluginId, PluginInstance, WidgetLayout, }; @@ -27,7 +28,7 @@ pub enum StoreError { } /// 当前 schema 版本(与 migration 列表一一对应)。 -const SCHEMA_VERSION: u32 = 4; +const SCHEMA_VERSION: u32 = 5; /// 打开数据库并迁移到最新版本。 /// @@ -67,6 +68,9 @@ impl Store { if current < 4 { self.migration_v4()?; } + if current < 5 { + self.migration_v5()?; + } Ok(()) } @@ -168,6 +172,47 @@ impl Store { .map_err(|error| StoreError::Migration(format!("v4 提交失败: {error}"))) } + fn migration_v5(&mut self) -> Result<(), StoreError> { + let tx = self.conn.transaction()?; + tx.execute_batch( + "CREATE TABLE IF NOT EXISTS connections ( + connection_id INTEGER PRIMARY KEY, + provider TEXT NOT NULL, + account_identity TEXT NOT NULL, + credential_ref TEXT NOT NULL UNIQUE, + health TEXT NOT NULL CHECK ( + health IN ('unknown','healthy','degraded','unavailable','revoked') + ), + credential_generation INTEGER NOT NULL DEFAULT 0 + CHECK (credential_generation >= 0), + created_at INTEGER NOT NULL CHECK (created_at >= 0), + updated_at INTEGER NOT NULL CHECK (updated_at >= created_at) + ); + CREATE INDEX IF NOT EXISTS connections_provider + ON connections(provider); + CREATE TABLE IF NOT EXISTS connection_id_allocator ( + singleton INTEGER PRIMARY KEY CHECK (singleton = 1), + next_id INTEGER NOT NULL CHECK (next_id >= 1) + ); + INSERT OR IGNORE INTO connection_id_allocator(singleton, next_id) + VALUES (1, 1); + CREATE TABLE IF NOT EXISTS instance_connection_grants ( + instance_id INTEGER NOT NULL, + connection_id INTEGER NOT NULL, + granted_at INTEGER NOT NULL CHECK (granted_at >= 0), + PRIMARY KEY (instance_id, connection_id), + FOREIGN KEY (instance_id) REFERENCES plugin_instances(instance_id), + FOREIGN KEY (connection_id) REFERENCES connections(connection_id) + ); + CREATE INDEX IF NOT EXISTS instance_connection_grants_connection + ON instance_connection_grants(connection_id); + PRAGMA user_version = 5;", + ) + .map_err(|error| StoreError::Migration(format!("v5 建立 Connection 表失败: {error}")))?; + tx.commit() + .map_err(|error| StoreError::Migration(format!("v5 提交失败: {error}"))) + } + /// 布局存储接口。 pub fn layout(&self) -> LayoutStore<'_> { LayoutStore { conn: &self.conn } @@ -185,6 +230,199 @@ impl Store { pub fn instances(&self) -> InstanceStore<'_> { InstanceStore { conn: &self.conn } } + + /// 宿主外部数据连接及其实例授权接口。只持久化不透明 CredentialRef,不保存 secret。 + pub fn connections(&self) -> ConnectionStore<'_> { + ConnectionStore { conn: &self.conn } + } +} + +pub struct ConnectionStore<'a> { + conn: &'a Connection, +} + +impl<'a> ConnectionStore<'a> { + pub fn create( + &self, + provider: &str, + account_identity: &str, + credential: &CredentialRef, + created_at: u64, + ) -> Result { + let created_at_sql = sqlite_i64(created_at, "created_at")?; + let tx = self.conn.unchecked_transaction()?; + let id: i64 = tx.query_row( + "UPDATE connection_id_allocator SET next_id = next_id + 1 + WHERE singleton = 1 RETURNING next_id - 1", + [], + |row| row.get(0), + )?; + let model = HostConnection::restore( + ConnectionId(read_positive_id(id, "connection_id")?), + provider, + account_identity, + credential.clone(), + ConnectionHealth::Unknown, + 0, + created_at, + created_at, + ) + .map_err(|error| StoreError::Corrupt(error.to_string()))?; + tx.execute( + "INSERT INTO connections ( + connection_id, provider, account_identity, credential_ref, health, + credential_generation, created_at, updated_at + ) VALUES (?1, ?2, ?3, ?4, 'unknown', 0, ?5, ?5)", + rusqlite::params![ + id, + provider, + account_identity, + credential.as_str(), + created_at_sql + ], + )?; + tx.commit()?; + Ok(model) + } + + pub fn get(&self, id: ConnectionId) -> Result, StoreError> { + let id = sqlite_i64(id.0, "connection_id")?; + let mut statement = self.conn.prepare( + "SELECT connection_id, provider, account_identity, credential_ref, health, + credential_generation, created_at, updated_at + FROM connections WHERE connection_id = ?1", + )?; + let mut rows = statement.query(rusqlite::params![id])?; + let Some(row) = rows.next()? else { + return Ok(None); + }; + row_to_connection(row).map(Some) + } + + pub fn list(&self) -> Result, StoreError> { + let mut statement = self.conn.prepare( + "SELECT connection_id, provider, account_identity, credential_ref, health, + credential_generation, created_at, updated_at + FROM connections ORDER BY connection_id", + )?; + let mut rows = statement.query([])?; + let mut result = Vec::new(); + while let Some(row) = rows.next()? { + result.push(row_to_connection(row)?); + } + Ok(result) + } + + pub fn grant( + &self, + instance_id: InstanceId, + connection_id: ConnectionId, + granted_at: u64, + ) -> Result { + let changed = self.conn.execute( + "INSERT OR IGNORE INTO instance_connection_grants + (instance_id, connection_id, granted_at) + SELECT ?1, ?2, ?3 + WHERE EXISTS (SELECT 1 FROM plugin_instances WHERE instance_id = ?1) + AND EXISTS (SELECT 1 FROM connections WHERE connection_id = ?2)", + rusqlite::params![ + sqlite_i64(instance_id.0, "instance_id")?, + sqlite_i64(connection_id.0, "connection_id")?, + sqlite_i64(granted_at, "granted_at")?, + ], + )?; + Ok(changed == 1) + } + + pub fn revoke( + &self, + instance_id: InstanceId, + connection_id: ConnectionId, + ) -> Result { + let changed = self.conn.execute( + "DELETE FROM instance_connection_grants + WHERE instance_id = ?1 AND connection_id = ?2", + rusqlite::params![ + sqlite_i64(instance_id.0, "instance_id")?, + sqlite_i64(connection_id.0, "connection_id")?, + ], + )?; + Ok(changed == 1) + } + + pub fn grants_for_instance( + &self, + instance_id: InstanceId, + ) -> Result, StoreError> { + let mut statement = self.conn.prepare( + "SELECT instance_id, connection_id, granted_at + FROM instance_connection_grants WHERE instance_id = ?1 ORDER BY connection_id", + )?; + let mut rows = + statement.query(rusqlite::params![sqlite_i64(instance_id.0, "instance_id")?])?; + let mut grants = Vec::new(); + while let Some(row) = rows.next()? { + grants.push(ConnectionGrant { + instance_id: InstanceId(read_u64(row, 0, "instance_id")?), + connection_id: ConnectionId(read_u64(row, 1, "connection_id")?), + granted_at: read_u64(row, 2, "granted_at")?, + }); + } + Ok(grants) + } + + pub fn rotate_credential( + &self, + id: ConnectionId, + credential: &CredentialRef, + updated_at: u64, + ) -> Result { + let changed = self.conn.execute( + "UPDATE connections + SET credential_ref = ?1, credential_generation = credential_generation + 1, + health = 'unknown', updated_at = ?2 + WHERE connection_id = ?3 AND updated_at <= ?2 + AND credential_generation < 9223372036854775807", + rusqlite::params![ + credential.as_str(), + sqlite_i64(updated_at, "updated_at")?, + sqlite_i64(id.0, "connection_id")?, + ], + )?; + Ok(changed == 1) + } + + /// Persist the latest host-observed health without allowing stale probes to overwrite newer + /// state. Secret or provider error text is intentionally not accepted by this API. + pub fn set_health( + &self, + id: ConnectionId, + health: ConnectionHealth, + updated_at: u64, + ) -> Result { + let changed = self.conn.execute( + "UPDATE connections SET health = ?1, updated_at = ?2 + WHERE connection_id = ?3 AND updated_at <= ?2", + rusqlite::params![ + health.as_str(), + sqlite_i64(updated_at, "updated_at")?, + sqlite_i64(id.0, "connection_id")?, + ], + )?; + Ok(changed == 1) + } + + /// 只有无实例引用时才能删除 Connection,避免破坏共享连接。 + pub fn delete_unreferenced(&self, id: ConnectionId) -> Result { + let changed = self.conn.execute( + "DELETE FROM connections WHERE connection_id = ?1 + AND NOT EXISTS ( + SELECT 1 FROM instance_connection_grants WHERE connection_id = ?1 + )", + rusqlite::params![sqlite_i64(id.0, "connection_id")?], + )?; + Ok(changed == 1) + } } /// 持久化插件实例 CRUD。 @@ -353,6 +591,10 @@ impl<'a> InstanceStore<'a> { pub fn delete(&self, instance_id: InstanceId) -> Result { let instance_id = sqlite_i64(instance_id.0, "instance_id")?; let tx = self.conn.unchecked_transaction()?; + tx.execute( + "DELETE FROM instance_connection_grants WHERE instance_id = ?1", + rusqlite::params![instance_id], + )?; let changed = tx.execute( "DELETE FROM plugin_instances WHERE instance_id = ?1", rusqlite::params![instance_id], @@ -582,6 +824,36 @@ fn row_to_instance(row: &rusqlite::Row<'_>) -> Result) -> Result { + let id = ConnectionId(read_u64(row, 0, "connection_id")?); + let provider = row.get::<_, String>(1)?; + let account_identity = row.get::<_, String>(2)?; + let credential = CredentialRef::new(row.get::<_, String>(3)?) + .map_err(|error| StoreError::Corrupt(error.to_string()))?; + let health = ConnectionHealth::parse(&row.get::<_, String>(4)?) + .map_err(|error| StoreError::Corrupt(error.to_string()))?; + HostConnection::restore( + id, + provider, + account_identity, + credential, + health, + read_u64(row, 5, "credential_generation")?, + read_u64(row, 6, "created_at")?, + read_u64(row, 7, "updated_at")?, + ) + .map_err(|error| StoreError::Corrupt(error.to_string())) +} + +fn read_positive_id(value: i64, field: &str) -> Result { + let value = + u64::try_from(value).map_err(|_| StoreError::Corrupt(format!("{field} 不得为负数")))?; + if value == 0 { + return Err(StoreError::Corrupt(format!("{field} 不得为 0"))); + } + Ok(value) +} + fn sqlite_i64(value: u64, field: &'static str) -> Result { i64::try_from(value) .map_err(|_| StoreError::Corrupt(format!("{field} 超出 SQLite INTEGER 范围: {value}"))) @@ -1243,6 +1515,217 @@ mod tests { )); } + fn credential(name: &str) -> CredentialRef { + CredentialRef::new(format!("cred://openai/{name}")).unwrap() + } + + fn v4_store() -> Store { + let conn = Connection::open_in_memory().unwrap(); + let mut store = Store { conn }; + store.migration_v1().unwrap(); + store.migration_v2().unwrap(); + store.migration_v3().unwrap(); + store.migration_v4().unwrap(); + store + } + + #[test] + fn migration_v5_failure_rolls_back_connection_allocator_and_version() { + let mut store = v4_store(); + store + .conn + .execute_batch("CREATE TABLE connections (broken INTEGER);") + .unwrap(); + + assert!(matches!(store.migrate(), Err(StoreError::Migration(_)))); + let version: u32 = store + .conn + .query_row("PRAGMA user_version", [], |row| row.get(0)) + .unwrap(); + assert_eq!(version, 4); + let allocator_exists: u32 = store + .conn + .query_row( + "SELECT COUNT(*) FROM sqlite_master + WHERE type = 'table' AND name = 'connection_id_allocator'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(allocator_exists, 0); + } + + #[test] + fn connection_grants_are_instance_scoped_and_shared_connection_survives_deletion() { + let store = open(":memory:").unwrap(); + let first = store + .instances() + .create( + &installation(), + &config("first"), + InstanceDesiredState::Stopped, + 100, + ) + .unwrap(); + let second = store + .instances() + .create( + &installation(), + &config("second"), + InstanceDesiredState::Stopped, + 100, + ) + .unwrap(); + let connection = store + .connections() + .create("openai", "account@example.com", &credential("primary"), 100) + .unwrap(); + + assert!( + store + .connections() + .grant(first.id(), connection.id(), 101) + .unwrap() + ); + assert!( + store + .connections() + .grant(second.id(), connection.id(), 102) + .unwrap() + ); + assert!( + !store + .connections() + .grant(second.id(), connection.id(), 103) + .unwrap() + ); + assert!( + !store + .connections() + .delete_unreferenced(connection.id()) + .unwrap() + ); + + assert!(store.instances().delete(first.id()).unwrap()); + assert!( + store + .connections() + .grants_for_instance(first.id()) + .unwrap() + .is_empty() + ); + assert_eq!( + store + .connections() + .grants_for_instance(second.id()) + .unwrap() + .len(), + 1 + ); + assert!(store.connections().get(connection.id()).unwrap().is_some()); + assert!( + store + .connections() + .revoke(second.id(), connection.id()) + .unwrap() + ); + assert!( + store + .connections() + .delete_unreferenced(connection.id()) + .unwrap() + ); + } + + #[test] + fn credential_rotation_only_persists_reference_and_advances_generation() { + let store = open(":memory:").unwrap(); + let connection = store + .connections() + .create("openai", "account", &credential("old"), 100) + .unwrap(); + assert!( + store + .connections() + .rotate_credential(connection.id(), &credential("new"), 110) + .unwrap() + ); + assert!( + !store + .connections() + .rotate_credential(connection.id(), &credential("stale"), 109) + .unwrap() + ); + let restored = store.connections().get(connection.id()).unwrap().unwrap(); + assert_eq!(restored.credential().as_str(), "cred://openai/new"); + assert_eq!(restored.credential_generation(), 1); + assert_eq!(restored.health(), ConnectionHealth::Unknown); + + let columns: Vec = store + .conn + .prepare("PRAGMA table_info(connections)") + .unwrap() + .query_map([], |row| row.get(1)) + .unwrap() + .collect::>() + .unwrap(); + assert!(!columns.iter().any(|column| column.contains("secret"))); + } + + #[test] + fn connection_health_rejects_stale_probe_updates() { + let store = open(":memory:").unwrap(); + let connection = store + .connections() + .create("openai", "account", &credential("health"), 100) + .unwrap(); + assert!( + store + .connections() + .set_health(connection.id(), ConnectionHealth::Healthy, 120) + .unwrap() + ); + assert!( + !store + .connections() + .set_health(connection.id(), ConnectionHealth::Unavailable, 119) + .unwrap() + ); + let restored = store.connections().get(connection.id()).unwrap().unwrap(); + assert_eq!(restored.health(), ConnectionHealth::Healthy); + assert_eq!(restored.updated_at(), 120); + } + + #[test] + fn connection_grant_rejects_unknown_instance_or_connection() { + let store = open(":memory:").unwrap(); + let instance = store + .instances() + .create( + &installation(), + &config("known"), + InstanceDesiredState::Stopped, + 100, + ) + .unwrap(); + let connection = store + .connections() + .create("openai", "account", &credential("known"), 100) + .unwrap(); + assert!( + !store + .connections() + .grant(InstanceId(999), connection.id(), 100) + .unwrap() + ); + assert!( + !store + .connections() + .grant(instance.id(), ConnectionId(999), 100) + .unwrap() + ); + } + #[test] fn audit_persists_across_reopen() { let path = TempDb::new(); diff --git a/docs/architecture/decisions/0005-connection-bound-https-templates.md b/docs/architecture/decisions/0005-connection-bound-https-templates.md new file mode 100644 index 0000000..1fa69f8 --- /dev/null +++ b/docs/architecture/decisions/0005-connection-bound-https-templates.md @@ -0,0 +1,49 @@ +# ADR-0005:Connection 绑定的 HTTPS 请求模板 + +> 状态:Accepted +> 日期:2026-08-27 +> 关联:PP-M5、PP-G1、PP-G2、PP-G3、PP-G4、PP-G5 + +## 背景 + +PP-M5 需要让 guest 获取外部数据,但不得获得 ambient socket、DNS、TLS、原始凭证或任意 URL 能力。 +现有 HTTP Broker 提案要求静态请求模板,PP-M3 则要求 Capability Registry 使用有限稳定 ID;若把每个 +origin 编码成动态 capability 名,manifest schema、WIT、Broker 和作者工具将重新出现无法穷举的权限语义。 +此外,ADR-0004 要求网络使用宿主 Operation,不能增加阻塞式 guest import 或通用 JSON-RPC。 + +## 决策 + +1. Capability Registry 新增固定能力 `network:https`,其参数包含规范化的精确 HTTPS origin、每分钟 + 请求数、单响应字节上限与最长 timeout。V1 不支持通配 origin、裸 IP、localhost、私网或非 HTTPS。 +2. manifest v1 以向后兼容的可选 `httpTemplates` 数组声明请求模板。每项包含稳定 template ID、固定 + method、固定 HTTPS URL(origin + path)、允许的 query 参数名、credential header 名、允许状态码、 + `maxBytes` 与 `timeoutMs`。模板不得包含 secret、URL userinfo、fragment 或运行时可变 host/path。 +3. 插件提交请求时只提供 template ID、一个已授予当前实例的 `connection-id` 和有界 query 参数键值。 + `connection-id` 可猜测但不可伪造授权:Broker 必须在同一 submit 入口重新读取实例 grant、Connection + health、credential generation 和 `network:https` origin scope。 +4. Connection 的 `CredentialRef` 只在宿主组合层解析。Broker 从 CredentialVault 借用 secret 并注入 + 模板指定 header;guest、Operation completion、审计、日志、State、Config、SQLite 和响应错误均不得 + 包含 secret 或完整 header/query/body。 +5. HTTPS 通过 ADR-0004 typed Operation 暴露:`submit` 立即返回 operation ID,completion 只含终态, + `take-result` 一次性返回有界 status/body。WIT 不暴露 header、socket、DNS 或 TLS 配置。 +6. V1 初始切片禁用自动 redirect。后续支持 redirect 时,每一 hop 必须重新执行 scheme/origin/DNS/ + 私网校验并剥离凭证;不得启用客户端默认 redirect。 +7. DNS 解析结果在连接前拒绝全部非公网地址,并固定连接到已验证 IP,同时保留原 host 进行 TLS SNI 和 + 证书校验。无法安全固定解析结果时返回 `unavailable`,不得退回客户端二次解析。 +8. 网络配额由 Broker 按实例维护;缓存、重试和调度只能调用同一模板 submit 路径,不得拥有绕过授权 + 的内部 HTTP 执行入口。权限撤销、Connection 轮换或 generation 变化使旧结果不可投递。 + +## 后果 + +- 新 provider 通常只需增加插件模板与 Connection 配置,不需要宿主专用 API。 +- manifest/WIT/SDK/Capability Registry 将发生一次联动版本演进,但保持单一事实源和类型化结果。 +- 初始版本有意限制动态 REST 客户端能力;需要可变路径、POST body 或分页时,应扩展模板 schema 和 + contract vectors,而不是向 guest 暴露自由 URL。 +- 平台 Keyring 不可用时 Connection 显式 unavailable;会话 vault 只支持开发和确定性测试。 + +## 验证要求 + +- contract vectors 覆盖允许请求,以及未授权 Connection/origin、未知模板、非法 query、私网解析、 + redirect、超时、取消、响应过大、限流、凭证缺失/轮换和旧 generation 丢弃。 +- 恶意 fixture 必须证明 secret 不进入 guest、completion、错误、审计、日志、State、Config 或包。 +- AI Balance Monitor 只能消费通用 Connection、HTTPS Operation、调度和缓存能力。 diff --git a/docs/architecture/workspace-and-crates.md b/docs/architecture/workspace-and-crates.md index 0f11b4d..cd3a28a 100644 --- a/docs/architecture/workspace-and-crates.md +++ b/docs/architecture/workspace-and-crates.md @@ -121,6 +121,9 @@ S5a 已实现:IR 类型、组件 registry v1、State/Event schema 模型与校 - Timer/Storage/Metrics/Theme/Clock/Log capability 的实现。 - 固有能力和声明能力使用同一 Broker 入口;固有能力只是固定 grant/scope。 - 后续 Notification/Keyring/HTTP 仍必须经 Broker;P0 不留可调用 stub 假装实现。 +- PP-M5 已建立 `CredentialVault` 宿主接口和有界进程内会话实现:secret 不可序列化、Debug、Clone 或 + 枚举,只能在宿主闭包内短暂借用,替换/删除时清零内存;平台持久 Keyring 尚未接入,不得把会话 + vault 表述为跨重启凭证存储。 - ADR-0004 Operation registry 拥有有界提交/完成队列、并发许可、deadline、取消和 typed one-shot result;原始 submit/cancel/take 仅 Broker 可见,避免 runtime 或 adapter 分离 authorize/execute。 - S5b 已实现:Broker 决策/配额/脱敏审计(target `floatile::audit`)与七个能力服务; @@ -129,7 +132,8 @@ S5a 已实现:IR 类型、组件 registry v1、State/Event schema 模型与校 ### 3.8 `floatile-store` - SQLite open/migration/transaction。 -- 当前 v4 持久化 layout、plugin instance 和 audit_log;plugin private KV 尚未接入 SQLite。 +- 当前 v5 持久化 layout、plugin instance、audit_log、宿主 Connection 元数据和实例级 Connection grant; + SQLite 只保存不透明 `CredentialRef`,不保存 secret;plugin private KV 尚未接入 SQLite。 - 实例 CRUD 负责不复用 ID、Config/时间戳复验和删除实例所有的布局;Installation 内容仍由 原子安装目录与 `install.json` digest 管理。 - 不做 permission 决策,不向 plugin 暴露连接/SQL/path。 diff --git a/docs/plugin-sdk/manifest-v1.md b/docs/plugin-sdk/manifest-v1.md index b53912a..29496fa 100644 --- a/docs/plugin-sdk/manifest-v1.md +++ b/docs/plugin-sdk/manifest-v1.md @@ -37,7 +37,7 @@ manifest 是安装与运行时的显式事实,不是开发者主要编辑界 "id": "dev.floatile", "name": "Floatile Labs" }, - "engineApiVersion": "1.1.0", + "engineApiVersion": "1.2.0", "uiApiVersion": "1.0.0", "type": "widget", "entrypoints": { @@ -88,6 +88,7 @@ manifest 是安装与运行时的显式事实,不是开发者主要编辑界 | `entrypoints.logic` | 是 | 规范相对路径,指向 WASM Component | | `sizes` | 是 | 有限正逻辑像素;default 在 min/max 内 | | `permissions` | 是 | 可以为空;未知 capability 或非法 params 拒绝 | +| `httpTemplates` | 否 | 固定 HTTPS GET 模板;origin/响应/超时预算不得超过 `network:https` | | `config.schema` | 否 | 包内规范路径;缺省表示无用户配置;只允许当前 schema 文档内 fragment 引用 | | `storage.migrationVersion` | 否 | 非负整数;只描述插件私有 KV 迁移 | | `build` | 否 | 诊断元数据,不参与信任/授权 | @@ -121,6 +122,14 @@ error;声明但未使用为 warning;CLI 不自动扩大权限。 ## 4. 权限对象 +PP-M5 的 `network:https` 使用精确 HTTPS origin 白名单,并绑定速率、最大响应和超时预算。 +`httpTemplates` 固定 URL、credential header(仅 `authorization`/`x-api-key`)、允许状态码及 query +参数名。guest 只能提交模板 ID、获授权的 Connection ID 和已声明 query;secret 不得进入 manifest、 +config、State、WIT 参数、SQLite、日志、审计或错误。 +模板还可声明 `cacheTtlMs`、`staleIfErrorMs`、`maxRetries`(最多 2)和 +`retryBaseDelayMs`;缓存键包含 Connection credential generation,轮换后不会复用旧响应。只有瞬时 +transport failure 会重试,权限、模板、响应校验和凭证错误不会重试。 + ```json { "capability": "storage:write", diff --git a/docs/plugin-sdk/wit-api-v1.md b/docs/plugin-sdk/wit-api-v1.md index efc8146..24e6e50 100644 --- a/docs/plugin-sdk/wit-api-v1.md +++ b/docs/plugin-sdk/wit-api-v1.md @@ -7,16 +7,20 @@ ## 0. 当前实现与迁移门 -`wit/floatile-widget.wit@1.1.0`、`floatile-sdk` guest bindings、`floatile-plugin-api` host async +`wit/floatile-widget.wit@1.2.0`、`floatile-sdk` guest bindings、`floatile-plugin-api` host async bindings 与 `plugins/clock-wasm` 已迁移到 ADR-0001 目标契约形状:包含 `host-ui`/`host-clock`、canonical initial State、统一 `start/handle-event/stop` lifecycle 与稳定 `widget-error`。host/guest 均从 `wit/` 单一源生成,engine version 一致,clock fixture 通过 `wasm-tools validate`,验证了 stable Rust、 wit-bindgen、Wasmtime bindgen 与 Component 构建链路。 -项目尚未对外分发插件,现有 `1.1.0` 不是发布兼容承诺。`floatile-runtime` 已实现 Wasmtime adapter, +项目尚未对外分发插件,现有 `1.2.0` 不是发布兼容承诺。`floatile-runtime` 已实现 Wasmtime adapter, 全部宿主能力经 `PermissionBroker`;clock/evil fixture 覆盖 lifecycle、State Patch、拒绝和宿主存活。 v1.1 增加 `host-operation`、`storage.submit-get/take-get-result` 与 `operation-completed`,验证 typed one-shot result 从真实 guest 往返,且完成事件不携带 payload。 +v1.2 增加 `host-http.submit/take-result`;guest 只传模板、Connection 与有界 query,请求构造、 +credential 注入和网络执行仍属于 Permission Broker。 +Rust 作者层对应 `ctx.http().submit(...)` 与 `ctx.http().take_result(...)`;调度继续使用有界的一次性 +`ctx.timer()`,参考插件不会获得 socket、URL 或 credential 句柄。 ## 1. v1 目标 @@ -41,6 +45,7 @@ WIT 只负责 WASM plugin 与 host 的跨边界调用。UI 结构由 `widget.ftu | `host-clock` | `ctx.clock` | 固有只读能力;不暴露系统句柄 | 必须 | | `host-timer` | `ctx.timer` | `timer:schedule` | 必须 | | `host-storage` | `ctx.storage` | `storage:read/write` | 必须 | +| `host-http` | `ctx.http` | `network:https` | 必须 | | `host-metrics` | `ctx.metrics` | `system:cpu/memory` | 必须 | | `host-theme` | `ctx.theme` | `theme:subscribe` | 必须 | | `widget-contract` | `Widget` lifecycle | host 调 guest export | 必须 | @@ -54,7 +59,7 @@ WIT 只负责 WASM plugin 与 host 的跨边界调用。UI 结构由 `widget.ftu bindings、runtime adapter、版本和 contract tests。 ```wit -package floatile:widget@1.1.0; +package floatile:widget@1.2.0; interface host-ui { variant ui-error { diff --git a/docs/product/plugin-platform-roadmap.md b/docs/product/plugin-platform-roadmap.md index ab36b0e..d2d001a 100644 --- a/docs/product/plugin-platform-roadmap.md +++ b/docs/product/plugin-platform-roadmap.md @@ -171,7 +171,7 @@ exit code。生成项目必须只依赖可获得的 SDK,并能从干净目录 | PP-M2 | Broker 化异步 Operation | 已完成(自动化契约验证) | ADR-0004;operation registry、队列、取消、deadline、generation、v1.1 WIT/SDK、元数据 completion 与首个 `storage:read` typed adapter | reference fixture 覆盖成功、拒绝、超时、取消、迟到结果、实例重启和过载;host/guest contract vectors 通过 | `core`、`runtime`、`services`、WIT、SDK | | PP-M3 | Capability Registry 单源 | 已完成(自动化契约验证) | 统一 capability 元数据,生成/校验 manifest、Broker、SDK 映射与 contract vectors | 注册表/WIT/manifest/CLI/Broker 动态覆盖测试;恶意插件和配额测试证明默认拒绝 | `core`、`services`、plugin API、SDK、CLI | | PP-M4 | Rust 作者闭环 | 已完成(自动化契约与 Xvfb 验证;公开发布受许可门阻断) | 可发布方式待许可决定的 SDK 解析、生成模板修复、dev/test/preview/build/install/run/inspect | 干净目录中的示例插件无需仓库私有路径即可完成全流程;JSON 契约有测试 | SDK、CLI、runtime、shell、docs | -| PP-M5 | 外部数据平台 | 规划中 | Connection、Credential Vault、HTTPS Broker、调度、缓存、重试、限流和连接健康状态 | AI 余额参考插件只使用通用能力,且 secret 不进入 guest、日志、State 或包 | `core`、`store`、`services`、shell、WIT、SDK | +| PP-M5 | 外部数据平台 | 已完成(自动化契约验证) | Connection、Credential Vault、HTTPS Broker、调度、缓存、重试、限流和连接健康状态 | AI 余额参考插件只使用通用能力,且 secret 不进入 guest、日志、State 或包 | `core`、`store`、`services`、shell、WIT、SDK | | PP-M6 | UI 平台 | 规划中 | loading/empty/error、列表/网格、badge、progress、sparkline/chart、主题与响应式布局 | 参考插件无需第三方 Slint/HTML 即可表达监控型 UI;预算和无障碍语义有契约 | UI schema、renderer、SDK、shell | | PP-M7 | SDK 与语言生态 | 规划中 | Rust API 稳定化;在工具链可行后接入 TypeScript;生成文档、迁移指南和 conformance kit | 双语言通过相同 contract vectors、恶意输入和端到端示例;不存在宿主语义分叉 | SDK、plugin API、CLI、CI | | PP-M8 | 分发与信任 | 规划中 | publisher/signing、来源与信任、权限 diff、兼容性解析、更新/回滚和可恢复安装 | 安装与升级能解释权限变化和失败原因;篡改/降级/回滚路径有测试 | CLI、core、store、shell、distribution | @@ -180,7 +180,7 @@ exit code。生成项目必须只依赖可获得的 SDK,并能从干净目录 ### 7.1 当前基线与最近顺序 -截至 2026-08-26,仓库已具备统一 UI IR、WIT 形状、Wasmtime actor、基础 capability 类型与 Broker、 +截至 2026-08-27,仓库已具备统一 UI IR、WIT 形状、Wasmtime actor、基础 capability 类型与 Broker、 部分宿主服务、Rust SDK、包校验/安装和第三方运行时窗口等基础。PP-M1 已打通自动化的 持久多实例生命周期:`floatile instance` 提供创建、枚举、读取、配置、启停和删除; CLI 与 shell 共用安装目录 digest/身份/Config schema 复验;shell 后台监督器在不阻塞 Slint @@ -207,7 +207,12 @@ Config Schema 表单、observed 状态和手动 retry;Linux X11/Xvfb 已自动 输出 State/audit 计数。自动化验收已在同一干净目录串行通过 `new → check → test → dev --once → preview → build → install → run → inspect`,全部自动化输出为 schema v1,三个窗口阶段使用 Xvfb 真实宿主; -- 网络、Connection 与凭证托管尚未成为可用契约; +- PP-M5 已建立宿主拥有的 Connection/CredentialRef、SQLite v5、会话 Credential Vault、typed HTTPS + Operation、静态模板、SSRF/DNS pinning、限流、generation-scoped cache、retry/backoff、健康状态更新 + 和 AI 余额参考插件;常驻实例监督器只组合实例显式授权的 Connection,并将 HTTPS service 传入 + runtime。包扫描、host/guest 契约、Broker 恶意路径及全 workspace 门禁证明 secret 不进入 guest、日志、 + State 或包。平台 Keyring、完整连接管理产品入口和真实 provider 人工网络证据属于后续增强与环境证据, + 不改变 PP-M5 通用能力退出门的完成状态; - TypeScript runtime 的 ADR-0003 spike 结论是 no-go,不能把语言目标标记为完成; - 设置、连接管理、权限解释和开发诊断还没有完整产品入口。 diff --git a/docs/security/http-broker.md b/docs/security/http-broker.md index 407fe4a..79cfe3e 100644 --- a/docs/security/http-broker.md +++ b/docs/security/http-broker.md @@ -1,8 +1,7 @@ # HTTP Broker 设计 -> 状态:Proposed -> 阶段:V1 实现目标。P0/MVP 不实现网络能力(WIT 中无对应接口 = 无攻击面)。 -> 本设计先行冻结,确保 V1 不会因“便利”绕过安全约束。 +> 状态:Accepted(ADR-0005;初始 V1 禁用自动 redirect) +> 阶段:PP-M5 已实现首个 HTTPS GET 纵向切片;WebSocket、redirect 和 localhost 仍不实现。 ## 1. 目标 @@ -14,6 +13,10 @@ ## 2. 请求模板(Request Template) +规范性契约由 ADR-0005 冻结:模板进入 manifest v1 的可选 `httpTemplates`,调用时由已授权 +`connection-id` 选择宿主 CredentialRef。本文示例中的 `fromCredential` 是早期设计草图,不再表示 +插件包可指定宿主凭证路径;实现与测试以 ADR-0005 为准。 + 插件不是「自由填 URL」,而是**注册模板**,宿主校验后绑定到 `network:` 权限: ```json @@ -53,7 +56,7 @@ request(template_id, params) ## 4. 域名白名单 -- 权限声明形式:`network:https://api.example.com/*`、`network:https://*.example.com/*`、`network:websocket:wss://stream.example.com/*`。 +- 当前权限声明为 `network:https`,参数使用精确 HTTPS origin 数组;不接受通配域和裸 IP。 - 匹配规则: - 精确 host 或单层通配 `*.`; - **禁止**裸 IP、`localhost`(需单独 `network:localhost` 授权)、公共后缀通配; @@ -87,6 +90,10 @@ request(template_id, params) - 模板引用 `fromCredential` 时,Broker 注入;插件拿到的永远是「已注入的请求」,读不到原始值。 - Keyring 不可用(如 Linux 无 Secret Service)→ 降级为宿主管理的加密文件凭证库(显式 opt-in),或拒绝网络能力。 +当前 PP-M5 基线已实现宿主 `CredentialVault` 接口与不落盘的会话 vault,用于 Broker 组合和确定性 +安全测试。它不支持跨宿主重启:平台 Keyring 未接入时,重启后的 Connection 必须显式报告 +`unavailable`,不得从 Config、State、环境变量或普通 SQLite 表恢复 secret。 + ## 9. 审计(脱敏) - 记录:时间、plugin_id、instance_id、template_id、method、origin(域名级)、status、bytes、duration、decision。 @@ -98,8 +105,9 @@ request(template_id, params) - 模板注册本身也是一次授权操作(审计 + 可在权限中心查看/撤销)。 - 撤销权限 → 已注册模板失效,无需插件配合。 -## 11. 未决问题 +## 11. 当前实现边界 1. 是否允许插件自定义非敏感 header 的**值**(模板内固定 vs 运行时可传)。倾向:非敏感且白名单内 header 允许运行时传值,敏感 header 只允许 fromCredential。 2. WebSocket 心跳/重连的归属(宿主负责,插件只订阅事件)。 -3. 缓存响应是否引入(倾向:V1 不做服务端缓存,减少攻击面)。 +3. PP-M5 已加入有界 generation-scoped cache、stale-if-error 和仅瞬时错误 retry;缓存不含 secret, + credential generation 轮换会自然隔离旧条目。 diff --git a/docs/security/permission-model.md b/docs/security/permission-model.md index 523dcd5..871e23f 100644 --- a/docs/security/permission-model.md +++ b/docs/security/permission-model.md @@ -41,7 +41,7 @@ P0/MVP 最小集: | `clipboard:read/write` | 剪贴板(V1+) | — | 需显式授权 | | `launcher:open-url` | 打开 URL(V1+) | `schemes: [https]`;域名白名单 | — | | `launcher:open-approved-app` | 打开已批准应用(V1+) | 应用路径白名单 | — | -| `network:https:///*` | 受控 HTTP(V1+,经 HTTP Broker) | 域名模式 | — | +| `network:https` | 受控 HTTPS(PP-M5,经 HTTP Broker) | 精确 HTTPS origin + 速率/响应/超时预算 | L2 | | `network:websocket:wss:///*` | 受控 WebSocket(V1+) | 域名模式 | — | | `network:localhost` | 本地回环访问(单独授权) | — | 高危,需二次确认 | | `file:read:user-selected` | 读用户显式选择的文件(V1+) | 文件范围 | 仅会话内 | diff --git a/plugins/ai-balance-wasm/Cargo.toml b/plugins/ai-balance-wasm/Cargo.toml new file mode 100644 index 0000000..b4f8f7a --- /dev/null +++ b/plugins/ai-balance-wasm/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "floatile-ai-balance-wasm" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[[bin]] +name = "build_ftui" +required-features = ["build-host"] + +[features] +build-host = [] + +[lints] +workspace = true + +[dependencies] +floatile-sdk = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/plugins/ai-balance-wasm/floatile.toml b/plugins/ai-balance-wasm/floatile.toml new file mode 100644 index 0000000..4b286f7 --- /dev/null +++ b/plugins/ai-balance-wasm/floatile.toml @@ -0,0 +1,33 @@ +[plugin] +id = "dev.floatile.ai-balance" +name = "AI Balance Monitor" +version = "0.1.0" + +[widget] +default_size = [280, 140] +min_size = [220, 100] +max_size = [600, 300] + +[permissions.timer] +max_per_minute = 6 +max_active = 1 + +[permissions.httpTemplates] +origins = ["https://api.example.com"] +max_requests_per_minute = 6 +max_response_bytes = 16384 +max_timeout_ms = 5000 + +[[httpTemplates]] +id = "balance" +method = "GET" +url = "https://api.example.com/v1/balance" +queryParams = [] +credentialHeader = "authorization" +allowedStatuses = [200] +maxResponseBytes = 16384 +timeoutMs = 5000 +cacheTtlMs = 60000 +staleIfErrorMs = 300000 +maxRetries = 2 +retryBaseDelayMs = 250 diff --git a/plugins/ai-balance-wasm/src/bin/build_ftui.rs b/plugins/ai-balance-wasm/src/bin/build_ftui.rs new file mode 100644 index 0000000..6f6659e --- /dev/null +++ b/plugins/ai-balance-wasm/src/bin/build_ftui.rs @@ -0,0 +1,3 @@ +fn main() { + println!("{}", floatile_ai_balance_wasm::__floatile_ftui_json()); +} diff --git a/plugins/ai-balance-wasm/src/lib.rs b/plugins/ai-balance-wasm/src/lib.rs new file mode 100644 index 0000000..fdabaa2 --- /dev/null +++ b/plugins/ai-balance-wasm/src/lib.rs @@ -0,0 +1,115 @@ +//! PP-M5 reference widget: a secret-free AI balance monitor using only generic host capabilities. + +#[cfg(target_arch = "wasm32")] +use floatile_sdk::impl_export_widget; +use floatile_sdk::{ + Context, FromWidgetEvent, OperationCapability, OperationTerminal, State, Widget, WidgetEvent, + host_http, view, view::View, +}; +use serde::{Deserialize, Serialize}; + +const CONNECTION_ID: u64 = 1; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, State)] +pub struct BalanceState { + pub balance: String, + pub status: String, +} + +#[derive(Debug)] +pub enum BalanceEvent { + Refresh, + Completed(u64, OperationTerminal), +} + +impl FromWidgetEvent for BalanceEvent { + fn from_widget_event(event: WidgetEvent) -> Option { + match event { + WidgetEvent::Timer(_) => Some(Self::Refresh), + WidgetEvent::OperationCompleted(completion) + if completion.capability == OperationCapability::HttpsRequest => + { + Some(Self::Completed(completion.id, completion.terminal)) + } + _ => None, + } + } +} + +#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +#[derive(Default)] +struct AiBalance; + +impl AiBalance { + fn refresh(&self, ctx: &mut Context) { + match ctx.http().submit("balance", CONNECTION_ID, &[]) { + Ok(_) => { + let _ = ctx.state().update(r#"{"status":"loading"}"#); + } + Err(_) => { + let _ = ctx.state().update(r#"{"status":"unavailable"}"#); + } + } + let _ = ctx.timer().schedule(60_000); + } +} + +impl Widget for AiBalance { + type State = BalanceState; + type Event = BalanceEvent; + + fn view(_state: &Self::State) -> View { + view::column(vec![ + view::text_bind("$.balance"), + view::text_bind("$.status"), + ]) + } + + fn start(&mut self, ctx: &mut Context) { + self.refresh(ctx); + } + + fn event(&mut self, event: BalanceEvent, ctx: &mut Context) { + match event { + BalanceEvent::Refresh => self.refresh(ctx), + BalanceEvent::Completed(id, OperationTerminal::Succeeded) => { + match ctx.http().take_result(id) { + Ok(response) => update_balance(ctx, response), + Err(_) => { + let _ = ctx.state().update(r#"{"status":"unavailable"}"#); + } + } + } + BalanceEvent::Completed(_, _) => { + let _ = ctx.state().update(r#"{"status":"unavailable"}"#); + } + } + } + + fn stop(&mut self) {} +} + +fn update_balance(ctx: &mut Context, response: host_http::HttpResponse) { + let parsed = serde_json::from_slice::(&response.body); + let balance = parsed + .ok() + .and_then(|value| value.get("balance").cloned()) + .map(|value| value.to_string()); + match balance { + Some(balance) => { + let patch = serde_json::json!({ "balance": balance, "status": "ok" }); + let _ = ctx.state().update(&patch.to_string()); + } + None => { + let _ = ctx.state().update(r#"{"status":"invalid-response"}"#); + } + } +} + +#[cfg(target_arch = "wasm32")] +impl_export_widget!(AiBalance); + +#[cfg(not(target_arch = "wasm32"))] +pub fn __floatile_ftui_json() -> String { + floatile_sdk::build::build_ftui::(std::collections::BTreeMap::new()) +} diff --git a/wit/floatile-widget.wit b/wit/floatile-widget.wit index 1d5c86c..a9f45cd 100644 --- a/wit/floatile-widget.wit +++ b/wit/floatile-widget.wit @@ -1,4 +1,4 @@ -// Floatile Widget 插件契约 v1.1.0(唯一事实源)。 +// Floatile Widget 插件契约 v1.2.0(唯一事实源)。 // // 宿主与 guest 绑定都由本文件生成;修改必须同步 floatile-plugin-api、 // floatile-sdk、floatile-runtime 适配、engineApiVersion 与契约测试。 @@ -8,7 +8,7 @@ // handle-event/stop)、canonical initial State、host-ui.update-state 与稳定 // guest error。宿主能力即 interface,world 显式 import 才算获得;所有能力 // 调用仍由 PermissionBroker 仲裁与审计。 -package floatile:widget@1.1.0; +package floatile:widget@1.2.0; // ---------- 宿主能力(插件 import;能力即接口,world 显式 import 才算获得) ---------- @@ -77,6 +77,7 @@ interface host-operation { enum operation-capability { storage-read, + https-request, } enum operation-terminal { @@ -111,6 +112,24 @@ interface host-operation { cancel: func(id: operation-id) -> result<_, operation-error>; } +interface host-http { + use host-operation.{operation-error, operation-id}; + + record query-param { + name: string, + value: string, + } + + record http-response { + status: u16, + body: list, + } + + // 模板、Connection grant、origin、预算与 credential 注入均由宿主验证。 + submit: func(template-id: string, connection-id: u64, query: list) -> result; + take-result: func(id: operation-id) -> result; +} + interface host-storage { use host-operation.{operation-error, operation-id}; @@ -231,6 +250,7 @@ world floatile-widget { import host-timer; import host-operation; import host-storage; + import host-http; import host-metrics; import host-theme;