relay_server/services/processor/
replay.rs

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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! Replay related processor code.
use std::error::Error;
use std::net::IpAddr;
use std::sync::Arc;

use crate::envelope::{ContentType, ItemType};
use crate::services::outcome::DiscardReason;
use crate::services::processor::{should_filter, ProcessingError, ReplayGroup};
use crate::services::projects::project::ProjectInfo;
use crate::statsd::{RelayCounters, RelayTimers};
use crate::utils::{sample, TypedEnvelope};
use bytes::Bytes;
use relay_base_schema::organization::OrganizationId;
use relay_base_schema::project::ProjectId;
use relay_config::Config;
use relay_dynamic_config::{Feature, GlobalConfig, ProjectConfig};
use relay_event_normalization::replay::{self, ReplayError};
use relay_event_normalization::{GeoIpLookup, RawUserAgentInfo};
use relay_event_schema::processor::{self, ProcessingState};
use relay_event_schema::protocol::{EventId, Replay};
use relay_pii::PiiProcessor;
use relay_protocol::Annotated;
use relay_replays::recording::RecordingScrubber;
use relay_statsd::metric;
use serde::{Deserialize, Serialize};

/// Removes replays if the feature flag is not enabled.
pub fn process(
    managed_envelope: &mut TypedEnvelope<ReplayGroup>,
    global_config: &GlobalConfig,
    config: Arc<Config>,
    project_info: Arc<ProjectInfo>,
    geoip_lookup: Option<&GeoIpLookup>,
) -> Result<(), ProcessingError> {
    // If the replay feature is not enabled drop the items silently.
    if should_filter(&config, &project_info, Feature::SessionReplay) {
        managed_envelope.drop_items_silently();
        return Ok(());
    }

    // If the replay video feature is not enabled check the envelope items for a
    // replay video event.
    if project_info.has_feature(Feature::SessionReplayVideoDisabled)
        && count_replay_video_events(managed_envelope) > 0
    {
        managed_envelope.drop_items_silently();
        return Ok(());
    }

    let rpc = {
        let meta = managed_envelope.envelope().meta();

        ReplayProcessingConfig {
            config: &project_info.config,
            global_config,
            geoip_lookup,
            event_id: managed_envelope.envelope().event_id(),
            project_id: project_info.project_id,
            organization_id: project_info.organization_id,
            client_addr: meta.client_addr(),
            user_agent: RawUserAgentInfo {
                user_agent: meta.user_agent().map(|s| s.to_owned()),
                client_hints: meta.client_hints().clone(),
            },
        }
    };

    let mut scrubber = if project_info.has_feature(Feature::SessionReplayRecordingScrubbing) {
        let datascrubbing_config = rpc
            .config
            .datascrubbing_settings
            .pii_config()
            .map_err(|e| ProcessingError::PiiConfigError(e.clone()))?
            .as_ref();

        Some(RecordingScrubber::new(
            config.max_replay_uncompressed_size(),
            rpc.config.pii_config.as_ref(),
            datascrubbing_config,
        ))
    } else {
        None
    };

    for item in managed_envelope.envelope_mut().items_mut() {
        if project_info.has_feature(Feature::SessionReplayCombinedEnvelopeItems) {
            item.set_replay_combined_payload(true);
        }

        match item.ty() {
            ItemType::ReplayEvent => {
                let replay_event = handle_replay_event_item(item.payload(), &rpc)?;
                item.set_payload(ContentType::Json, replay_event);
            }
            ItemType::ReplayRecording => {
                let replay_recording =
                    handle_replay_recording_item(item.payload(), scrubber.as_mut(), &rpc)?;
                item.set_payload(ContentType::OctetStream, replay_recording);
            }
            ItemType::ReplayVideo => {
                let replay_video =
                    handle_replay_video_item(item.payload(), scrubber.as_mut(), &rpc)?;
                item.set_payload(ContentType::OctetStream, replay_video);
            }
            _ => {}
        }
    }

    Ok(())
}

#[derive(Debug)]
struct ReplayProcessingConfig<'a> {
    pub config: &'a ProjectConfig,
    pub global_config: &'a GlobalConfig,
    pub geoip_lookup: Option<&'a GeoIpLookup>,
    pub event_id: Option<EventId>,
    pub project_id: Option<ProjectId>,
    pub organization_id: Option<OrganizationId>,
    pub client_addr: Option<IpAddr>,
    pub user_agent: RawUserAgentInfo<String>,
}

// Replay Event Processing.

fn handle_replay_event_item(
    payload: Bytes,
    config: &ReplayProcessingConfig<'_>,
) -> Result<Bytes, ProcessingError> {
    match process_replay_event(&payload, config) {
        Ok(replay) => {
            if let Some(replay_type) = replay.value() {
                relay_filter::should_filter(
                    replay_type,
                    config.client_addr,
                    &config.config.filter_settings,
                    config.global_config.filters(),
                )
                .map_err(ProcessingError::ReplayFiltered)?;

                // Log segments that exceed the hour limit so we can diagnose errant SDKs
                // or exotic customer implementations.
                if let Some(segment_id) = replay_type.segment_id.value() {
                    if *segment_id > 720 {
                        metric!(counter(RelayCounters::ReplayExceededSegmentLimit) += 1);

                        relay_log::debug!(
                            event_id = ?config.event_id,
                            project_id = config.project_id.map(|v| v.value()),
                            organization_id = config.organization_id.map(|o| o.value()),
                            segment_id = segment_id,
                            "replay segment-exceeded-limit"
                        );
                    }
                }
            }

            match replay.to_json() {
                Ok(json) => Ok(json.into_bytes().into()),
                Err(error) => {
                    relay_log::error!(
                        error = &error as &dyn Error,
                        event_id = ?config.event_id,
                        "failed to serialize replay"
                    );
                    Ok(payload)
                }
            }
        }
        Err(error) => {
            relay_log::warn!(
                error = &error as &dyn Error,
                event_id = ?config.event_id,
                project_id = config.project_id.map(|v| v.value()),
                organization_id = config.organization_id.map(|o| o.value()),
                "invalid replay event"
            );
            Err(match error {
                ReplayError::NoContent => {
                    ProcessingError::InvalidReplay(DiscardReason::InvalidReplayEventNoPayload)
                }
                ReplayError::CouldNotScrub(_) => {
                    ProcessingError::InvalidReplay(DiscardReason::InvalidReplayEventPii)
                }
                ReplayError::CouldNotParse(_) => {
                    ProcessingError::InvalidReplay(DiscardReason::InvalidReplayEvent)
                }
                ReplayError::InvalidPayload(_) => {
                    ProcessingError::InvalidReplay(DiscardReason::InvalidReplayEvent)
                }
            })
        }
    }
}

/// Validates, normalizes, and scrubs PII from a replay event.
fn process_replay_event(
    payload: &[u8],
    config: &ReplayProcessingConfig<'_>,
) -> Result<Annotated<Replay>, ReplayError> {
    let mut replay =
        Annotated::<Replay>::from_json_bytes(payload).map_err(ReplayError::CouldNotParse)?;

    let Some(replay_value) = replay.value_mut() else {
        return Err(ReplayError::NoContent);
    };

    replay::validate(replay_value)?;
    replay::normalize(
        &mut replay,
        config.client_addr,
        config.user_agent.as_deref(),
        config.geoip_lookup,
    );

    if let Some(ref config) = config.config.pii_config {
        let mut processor = PiiProcessor::new(config.compiled());
        processor::process_value(&mut replay, &mut processor, ProcessingState::root())
            .map_err(|e| ReplayError::CouldNotScrub(e.to_string()))?;
    }

    let pii_config = config
        .config
        .datascrubbing_settings
        .pii_config()
        .map_err(|e| ReplayError::CouldNotScrub(e.to_string()))?;

    if let Some(config) = pii_config {
        let mut processor = PiiProcessor::new(config.compiled());
        processor::process_value(&mut replay, &mut processor, ProcessingState::root())
            .map_err(|e| ReplayError::CouldNotScrub(e.to_string()))?;
    }

    Ok(replay)
}

// Replay Recording Processing

fn handle_replay_recording_item(
    payload: Bytes,
    scrubber: Option<&mut RecordingScrubber>,
    config: &ReplayProcessingConfig<'_>,
) -> Result<Bytes, ProcessingError> {
    // XXX: Processing is there just for data scrubbing. Skip the entire expensive
    // processing step if we do not need to scrub.
    let Some(scrubber) = scrubber else {
        return Ok(payload);
    };
    if scrubber.is_empty() {
        return Ok(payload);
    }

    // Limit expansion of recordings to the max replay size. The payload is
    // decompressed temporarily and then immediately re-compressed. However, to
    // limit memory pressure, we use the replay limit as a good overall limit for
    // allocations.
    metric!(timer(RelayTimers::ReplayRecordingProcessing), {
        scrubber.process_recording(&payload)
    })
    .map(Into::into)
    .map_err(|error| {
        match &error {
            relay_replays::recording::ParseRecordingError::Compression(e) => {
                // 20k errors per day at 0.1% sample rate == 20 logs per day
                if sample(0.001) {
                    relay_log::with_scope(
                        move |scope| {
                            scope.add_attachment(relay_log::protocol::Attachment {
                                buffer: payload.into(),
                                filename: "payload".to_owned(),
                                content_type: Some("application/octet-stream".to_owned()),
                                ty: None,
                            });
                        },
                        || {
                            relay_log::error!(
                                error = e as &dyn Error,
                                event_id = ?config.event_id,
                                project_id = config.project_id.map(|v| v.value()),
                                organization_id = config.organization_id.map(|o| o.value()),
                                "ParseRecordingError::Compression"
                            )
                        },
                    );
                }
            }
            relay_replays::recording::ParseRecordingError::Message(e) => {
                // Only 118 errors in the past 30 days. We log everything.
                relay_log::with_scope(
                    move |scope| {
                        scope.add_attachment(relay_log::protocol::Attachment {
                            buffer: payload.into(),
                            filename: "payload".to_owned(),
                            content_type: Some("application/octet-stream".to_owned()),
                            ty: None,
                        });
                    },
                    || {
                        relay_log::error!(
                            error = e,
                            event_id = ?config.event_id,
                            project_id = config.project_id.map(|v| v.value()),
                            organization_id = config.organization_id.map(|o| o.value()),
                            "ParseRecordingError::Message"
                        )
                    },
                );
            }
            _ => (),
        };
        ProcessingError::InvalidReplay(DiscardReason::InvalidReplayRecordingEvent)
    })
}

// Replay Video Processing

#[derive(Debug, Deserialize, Serialize)]
struct ReplayVideoEvent {
    replay_event: Bytes,
    replay_recording: Bytes,
    replay_video: Bytes,
}

fn handle_replay_video_item(
    payload: Bytes,
    scrubber: Option<&mut RecordingScrubber>,
    config: &ReplayProcessingConfig<'_>,
) -> Result<Bytes, ProcessingError> {
    let ReplayVideoEvent {
        replay_event,
        replay_recording,
        replay_video,
    } = rmp_serde::from_slice(&payload)
        .map_err(|_| ProcessingError::InvalidReplay(DiscardReason::InvalidReplayVideoEvent))?;

    // Process as a replay-event envelope item.
    let replay_event = handle_replay_event_item(replay_event, config)?;

    // Process as a replay-recording envelope item.
    let replay_recording = handle_replay_recording_item(replay_recording, scrubber, config)?;

    // Verify the replay-video payload is not empty.
    if replay_video.is_empty() {
        return Err(ProcessingError::InvalidReplay(
            DiscardReason::InvalidReplayVideoEvent,
        ));
    }

    match rmp_serde::to_vec_named(&ReplayVideoEvent {
        replay_event,
        replay_recording,
        replay_video,
    }) {
        Ok(payload) => Ok(payload.into()),
        Err(_) => Err(ProcessingError::InvalidReplay(
            DiscardReason::InvalidReplayVideoEvent,
        )),
    }
}

// Pre-processors

fn count_replay_video_events(managed_envelope: &mut TypedEnvelope<ReplayGroup>) -> usize {
    managed_envelope
        .envelope()
        .items()
        .filter(|item| item.ty() == &ItemType::ReplayVideo)
        .count()
}