Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(skills): fetch pasted SKILL.md URLs through the registry guard

oxoxDevf53022da1536
diff --git a/crates/openhuman-core/src/skills/ops_create_and_url_tests.rs b/crates/openhuman-core/src/skills/ops_create_and_url_tests.rs
index 6e3393540c..63d10fcb89 100644
--- a/crates/openhuman-core/src/skills/ops_create_and_url_tests.rs
+++ b/crates/openhuman-core/src/skills/ops_create_and_url_tests.rs
@@ -359,19 +359,11 @@ async fn install_workflow_from_url_is_idempotent_when_skill_already_exists() {
#[test]
fn install_fetch_status_reporting_suppresses_client_errors_only() {
- assert!(!should_report_install_fetch_status(reqwest::StatusCode::OK));
- assert!(!should_report_install_fetch_status(
- reqwest::StatusCode::NOT_FOUND
- ));
- assert!(!should_report_install_fetch_status(
- reqwest::StatusCode::GONE
- ));
- assert!(should_report_install_fetch_status(
- reqwest::StatusCode::INTERNAL_SERVER_ERROR
- ));
- assert!(should_report_install_fetch_status(
- reqwest::StatusCode::BAD_GATEWAY
- ));
+ assert!(!should_report_install_fetch_status(200));
+ assert!(!should_report_install_fetch_status(404));
+ assert!(!should_report_install_fetch_status(410));
+ assert!(should_report_install_fetch_status(500));
+ assert!(should_report_install_fetch_status(502));
}
/// Happy path: install a SKILL.md under a synthetic user home, verify
diff --git a/crates/openhuman-core/src/skills/ops_install.rs b/crates/openhuman-core/src/skills/ops_install.rs
index f4cc4a9683..13922a497f 100644
--- a/crates/openhuman-core/src/skills/ops_install.rs
+++ b/crates/openhuman-core/src/skills/ops_install.rs
@@ -8,7 +8,7 @@ mod fetch;
mod uninstall;
mod url_validation;
-pub(crate) use fetch::install_validated_document;
+pub(crate) use fetch::{install_validated_document, report_install_fetch_failure};
pub use fetch::{
install_workflow_from_url, InstallWorkflowFromUrlOutcome, InstallWorkflowFromUrlParams,
DEFAULT_INSTALL_TIMEOUT_SECS, MAX_INSTALL_TIMEOUT_SECS, MAX_WORKFLOW_MD_BYTES,
diff --git a/crates/openhuman-core/src/skills/ops_install/fetch.rs b/crates/openhuman-core/src/skills/ops_install/fetch.rs
index eeb2185606..5935158b9c 100644
--- a/crates/openhuman-core/src/skills/ops_install/fetch.rs
+++ b/crates/openhuman-core/src/skills/ops_install/fetch.rs
@@ -2,19 +2,21 @@
//! root.
use std::path::Path;
+use std::sync::Arc;
+use std::time::Duration;
use serde::{Deserialize, Serialize};
use tinyskills::{
- check_document_size, redact_url, validate_fetched_document, write_installed_document,
- DocumentWrite, FetchedDocument, MAX_INSTALL_DOCUMENT_BYTES,
+ fetch_skill_document, redact_url, write_installed_document, DocumentWrite, FetchPolicy,
+ FetchedDocument, RegistryError, RegistryLimits, RegistryTimeouts, SystemResolver,
+ MAX_INSTALL_DOCUMENT_BYTES,
};
use super::super::ops_discover::{discover_workflows_inner, is_workspace_trusted};
-use super::url_validation::{is_loopback_http_url, read_allow_local_http_env};
-use super::url_validation::{
- normalize_install_url, validate_install_url_with_config, validate_resolved_host,
-};
+use super::url_validation::read_allow_local_http_env;
+use super::url_validation::{normalize_install_url, validate_install_url_with_config};
+use crate::skills::catalog::ReqwestTransport;
/// Default wall-clock budget for the SKILL.md fetch.
pub const DEFAULT_INSTALL_TIMEOUT_SECS: u64 = 60;
@@ -88,10 +90,11 @@ pub struct InstallWorkflowFromUrlOutcome {
/// tarballs are rejected with `unsupported url form:`.
/// * `timeout_secs` is clamped to [`MAX_INSTALL_TIMEOUT_SECS`].
///
-/// Runtime:
-/// * Body size is capped by [`MAX_WORKFLOW_MD_BYTES`] (1 MiB). The advertised
-/// `Content-Length` is checked up front; the buffered body length is
-/// checked again after the download as defense against a lying header.
+/// Runtime (the tinyskills fetch guard over [`ReqwestTransport`]):
+/// * The host is resolved once and the connection pinned to the checked
+/// public addresses; every redirect hop is re-validated.
+/// * Body size is capped by [`MAX_WORKFLOW_MD_BYTES`] (1 MiB), from the
+/// advertised `Content-Length` and again while the body streams.
/// * Frontmatter is validated — `name` and `description` are required per
/// the agentskills.io spec.
/// * The slug is derived from `metadata.id` when present, otherwise the
@@ -115,24 +118,70 @@ pub async fn install_workflow_from_url(
.await
}
-/// Seconds from a `Retry-After` header, when it is the delta-seconds form.
-///
-/// RFC 9110 also permits an HTTP-date. We deliberately do not parse that: it
-/// would pull in a date parser to serve a form GitHub's raw CDN does not send,
-/// and the caller degrades correctly without it — the error still says the host
-/// is throttling, just without a specific delay.
-pub(crate) fn retry_after_secs(headers: &reqwest::header::HeaderMap) -> Option<u64> {
- headers
- .get(reqwest::header::RETRY_AFTER)?
- .to_str()
- .ok()?
- .trim()
- .parse::<u64>()
- .ok()
+/// Whether a non-`2xx` status is worth reporting: a `4xx` means the URL is
+/// wrong or the skill is gone, which is user or catalog input, not a defect.
+pub(crate) fn should_report_install_fetch_status(status: u16) -> bool {
+ !(200..300).contains(&status) && !(400..500).contains(&status)
}
-pub(crate) fn should_report_install_fetch_status(status: reqwest::StatusCode) -> bool {
- !status.is_success() && !status.is_client_error()
+/// Report a failed `SKILL.md` fetch when it is not user input: timeouts,
+/// transport failures, a broken transport contract and `5xx` statuses. `url`
+/// is the redacted URL when the caller knows it.
+pub(crate) fn report_install_fetch_failure(error: &RegistryError, url: Option<&str>) {
+ let (failure, status) = match error {
+ _ if error.is_timeout() => ("timeout", None),
+ RegistryError::Transport(_) => ("transport", None),
+ RegistryError::TransportContract { .. } => ("transport_contract", None),
+ RegistryError::Unavailable { status } if should_report_install_fetch_status(*status) => {
+ ("non_2xx", Some(status.to_string()))
+ }
+ _ => {
+ tracing::debug!(
+ kind = error.kind().as_str(),
+ "[skills] install fetch: not reported (user or catalog input)"
+ );
+ return;
+ }
+ };
+ let message = match (url, status.as_deref()) {
+ (Some(url), Some(status)) => format!("fetch failed: {url} returned status {status}"),
+ _ => format!("fetch failed: {error}"),
+ };
+ let mut tags = vec![("failure", failure)];
+ if let Some(url) = url {
+ tags.push(("url", url));
+ }
+ if let Some(status) = status.as_deref() {
+ tags.push(("status", status));
+ }
+ crate::core::observability::report_error(message.as_str(), "skills", "install_fetch", &tags);
+}
+
+/// The caller-facing message for a failed `SKILL.md` fetch from a URL.
+pub(crate) fn install_fetch_error(
+ error: &RegistryError,
+ fetch_url: &str,
+ timeout_secs: u64,
+) -> String {
+ report_install_fetch_failure(error, Some(&redact_url(fetch_url)));
+ match error {
+ _ if error.is_timeout() => format!("fetch timed out after {timeout_secs}s"),
+ RegistryError::Transport(transport) => format!("fetch failed: {transport}"),
+ RegistryError::TransportContract { .. } => format!("fetch failed: {error}"),
+ RegistryError::RateLimited { retry_after } => match retry_after {
+ Some(delay) => format!(
+ "{RATE_LIMITED_ERROR_PREFIX} by {fetch_url}: retry after {}s",
+ delay.as_secs()
+ ),
+ None => format!("{RATE_LIMITED_ERROR_PREFIX} by {fetch_url}: retry shortly"),
+ },
+ RegistryError::Unavailable { status } => {
+ format!("fetch failed: {fetch_url} returned status {status}")
+ }
+ RegistryError::UnsafeUrl(inner) => inner.to_string(),
+ RegistryError::InvalidDocument(inner) => inner.to_string(),
+ other => other.to_string(),
+ }
}
pub(crate) async fn install_workflow_from_url_with_home(
@@ -151,131 +200,40 @@ pub(crate) async fn install_workflow_from_url_with_home(
let fetch_url = normalize_install_url(&raw_url)?;
- // Second-layer SSRF guard: a public-looking hostname can still resolve
- // to a loopback / private / link-local address (DNS-to-private-IP). We
- // resolve the host up-front and reject if any returned IP is private.
- // Known caveat: this does not fully prevent DNS rebinding — reqwest's
- // resolver may see different answers than ours. Closing that gap requires
- // pinning a `SocketAddr` and passing it to reqwest via a custom resolver,
- // tracked separately.
- if !(allow_local_http && is_loopback_http_url(&fetch_url)) {
- validate_resolved_host(&fetch_url).await?;
- }
-
- let redacted_raw_url = redact_url(&raw_url);
- let redacted_fetch_url = redact_url(&fetch_url);
-
tracing::debug!(
- raw_url = %redacted_raw_url,
- fetch_url = %redacted_fetch_url,
+ raw_url = %redact_url(&raw_url),
+ fetch_url = %redact_url(&fetch_url),
workspace = %workspace_dir.display(),
timeout_secs = timeout_secs,
"[skills] install_workflow_from_url: entry"
);
- let client = reqwest::Client::builder()
- .timeout(std::time::Duration::from_secs(timeout_secs))
- .build()
- .map_err(|e| format!("fetch failed: build http client: {e}"))?;
-
- tracing::info!(
- fetch_url = %redacted_fetch_url,
- "[skills] install_workflow_from_url: fetching SKILL.md"
- );
-
- let response = match client.get(&fetch_url).send().await {
- Ok(resp) => resp,
- Err(e) => {
- let (failure, msg) = if e.is_timeout() {
- ("timeout", format!("fetch timed out after {timeout_secs}s"))
- } else {
- ("transport", format!("fetch failed: {e}"))
- };
- crate::core::observability::report_error(
- msg.as_str(),
- "skills",
- "install_fetch",
- &[("url", redacted_fetch_url.as_str()), ("failure", failure)],
- );
- return Err(msg);
- }
- };
-
- let status = response.status();
- if !status.is_success() {
- // A 4xx (esp. 404/410) means the requested SKILL.md is gone or the URL
- // is wrong — expected user/catalog input state, surfaced to the UI as
- // "skill not found". Don't page Sentry for it (TAURI-RUST-CGE: ~1,446
- // events / 72 users on `[email protected]`, almost all 404). Keep
- // reporting 5xx — a genuine remote failure is still Sentry-actionable.
- // The `Err(msg)` return is unchanged in both cases so the UI always
- // surfaces the failure.
- let status_str = status.as_u16().to_string();
- // Read `Retry-After` off the response BEFORE anything consumes the
- // body: `response.bytes()` below takes `response` by value, and a
- // header read afterwards is not available at all. (The same ordering
- // trap silently drops the header on the model-call path — see #6413.)
- let retry_after = retry_after_secs(response.headers());
- // A throttled host is a different user action from an unreachable one:
- // "try again shortly" versus "this host is not answering". Both were
- // previously the same opaque `returned status N` string, so the UI
- // could not tell the user which had happened (#6409).
- let msg = if status == reqwest::StatusCode::TOO_MANY_REQUESTS
- || (status.is_server_error() && retry_after.is_some())
- {
- match retry_after {
- Some(secs) => {
- format!("{RATE_LIMITED_ERROR_PREFIX} by {fetch_url}: retry after {secs}s")
- }
- None => format!("{RATE_LIMITED_ERROR_PREFIX} by {fetch_url}: retry shortly"),
- }
- } else {
- format!(
- "fetch failed: {fetch_url} returned status {}",
- status.as_u16()
- )
- };
- let report_msg = format!(
- "fetch failed: {redacted_fetch_url} returned status {}",
- status.as_u16()
+ let mut policy = FetchPolicy::default();
+ policy.allow_loopback_http = allow_local_http;
+ policy.user_agent = format!("openhuman-core/{}", env!("CARGO_PKG_VERSION"));
+ let mut timeouts = RegistryTimeouts::default();
+ timeouts.document = Duration::from_secs(timeout_secs);
+ let mut limits = RegistryLimits::default();
+ limits.max_document_bytes = MAX_WORKFLOW_MD_BYTES as u64;
+
+ let fetched = fetch_skill_document(
+ Arc::new(ReqwestTransport::new()),
+ Arc::new(SystemResolver),
+ &fetch_url,
+ &policy,
+ &timeouts,
+ &limits,
+ )
+ .await
+ .map_err(|error| install_fetch_error(&error, &fetch_url, timeout_secs))?;
+
+ if fetched.is_blocked() {
+ tracing::warn!(
+ fetch_url = %redact_url(&fetch_url),
+ "[skills] install_workflow_from_url: supply-chain scan flagged the document"
);
- if should_report_install_fetch_status(status) {
- crate::core::observability::report_error(
- report_msg.as_str(),
- "skills",
- "install_fetch",
- &[
- ("url", redacted_fetch_url.as_str()),
- ("status", status_str.as_str()),
- ("failure", "non_2xx"),
- ],
- );
- } else {
- tracing::debug!(
- fetch_url = %redacted_fetch_url,
- status = status.as_u16(),
- "[skills] install_workflow_from_url: skipped Sentry report for user/catalog fetch status"
- );
- }
- return Err(msg);
}
-
- if let Some(len) = response.content_length() {
- check_document_size(len).map_err(|e| e.to_string())?;
- }
-
- let bytes = match response.bytes().await {
- Ok(b) => b,
- Err(e) => {
- if e.is_timeout() {
- return Err(format!("fetch timed out after {timeout_secs}s"));
- }
- return Err(format!("fetch failed: reading body: {e}"));
- }
- };
-
- let document = validate_fetched_document(&bytes).map_err(|e| e.to_string())?;
- install_validated_document(workspace_dir, home, &raw_url, &fetch_url, document)
+ install_validated_document(workspace_dir, home, &raw_url, &fetch_url, fetched.document)
}
/// Write a validated `SKILL.md` into the user skills root, re-discover, and
diff --git a/crates/openhuman-core/src/skills/ops_install/url_validation.rs b/crates/openhuman-core/src/skills/ops_install/url_validation.rs
index 03ce756fa8..6112fa9bcb 100644
--- a/crates/openhuman-core/src/skills/ops_install/url_validation.rs
+++ b/crates/openhuman-core/src/skills/ops_install/url_validation.rs
@@ -4,25 +4,7 @@ pub const MAX_INSTALL_URL_LEN: usize = tinyskills::MAX_INSTALL_URL_LEN;
pub(crate) const ALLOW_LOCAL_HTTP_ENV: &str = "OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP";
pub(crate) fn normalize_install_url(raw: &str) -> Result<String, String> {
- // ClawHub's file API identifies the requested Markdown file in its query
- // rather than in the URL path. Preserve this OpenHuman-compatible form
- // while keeping the portable validator strict for every other host/path.
- if let Ok(url) = url::Url::parse(raw) {
- let is_clawhub_file_api = url.host_str() == Some("clawhub.ai")
- && url.path().starts_with("/api/v1/skills/")
- && url.path().ends_with("/file");
- if is_clawhub_file_api {
- let markdown_path = url
- .query_pairs()
- .find(|(key, _)| key == "path")
- .map(|(_, value)| value.to_ascii_lowercase().ends_with(".md"))
- .unwrap_or(false);
- if markdown_path {
- return Ok(raw.to_owned());
- }
- }
- }
- tinyskills::normalize_install_url(raw).map_err(|error| error.to_string())
+ tinyskills::normalize_registry_document_url(raw).map_err(|error| error.to_string())
}
pub fn validate_install_url(raw: &str) -> Result<(), String> {
@@ -44,10 +26,6 @@ pub(super) fn read_allow_local_http_env() -> bool {
allow_local_http(std::env::var(ALLOW_LOCAL_HTTP_ENV).ok())
}
-pub(super) fn is_loopback_http_url(raw: &str) -> bool {
- tinyskills::is_loopback_http_url(raw)
-}
-
pub async fn validate_resolved_host(raw_url: &str) -> Result<(), String> {
tinyskills::validate_resolved_host(raw_url)
.await
diff --git a/crates/openhuman-core/src/skills/ops_install_failure_tests.rs b/crates/openhuman-core/src/skills/ops_install_failure_tests.rs
index 541c1d9fbd..ea08818bc1 100644
--- a/crates/openhuman-core/src/skills/ops_install_failure_tests.rs
+++ b/crates/openhuman-core/src/skills/ops_install_failure_tests.rs
@@ -122,3 +122,93 @@ async fn a_missing_skill_is_not_reported_as_rate_limiting() {
);
assert!(error.contains("404"), "got: {error}");
}
+
+#[cfg(feature = "crash-reporting")]
+#[test]
+fn a_4xx_fetch_is_not_reported_and_a_5xx_is() {
+ use crate::skills::ops_install::report_install_fetch_failure;
+ use tinyskills::RegistryError;
+
+ let missing = sentry::test::with_captured_events(|| {
+ report_install_fetch_failure(&RegistryError::Unavailable { status: 404 }, Some("u"));
+ report_install_fetch_failure(&RegistryError::RateLimited { retry_after: None }, None);
+ report_install_fetch_failure(
+ &RegistryError::NotFound {
+ id: "x".into(),
+ closest: Vec::new(),
+ },
+ None,
+ );
+ });
+ assert!(
+ missing.is_empty(),
+ "user input is not reported: {missing:?}"
+ );
+
+ let outage = sentry::test::with_captured_events(|| {
+ report_install_fetch_failure(&RegistryError::Unavailable { status: 503 }, Some("u"));
+ });
+ assert_eq!(outage.len(), 1);
+ let tags = &outage[0].tags;
+ assert_eq!(tags.get("domain").map(String::as_str), Some("skills"));
+ assert_eq!(
+ tags.get("operation").map(String::as_str),
+ Some("install_fetch")
+ );
+ assert_eq!(tags.get("failure").map(String::as_str), Some("non_2xx"));
+ assert_eq!(tags.get("status").map(String::as_str), Some("503"));
+}
+
+#[tokio::test]
+async fn a_slow_host_reports_the_clamped_timeout() {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/SKILL.md"))
+ .respond_with(ResponseTemplate::new(200).set_delay(std::time::Duration::from_secs(5)))
+ .mount(&server)
+ .await;
+
+ let home = tempfile::tempdir().unwrap();
+ let error = install_workflow_from_url_with_home(
+ home.path(),
+ InstallWorkflowFromUrlParams {
+ url: format!("{}/SKILL.md", server.uri()),
+ timeout_secs: Some(1),
+ },
+ Some(home.path()),
+ true,
+ )
+ .await
+ .expect_err("the host outlasts the budget");
+ assert_eq!(error, "fetch timed out after 1s");
+}
+
+#[tokio::test]
+async fn a_document_without_frontmatter_is_refused() {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/SKILL.md"))
+ .respond_with(ResponseTemplate::new(200).set_body_string("# no frontmatter\n"))
+ .mount(&server)
+ .await;
+
+ let home = tempfile::tempdir().unwrap();
+ let error = install_workflow_from_url_with_home(
+ home.path(),
+ InstallWorkflowFromUrlParams {
+ url: format!("{}/SKILL.md", server.uri()),
+ timeout_secs: Some(5),
+ },
+ Some(home.path()),
+ true,
+ )
+ .await
+ .expect_err("not a SKILL.md");
+ assert!(!error.starts_with("fetch failed"), "{error}");
+}