1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use conduit::{Host, RequestExt, Scheme};
use conduit_middleware::{AfterResult, BeforeResult, Middleware};
use sentry_core::protocol::{ClientSdkPackage, Event, Request, SessionStatus};
use sentry_core::{Hub, ScopeGuard};
use std::borrow::Cow;

pub struct SentryMiddleware {
    track_sessions: bool,
    with_pii: bool,
}

impl Default for SentryMiddleware {
    fn default() -> Self {
        // Read `send_default_pii` and `auto_session_tracking` options from
        // Sentry configuration by default
        let (with_pii, track_sessions) = Hub::with_active(|hub| {
            let client = hub.client();

            let with_pii = client
                .as_ref()
                .map_or(false, |client| client.options().send_default_pii);

            let track_sessions = client.as_ref().map_or(false, |client| {
                let options = client.options();
                options.auto_session_tracking
                    && options.session_mode == sentry_core::SessionMode::Request
            });

            (with_pii, track_sessions)
        });

        SentryMiddleware {
            track_sessions,
            with_pii,
        }
    }
}

impl SentryMiddleware {
    pub fn new() -> SentryMiddleware {
        Default::default()
    }
}

impl Middleware for SentryMiddleware {
    fn before(&self, req: &mut dyn RequestExt) -> BeforeResult {
        // Push a `Scope` to the stack so that all further `configure_scope()`
        // calls are scoped to this specific request.
        let scope = Hub::with_active(|hub| hub.push_scope());

        // Start a `Session`, if session tracking is enabled
        if self.track_sessions {
            sentry_core::start_session();
        }

        // Extract HTTP request information from `req`
        let sentry_req = sentry_request_from_http(req, self.with_pii);
        // ... and configure Sentry to use it
        sentry_core::configure_scope(|scope| {
            scope.add_event_processor(Box::new(move |event| {
                Some(process_event(event, &sentry_req))
            }));
        });

        // Save the `ScopeGuard` in the request to ensure that it's not dropped yet
        req.mut_extensions().insert(scope);

        Ok(())
    }

    fn after(&self, req: &mut dyn RequestExt, result: AfterResult) -> AfterResult {
        if let Some(scope) = req.mut_extensions().pop::<ScopeGuard>() {
            #[cfg(feature = "router")]
            {
                sentry_core::configure_scope(|scope| {
                    // unfortunately, `RoutePattern` is only available in the `after` handler
                    // so we can't add the `transaction` field to any captures that happen
                    // before this is called.
                    use conduit_router::RoutePattern;

                    let transaction = req
                        .extensions()
                        .find::<RoutePattern>()
                        .map(|pattern| pattern.pattern());

                    scope.set_transaction(transaction);
                });
            }

            // Capture `Err` results as errors
            if let Err(error) = &result {
                sentry_core::capture_error(error.as_ref());
            }

            // End the `Session`, if session tracking is enabled
            if self.track_sessions {
                let status = match &result {
                    Ok(_) => SessionStatus::Exited,
                    Err(_) => SessionStatus::Abnormal,
                };
                sentry_core::end_session_with_status(status);
            }

            // Explicitly drop the `Scope` (technically unnecessary)
            drop(scope);
        }

        result
    }
}

/// Build a Sentry request struct from the HTTP request
fn sentry_request_from_http(request: &dyn RequestExt, with_pii: bool) -> Request {
    let method = Some(request.method().to_string());

    let scheme = match request.scheme() {
        Scheme::Http => "http",
        Scheme::Https => "https",
    };

    let host = match request.host() {
        Host::Name(name) => Cow::from(name),
        Host::Socket(addr) => Cow::from(addr.to_string()),
    };

    let path = request.path();

    let mut url = format!("{}://{}{}", scheme, host, path);

    if let Some(query_string) = request.query_string() {
        url += "?";
        url += query_string;
    }

    let headers = request
        .headers()
        .iter()
        .filter(|(_name, value)| !value.is_sensitive())
        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or_default().to_string()))
        .collect();

    let mut sentry_req = Request {
        url: url.parse().ok(),
        method,
        headers,
        ..Default::default()
    };

    // If PII is enabled, include the remote address
    if with_pii {
        let remote_addr = request.remote_addr().to_string();
        sentry_req.env.insert("REMOTE_ADDR".into(), remote_addr);
    };

    sentry_req
}

/// Add request data to a Sentry event
fn process_event(mut event: Event<'static>, request: &Request) -> Event<'static> {
    // Request
    if event.request.is_none() {
        event.request = Some(request.clone());
    }

    // SDK
    if let Some(sdk) = event.sdk.take() {
        let mut sdk = sdk.into_owned();
        sdk.packages.push(ClientSdkPackage {
            name: "sentry-conduit".into(),
            version: env!("CARGO_PKG_VERSION").into(),
        });
        event.sdk = Some(Cow::Owned(sdk));
    }

    event
}