synapse-waf 0.9.1

High-performance WAF and reverse proxy with embedded intelligence — built on Cloudflare Pingora
Documentation
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
//! Online statistics using Welford's algorithm and P-square percentiles.
//!
//! Provides streaming statistical analysis without storing all samples:
//! - Mean and variance tracking via Welford's algorithm
//! - Approximate percentiles (p50, p95, p99) via P-square algorithm
//!
//! ## Performance
//! - Update: O(1) time and space
//! - Z-score calculation: O(1)
//! - Memory: ~130 bytes per Distribution

use serde::{Deserialize, Serialize};

// ============================================================================
// PercentilesTracker - P-square algorithm for streaming percentiles
// ============================================================================

/// P-square algorithm for dynamic percentile estimation.
///
/// Maintains 5 markers for min, p50, p95, p99, max with O(1) updates.
/// Memory: ~56 bytes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PercentilesTracker {
    /// Marker heights (actual values)
    q: [f64; 5],
    /// Marker positions (counts)
    n: [f64; 5],
    /// Desired marker positions
    n_prime: [f64; 5],
    /// Initialization buffer (first 5 samples)
    init_count: u8,
    init_buffer: [f64; 5],
}

impl Default for PercentilesTracker {
    fn default() -> Self {
        Self::new()
    }
}

impl PercentilesTracker {
    /// Create a new tracker for p50, p95, p99.
    ///
    /// Increments for desired positions are constants: 0, 0.5, 0.95, 0.99, 1.0
    /// These are used inline in the update method rather than stored.
    pub fn new() -> Self {
        Self {
            q: [0.0; 5],
            n: [1.0, 2.0, 3.0, 4.0, 5.0],
            // Desired positions for min, p50, p95, p99, max
            n_prime: [1.0, 2.0, 3.0, 4.0, 5.0],
            init_count: 0,
            init_buffer: [0.0; 5],
        }
    }

    /// Update with a new sample.
    #[inline]
    pub fn update(&mut self, value: f64) {
        // SECURITY: Ignore non-finite values to prevent marker corruption (WAF-P0-2)
        if !value.is_finite() {
            return;
        }

        // Initialization phase: collect first 5 samples
        if self.init_count < 5 {
            self.init_buffer[self.init_count as usize] = value;
            self.init_count += 1;
            if self.init_count == 5 {
                // Sort and initialize markers
                self.init_buffer.sort_by(|a, b| a.partial_cmp(b).unwrap());
                self.q = self.init_buffer;
            }
            return;
        }

        // Find cell k where value belongs
        let k = if value < self.q[0] {
            self.q[0] = value;
            0
        } else if value < self.q[1] {
            0
        } else if value < self.q[2] {
            1
        } else if value < self.q[3] {
            2
        } else if value < self.q[4] {
            3
        } else {
            self.q[4] = value;
            3
        };

        // Increment positions for markers > k
        for i in (k + 1)..5 {
            self.n[i] += 1.0;
        }

        // Update desired positions
        let total = self.n[4];
        self.n_prime[1] = 1.0 + 0.5 * total;
        self.n_prime[2] = 1.0 + 0.95 * total;
        self.n_prime[3] = 1.0 + 0.99 * total;
        self.n_prime[4] = total;

        // Adjust marker heights if needed (P-square adjustment)
        for i in 1..4 {
            let d = self.n_prime[i] - self.n[i];
            if (d >= 1.0 && self.n[i + 1] - self.n[i] > 1.0)
                || (d <= -1.0 && self.n[i - 1] - self.n[i] < -1.0)
            {
                let d_sign = if d >= 0.0 { 1.0 } else { -1.0 };
                // Parabolic adjustment
                let qi = self.q[i];
                let qip1 = self.q[i + 1];
                let qim1 = self.q[i - 1];
                let ni = self.n[i];
                let nip1 = self.n[i + 1];
                let nim1 = self.n[i - 1];

                let q_new = qi
                    + d_sign / (nip1 - nim1)
                        * ((ni - nim1 + d_sign) * (qip1 - qi) / (nip1 - ni)
                            + (nip1 - ni - d_sign) * (qi - qim1) / (ni - nim1));

                // Check bounds and use linear if parabolic fails
                if qim1 < q_new && q_new < qip1 {
                    self.q[i] = q_new;
                } else {
                    // Linear adjustment
                    let idx = if d_sign >= 0.0 { i + 1 } else { i - 1 };
                    self.q[i] = qi + d_sign * (self.q[idx] - qi) / (self.n[idx] - ni);
                }
                self.n[i] += d_sign;
            }
        }
    }

    /// Get percentiles (p50, p95, p99).
    #[inline]
    pub fn get(&self) -> (f64, f64, f64) {
        if self.init_count < 5 {
            // Not enough data
            return (0.0, 0.0, 0.0);
        }
        (self.q[1], self.q[2], self.q[3])
    }

    /// Get minimum value seen.
    #[inline]
    pub fn min(&self) -> f64 {
        if self.init_count < 5 {
            return 0.0;
        }
        self.q[0]
    }

    /// Get maximum value seen.
    #[inline]
    pub fn max(&self) -> f64 {
        if self.init_count < 5 {
            return 0.0;
        }
        self.q[4]
    }

    /// Check if tracker has enough data for meaningful percentiles.
    #[inline]
    pub fn is_initialized(&self) -> bool {
        self.init_count >= 5
    }
}

// ============================================================================
// Distribution - Online statistics with Welford's algorithm
// ============================================================================

/// Online statistics calculator using Welford's algorithm.
///
/// Tracks mean, variance, and approximate percentiles without storing all samples.
/// Memory: ~130 bytes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Distribution {
    /// Sample count
    count: u32,
    /// Running mean
    mean: f64,
    /// Running M2 (sum of squared differences from mean)
    /// Variance = M2 / count
    m2: f64,
    /// Approximate percentiles using P-square algorithm
    percentiles: PercentilesTracker,
}

impl Default for Distribution {
    fn default() -> Self {
        Self::new()
    }
}

impl Distribution {
    /// Create a new empty distribution.
    #[inline]
    pub fn new() -> Self {
        Self {
            count: 0,
            mean: 0.0,
            m2: 0.0,
            percentiles: PercentilesTracker::new(),
        }
    }

    /// Add a sample using Welford's online algorithm.
    /// O(1) time and space.
    #[inline]
    pub fn update(&mut self, value: f64) {
        // SECURITY: Ignore non-finite values to prevent statistical poisoning (WAF-P0-1)
        if !value.is_finite() {
            return;
        }

        self.count += 1;
        let delta = value - self.mean;
        self.mean += delta / self.count as f64;
        let delta2 = value - self.mean;
        self.m2 += delta * delta2;

        self.percentiles.update(value);
    }

    /// Get sample count.
    #[inline]
    pub fn count(&self) -> u32 {
        self.count
    }

    /// Get the mean.
    #[inline]
    pub fn mean(&self) -> f64 {
        self.mean
    }

    /// Compute standard deviation.
    #[inline]
    pub fn stddev(&self) -> f64 {
        if self.count < 2 {
            return 0.0;
        }
        (self.m2 / self.count as f64).sqrt()
    }

    /// Compute variance.
    #[inline]
    pub fn variance(&self) -> f64 {
        if self.count < 2 {
            return 0.0;
        }
        self.m2 / self.count as f64
    }

    /// Calculate z-score for a value.
    /// Returns how many standard deviations from the mean.
    #[inline]
    pub fn z_score(&self, value: f64) -> f64 {
        let std = self.stddev();
        if std < 0.01 {
            // Avoid division by zero or near-zero
            return 0.0;
        }
        (value - self.mean) / std
    }

    /// Get approximate percentiles (p50, p95, p99).
    #[inline]
    pub fn percentiles(&self) -> (f64, f64, f64) {
        self.percentiles.get()
    }

    /// Get minimum value seen.
    #[inline]
    pub fn min(&self) -> f64 {
        self.percentiles.min()
    }

    /// Get maximum value seen.
    #[inline]
    pub fn max(&self) -> f64 {
        self.percentiles.max()
    }

    /// Check if distribution has enough data for statistical analysis.
    #[inline]
    pub fn is_valid(&self) -> bool {
        self.count >= 5
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_distribution_welford() {
        let mut d = Distribution::new();
        for v in [10.0, 20.0, 30.0, 40.0, 50.0] {
            d.update(v);
        }
        assert!((d.mean() - 30.0).abs() < 0.01);
        // Population stddev of [10,20,30,40,50] is ~14.14
        assert!((d.stddev() - 14.14).abs() < 0.5);
    }

    #[test]
    fn test_distribution_z_score() {
        let mut d = Distribution::new();
        // Create distribution with mean=100, stddev≈10
        for v in [90.0, 95.0, 100.0, 105.0, 110.0] {
            d.update(v);
        }

        // Value at mean should have z-score ~0
        assert!(d.z_score(100.0).abs() < 0.1);

        // Value 2 stddev above mean
        let z = d.z_score(100.0 + 2.0 * d.stddev());
        assert!((z - 2.0).abs() < 0.1);
    }

    #[test]
    fn test_distribution_empty() {
        let d = Distribution::new();
        assert_eq!(d.count(), 0);
        assert_eq!(d.mean(), 0.0);
        assert_eq!(d.stddev(), 0.0);
        assert_eq!(d.variance(), 0.0);
        assert!(!d.is_valid());
    }

    #[test]
    fn test_distribution_single_value() {
        let mut d = Distribution::new();
        d.update(42.0);
        assert_eq!(d.count(), 1);
        assert_eq!(d.mean(), 42.0);
        assert_eq!(d.stddev(), 0.0); // Need 2+ samples for stddev
    }

    #[test]
    fn test_distribution_variance() {
        let mut d = Distribution::new();
        // Uniform distribution from 0 to 10: variance = (10-0)^2 / 12 ≈ 8.33
        for v in [0.0, 2.0, 4.0, 6.0, 8.0, 10.0] {
            d.update(v);
        }
        // Mean should be 5.0
        assert!((d.mean() - 5.0).abs() < 0.01);
        // Variance should be roughly 11.67 (sample variance)
        assert!(d.variance() > 0.0);
    }

    #[test]
    fn test_percentiles_tracker() {
        let mut pt = PercentilesTracker::new();

        // Add 100 samples (1 to 100)
        for i in 1..=100 {
            pt.update(i as f64);
        }

        let (p50, p95, p99) = pt.get();

        // p50 should be around 50
        assert!((p50 - 50.0).abs() < 5.0);
        // p95 should be around 95
        assert!((p95 - 95.0).abs() < 5.0);
        // p99 should be around 99
        assert!((p99 - 99.0).abs() < 3.0);
    }

    #[test]
    fn test_percentiles_tracker_not_initialized() {
        let mut pt = PercentilesTracker::new();
        assert!(!pt.is_initialized());

        pt.update(1.0);
        pt.update(2.0);
        assert!(!pt.is_initialized());

        let (p50, p95, p99) = pt.get();
        assert_eq!(p50, 0.0);
        assert_eq!(p95, 0.0);
        assert_eq!(p99, 0.0);
    }

    #[test]
    fn test_percentiles_tracker_min_max() {
        let mut pt = PercentilesTracker::new();
        for i in 1..=10 {
            pt.update(i as f64);
        }

        assert_eq!(pt.min(), 1.0);
        assert_eq!(pt.max(), 10.0);
    }

    #[test]
    fn test_distribution_z_score_edge_cases() {
        let mut d = Distribution::new();
        // All same values - stddev is 0
        for _ in 0..10 {
            d.update(50.0);
        }

        // Z-score should be 0 when stddev is 0 (avoids division by zero)
        assert_eq!(d.z_score(100.0), 0.0);
    }

    #[test]
    fn test_distribution_negative_values() {
        let mut d = Distribution::new();
        for v in [-10.0, -5.0, 0.0, 5.0, 10.0] {
            d.update(v);
        }
        assert!((d.mean() - 0.0).abs() < 0.01);
        assert!(d.stddev() > 0.0);
    }

    #[test]
    fn test_distribution_large_values() {
        let mut d = Distribution::new();
        for v in [1e9, 1e9 + 1.0, 1e9 + 2.0, 1e9 + 3.0, 1e9 + 4.0] {
            d.update(v);
        }
        assert!((d.mean() - (1e9 + 2.0)).abs() < 0.01);
    }

    #[test]
    fn test_percentiles_with_outliers() {
        let mut pt = PercentilesTracker::new();

        // Add normal values
        for i in 1..=95 {
            pt.update(i as f64);
        }
        // Add outliers
        for _ in 0..5 {
            pt.update(1000.0);
        }

        let (p50, p95, p99) = pt.get();

        // p50 should still be around 50 (median is robust to outliers)
        assert!((p50 - 50.0).abs() < 10.0);
    }

    #[test]
    fn test_distribution_nan_stability() {
        let mut d = Distribution::new();
        d.update(10.0);
        d.update(f64::NAN);
        d.update(f64::INFINITY);
        d.update(20.0);

        assert_eq!(d.count(), 2);
        assert!((d.mean() - 15.0).abs() < 0.01);
        assert!(d.stddev().is_finite());
    }

    #[test]
    fn test_percentiles_nan_stability() {
        let mut pt = PercentilesTracker::new();
        for _ in 0..10 {
            pt.update(10.0);
            pt.update(f64::NAN);
        }

        let (p50, p95, p99) = pt.get();
        assert!(p50.is_finite());
        assert!(p95.is_finite());
        assert!(p99.is_finite());
    }
}