Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(actix): capture HTTP request body #731

Merged
merged 18 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from 16 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
1 change: 1 addition & 0 deletions sentry-actix/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ futures-util = { version = "0.3.5", default-features = false }
sentry-core = { version = "0.36.0", path = "../sentry-core", default-features = false, features = [
"client",
] }
actix-http = "3.9.0"

[dev-dependencies]
actix-web = { version = "4" }
Expand Down
105 changes: 86 additions & 19 deletions sentry-actix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,20 @@

use std::borrow::Cow;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;

use actix_http::header::{self, HeaderMap};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::error::PayloadError;
use actix_web::http::StatusCode;
use actix_web::Error;
use actix_web::web::BytesMut;
use actix_web::{Error, HttpMessage};
use futures_util::future::{ok, Future, Ready};
use futures_util::FutureExt;

use sentry_core::protocol::{self, ClientSdkPackage, Event, Request};
use sentry_core::MaxRequestBodySize;
use sentry_core::{Hub, SentryFutureExt};

/// A helper construct that can be used to reconfigure and build the middleware.
Expand Down Expand Up @@ -180,7 +185,7 @@ impl Default for Sentry {

impl<S, B> Transform<S, ServiceRequest> for Sentry
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
{
type Response = ServiceResponse<B>;
Expand All @@ -191,21 +196,75 @@ where

fn new_transform(&self, service: S) -> Self::Future {
ok(SentryMiddleware {
service,
service: Rc::new(service),
inner: self.clone(),
})
}
}

/// The middleware for individual services.
pub struct SentryMiddleware<S> {
service: S,
service: Rc<S>,
inner: Sentry,
}

fn should_capture_request_body(
headers: &HeaderMap,
max_request_body_size: MaxRequestBodySize,
) -> bool {
let is_chunked = headers
.get(header::TRANSFER_ENCODING)
.and_then(|h| h.to_str().ok())
.map(|transfer_encoding| transfer_encoding.contains("chunked"))
.unwrap_or(false);

let is_valid_content_type = headers
.get(header::CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
.is_some_and(|content_type| {
matches!(
content_type,
"application/json" | "application/x-www-form-urlencoded"
)
});

let is_within_size_limit = headers
.get(header::CONTENT_LENGTH)
.and_then(|h| h.to_str().ok())
.and_then(|content_length| content_length.parse::<usize>().ok())
.map(|content_length| max_request_body_size.is_within_size_limit(content_length))
.unwrap_or(false);

!is_chunked && is_valid_content_type && is_within_size_limit
}

/// Extract a body from the HTTP request
async fn body_from_http(req: &mut ServiceRequest) -> Result<BytesMut, PayloadError> {
let mut stream = req.take_payload();

let mut body = BytesMut::new();
while let Some(chunk) = futures_util::StreamExt::next(&mut stream).await {
let chunk = chunk?;
body.extend_from_slice(&chunk);
}
let (_, mut orig_payload) = actix_http::h1::Payload::create(true);
orig_payload.unread_data(body.clone().freeze());
req.set_payload(actix_web::dev::Payload::from(orig_payload));

Ok::<_, PayloadError>(body)
}

async fn capture_request_body(req: &mut ServiceRequest) -> String {
if let Ok(request_body) = body_from_http(req).await {
String::from_utf8_lossy(&request_body).into_owned()
} else {
String::new()
}
}

impl<S, B> Service<ServiceRequest> for SentryMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
{
type Response = ServiceResponse<B>;
Expand All @@ -230,14 +289,18 @@ where
options.auto_session_tracking
&& options.session_mode == sentry_core::SessionMode::Request
});
let max_request_body_size = client
.as_ref()
.map(|client| client.options().max_request_body_size)
.unwrap_or(MaxRequestBodySize::None);
if track_sessions {
hub.start_session();
}
let with_pii = client
.as_ref()
.is_some_and(|client| client.options().send_default_pii);

let sentry_req = sentry_request_from_http(&req, with_pii);
let mut sentry_req = sentry_request_from_http(&req, with_pii);
let name = transaction_name_from_http(&req);

let transaction = if inner.start_transaction {
Expand All @@ -258,21 +321,25 @@ where
None
};

let parent_span = hub.configure_scope(|scope| {
let parent_span = scope.get_span();
if let Some(transaction) = transaction.as_ref() {
scope.set_span(Some(transaction.clone().into()));
} else {
scope.set_transaction((!inner.start_transaction).then_some(&name));
}
scope.add_event_processor(move |event| Some(process_event(event, &sentry_req)));
parent_span
});
let svc = self.service.clone();
async move {
let mut req = req;

let fut = self.service.call(req).bind_hub(hub.clone());
if should_capture_request_body(req.headers(), max_request_body_size) {
sentry_req.data = Some(capture_request_body(&mut req).await);
}

async move {
// Service errors
let parent_span = hub.configure_scope(|scope| {
let parent_span = scope.get_span();
if let Some(transaction) = transaction.as_ref() {
scope.set_span(Some(transaction.clone().into()));
} else {
scope.set_transaction((!inner.start_transaction).then_some(&name));
}
scope.add_event_processor(move |event| Some(process_event(event, &sentry_req)));
parent_span
});
let fut = svc.call(req).bind_hub(hub.clone());
let mut res: Self::Response = match fut.await {
Ok(res) => res,
Err(e) => {
Expand Down
36 changes: 36 additions & 0 deletions sentry-core/src/clientoptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,39 @@ pub enum SessionMode {
Request,
}

/// The maximum size of an HTTP request body that the SDK captures.
///
/// Only request bodies that parse as JSON or form data are currently captured.
/// See the [Documentation on attaching request body](https://develop.sentry.dev/sdk/expected-features/#attaching-request-body-in-server-sdks)
/// and the [Documentation on handling sensitive data](https://develop.sentry.dev/sdk/expected-features/data-handling/#sensitive-data)
/// for more information.
#[derive(Clone, Copy, PartialEq)]
pub enum MaxRequestBodySize {
/// Don't capture request body
None,
/// Capture up to 1000 bytes
Small,
/// Capture up to 10000 bytes
Medium,
/// Capture entire body
Always,
/// Capture up to a specific size
Explicit(usize),
}

impl MaxRequestBodySize {
/// Check if the content length is within the size limit.
pub fn is_within_size_limit(&self, content_length: usize) -> bool {
match self {
MaxRequestBodySize::None => false,
MaxRequestBodySize::Small => content_length <= 1_000,
MaxRequestBodySize::Medium => content_length <= 10_000,
MaxRequestBodySize::Always => true,
MaxRequestBodySize::Explicit(size) => content_length <= *size,
}
}
}

/// Configuration settings for the client.
///
/// These options are explained in more detail in the general
Expand Down Expand Up @@ -148,6 +181,8 @@ pub struct ClientOptions {
pub trim_backtraces: bool,
/// The user agent that should be reported.
pub user_agent: Cow<'static, str>,
/// Controls how much of request bodies are captured
pub max_request_body_size: MaxRequestBodySize,
}

impl ClientOptions {
Expand Down Expand Up @@ -256,6 +291,7 @@ impl Default for ClientOptions {
extra_border_frames: vec![],
trim_backtraces: true,
user_agent: Cow::Borrowed(USER_AGENT),
max_request_body_size: MaxRequestBodySize::None,
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions sentry-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ mod session;
#[cfg(all(feature = "client", feature = "metrics"))]
mod units;

#[cfg(feature = "client")]
pub use crate::clientoptions::MaxRequestBodySize;

#[cfg(feature = "client")]
pub use crate::{client::Client, hub_impl::SwitchGuard as HubSwitchGuard};

Expand Down