Make feedback uploads proxy-aware

This commit is contained in:
celia-oai
2026-08-17 16:22:49 -07:00
parent 050aa077b5
commit f385d036f3
8 changed files with 379 additions and 433 deletions
+5 -1
View File
@@ -9,16 +9,20 @@ workspace = true
[dependencies]
anyhow = { workspace = true }
codex-http-client = { workspace = true }
codex-login = { workspace = true }
codex-protocol = { workspace = true }
mime_guess = { workspace = true }
sentry = { version = "0.46" }
sentry = { version = "0.46", default-features = false }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
[dev-dependencies]
log = { workspace = true }
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
wiremock = { workspace = true }
[lib]
doctest = false
+2 -75
View File
@@ -8,10 +8,7 @@ use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::Result;
use anyhow::anyhow;
use codex_login::AuthEnvTelemetry;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
@@ -25,9 +22,11 @@ use tracing_subscriber::fmt::writer::MakeWriter;
use tracing_subscriber::registry::LookupSpan;
pub(crate) mod feedback_diagnostics;
mod upload;
pub use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME;
pub use feedback_diagnostics::FeedbackDiagnostic;
pub use feedback_diagnostics::FeedbackDiagnostics;
pub use upload::PreparedFeedbackUpload;
/// Filename used for the redacted `codex doctor --json` feedback attachment.
pub const DOCTOR_REPORT_ATTACHMENT_FILENAME: &str = "codex-doctor-report.json";
@@ -419,78 +418,6 @@ impl FeedbackSnapshot {
self.feedback_diagnostics.attachment_text()
}
/// Upload feedback to Sentry with optional attachments.
pub fn upload_feedback(&self, options: FeedbackUploadOptions<'_>) -> Result<()> {
use std::str::FromStr;
use std::sync::Arc;
use sentry::Client;
use sentry::ClientOptions;
use sentry::protocol::Envelope;
use sentry::protocol::EnvelopeItem;
use sentry::protocol::Event;
use sentry::protocol::Level;
use sentry::transports::DefaultTransportFactory;
use sentry::types::Dsn;
// Build Sentry client
let client = Client::from_config(ClientOptions {
dsn: Some(Dsn::from_str(SENTRY_DSN).map_err(|e| anyhow!("invalid DSN: {e}"))?),
transport: Some(Arc::new(DefaultTransportFactory {})),
..Default::default()
});
let tags = self.upload_tags(
options.classification,
options.reason,
options.tags,
options.session_source.as_ref(),
);
let level = match options.classification {
"bug" | "bad_result" | "safety_check" => Level::Error,
_ => Level::Info,
};
let mut envelope = Envelope::new();
let title = format!(
"[{}]: Codex session {}",
display_classification(options.classification),
self.thread_id
);
let mut event = Event {
level,
message: Some(title.clone()),
tags,
..Default::default()
};
if let Some(r) = options.reason {
use sentry::protocol::Exception;
use sentry::protocol::Values;
event.exception = Values::from(vec![Exception {
ty: title,
value: Some(r.to_string()),
..Default::default()
}]);
}
envelope.add_item(EnvelopeItem::Event(event));
for attachment in self.feedback_attachments(
options.include_logs,
options.extra_attachments,
options.extra_attachment_paths,
options.logs_override,
) {
envelope.add_item(EnvelopeItem::Attachment(attachment));
}
client.send_envelope(envelope);
client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS)));
Ok(())
}
fn upload_tags(
&self,
classification: &str,
+128
View File
@@ -0,0 +1,128 @@
use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientFactory;
use sentry::ClientOptions;
use sentry::protocol::Envelope;
use sentry::protocol::EnvelopeItem;
use sentry::protocol::Event;
use sentry::protocol::Exception;
use sentry::protocol::Level;
use sentry::protocol::Values;
use sentry::types::Dsn;
use crate::FeedbackSnapshot;
use crate::FeedbackUploadOptions;
use crate::SENTRY_DSN;
use crate::UPLOAD_TIMEOUT_SECS;
use crate::display_classification;
/// Serialized feedback ready to upload without performing additional filesystem reads.
pub struct PreparedFeedbackUpload {
endpoint: String,
authorization: String,
body: Vec<u8>,
}
impl PreparedFeedbackUpload {
/// Sends the prepared envelope using the application's configured outbound proxy policy.
pub async fn send(self, http_client_factory: &HttpClientFactory) -> Result<()> {
let client = http_client_factory
.build_client(&self.endpoint, ClientRouteClass::Other)
.context("failed to build Sentry feedback HTTP client")?;
client
.post(&self.endpoint)
.header("X-Sentry-Auth", self.authorization)
.timeout(Duration::from_secs(UPLOAD_TIMEOUT_SECS))
.body(self.body)
.send()
.await
.context("failed to send Sentry feedback envelope")?
.error_for_status()
.context("Sentry feedback upload returned an unsuccessful HTTP status")?;
Ok(())
}
}
impl FeedbackSnapshot {
/// Builds a feedback envelope and synchronously reads any file-backed attachments.
///
/// Call this from a blocking task, then send the resulting upload asynchronously with the
/// application's configured [`HttpClientFactory`].
pub fn prepare_feedback_upload(
&self,
options: FeedbackUploadOptions<'_>,
) -> Result<PreparedFeedbackUpload> {
let dsn = SENTRY_DSN.parse::<Dsn>().context("invalid Sentry DSN")?;
self.prepare_feedback_upload_with_dsn(options, &dsn)
}
fn prepare_feedback_upload_with_dsn(
&self,
options: FeedbackUploadOptions<'_>,
dsn: &Dsn,
) -> Result<PreparedFeedbackUpload> {
let tags = self.upload_tags(
options.classification,
options.reason,
options.tags,
options.session_source.as_ref(),
);
let level = match options.classification {
"bug" | "bad_result" | "safety_check" => Level::Error,
_ => Level::Info,
};
let mut envelope = Envelope::new();
let title = format!(
"[{}]: Codex session {}",
display_classification(options.classification),
self.thread_id
);
let mut event = Event {
level,
message: Some(title.clone()),
tags,
..Default::default()
};
if let Some(reason) = options.reason {
event.exception = Values::from(vec![Exception {
ty: title,
value: Some(reason.to_string()),
..Default::default()
}]);
}
envelope.add_item(EnvelopeItem::Event(event));
for attachment in self.feedback_attachments(
options.include_logs,
options.extra_attachments,
options.extra_attachment_paths,
options.logs_override,
) {
envelope.add_item(EnvelopeItem::Attachment(attachment));
}
let mut body = Vec::new();
envelope
.to_writer(&mut body)
.context("failed to serialize Sentry feedback envelope")?;
let user_agent = ClientOptions::default().user_agent;
Ok(PreparedFeedbackUpload {
endpoint: dsn.envelope_api_url().to_string(),
authorization: dsn.to_auth(Some(user_agent.as_ref())).to_string(),
body,
})
}
}
#[cfg(test)]
#[path = "upload_tests.rs"]
mod tests;
+232
View File
@@ -0,0 +1,232 @@
use anyhow::Context;
use anyhow::Result;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_http_client::cache_system_proxy_route_for_test;
use pretty_assertions::assert_eq;
use sentry::ClientOptions;
use sentry::types::Auth;
use sentry::types::Dsn;
use serde_json::Value;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use crate::CodexFeedback;
use crate::FeedbackAttachment;
use crate::FeedbackDiagnostics;
use crate::FeedbackUploadOptions;
#[tokio::test]
async fn sends_authenticated_envelope_with_existing_event_and_attachments() -> Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/42/envelope/"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let dsn = format!("http://public@{}/42", server.address()).parse::<Dsn>()?;
let snapshot = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.with_feedback_diagnostics(FeedbackDiagnostics::default());
let extra_attachments = [FeedbackAttachment {
filename: "doctor.json".to_string(),
content_type: Some("application/json".to_string()),
buffer: br#"{"ok":true}"#.to_vec(),
}];
let upload = snapshot.prepare_feedback_upload_with_dsn(
FeedbackUploadOptions {
classification: "bug",
reason: Some("proxy regression"),
tags: None,
include_logs: true,
extra_attachments: &extra_attachments,
extra_attachment_paths: &[],
session_source: None,
logs_override: Some(b"captured logs".to_vec()),
},
&dsn,
)?;
upload
.send(&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault))
.await?;
let requests = server.received_requests().await.unwrap_or_default();
assert_eq!(requests.len(), 1);
let request = &requests[0];
let user_agent = ClientOptions::default().user_agent;
let authorization = request
.headers
.get("x-sentry-auth")
.context("feedback request should include Sentry authentication")?
.to_str()?
.parse::<Auth>()?;
assert_eq!(
(
authorization.public_key(),
authorization.version(),
authorization.client_agent(),
authorization.timestamp().is_some(),
),
("public", 7, Some(user_agent.as_ref()), true)
);
let body = String::from_utf8(request.body.clone())?;
let lines = body.lines().collect::<Vec<_>>();
assert_eq!(lines.len(), 7);
let event = serde_json::from_str::<Value>(lines[2])?;
assert_eq!(
(
event["message"].as_str(),
event["tags"]["classification"].as_str(),
event["exception"]["values"][0]["value"].as_str(),
),
(
Some(format!("[Bug]: Codex session {}", snapshot.thread_id).as_str()),
Some("bug"),
Some("proxy regression"),
)
);
let logs_header = serde_json::from_str::<Value>(lines[3])?;
let doctor_header = serde_json::from_str::<Value>(lines[5])?;
assert_eq!(
vec![
(
logs_header["filename"].as_str(),
logs_header["content_type"].as_str(),
lines[4],
),
(
doctor_header["filename"].as_str(),
doctor_header["content_type"].as_str(),
lines[6],
),
],
vec![
(Some("codex-logs.log"), Some("text/plain"), "captured logs"),
(
Some("doctor.json"),
Some("application/json"),
r#"{"ok":true}"#,
),
]
);
Ok(())
}
#[tokio::test]
async fn respects_system_proxy_for_sentry_envelope_destination() -> Result<()> {
let proxy = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/42/envelope/"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&proxy)
.await;
let dsn = "http://public@feedback-proxy.invalid/42".parse::<Dsn>()?;
let endpoint = dsn.envelope_api_url().to_string();
cache_system_proxy_route_for_test(&endpoint, proxy.uri());
let upload = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.prepare_feedback_upload_with_dsn(
FeedbackUploadOptions {
classification: "bug",
reason: None,
tags: None,
include_logs: false,
extra_attachments: &[],
extra_attachment_paths: &[],
session_source: None,
logs_override: None,
},
&dsn,
)?;
upload
.send(&HttpClientFactory::new(
OutboundProxyPolicy::RespectSystemProxy,
))
.await?;
Ok(())
}
#[tokio::test]
async fn returns_sentry_http_failures_to_the_caller() -> Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/api/42/envelope/"))
.respond_with(ResponseTemplate::new(503))
.expect(1)
.mount(&server)
.await;
let dsn = format!("http://public@{}/42", server.address()).parse::<Dsn>()?;
let upload = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.prepare_feedback_upload_with_dsn(
FeedbackUploadOptions {
classification: "bug",
reason: None,
tags: None,
include_logs: false,
extra_attachments: &[],
extra_attachment_paths: &[],
session_source: None,
logs_override: None,
},
&dsn,
)?;
let error = upload
.send(&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault))
.await
.expect_err("Sentry HTTP failures should fail the feedback upload");
assert!(format!("{error:#}").contains("503"));
Ok(())
}
#[tokio::test]
async fn returns_invalid_proxy_configuration_to_the_caller() -> Result<()> {
let dsn = "http://public@invalid-feedback-proxy.invalid/42".parse::<Dsn>()?;
let endpoint = dsn.envelope_api_url().to_string();
cache_system_proxy_route_for_test(&endpoint, "not a valid proxy".to_string());
let upload = CodexFeedback::new()
.snapshot(/*session_id*/ None)
.prepare_feedback_upload_with_dsn(
FeedbackUploadOptions {
classification: "bug",
reason: None,
tags: None,
include_logs: false,
extra_attachments: &[],
extra_attachment_paths: &[],
session_source: None,
logs_override: None,
},
&dsn,
)?;
let error = upload
.send(&HttpClientFactory::new(
OutboundProxyPolicy::RespectSystemProxy,
))
.await
.expect_err("invalid proxy configuration should fail the feedback upload");
assert!(
error
.to_string()
.contains("failed to build Sentry feedback HTTP client")
);
Ok(())
}