relay_event_normalization/
validation.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
use std::ops::Range;

use chrono::{DateTime, Duration, Utc};
use relay_base_schema::events::EventType;
use relay_common::time::UnixTimestamp;
use relay_event_schema::processor::{
    self, ProcessingAction, ProcessingResult, ProcessingState, Processor,
};
use relay_event_schema::protocol::{Event, Span, Timestamp, TraceContext};
use relay_protocol::{Annotated, ErrorKind, Meta};

use crate::{ClockDriftProcessor, TimestampProcessor};

/// Configuration for [`validate_event`].
#[derive(Debug, Default)]
pub struct EventValidationConfig {
    /// The time at which the event was received in this Relay.
    ///
    /// This timestamp is persisted into the event payload.
    pub received_at: Option<DateTime<Utc>>,

    /// The maximum amount of seconds an event can be dated in the past.
    ///
    /// If the event's timestamp is older, the received timestamp is assumed.
    pub max_secs_in_past: Option<i64>,

    /// The maximum amount of seconds an event can be predated into the future.
    ///
    /// If the event's timestamp lies further into the future, the received timestamp is assumed.
    pub max_secs_in_future: Option<i64>,

    /// Timestamp range in which a transaction must end.
    ///
    /// Transactions that finish outside this range are invalid. The check is
    /// skipped if no range is provided.
    pub transaction_timestamp_range: Option<Range<UnixTimestamp>>,

    /// Controls whether the event has been validated before, in which case disables validation.
    ///
    /// By default, `is_validated` is disabled and event validation is run.
    ///
    /// Similar to `is_renormalize` for normalization, `sentry_relay` may configure this value.
    pub is_validated: bool,
}

/// Validates an event.
///
/// Validation consists of performing multiple checks on the payload, based on
/// the given configuration.
///
/// The returned [`ProcessingResult`] indicates whether the passed event is
/// invalid and thus should be dropped.
pub fn validate_event(
    event: &mut Annotated<Event>,
    config: &EventValidationConfig,
) -> ProcessingResult {
    if config.is_validated {
        return Ok(());
    }

    let Annotated(Some(ref mut event), ref mut meta) = event else {
        return Ok(());
    };

    // TimestampProcessor is required in validation, and requires normalizing
    // timestamps before (especially clock drift changes).
    normalize_timestamps(
        event,
        meta,
        config.received_at,
        config.max_secs_in_past,
        config.max_secs_in_future,
    );
    TimestampProcessor.process_event(event, meta, ProcessingState::root())?;

    if event.ty.value() == Some(&EventType::Transaction) {
        validate_transaction_timestamps(event, config)?;
        validate_trace_context(event)?;
        // There are no timestamp range requirements for span timestamps.
        // Transaction will be rejected only if either end or start timestamp is missing.
        end_all_spans(event);
        validate_spans(event, None)?;
    }

    Ok(())
}

/// Validates the timestamp range and sets a default value.
fn normalize_timestamps(
    event: &mut Event,
    meta: &mut Meta,
    received_at: Option<DateTime<Utc>>,
    max_secs_in_past: Option<i64>,
    max_secs_in_future: Option<i64>,
) {
    let received_at = received_at.unwrap_or_else(Utc::now);

    let mut sent_at = None;
    let mut error_kind = ErrorKind::ClockDrift;

    let _ = processor::apply(&mut event.timestamp, |timestamp, _meta| {
        if let Some(secs) = max_secs_in_future {
            if *timestamp > received_at + Duration::seconds(secs) {
                error_kind = ErrorKind::FutureTimestamp;
                sent_at = Some(*timestamp);
                return Ok(());
            }
        }

        if let Some(secs) = max_secs_in_past {
            if *timestamp < received_at - Duration::seconds(secs) {
                error_kind = ErrorKind::PastTimestamp;
                sent_at = Some(*timestamp);
                return Ok(());
            }
        }

        Ok(())
    });

    let _ = ClockDriftProcessor::new(sent_at.map(|ts| ts.into_inner()), received_at)
        .error_kind(error_kind)
        .process_event(event, meta, ProcessingState::root());

    // Apply this after clock drift correction, otherwise we will malform it.
    event.received = Annotated::new(received_at.into());

    if event.timestamp.value().is_none() {
        event.timestamp.set_value(Some(received_at.into()));
    }

    let _ = processor::apply(&mut event.time_spent, |time_spent, _| {
        validate_bounded_integer_field(*time_spent)
    });
}

/// Returns whether the transacion's start and end timestamps are both set and start <= end.
fn validate_transaction_timestamps(
    transaction_event: &Event,
    config: &EventValidationConfig,
) -> ProcessingResult {
    match (
        transaction_event.start_timestamp.value(),
        transaction_event.timestamp.value(),
    ) {
        (Some(start), Some(end)) => {
            validate_timestamps(start, end, config.transaction_timestamp_range.as_ref())?;
            Ok(())
        }
        (_, None) => Err(ProcessingAction::InvalidTransaction(
            "timestamp hard-required for transaction events",
        )),
        // XXX: Maybe copy timestamp over?
        (None, _) => Err(ProcessingAction::InvalidTransaction(
            "start_timestamp hard-required for transaction events",
        )),
    }
}

/// Validates that start <= end timestamps and that the end timestamp is inside the valid range.
fn validate_timestamps(
    start: &Timestamp,
    end: &Timestamp,
    valid_range: Option<&Range<UnixTimestamp>>,
) -> ProcessingResult {
    if end < start {
        return Err(ProcessingAction::InvalidTransaction(
            "end timestamp is smaller than start timestamp",
        ));
    }

    let Some(range) = valid_range else {
        return Ok(());
    };

    let Some(timestamp) = UnixTimestamp::from_datetime(end.into_inner()) else {
        return Err(ProcessingAction::InvalidTransaction(
            "invalid unix timestamp",
        ));
    };
    if !range.contains(&timestamp) {
        return Err(ProcessingAction::InvalidTransaction(
            "timestamp is out of the valid range for metrics",
        ));
    }

    Ok(())
}

/// Validates the trace context in a transaction.
///
/// A [`ProcessingResult`] error is returned if the context is not valid. The
/// context is valid if the trace context meets the following conditions:
/// - It exists.
/// - It has a trace id.
/// - It has a span id.
fn validate_trace_context(transaction: &Event) -> ProcessingResult {
    let Some(trace_context) = transaction.context::<TraceContext>() else {
        return Err(ProcessingAction::InvalidTransaction(
            "missing valid trace context",
        ));
    };

    if trace_context.trace_id.value().is_none() {
        return Err(ProcessingAction::InvalidTransaction(
            "trace context is missing trace_id",
        ));
    }

    if trace_context.span_id.value().is_none() {
        return Err(ProcessingAction::InvalidTransaction(
            "trace context is missing span_id",
        ));
    }

    Ok(())
}

/// Copies the event's end timestamp into the spans that don't have one.
fn end_all_spans(event: &mut Event) {
    let spans = event.spans.value_mut().get_or_insert_with(Vec::new);
    for span in spans {
        if let Some(span) = span.value_mut() {
            if span.timestamp.value().is_none() {
                // event timestamp guaranteed to be `Some` due to validate_transaction call
                span.timestamp.set_value(event.timestamp.value().cloned());
                span.status =
                    Annotated::new(relay_base_schema::spans::SpanStatus::DeadlineExceeded);
            }
        }
    }
}

/// Validates the spans in the transaction.
///
/// A [`ProcessingResult`] error is returned if there's an invalid span. For
/// span validity, see [`validate_span`].
fn validate_spans(
    transaction: &Event,
    timestamp_range: Option<&Range<UnixTimestamp>>,
) -> ProcessingResult {
    let Some(spans) = transaction.spans.value() else {
        return Ok(());
    };

    for span in spans {
        if let Some(span) = span.value() {
            validate_span(span, timestamp_range)?;
        } else {
            return Err(ProcessingAction::InvalidTransaction(
                "spans must be valid in transaction event",
            ));
        }
    }

    Ok(())
}

/// Validates a span.
///
/// A [`ProcessingResult`] error is returned when the span is invalid. A span is
/// valid if all the following conditions are met:
/// - A start timestamp exists.
/// - An end timestamp exists.
/// - Start timestamp must be no later than end timestamp.
/// - A trace id exists.
/// - A span id exists.
pub fn validate_span(
    span: &Span,
    timestamp_range: Option<&Range<UnixTimestamp>>,
) -> ProcessingResult {
    match (span.start_timestamp.value(), span.timestamp.value()) {
        (Some(start), Some(end)) => {
            validate_timestamps(start, end, timestamp_range)?;
        }
        (_, None) => {
            // XXX: Maybe do the same as event.timestamp?
            return Err(ProcessingAction::InvalidTransaction(
                "span is missing timestamp",
            ));
        }
        (None, _) => {
            // XXX: Maybe copy timestamp over?
            return Err(ProcessingAction::InvalidTransaction(
                "span is missing start_timestamp",
            ));
        }
    }

    if span.trace_id.value().is_none() {
        return Err(ProcessingAction::InvalidTransaction(
            "span is missing trace_id",
        ));
    }

    if span.span_id.value().is_none() {
        return Err(ProcessingAction::InvalidTransaction(
            "span is missing span_id",
        ));
    }

    Ok(())
}

/// Validate fields that go into a `sentry.models.BoundedIntegerField`.
fn validate_bounded_integer_field(value: u64) -> ProcessingResult {
    if value < 2_147_483_647 {
        Ok(())
    } else {
        Err(ProcessingAction::DeleteValueHard)
    }
}

#[cfg(test)]
mod tests {
    use chrono::TimeZone;
    use relay_base_schema::spans::SpanStatus;
    use relay_event_schema::protocol::{Contexts, SpanId, TraceId};
    use relay_protocol::{get_value, Object};

    use super::*;

    fn new_test_event() -> Annotated<Event> {
        let start = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap();
        let end = Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 10).unwrap();
        Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            transaction: Annotated::new("/".to_owned()),
            start_timestamp: Annotated::new(start.into()),
            timestamp: Annotated::new(end.into()),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext {
                    trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                    span_id: Annotated::new(SpanId("fa90fdead5f74053".into())),
                    op: Annotated::new("http.server".to_owned()),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            spans: Annotated::new(vec![Annotated::new(Span {
                start_timestamp: Annotated::new(start.into()),
                timestamp: Annotated::new(end.into()),
                trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                span_id: Annotated::new(SpanId("fa90fdead5f74053".into())),
                op: Annotated::new("db.statement".to_owned()),
                ..Default::default()
            })]),
            ..Default::default()
        })
    }

    #[test]
    fn test_timestamp_added_if_missing() {
        let mut event = Annotated::new(Event::default());
        assert!(get_value!(event.timestamp).is_none());
        assert!(validate_event(&mut event, &EventValidationConfig::default()).is_ok());
        assert!(get_value!(event.timestamp).is_some());
    }

    #[test]
    fn test_discards_when_timestamp_out_of_range() {
        let mut event = new_test_event();

        assert!(matches!(
            validate_event(
                &mut event,
                &EventValidationConfig {
                    transaction_timestamp_range: Some(UnixTimestamp::now()..UnixTimestamp::now()),
                    is_validated: false,
                    ..Default::default()
                }
            ),
            Err(ProcessingAction::InvalidTransaction(
                "timestamp is out of the valid range for metrics"
            ))
        ));
    }

    #[test]
    fn test_discards_when_missing_start_timestamp() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "start_timestamp hard-required for transaction events"
            ))
        );
    }

    #[test]
    fn test_discards_on_missing_contexts_map() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            ..Default::default()
        });

        assert_eq!(
            validate_event(
                &mut event,
                &EventValidationConfig {
                    transaction_timestamp_range: None,
                    is_validated: false,
                    ..Default::default()
                }
            ),
            Err(ProcessingAction::InvalidTransaction(
                "missing valid trace context"
            ))
        );
    }

    #[test]
    fn test_discards_on_missing_context() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: Annotated::new(Contexts::new()),
            ..Default::default()
        });

        assert_eq!(
            validate_event(
                &mut event,
                &EventValidationConfig {
                    transaction_timestamp_range: None,
                    is_validated: false,
                    ..Default::default()
                }
            ),
            Err(ProcessingAction::InvalidTransaction(
                "missing valid trace context"
            ))
        );
    }

    #[test]
    fn test_discards_on_null_context() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: Annotated::new(Contexts({
                let mut contexts = Object::new();
                contexts.insert("trace".to_owned(), Annotated::empty());
                contexts
            })),
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "missing valid trace context"
            ))
        );
    }

    #[test]
    fn test_discards_on_missing_trace_id_in_context() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext::default());
                Annotated::new(contexts)
            },
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "trace context is missing trace_id"
            ))
        );
    }

    #[test]
    fn test_discards_on_missing_span_id_in_context() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext {
                    trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "trace context is missing span_id"
            ))
        );
    }

    #[test]
    fn test_discards_transaction_event_with_nulled_out_span() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext {
                    trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                    span_id: Annotated::new(SpanId("fa90fdead5f74053".into())),
                    op: Annotated::new("http.server".to_owned()),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            spans: Annotated::new(vec![Annotated::empty()]),
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "spans must be valid in transaction event"
            ))
        );
    }

    #[test]
    fn test_discards_transaction_event_with_span_with_missing_start_timestamp() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext {
                    trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                    span_id: Annotated::new(SpanId("fa90fdead5f74053".into())),
                    op: Annotated::new("http.server".to_owned()),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            spans: Annotated::new(vec![Annotated::new(Span {
                timestamp: Annotated::new(
                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
                ),
                ..Default::default()
            })]),
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "span is missing start_timestamp"
            ))
        );
    }

    #[test]
    fn test_discards_transaction_event_with_span_with_missing_trace_id() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext {
                    trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                    span_id: Annotated::new(SpanId("fa90fdead5f74053".into())),
                    op: Annotated::new("http.server".to_owned()),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            spans: Annotated::new(vec![Annotated::new(Span {
                timestamp: Annotated::new(
                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
                ),
                start_timestamp: Annotated::new(
                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
                ),
                ..Default::default()
            })]),
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "span is missing trace_id"
            ))
        );
    }

    #[test]
    fn test_discards_transaction_event_with_span_with_missing_span_id() {
        let mut event = Annotated::new(Event {
            ty: Annotated::new(EventType::Transaction),
            timestamp: Annotated::new(Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into()),
            start_timestamp: Annotated::new(
                Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
            ),
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(TraceContext {
                    trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                    span_id: Annotated::new(SpanId("fa90fdead5f74053".into())),
                    op: Annotated::new("http.server".to_owned()),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            spans: Annotated::new(vec![Annotated::new(Span {
                timestamp: Annotated::new(
                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
                ),
                start_timestamp: Annotated::new(
                    Utc.with_ymd_and_hms(2000, 1, 1, 0, 0, 0).unwrap().into(),
                ),
                trace_id: Annotated::new(TraceId("4c79f60c11214eb38604f4ae0781bfb2".into())),
                ..Default::default()
            })]),
            ..Default::default()
        });

        assert_eq!(
            validate_event(&mut event, &EventValidationConfig::default()),
            Err(ProcessingAction::InvalidTransaction(
                "span is missing span_id"
            ))
        );
    }

    #[test]
    fn test_reject_stale_transaction() {
        let json = r#"{
  "event_id": "52df9022835246eeb317dbd739ccd059",
  "start_timestamp": -2,
  "timestamp": -1
}"#;
        let mut transaction = Annotated::<Event>::from_json(json).unwrap();
        let res = validate_event(&mut transaction, &EventValidationConfig::default());
        assert_eq!(
            res.unwrap_err().to_string(),
            "invalid transaction event: timestamp is too stale"
        );
    }

    /// Test that timestamp normalization updates a transaction's timestamps to
    /// be acceptable, when both timestamps are similarly stale.
    #[test]
    fn test_accept_recent_transactions_with_stale_timestamps() {
        let config = EventValidationConfig {
            received_at: Some(Utc::now()),
            max_secs_in_past: Some(2),
            max_secs_in_future: Some(1),
            is_validated: false,
            ..Default::default()
        };

        let json = r#"{
  "event_id": "52df9022835246eeb317dbd739ccd059",
  "transaction": "I have a stale timestamp, but I'm recent!",
  "start_timestamp": -2,
  "timestamp": -1
}"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();

        assert!(validate_event(&mut event, &config).is_ok());
    }

    /// Test that transactions are rejected as invalid when timestamp normalization isn't enough.
    ///
    /// When the end timestamp is recent but the start timestamp is stale, timestamp normalization
    /// will fix the timestamps based on the end timestamp. The start timestamp will be more recent,
    /// but not recent enough for the transaction to be accepted. The transaction will be rejected.
    #[test]
    fn test_reject_stale_transactions_after_timestamp_normalization() {
        let now = Utc::now();
        let config = EventValidationConfig {
            received_at: Some(now),
            max_secs_in_past: Some(2),
            max_secs_in_future: Some(1),
            is_validated: false,
            ..Default::default()
        };

        let json = format!(
            r#"{{
          "event_id": "52df9022835246eeb317dbd739ccd059",
          "transaction": "clockdrift is not enough to accept me :(",
          "start_timestamp": -62135811111,
          "timestamp": {}
        }}"#,
            now.timestamp()
        );
        let mut event = Annotated::<Event>::from_json(json.as_str()).unwrap();

        assert_eq!(
            validate_event(&mut event, &config).unwrap_err().to_string(),
            "invalid transaction event: timestamp is too stale"
        );
    }

    /// Validates an unfinished span in a transaction, and the transaction is accepted.
    #[test]
    fn test_accept_transactions_with_unfinished_spans() {
        let json = r#"{
  "event_id": "52df9022835246eeb317dbd739ccd059",
  "type": "transaction",
  "transaction": "I have a stale timestamp, but I'm recent!",
  "start_timestamp": 1,
  "timestamp": 2,
  "contexts": {
    "trace": {
      "trace_id": "ff62a8b040f340bda5d830223def1d81",
      "span_id": "bd429c44b67a3eb4"
    }
  },
  "spans": [
    {
      "span_id": "bd429c44b67a3eb4",
      "start_timestamp": 1,
      "timestamp": null,
      "trace_id": "ff62a8b040f340bda5d830223def1d81"
    }
  ]
}"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();

        assert!(validate_event(&mut event, &EventValidationConfig::default()).is_ok());

        let event = get_value!(event!);
        let spans = &event.spans;
        let span = get_value!(spans[0]!);

        assert_eq!(span.timestamp, event.timestamp);
        assert_eq!(span.status.value().unwrap(), &SpanStatus::DeadlineExceeded);
    }

    /// Validates an unfinished span is finished with the normalized transaction's timestamp.
    #[test]
    fn test_finish_spans_with_normalized_transaction_end_timestamp() {
        let json = r#"{
  "event_id": "52df9022835246eeb317dbd739ccd059",
  "type": "transaction",
  "transaction": "I have a stale timestamp, but I'm recent!",
  "start_timestamp": 946731000,
  "timestamp": 946731555,
  "contexts": {
    "trace": {
      "trace_id": "ff62a8b040f340bda5d830223def1d81",
      "span_id": "bd429c44b67a3eb4"
    }
  },
  "spans": [
    {
      "span_id": "bd429c44b67a3eb4",
      "start_timestamp": 946731000,
      "timestamp": null,
      "trace_id": "ff62a8b040f340bda5d830223def1d81"
    }
  ]
}"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();

        validate_event(
            &mut event,
            &EventValidationConfig {
                received_at: Some(Utc::now()),
                max_secs_in_past: Some(2),
                max_secs_in_future: Some(1),
                is_validated: false,
                ..Default::default()
            },
        )
        .unwrap();
        validate_event(&mut event, &EventValidationConfig::default()).unwrap();

        let event = get_value!(event!);
        let spans = &event.spans;
        let span = get_value!(spans[0]!);

        assert_eq!(span.timestamp.value(), event.timestamp.value());
    }

    #[test]
    fn test_skip_transaction_validation_on_renormalization() {
        let json = r#"{
  "event_id": "52df9022835246eeb317dbd739ccd059",
  "type": "transaction",
  "transaction": "I'm invalid because I don't have any timestamps!"
}"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();

        assert!(validate_event(&mut event, &EventValidationConfig::default()).is_err());
        assert!(validate_event(
            &mut event,
            &EventValidationConfig {
                is_validated: true,
                ..Default::default()
            }
        )
        .is_ok());
    }

    #[test]
    fn test_skip_event_timestamp_validation_on_renormalization() {
        let json = r#"{
  "event_id": "52df9022835246eeb317dbd739ccd059",
  "transaction": "completely outdated transaction",
  "start_timestamp": -2,
  "timestamp": -1
}"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();

        assert!(validate_event(&mut event, &EventValidationConfig::default()).is_err());
        assert!(validate_event(
            &mut event,
            &EventValidationConfig {
                is_validated: true,
                ..Default::default()
            }
        )
        .is_ok());
    }
}