Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
),
Expand Down
83 changes: 83 additions & 0 deletions docs/CONVERSATION_FILE_IMPORT.md
Original file line number Diff line number Diff line change
@@ -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<region>.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.
4 changes: 4 additions & 0 deletions docs/DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions docs/MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 23 additions & 3 deletions src/mcp/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
}

Expand Down Expand Up @@ -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)]
{
Expand All @@ -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),
Expand All @@ -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<Option<String>, String> {
Expand Down
100 changes: 100 additions & 0 deletions src/mcp_tests/file_import.rs
Original file line number Diff line number Diff line change
@@ -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<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for Capture {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
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<std::ffi::OsString>)>,
Expand Down
Loading
Loading