diff --git a/crates/webcodex-tool-contracts/src/tool_definition/artifacts.rs b/crates/webcodex-tool-contracts/src/tool_definition/artifacts.rs index 80ff5f6cc..0e6637b5e 100644 --- a/crates/webcodex-tool-contracts/src/tool_definition/artifacts.rs +++ b/crates/webcodex-tool-contracts/src/tool_definition/artifacts.rs @@ -92,7 +92,7 @@ pub(super) const DEFINITIONS: &[ToolDefinition] = &[ false, super::ToolSessionEvidencePolicy::NONE, ), - "Import 1..10 current ChatGPT/host attachments into a Runner project using openaiFileIdRefs from the host file-reference mechanism, up to 256 MiB per file. This is the preferred host-native attachment-to-project transfer path: do not base64-transfer files, construct download URLs, or use local /mnt/data paths; Control streams downloads into project artifacts. A multi-file batch is not atomic: if a later item fails, structured output preserves imported/succeeded items, identifies the failed item and reason, and sets partial_success=true. MCP trust has two tiers: an active authenticated OAuth client may import only from OpenAI file hosts; an exact WEBCODEX_OAUTH2_TRUSTED_MCP_FILE_CLIENT_IDS match may import from arbitrary public HTTPS. Both retain DNS/public-IP, pinning, redirect, bounded-download, and Project write protections.", + "Import 1..10 current ChatGPT/host attachments into a Runner project using openaiFileIdRefs from the host file-reference mechanism, up to 256 MiB per file. This is the preferred host-native attachment-to-project transfer path: do not base64-transfer files, construct download URLs, or use local /mnt/data paths; Control streams downloads into project artifacts. A multi-file batch is not atomic: if a later item fails, structured output preserves imported/succeeded items, identifies the failed item and reason, and sets partial_success=true. MCP trust has two tiers: an active authenticated OAuth client may import only from OpenAI file hosts; an exact WEBCODEX_OAUTH2_TRUSTED_MCP_FILE_CLIENT_IDS match may import from arbitrary public HTTPS. Both retain DNS/public-IP, pinning, redirect, bounded-download, and Project write protections. Before adding document links, use only completed imported/succeeded paths and verify the destination against bytes_written and sha256 with inspect_project_artifact metadata. A failed item is not a link target; unresolved upload effects require reconciliation before retry.", ), PERMISSION_RISK_ARTIFACT_WRITE, ), diff --git a/docs/CONVERSATION_FILE_IMPORT.md b/docs/CONVERSATION_FILE_IMPORT.md new file mode 100644 index 000000000..d2d6e0ab9 --- /dev/null +++ b/docs/CONVERSATION_FILE_IMPORT.md @@ -0,0 +1,83 @@ +# Conversation attachment import + +Use `import_host_files` with current host-populated file +references. Do not construct attachment URLs, infer host file IDs, or copy +signed download URLs into logs. Import runs on Control and commits through the +bounded Runner artifact-upload protocol; it does not edit documents or create +Markdown links. + +## Create references after confirmed import + +1. Await the terminal import result. Inspect `output.imported` (also exposed as + `output.succeeded`). Each completed item contains `project`, `path`, + `bytes_written`, `sha256`, `mime_type`, and `source_name`. +2. Verify the completed destination with `inspect_project_artifact(action=metadata)`; + its existence, byte count and SHA-256 must match the completed item. Use the + returned path, including any normalized file name, rather than predicting it. + Metadata verification requires its own Project read authority; if it is + unavailable, report verification as blocked rather than assuming existence. +3. Only then write the document reference using the document's relative-path + conventions. Document edits have their own write authority and revision + fences; import does not authorize a separate document edit. + +A batch is non-atomic. If a later item fails, the overall result can fail while +`imported`/`succeeded` retain prior committed items. `partial_success=true`, +`failed_item`, `failure_reason`, and `failure` describe that outcome. Preserve +the verified successes; never turn the failed item into a link target. An upload +whose result is uncertain is not a confirmed success: reconcile its existing +upload state before retrying, and avoid blindly replaying the entire batch. +Do not equate a document link, a host download response, or `upload_begin` +success with a committed destination. + +## Diagnose failures without exposing attachments + +At WARN level, `mcp_host_file_import_failed` reports fixed `stage` and +`failure_class` fields. Stages are `dns`, `download_request`, `download_body`, +`upload_begin`, `upload_chunk`, and `upload_finish`. Classes distinguish +`timeout`, `connection_failed`, `failed`, `http_status`, `size_limit`, and +`protocol_mismatch`. An HTTP rejection includes only the numeric `http_status`. +When a current request trace is available and parses as a UUID, it is emitted +as the canonical `server_trace_id`; absent or invalid trace IDs are omitted. + +These events contain no URL, path, query, file name, raw error text, upload ID, +credentials, or attachment contents. They diagnose a failure location, not a +root cause. Upload failures retain the existing definite-versus-uncertain +cleanup policy; a diagnostic event grants no authority to retry or abort. + +`mcp_host_file_download_dns_rejected` separately reports a bounded DNS host, +address classes, and a safe request UUID. No raw resolved addresses or signed +URL are emitted. Empty results, mixed public/non-public answers, loopback, +link-local and other non-public answers remain rejected. Trust rejection has +its own `mcp_host_file_import_trust_decision` event. Correlate the request and +the failing stage before changing configuration. + +## Fake-IP DNS troubleshooting + +Some DNS/proxy tools return synthetic addresses in the benchmarking range +`198.18.0.0/15`. These are non-public addresses. A `benchmarking` class can +indicate Fake-IP DNS but does not prove which resolver or rule produced it. +Keep WebCodex's SSRF rejection intact; do not permit this range, disable DNS +checks, remove address pinning, enable redirects, or widen credential trust to +work around DNS results. + +An operator may inspect DNS answers for the exact host in the rejection event +through the configured system resolver. Check A and AAAA answers and every +resolver layer actually used by Control. Use only the host name; do not paste a +signed URL into shell history or DNS tools. A host such as +`oaisdmntpr.blob.core.windows.net` illustrates the narrow Sediment +account pattern; it is not a download URL or a rule to apply literally. + +If the resolver supports a documented Fake-IP exclusion, propose an exact-host +exception for the observed attachment host. Apply it only with the operator's +authorization, preserve a rollback copy, validate configuration using the +resolver's native checker, and follow its documented reload procedure. Do not +exclude all Azure Blob storage, all OpenAI traffic, or all HTTPS hosts. Changes +to shared DNS affect other clients and require the appropriate operator scope. + +After an authorized resolver change, confirm that all A/AAAA answers used by +Control are public, retry the same authorized import with a fresh host reference +if necessary, and verify the committed destination metadata before linking it. +A public answer only passes DNS admission; HTTP expiry, upload authority and +write failures remain possible. Preserve HTTPS, port 443, no userinfo, no +redirects, public-address checks, pinning, normal PAT/OAuth trust gates, and +bounded streaming throughout. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index ba06033a1..4dc035b00 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -511,6 +511,10 @@ used by the regular Desktop Tunnel. That Tunnel derives the credential from the The flag is ignored for non-loopback binds and all other credential classes; leave it unset on network-accessible Servers. +For import-stage diagnostics and exact-host Fake-IP DNS troubleshooting, see +[Conversation attachment import](CONVERSATION_FILE_IMPORT.md). Resolver changes +must retain the import trust gates and public-address/pinning protections. + List and revoke clients with `POST /api/oauth/clients/list` and `POST /api/oauth/clients/revoke`. OAuth uses the authorization-code flow; dynamic client registration, OIDC, and the device-code flow are not diff --git a/docs/MCP.md b/docs/MCP.md index 7166c347e..e454b3d04 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -595,6 +595,9 @@ payloads through model text: them as file parameters. The Control downloads the referenced bytes and commits them through the existing bounded artifact-write path; callers should not construct download URLs or manually Base64-transfer those files. + Create document links only from confirmed imported paths after checking + destination bytes and SHA-256. See [attachment import](CONVERSATION_FILE_IMPORT.md) + for partial-success handling, safe diagnostics and Fake-IP DNS troubleshooting. - `inspect_project_artifact` is the preferred Project-to-model/host read surface. Use `action=metadata` for existence/size/MIME/digest/image/archive facts, `action=inspect` for one bounded snapshot-fenced Base64 segment, diff --git a/src/mcp.rs b/src/mcp.rs index 1c01d8a2b..2371fe8ff 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -841,6 +841,7 @@ pub async fn mcp_post(req: &mut Request, depot: &mut Depot, res: &mut Response) auth.as_ref(), config.as_deref(), db.as_deref(), + Some(&server_trace_id), ); // Defense-in-depth backstop: every tool bounds its own agent/subprocess // waits at <= 124s, so this outer limit never preempts a legitimate inner diff --git a/src/mcp/tools.rs b/src/mcp/tools.rs index a9f0ae92b..f6db4f808 100644 --- a/src/mcp/tools.rs +++ b/src/mcp/tools.rs @@ -1669,6 +1669,7 @@ pub(super) fn host_file_import_trust_for_call( auth: Option<&AuthContext>, config: Option<&crate::Config>, db: Option<&crate::Database>, + server_trace_id: Option<&str>, ) -> HostFileImportTrust { if tool_name != Some("import_host_files") { return HostFileImportTrust::Untrusted; @@ -1683,7 +1684,7 @@ pub(super) fn host_file_import_trust_for_call( Some(db) => mcp_host_file_import_trust_decision_from_state(config, db, auth), }, }; - log_mcp_host_file_import_trust_decision(auth, &decision); + log_mcp_host_file_import_trust_decision(auth, &decision, server_trace_id); decision.trust } @@ -1716,6 +1717,7 @@ fn mcp_token_kind_classification(auth: Option<&AuthContext>) -> &'static str { fn log_mcp_host_file_import_trust_decision( auth: Option<&AuthContext>, decision: &HostFileImportTrustDecision, + server_trace_id: Option<&str>, ) { #[cfg(test)] { @@ -1727,8 +1729,19 @@ fn log_mcp_host_file_import_trust_decision( let allowed_client_id_present = auth .and_then(|auth| auth.allowed_client_id.as_deref()) .is_some_and(|client_id| !client_id.trim().is_empty()); - tracing::info!( + let safe_trace_id = server_trace_id + .and_then(|id| uuid::Uuid::parse_str(id).ok()) + .map(|id| id.hyphenated().to_string()); + let server_trace_id = safe_trace_id.as_deref(); + // Denials must remain observable when an operator filters normal traffic + // at WARN. Keep successful decisions at INFO and log classifications only. + macro_rules! log_decision { + ($level:expr) => { + tracing::event!( target: "webcodex::mcp", + $level, + tool = "import_host_files", + server_trace_id, trust = decision.trust.is_trusted(), reason = decision.reason.as_str(), auth_kind = mcp_auth_kind_classification(auth), @@ -1741,7 +1754,14 @@ fn log_mcp_host_file_import_trust_decision( client_id_configured = ?decision.client_id_configured, active_client_registration_found = ?decision.active_client_registration_found, "mcp_host_file_import_trust_decision" - ); + ); + }; + } + if decision.trust == HostFileImportTrust::Untrusted { + log_decision!(tracing::Level::WARN); + } else { + log_decision!(tracing::Level::INFO); + } } pub(super) fn strip_recording_session_id(arguments: &mut Value) -> Result, String> { diff --git a/src/mcp_tests/file_import.rs b/src/mcp_tests/file_import.rs index 6c83d13a5..ff25b7a67 100644 --- a/src/mcp_tests/file_import.rs +++ b/src/mcp_tests/file_import.rs @@ -1,7 +1,107 @@ use super::*; +use crate::mcp::tools::host_file_import_trust_for_call; const MCP_IMPORT_TRUSTED_REDIRECT: &str = "https://chatgpt.example/connector/oauth/webcodex-test"; +#[tokio::test] +async fn mcp_file_import_denial_is_observable_with_warn_filter_without_identity_or_secrets() { + let _lock = lock_mcp_import_test().await; + #[derive(Clone)] + struct Capture(std::sync::Arc>>); + impl std::io::Write for Capture { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let capture = Capture(Default::default()); + let writer = capture.clone(); + let subscriber = tracing_subscriber::fmt() + .with_env_filter("warn") + .with_ansi(false) + .without_time() + .with_writer(move || writer.clone()) + .finish(); + let (_tmp, db) = test_db(); + let mut config = (*test_config(Some("credential-secret-sentinel"))).clone(); + config.oauth2.trust_loopback_api_token_mcp_file_import = false; + let auth = crate::auth::AuthContext { + username: Some("private-user-sentinel".to_string()), + user_id: Some("private-user-id-sentinel".to_string()), + api_key_id: Some("private-key-id-sentinel".to_string()), + token_kind: Some("user".to_string()), + ..crate::auth::AuthContext::new(crate::auth::AuthKind::ApiToken) + }; + tracing::subscriber::with_default(subscriber, || { + assert_eq!( + host_file_import_trust_for_call( + Some("import_host_files"), + Some(&auth), + Some(&config), + Some(&db), + Some("c77c5ec6-32e4-4a54-8590-4da44d35a8be"), + ), + HostFileImportTrust::Untrusted, + ); + // Enabling the existing explicit trust flag admits only the already + // supported local PAT case; its success must not become WARN noise. + config.oauth2.trust_loopback_api_token_mcp_file_import = true; + assert_eq!( + host_file_import_trust_for_call( + Some("import_host_files"), + Some(&auth), + Some(&config), + Some(&db), + Some("c77c5ec6-32e4-4a54-8590-4da44d35a8be"), + ), + HostFileImportTrust::TrustedMcpHostFile, + ); + config.oauth2.trust_loopback_api_token_mcp_file_import = false; + for invalid_trace in [ + "https://private.example/path?sig=trace-secret-sentinel", + "\ntrace-secret-sentinel", + ] { + assert_eq!( + host_file_import_trust_for_call( + Some("import_host_files"), + Some(&auth), + Some(&config), + Some(&db), + Some(invalid_trace), + ), + HostFileImportTrust::Untrusted + ); + } + }); + let output = String::from_utf8(capture.0.lock().unwrap().clone()).unwrap(); + assert!(output.contains("WARN"), "{output}"); + assert!( + output.contains("mcp_host_file_import_trust_decision"), + "{output}" + ); + assert!(output.contains("reason=\"not_oauth_token\""), "{output}"); + assert!(output.contains("auth_kind=\"api_token\""), "{output}"); + assert!( + output.contains("server_trace_id=\"c77c5ec6-32e4-4a54-8590-4da44d35a8be\""), + "{output}" + ); + assert!(output.contains("tool=\"import_host_files\""), "{output}"); + assert!(!output.contains("trusted_loopback_api_token"), "{output}"); + for private in [ + "credential-secret-sentinel", + "trace-secret-sentinel", + "private.example", + "private-user-sentinel", + "private-user-id-sentinel", + "private-key-id-sentinel", + ] { + assert!(!output.contains(private), "{output}"); + } +} + struct McpImportStartupEnvGuard { _env_lock: std::sync::MutexGuard<'static, ()>, previous: Vec<(&'static str, Option)>, diff --git a/src/runtime_http/tests/import_http_tests.rs b/src/runtime_http/tests/import_http_tests.rs index 9694b4e42..f9b023ffa 100644 --- a/src/runtime_http/tests/import_http_tests.rs +++ b/src/runtime_http/tests/import_http_tests.rs @@ -14,8 +14,172 @@ use salvo::Service; use serde_json::{json, Value}; use std::sync::Arc; use std::time::Duration; +use tracing::instrument::WithSubscriber; + +fn capture_import_warnings() -> ( + Arc>>, + impl tracing::Subscriber + Send + Sync, +) { + #[derive(Clone)] + struct Capture(Arc>>); + impl std::io::Write for Capture { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let output = Arc::new(std::sync::Mutex::new(Vec::new())); + let writer = Capture(output.clone()); + let subscriber = tracing_subscriber::fmt() + .with_env_filter("webcodex::mcp=warn") + .with_ansi(false) + .without_time() + .with_writer(move || writer.clone()) + .finish(); + (output, subscriber) +} + +#[tokio::test] +async fn import_http_status_failure_logs_only_stage_status_and_safe_uuid() { + let _guard = lock_import_http_test().await; + let server = start_mock_http_server(vec![http_response( + "403 Forbidden", + &[("Content-Length", "20".to_string())], + b"private-body-secret!", + )]) + .await; + let _download_base = ImportDownloadBaseUrlGuard::set(server.base_url.clone()); + let tmp = tempfile::tempdir().unwrap(); + let (runtime, _registry) = super::register_import_agent_with_capabilities( + tmp.path(), + Some(crate::runner_protocol::RunnerCapabilities { + file_write: true, + ..Default::default() + }), + ) + .await; + let config = super::test_config(Some("secret")); + let (_db_tmp, db) = super::test_db(); + let service = Service::new(fixture::router(config, db, runtime)); + let (output, subscriber) = capture_import_warnings(); + let trace = "c77c5ec6-32e4-4a54-8590-4da44d35a8be"; + let mut resp = crate::tool_request_trace::scope_active_trace(Some(trace.to_string()), async { + TestClient::post("http://localhost/test-host-file-import") + .bearer_auth("secret") + .json(&import_body( + "https://files.oaiusercontent.com/private-path-secret?sig=signed-query-secret", + "image/png", + "private-file-secret.png", + )) + .send(&service) + .await + }) + .with_subscriber(subscriber) + .await; + let body: Value = resp.take_json().await.unwrap(); + assert_eq!(body["success"], false); + assert_eq!(body["output"]["count"], 0); + assert_eq!(body["output"]["partial_success"], false); + assert!(!tmp + .path() + .join("docs/assets/private-file-secret.png") + .exists()); + let log = String::from_utf8(output.lock().unwrap().clone()).unwrap(); + let event = log + .lines() + .find(|line| line.contains("mcp_host_file_import_failed")) + .unwrap(); + assert_eq!( + log.lines() + .filter(|line| line.contains("mcp_host_file_import_failed")) + .count(), + 1 + ); + for expected in [ + "WARN", + "stage=\"download_request\"", + "failure_class=\"http_status\"", + "http_status=403", + trace, + ] { + assert!(event.contains(expected), "{event}"); + } + for secret in [ + "private-path-secret", + "signed-query-secret", + "private-file-secret", + "private-body-secret", + "https://", + "Authorization", + "Bearer", + "files.oaiusercontent.com", + ] { + assert!(!log.contains(secret), "{log}"); + } +} const IMPORT_TEST_AGENT_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); + +#[tokio::test] +async fn import_http_truncated_body_logs_read_stage_and_aborts_without_success() { + let _guard = lock_import_http_test().await; + let server = start_mock_http_server(vec![http_response( + "200 OK", + &[("Content-Length", "100".to_string())], + b"short", + )]) + .await; + let _download_base = ImportDownloadBaseUrlGuard::set(server.base_url.clone()); + let tmp = tempfile::tempdir().unwrap(); + let (runtime, registry) = super::register_import_agent_with_capabilities( + tmp.path(), + Some(crate::runner_protocol::RunnerCapabilities { + file_write: true, + ..Default::default() + }), + ) + .await; + let config = super::test_config(Some("secret")); + let (_db_tmp, db) = super::test_db(); + let service = Service::new(fixture::router(config, db, runtime)); + let agent = tokio::spawn(complete_import_artifact_uploads(registry, 1)); + let (output, subscriber) = capture_import_warnings(); + let mut resp = TestClient::post("http://localhost/test-host-file-import") + .bearer_auth("secret") + .json(&import_body( + "https://files.oaiusercontent.com/body-secret?sig=SECRET", + "image/png", + "private-body.png", + )) + .send(&service) + .with_subscriber(subscriber) + .await; + let outcomes = tokio::time::timeout(Duration::from_secs(5), agent) + .await + .unwrap() + .unwrap(); + assert!(outcomes[0].aborted); + assert!(!outcomes[0].finished); + let body: Value = resp.take_json().await.unwrap(); + assert_eq!(body["success"], false); + assert_eq!(body["output"]["count"], 0); + assert!(!tmp.path().join("docs/assets/private-body.png").exists()); + let log = String::from_utf8(output.lock().unwrap().clone()).unwrap(); + assert!(log.contains("stage=\"download_body\""), "{log}"); + assert!(log.contains("failure_class=\"failed\""), "{log}"); + for excluded in [ + "body-secret", + "SECRET", + "private-body.png", + "https://", + "docs/assets", + ] { + assert!(!log.contains(excluded), "{log}"); + } +} // The global import-network override is shared with MCP and DNS import fixtures. // Budget for queued full-suite contention while still failing a genuinely stuck wait. const IMPORT_TEST_LOCK_TIMEOUT: Duration = Duration::from_secs(60); @@ -876,6 +1040,16 @@ async fn import_http_batch_failure_reports_prior_success_and_preserves_unicode_n ); assert_eq!(body["output"]["failed_item"]["index"], 1); assert_eq!(body["output"]["failed_item"]["source_name"], "source.docx"); + use sha2::{Digest, Sha256}; + let confirmed = &body["output"]["imported"][0]; + assert_eq!(confirmed["bytes_written"], first_bytes.len()); + assert_eq!( + confirmed["sha256"], + format!("{:x}", Sha256::digest(&first_bytes)) + ); + assert_eq!(body["output"]["succeeded"], body["output"]["imported"]); + assert_eq!(body["output"]["imported"].as_array().unwrap().len(), 1); + assert!(!tmp.path().join("docs/assets/wrong.bin").exists()); assert!(body["output"]["failure_reason"] .as_str() .unwrap() @@ -913,6 +1087,7 @@ async fn import_http_preserves_overwrite_false_protection() { let (_db_tmp, db) = super::test_db(); let service = Service::new(fixture::router(config, db, runtime)); let agent = tokio::spawn(complete_import_artifact_uploads(registry, 1)); + let (output, subscriber) = capture_import_warnings(); let mut resp = TestClient::post("http://localhost/test-host-file-import") .bearer_auth("secret") .json(&json!({ @@ -928,6 +1103,7 @@ async fn import_http_preserves_overwrite_false_protection() { }] })) .send(&service) + .with_subscriber(subscriber) .await; tokio::time::timeout(Duration::from_secs(5), agent) .await @@ -943,6 +1119,18 @@ async fn import_http_preserves_overwrite_false_protection() { .unwrap() .contains("overwrite is false")); assert_eq!(std::fs::read(existing).unwrap(), b"original"); + let log = String::from_utf8(output.lock().unwrap().clone()).unwrap(); + assert!(log.contains("stage=\"upload_begin\""), "{log}"); + assert!(log.contains("failure_class=\"failed\""), "{log}"); + for excluded in [ + "existing.png", + "replacement.png", + "docs/assets", + "original", + "overwrite is false", + ] { + assert!(!log.contains(excluded), "{log}"); + } } #[tokio::test] diff --git a/src/tool_runtime/conversation_import.rs b/src/tool_runtime/conversation_import.rs index 6c01a35cf..9b0e5c5b3 100644 --- a/src/tool_runtime/conversation_import.rs +++ b/src/tool_runtime/conversation_import.rs @@ -35,6 +35,86 @@ const IMPORT_DNS_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(5); const IMPORT_DOWNLOAD_IDLE_TIMEOUT: Duration = Duration::from_secs(30); const IMPORT_DOWNLOAD_OVERALL_NETWORK_TIMEOUT: Duration = Duration::from_secs(15 * 60); +#[derive(Clone, Copy)] +enum ImportFailureStage { + Dns, + DownloadRequest, + DownloadBody, + UploadBegin, + UploadChunk, + UploadFinish, +} + +impl ImportFailureStage { + fn as_str(self) -> &'static str { + match self { + Self::Dns => "dns", + Self::DownloadRequest => "download_request", + Self::DownloadBody => "download_body", + Self::UploadBegin => "upload_begin", + Self::UploadChunk => "upload_chunk", + Self::UploadFinish => "upload_finish", + } + } +} + +#[derive(Clone, Copy)] +enum ImportFailureClass { + Timeout, + ConnectionFailed, + Failed, + HttpStatus, + SizeLimit, + ProtocolMismatch, +} + +impl ImportFailureClass { + fn as_str(self) -> &'static str { + match self { + Self::Timeout => "timeout", + Self::ConnectionFailed => "connection_failed", + Self::Failed => "failed", + Self::HttpStatus => "http_status", + Self::SizeLimit => "size_limit", + Self::ProtocolMismatch => "protocol_mismatch", + } + } +} + +fn diagnostic_trace_id() -> Option { + crate::tool_request_trace::current_active_trace_id() + .and_then(|id| uuid::Uuid::parse_str(&id).ok()) + .map(|id| id.hyphenated().to_string()) +} + +fn log_import_failure( + stage: ImportFailureStage, + failure: ImportFailureClass, + http_status: Option, +) { + let server_trace_id = diagnostic_trace_id(); + // Only fixed categories, a bounded status and a canonical UUID. Never pass + // error text, URLs, file names, paths, upload IDs or caller identities here. + tracing::warn!( + target: "webcodex::mcp", + stage = stage.as_str(), + failure_class = failure.as_str(), + http_status = http_status.filter(|status| (100..=599).contains(status)), + server_trace_id = server_trace_id.as_deref(), + "mcp_host_file_import_failed" + ); +} + +fn download_failure_class(error: &reqwest::Error) -> ImportFailureClass { + if error.is_timeout() { + ImportFailureClass::Timeout + } else if error.is_connect() { + ImportFailureClass::ConnectionFailed + } else { + ImportFailureClass::Failed + } +} + #[derive(Debug)] struct TrustedDownloadTarget { url: reqwest::Url, @@ -244,6 +324,65 @@ fn ip_is_public(ip: IpAddr) -> bool { } } +fn dns_diagnostic_host(host: &str) -> Option<&str> { + let host = host.strip_suffix('.').unwrap_or(host); + if host.is_empty() || host.len() > 253 { + return None; + } + host.split('.') + .all(|label| { + !label.is_empty() + && label.len() <= 63 + && !label.starts_with('-') + && !label.ends_with('-') + && label + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + }) + .then_some(host) +} + +fn dns_diagnostic_address_class(ip: IpAddr) -> &'static str { + if ip_is_public(ip) { + return "public"; + } + if let IpAddr::V6(v6) = ip { + if let Some(v4) = ipv6_embedded_ipv4(v6) { + return dns_diagnostic_address_class(IpAddr::V4(v4)); + } + } + match ip { + IpAddr::V4(v4) if v4.octets()[0] == 198 && matches!(v4.octets()[1], 18 | 19) => { + "benchmarking" + } + ip if ip.is_loopback() => "loopback", + IpAddr::V4(v4) if v4.is_link_local() => "link_local", + IpAddr::V6(v6) if v6.segments()[0] & 0xffc0 == 0xfe80 => "link_local", + _ => "non_public", + } +} + +fn log_download_dns_rejection(host: Option<&str>, ips: &[IpAddr]) { + let Some(host) = host.and_then(dns_diagnostic_host) else { + return; + }; + let address_classes: std::collections::BTreeSet<_> = ips + .iter() + .copied() + .map(dns_diagnostic_address_class) + .collect(); + let server_trace_id = diagnostic_trace_id(); + // Log no URL, path, query, raw address, file identity or caller identity. + // Domains are bounded DNS labels; classes and event name are constants. + tracing::warn!( + target: "webcodex::mcp", + download_host = host, + address_classes = ?address_classes, + server_trace_id = server_trace_id.as_deref(), + "mcp_host_file_download_dns_rejected" + ); +} + #[cfg(test)] static IMPORT_TEST_NETWORK_LOCK: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -293,14 +432,27 @@ async fn resolve_download_domain(host: &str) -> Result, String> { return Ok(ips); } } - let resolved = tokio::time::timeout( - IMPORT_DNS_RESOLUTION_TIMEOUT, - tokio::net::lookup_host((host, 443)), - ) + bounded_download_dns_resolution(async { + tokio::net::lookup_host((host, 443)) + .await + .map(|resolved| resolved.map(|addr| addr.ip()).collect()) + }) .await - .map_err(|_| "host-provided download URL DNS resolution timed out".to_string())? - .map_err(|_| "host-provided download URL DNS resolution failed".to_string())?; - Ok(resolved.map(|addr| addr.ip()).collect()) +} + +async fn bounded_download_dns_resolution( + lookup: impl std::future::Future>>, +) -> Result, String> { + tokio::time::timeout(IMPORT_DNS_RESOLUTION_TIMEOUT, lookup) + .await + .map_err(|_| { + log_import_failure(ImportFailureStage::Dns, ImportFailureClass::Timeout, None); + "host-provided download URL DNS resolution timed out".to_string() + })? + .map_err(|_| { + log_import_failure(ImportFailureStage::Dns, ImportFailureClass::Failed, None); + "host-provided download URL DNS resolution failed".to_string() + }) } async fn validate_trusted_mcp_download_url( @@ -336,9 +488,11 @@ async fn validate_trusted_mcp_download_url( } }; if ips.is_empty() { + log_download_dns_rejection(resolver_host.as_deref(), &ips); return Err("host-provided download URL resolved to no addresses".to_string()); } if ips.iter().copied().any(|ip| !ip_is_public(ip)) { + log_download_dns_rejection(resolver_host.as_deref(), &ips); return Err("host-provided download URL resolves to a non-public address".to_string()); } let mut pinned_addrs = Vec::with_capacity(ips.len()); @@ -480,6 +634,11 @@ impl ToolRuntime { ) .await; if !result.success { + log_import_failure( + ImportFailureStage::UploadChunk, + ImportFailureClass::Failed, + None, + ); if artifact_upload_failure_is_definite(&result, upload_id) { self.abort_import_upload( &input.project, @@ -494,6 +653,11 @@ impl ToolRuntime { return Err(result); } if result.output.get("next_offset").and_then(Value::as_u64) != Some(next_offset as u64) { + log_import_failure( + ImportFailureStage::UploadChunk, + ImportFailureClass::ProtocolMismatch, + None, + ); self.abort_import_upload( &input.project, path, @@ -556,13 +720,23 @@ impl ToolRuntime { network_budget = network_budget.saturating_sub(send_started.elapsed()); let mut response = match send_result { Ok(Ok(response)) => response, - Ok(Err(_)) | Err(_) => { + failure => { + let class = match failure { + Ok(Err(error)) => download_failure_class(&error), + _ => ImportFailureClass::Timeout, + }; + log_import_failure(ImportFailureStage::DownloadRequest, class, None); return Err(ToolResult::err(format!( "failed to download '{source_name}'" ))); } }; if !response.status().is_success() { + log_import_failure( + ImportFailureStage::DownloadRequest, + ImportFailureClass::HttpStatus, + Some(response.status().as_u16()), + ); return Err(ToolResult::err(format!( "download for '{source_name}' returned HTTP {}", response.status() @@ -570,6 +744,11 @@ impl ToolRuntime { } let expected_bytes = match response.content_length() { Some(len) if len > MAX_IMPORT_FILE_BYTES as u64 => { + log_import_failure( + ImportFailureStage::DownloadBody, + ImportFailureClass::SizeLimit, + None, + ); return Err(ToolResult::err(format!( "download for '{source_name}' exceeds {MAX_IMPORT_FILE_BYTES} bytes" ))); @@ -593,6 +772,11 @@ impl ToolRuntime { ) .await; if !begin.success { + log_import_failure( + ImportFailureStage::UploadBegin, + ImportFailureClass::Failed, + None, + ); return Err(begin); } let Some(upload_id) = begin @@ -601,6 +785,11 @@ impl ToolRuntime { .and_then(Value::as_str) .map(str::to_string) else { + log_import_failure( + ImportFailureStage::UploadBegin, + ImportFailureClass::ProtocolMismatch, + None, + ); return Err(ToolResult::err( "artifact upload begin returned no upload_id", )); @@ -611,6 +800,11 @@ impl ToolRuntime { let mut pending = Vec::with_capacity(MAX_PROJECT_ARTIFACT_UPLOAD_CHUNK_BYTES); loop { if network_budget.is_zero() { + log_import_failure( + ImportFailureStage::DownloadBody, + ImportFailureClass::Timeout, + None, + ); self.abort_import_upload( &input.project, &path, @@ -634,7 +828,12 @@ impl ToolRuntime { let chunk = match read_result { Ok(Ok(Some(chunk))) => chunk, Ok(Ok(None)) => break, - Ok(Err(_)) | Err(_) => { + failure => { + let class = match failure { + Ok(Err(error)) => download_failure_class(&error), + _ => ImportFailureClass::Timeout, + }; + log_import_failure(ImportFailureStage::DownloadBody, class, None); self.abort_import_upload( &input.project, &path, @@ -650,6 +849,11 @@ impl ToolRuntime { } }; let Some(next_downloaded_bytes) = downloaded_bytes.checked_add(chunk.len()) else { + log_import_failure( + ImportFailureStage::DownloadBody, + ImportFailureClass::SizeLimit, + None, + ); self.abort_import_upload( &input.project, &path, @@ -664,6 +868,11 @@ impl ToolRuntime { ))); }; if next_downloaded_bytes > MAX_IMPORT_FILE_BYTES { + log_import_failure( + ImportFailureStage::DownloadBody, + ImportFailureClass::SizeLimit, + None, + ); self.abort_import_upload( &input.project, &path, @@ -727,6 +936,11 @@ impl ToolRuntime { ) .await; if !result.success { + log_import_failure( + ImportFailureStage::UploadFinish, + ImportFailureClass::Failed, + None, + ); if artifact_upload_failure_is_definite(&result, &upload_id) { self.abort_import_upload( &input.project, @@ -885,6 +1099,174 @@ impl ToolRuntime { mod tests { use super::*; + #[tokio::test] + async fn diagnostic_trace_accepts_only_canonical_uuids() { + for unsafe_id in [ + "SECRET", + "safe-request-correlation", + "https://example/path?token=SECRET", + "\nINJECT", + ] { + crate::tool_request_trace::scope_active_trace(Some(unsafe_id.to_string()), async { + assert!(diagnostic_trace_id().is_none()); + }) + .await; + } + crate::tool_request_trace::scope_active_trace( + Some("C77C5EC6-32E4-4A54-8590-4DA44D35A8BE".to_string()), + async { + assert_eq!( + diagnostic_trace_id().as_deref(), + Some("c77c5ec6-32e4-4a54-8590-4da44d35a8be") + ); + }, + ) + .await; + } + + #[tokio::test(start_paused = true)] + async fn dns_failures_are_bounded_and_never_return_resolver_error_text() { + let start = tokio::time::Instant::now(); + let timeout = bounded_download_dns_resolution(std::future::pending()) + .await + .unwrap_err(); + assert_eq!( + tokio::time::Instant::now() - start, + IMPORT_DNS_RESOLUTION_TIMEOUT + ); + assert_eq!( + timeout, + "host-provided download URL DNS resolution timed out" + ); + let failed = bounded_download_dns_resolution(async { + Err(std::io::Error::other( + "https://private.example/path?sig=SECRET", + )) + }) + .await + .unwrap_err(); + assert_eq!(failed, "host-provided download URL DNS resolution failed"); + } + + #[tokio::test] + async fn dns_rejection_diagnostic_is_bounded_correlated_and_secret_free() { + #[derive(Clone)] + struct Capture(std::sync::Arc>>); + impl std::io::Write for Capture { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let capture = Capture(Default::default()); + let writer = capture.clone(); + let subscriber = tracing_subscriber::fmt() + .with_env_filter("warn") + .with_ansi(false) + .without_time() + .with_writer(move || writer.clone()) + .finish(); + let trace = "c77c5ec6-32e4-4a54-8590-4da44d35a8be"; + crate::tool_request_trace::scope_active_trace(Some(trace.to_string()), async { + tracing::subscriber::with_default(subscriber, || { + log_download_dns_rejection( + Some("files.oaiusercontent.com"), + &[ + "198.18.5.253".parse().unwrap(), + "198.19.0.1".parse().unwrap(), + "8.8.8.8".parse().unwrap(), + "127.0.0.1".parse().unwrap(), + "169.254.1.1".parse().unwrap(), + ], + ); + for unsafe_host in [ + "evil.example\nINJECT", + "evil.example?token=SECRET", + "evil.example/SECRET", + "user:SECRET@evil.example", + "-bad.example", + ] { + log_download_dns_rejection( + Some(unsafe_host), + &["198.18.5.253".parse().unwrap()], + ); + } + for stage in [ + ImportFailureStage::Dns, + ImportFailureStage::DownloadRequest, + ImportFailureStage::DownloadBody, + ImportFailureStage::UploadBegin, + ImportFailureStage::UploadChunk, + ImportFailureStage::UploadFinish, + ] { + log_import_failure(stage, ImportFailureClass::Failed, Some(999)); + } + }); + }) + .await; + let output = String::from_utf8(capture.0.lock().unwrap().clone()).unwrap(); + assert_eq!(output.lines().count(), 7, "{output}"); + assert!(!output.contains("999"), "{output}"); + for line in output.lines() { + assert!(line.contains(trace), "{line}"); + } + for expected in [ + "WARN", + "mcp_host_file_download_dns_rejected", + "files.oaiusercontent.com", + trace, + "benchmarking", + "public", + "loopback", + "link_local", + ] { + assert!(output.contains(expected), "{output}"); + } + for excluded in [ + "198.18.5.253", + "198.19.0.1", + "8.8.8.8", + "127.0.0.1", + "169.254.1.1", + "SECRET", + "INJECT", + "token=", + "evil.example", + "download_url", + "query", + ] { + assert!(!output.contains(excluded), "{output}"); + } + } + + #[test] + fn dns_diagnostic_domains_and_address_classes_preserve_rejection_boundaries() { + assert_eq!( + dns_diagnostic_host("xn--bcher-kva.example."), + Some("xn--bcher-kva.example") + ); + assert!(dns_diagnostic_host(&format!("{}.example", "a".repeat(64))).is_none()); + assert!(dns_diagnostic_host(&format!("{}.example", "a".repeat(254))).is_none()); + for ip in [ + "198.18.0.0", + "198.18.5.253", + "198.19.255.255", + "::ffff:198.18.5.253", + ] { + let ip = ip.parse().unwrap(); + assert!(!ip_is_public(ip)); + assert_eq!(dns_diagnostic_address_class(ip), "benchmarking"); + } + for ip in ["10.0.0.1", "192.168.1.1", "::1", "fe80::1", "fc00::1"] { + let ip = ip.parse().unwrap(); + assert!(!ip_is_public(ip)); + assert_ne!(dns_diagnostic_address_class(ip), "public"); + } + } + #[test] fn import_limit_matches_canonical_streaming_artifact_limit() { assert_eq!(MAX_IMPORT_FILE_BYTES, MAX_PROJECT_ARTIFACT_UPLOAD_BYTES); @@ -1102,6 +1484,8 @@ mod tests { vec!["169.254.1.1".parse().unwrap()], vec!["::1".parse().unwrap()], vec!["fe80::1".parse().unwrap()], + vec!["198.18.5.253".parse().unwrap()], + vec!["8.8.8.8".parse().unwrap(), "198.18.5.253".parse().unwrap()], ] { set_import_test_resolved_ips(Some(ips)); reset_import_test_dns_resolution_count(); @@ -1115,6 +1499,14 @@ mod tests { ); assert_eq!(import_test_dns_resolution_count(), 1); } + // A resolver-specific Fake-IP exception may restore real public answers; + // admission still uses the same all-public predicate and pinned addresses. + set_import_test_resolved_ips(Some(vec!["8.8.8.8".parse().unwrap()])); + let target = validate_trusted_mcp_download_url("https://download.example/file") + .await + .expect("public DNS answer may pass the unchanged SSRF policy"); + assert_eq!(target.pinned_addrs, vec!["8.8.8.8:443".parse().unwrap()]); + assert_eq!(target.resolver_host.as_deref(), Some("download.example")); set_import_test_resolved_ips(None); reset_import_test_dns_resolution_count(); }