The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(skills): add a supply-chain scan gate for skill installs (#7082)
oxoxDev8a40be382ef4
diff --git a/crates/openhuman-core/src/skills/ops_install.rs b/crates/openhuman-core/src/skills/ops_install.rsindex 13922a497f..4d302860ea 100644--- a/crates/openhuman-core/src/skills/ops_install.rs+++ b/crates/openhuman-core/src/skills/ops_install.rs@@ -5,6 +5,7 @@mod install_fetch_tests;mod fetch;+mod scan_gate;mod uninstall;mod url_validation;@@ -14,6 +15,10 @@ pub use fetch::{DEFAULT_INSTALL_TIMEOUT_SECS, MAX_INSTALL_TIMEOUT_SECS, MAX_WORKFLOW_MD_BYTES,RATE_LIMITED_ERROR_PREFIX,};+pub(crate) use scan_gate::{fetch_scanned, gate_install};+pub use scan_gate::{+ ScanAcknowledgement, ScanBlockedOutcome, ScanFindingSummary, SkillInstallOutcome,+};pub use uninstall::{uninstall_workflow, UninstallWorkflowOutcome, UninstallWorkflowParams};pub(crate) use url_validation::{allow_local_http, ALLOW_LOCAL_HTTP_ENV};pub use url_validation::{validate_install_url, validate_resolved_host, MAX_INSTALL_URL_LEN};diff --git a/crates/openhuman-core/src/skills/ops_install/scan_gate.rs b/crates/openhuman-core/src/skills/ops_install/scan_gate.rsnew file mode 100644index 0000000000..490b0e5cbe--- /dev/null+++ b/crates/openhuman-core/src/skills/ops_install/scan_gate.rs@@ -0,0 +1,212 @@+//! The supply-chain scan gate shared by catalog and URL installs.+//!+//! A fetched `SKILL.md` whose scan blocks, or a fetch that fails, is fetched+//! and scanned once more. A document that still blocks is not installed+//! unless the user acknowledged its findings in the Skills UI; the caller gets+//! a [`SkillInstallOutcome::ScanBlocked`] instead.++use std::future::Future;++use serde::Serialize;+use tinyskills::{RegistryDocument, RegistryError, RegistryErrorKind, ScanCheck, Verdict};++use super::fetch::InstallWorkflowFromUrlOutcome;++/// Whether the user has reviewed a blocking scan and chosen to install anyway.+///+/// Only the Skills UI sets [`ScanAcknowledgement::ByUser`], through the+/// `acknowledge_scan_findings` JSON-RPC param. Agent tools always pass+/// [`ScanAcknowledgement::Absent`].+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ScanAcknowledgement {+ /// Nobody acknowledged the findings: a blocking scan refuses the install.+ Absent,+ /// The user acknowledged the findings and asked to install anyway.+ ByUser,+}++impl ScanAcknowledgement {+ pub fn from_user_flag(acknowledged: bool) -> Self {+ if acknowledged {+ Self::ByUser+ } else {+ Self::Absent+ }+ }+}++/// One scan finding, in operator-facing language.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct ScanFindingSummary {+ pub check: ScanCheck,+ pub verdict: Verdict,+ /// Where in the skill it fired, e.g. `the document body`.+ pub field: String,+ /// The finding as one readable line, without the offending value.+ pub message: String,+}++/// A document the scan blocked, returned instead of installing it.+#[derive(Debug, Clone, Serialize)]+pub struct ScanBlockedOutcome {+ /// The catalog entry id or URL the caller asked to install.+ pub target: String,+ /// The URL the document was fetched from, redacted.+ pub fetched_from: String,+ /// The install slug the document would have used.+ pub slug: String,+ pub findings: Vec<ScanFindingSummary>,+ pub message: String,+}++impl ScanBlockedOutcome {+ pub(crate) fn of(target: &str, document: &RegistryDocument) -> Self {+ let findings: Vec<ScanFindingSummary> = document+ .scan+ .findings+ .iter()+ .map(|finding| ScanFindingSummary {+ check: finding.check,+ verdict: finding.verdict,+ field: finding.field.label(),+ message: finding.message(),+ })+ .collect();+ let blocking: Vec<&str> = findings+ .iter()+ .filter(|finding| finding.verdict == Verdict::Block)+ .map(|finding| finding.message.as_str())+ .collect();+ Self {+ target: target.to_owned(),+ fetched_from: document.fetched_from.clone(),+ slug: document.document.slug.clone(),+ message: format!(+ "The security scan blocked this skill and it was not installed: {}.",+ blocking.join("; ")+ ),+ findings,+ }+ }+}++/// What an install did: installed the skill, or refused it on its scan.+#[derive(Debug, Clone, Serialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum SkillInstallOutcome {+ Installed(InstallWorkflowFromUrlOutcome),+ ScanBlocked(ScanBlockedOutcome),+}++impl SkillInstallOutcome {+ pub fn status(&self) -> &'static str {+ match self {+ Self::Installed(_) => "installed",+ Self::ScanBlocked(_) => "scan_blocked",+ }+ }++ /// The install, or `None` when the scan refused it.+ pub fn installed(self) -> Option<InstallWorkflowFromUrlOutcome> {+ match self {+ Self::Installed(installed) => Some(installed),+ Self::ScanBlocked(_) => None,+ }+ }+}++/// Whether a failed fetch is worth one more attempt. Refusals that depend+/// only on the request (an unknown id, an unsafe URL, a portal entry), an+/// oversized body and an upstream asking us to back off are not.+pub(crate) fn fetch_error_is_retryable(error: &RegistryError) -> bool {+ !matches!(+ error.kind(),+ RegistryErrorKind::NotFound+ | RegistryErrorKind::Ambiguous+ | RegistryErrorKind::UpstreamAmbiguous+ | RegistryErrorKind::NoDirectDownload+ | RegistryErrorKind::UnsafeUrl+ | RegistryErrorKind::UnknownRegistry+ | RegistryErrorKind::TooLarge+ | RegistryErrorKind::RateLimited+ )+}++/// Fetch and scan a document, retrying once when the scan blocks or the+/// fetch fails with a retryable error. An acknowledged install takes the+/// first document as is.+pub(crate) async fn fetch_scanned<F, Fut>(+ target: &str,+ acknowledgement: ScanAcknowledgement,+ mut fetch: F,+) -> Result<RegistryDocument, RegistryError>+where+ F: FnMut() -> Fut,+ Fut: Future<Output = Result<RegistryDocument, RegistryError>>,+{+ match fetch().await {+ Ok(document) if !document.is_blocked() => return Ok(document),+ Ok(document) if acknowledgement == ScanAcknowledgement::ByUser => {+ tracing::warn!(+ install_target = %target,+ fetched_from = %document.fetched_from,+ findings = document.scan.findings.len(),+ "[skills] scan gate: blocked document installed on user acknowledgement"+ );+ return Ok(document);+ }+ Ok(document) => tracing::info!(+ install_target = %target,+ fetched_from = %document.fetched_from,+ findings = document.scan.findings.len(),+ "[skills] scan gate: scan blocked the document; fetching it once more"+ ),+ Err(error) if fetch_error_is_retryable(&error) => tracing::info!(+ install_target = %target,+ kind = error.kind().as_str(),+ error = %error,+ "[skills] scan gate: fetch failed; fetching it once more"+ ),+ Err(error) => return Err(error),+ }+ let retried = fetch().await;+ match &retried {+ Ok(document) => tracing::info!(+ install_target = %target,+ blocked = document.is_blocked(),+ "[skills] scan gate: retry fetched the document"+ ),+ Err(error) => tracing::info!(+ install_target = %target,+ kind = error.kind().as_str(),+ "[skills] scan gate: retry failed"+ ),+ }+ retried+}++/// Turn a scanned document into an install, or into a refusal when its scan+/// blocks and the user has not acknowledged it.+pub(crate) fn gate_install(+ target: &str,+ acknowledgement: ScanAcknowledgement,+ document: RegistryDocument,+ install: impl FnOnce(RegistryDocument) -> Result<InstallWorkflowFromUrlOutcome, String>,+) -> Result<SkillInstallOutcome, String> {+ if document.is_blocked() && acknowledgement == ScanAcknowledgement::Absent {+ let blocked = ScanBlockedOutcome::of(target, &document);+ tracing::warn!(+ install_target = %target,+ fetched_from = %blocked.fetched_from,+ slug = %blocked.slug,+ findings = blocked.findings.len(),+ "[skills] scan gate: refused install; scan still blocks after a retry"+ );+ return Ok(SkillInstallOutcome::ScanBlocked(blocked));+ }+ install(document).map(SkillInstallOutcome::Installed)+}++#[cfg(test)]+#[path = "scan_gate_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/skills/ops_install/scan_gate_tests.rs b/crates/openhuman-core/src/skills/ops_install/scan_gate_tests.rsnew file mode 100644index 0000000000..b727bb533b--- /dev/null+++ b/crates/openhuman-core/src/skills/ops_install/scan_gate_tests.rs@@ -0,0 +1,107 @@+use super::*;++use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++#[test]+fn only_an_explicit_user_flag_acknowledges_findings() {+ assert_eq!(+ ScanAcknowledgement::from_user_flag(true),+ ScanAcknowledgement::ByUser+ );+ assert_eq!(+ ScanAcknowledgement::from_user_flag(false),+ ScanAcknowledgement::Absent+ );+}++#[test]+fn outages_and_bad_documents_are_retried_but_request_refusals_are_not() {+ for retryable in [+ RegistryError::Unavailable { status: 503 },+ RegistryError::Timeout {+ operation: "document",+ budget: std::time::Duration::from_secs(1),+ },+ ] {+ assert!(fetch_error_is_retryable(&retryable), "{retryable}");+ }+ for refused in [+ RegistryError::NotFound {+ id: "x".into(),+ closest: Vec::new(),+ },+ RegistryError::NoDirectDownload {+ name: "x".into(),+ source_url: None,+ },+ RegistryError::RateLimited { retry_after: None },+ ] {+ assert!(!fetch_error_is_retryable(&refused), "{refused}");+ }+}++async fn run_failing(error: fn() -> RegistryError) -> (usize, RegistryError) {+ let calls = Arc::new(AtomicUsize::new(0));+ let counted = Arc::clone(&calls);+ let result = fetch_scanned("entry", ScanAcknowledgement::Absent, move || {+ counted.fetch_add(1, Ordering::SeqCst);+ let error = error();+ async move { Err::<RegistryDocument, _>(error) }+ })+ .await;+ (+ calls.load(Ordering::SeqCst),+ result.expect_err("every attempt fails"),+ )+}++#[tokio::test]+async fn a_failed_fetch_is_attempted_exactly_twice() {+ let (calls, error) = run_failing(|| RegistryError::Unavailable { status: 503 }).await;+ assert_eq!(calls, 2, "one retry after the failure");+ assert_eq!(error.kind(), RegistryErrorKind::Unavailable);+}++#[tokio::test]+async fn a_refused_request_is_not_retried() {+ let (calls, error) = run_failing(|| RegistryError::NotFound {+ id: "x".into(),+ closest: Vec::new(),+ })+ .await;+ assert_eq!(calls, 1);+ assert_eq!(error.kind(), RegistryErrorKind::NotFound);+}++#[test]+fn outcomes_serialize_with_a_status_tag() {+ let installed = SkillInstallOutcome::Installed(InstallWorkflowFromUrlOutcome {+ url: "u".into(),+ stdout: "Installed to /x".into(),+ stderr: String::new(),+ new_skills: vec!["x".into()],+ });+ let value = serde_json::to_value(&installed).unwrap();+ assert_eq!(value["status"], "installed");+ assert_eq!(value["new_skills"][0], "x");+ assert_eq!(installed.status(), "installed");++ let blocked = SkillInstallOutcome::ScanBlocked(ScanBlockedOutcome {+ target: "x".into(),+ fetched_from: "https://example.com/SKILL.md".into(),+ slug: "x".into(),+ findings: vec![ScanFindingSummary {+ check: ScanCheck::InvisibleCodePoints,+ verdict: Verdict::Block,+ field: "the document body".into(),+ message: "an invisible character in the document body".into(),+ }],+ message: "blocked".into(),+ });+ let value = serde_json::to_value(&blocked).unwrap();+ assert_eq!(value["status"], "scan_blocked");+ assert_eq!(value["findings"][0]["check"], "invisible_code_points");+ assert_eq!(value["findings"][0]["verdict"], "block");+ assert_eq!(blocked.status(), "scan_blocked");+}