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
#[cfg(test)]
mod tests {
    use crate::config::ProfilerConfig;
    use crate::profiler::{is_likely_pii, redact_value, AnomalySignalType, Profiler};

    fn default_config() -> ProfilerConfig {
        ProfilerConfig {
            enabled: true,
            max_profiles: 100,
            max_schemas: 50,
            min_samples_for_validation: 10,
            ..Default::default()
        }
    }

    #[test]
    fn test_value_length_anomaly() {
        let profiler = Profiler::new(default_config());
        let template = "/api/test";

        // Train with varied short strings (length ~3-8) to establish variance
        let training_values = ["hi", "hey", "hello", "short", "testing", "goodbye"];
        for i in 0..50 {
            let value = training_values[i % training_values.len()];
            profiler.update_profile(template, 100, &[("param", value)], None);
        }

        // Test with very long string (100 chars vs ~5 average)
        let long_string = "a".repeat(100);
        let result = profiler.analyze_request(template, 100, &[("param", &long_string)], None);

        assert!(result
            .signals
            .iter()
            .any(|s| s.signal_type == AnomalySignalType::ParamValueAnomaly));
    }

    #[test]
    fn test_value_type_anomaly() {
        let profiler = Profiler::new(default_config());
        let template = "/api/test";

        // Train with numeric strings
        for i in 0..50 {
            profiler.update_profile(template, 100, &[("id", &i.to_string())], None);
        }

        // Test with non-numeric string
        let result = profiler.analyze_request(template, 100, &[("id", "not_a_number")], None);

        assert!(result
            .signals
            .iter()
            .any(|s| s.signal_type == AnomalySignalType::ParamValueAnomaly));
    }

    #[test]
    fn test_email_detection() {
        let profiler = Profiler::new(default_config());
        let template = "/api/users";

        profiler.update_profile(template, 100, &[("email", "test@example.com")], None);

        let profile = profiler.get_profile(template).unwrap();
        let stats = profile.expected_params.get("email").unwrap();

        assert_eq!(*stats.type_counts.get("email").unwrap_or(&0), 1);
    }

    #[test]
    fn test_uuid_detection() {
        let profiler = Profiler::new(default_config());
        let template = "/api/items";
        let uuid = "123e4567-e89b-12d3-a456-426614174000";

        profiler.update_profile(template, 100, &[("id", uuid)], None);

        let profile = profiler.get_profile(template).unwrap();
        let stats = profile.expected_params.get("id").unwrap();

        assert_eq!(*stats.type_counts.get("uuid").unwrap_or(&0), 1);
    }

    // ========================================================================
    // PII Redaction Tests
    // ========================================================================

    #[test]
    fn test_redact_value_email() {
        let email = "user@example.com";
        let redacted = redact_value(email);
        // Should show first 2 and last 2 chars
        assert!(redacted.starts_with("us"));
        assert!(redacted.ends_with("om"));
        assert!(redacted.contains("*"));
        // Original value should not appear
        assert!(!redacted.contains("@example"));
    }

    #[test]
    fn test_redact_value_short() {
        let short = "abc";
        let redacted = redact_value(short);
        // Short values are fully redacted
        assert_eq!(redacted, "***");
    }

    #[test]
    fn test_redact_value_uuid() {
        let uuid = "123e4567-e89b-12d3-a456-426614174000";
        let redacted = redact_value(uuid);
        assert!(redacted.starts_with("12"));
        assert!(redacted.ends_with("00"));
        assert!(redacted.contains("*"));
    }

    #[test]
    fn test_is_likely_pii_email() {
        assert!(is_likely_pii("test@example.com"));
        assert!(is_likely_pii("user.name@company.org"));
        assert!(!is_likely_pii("not-an-email"));
    }

    #[test]
    fn test_is_likely_pii_uuid() {
        assert!(is_likely_pii("123e4567-e89b-12d3-a456-426614174000"));
        assert!(!is_likely_pii("not-a-uuid"));
    }

    #[test]
    fn test_is_likely_pii_long_token() {
        // Long alphanumeric strings (API keys, tokens) are flagged as PII
        assert!(is_likely_pii("abcdefghijklmnopqrstuvwxyz123456"));
        assert!(!is_likely_pii("short"));
    }

    // ========================================================================
    // Frozen Baseline Tests (Anti-Poisoning)
    // ========================================================================

    #[test]
    fn test_frozen_baseline_prevents_updates() {
        let config = ProfilerConfig {
            enabled: true,
            max_profiles: 100,
            max_schemas: 50,
            min_samples_for_validation: 5,
            freeze_after_samples: 10,
            ..Default::default()
        };
        let profiler = Profiler::new(config);
        let template = "/api/frozen";

        // Add 10 samples to reach freeze threshold
        for i in 0..10 {
            profiler.update_profile(template, 100, &[("val", &i.to_string())], None);
        }

        assert!(profiler.is_profile_frozen(template));

        // Get sample count before attempting more updates
        let count_before = profiler.get_profile(template).unwrap().sample_count;

        // Try to add more samples - should be rejected
        for i in 10..20 {
            profiler.update_profile(template, 100, &[("val", &i.to_string())], None);
        }

        // Sample count should not have changed
        let count_after = profiler.get_profile(template).unwrap().sample_count;
        assert_eq!(count_before, count_after);
    }

    #[test]
    fn test_unfrozen_profile_accepts_updates() {
        let config = ProfilerConfig {
            enabled: true,
            max_profiles: 100,
            max_schemas: 50,
            min_samples_for_validation: 5,
            freeze_after_samples: 0, // Disabled
            ..Default::default()
        };
        let profiler = Profiler::new(config);
        let template = "/api/unfrozen";

        // Add samples
        for i in 0..20 {
            profiler.update_profile(template, 100, &[("val", &i.to_string())], None);
        }

        assert!(!profiler.is_profile_frozen(template));
        assert_eq!(profiler.get_profile(template).unwrap().sample_count, 20);
    }

    // ========================================================================
    // Type Count Bounds Tests
    // ========================================================================

    #[test]
    fn test_type_counts_bounded() {
        use crate::profiler::ParamStats;

        let mut stats = ParamStats::new();

        // Try to add many different type-like values
        // The type_counts map should stay bounded
        for _ in 0..100 {
            stats.update("12345"); // numeric
            stats.update("hello"); // string
            stats.update("test@example.com"); // email
            stats.update("123e4567-e89b-12d3-a456-426614174000"); // uuid
        }

        // Type counts should not exceed the default limit (10 types)
        // Standard types: numeric, string, email, uuid = 4
        assert!(stats.type_counts.len() <= 10);
    }

    // ========================================================================
    // Division by Zero Protection Tests
    // ========================================================================

    #[test]
    fn test_no_division_by_zero_empty_stats() {
        let profiler = Profiler::new(default_config());
        let template = "/api/divzero";

        // Create profile with minimal training
        for _ in 0..10 {
            profiler.update_profile(template, 100, &[], None);
        }

        // Analyze with parameter that has no stats (would cause div/0 if unprotected)
        let result = profiler.analyze_request(template, 100, &[("new_param", "value")], None);

        // Should not panic, should flag as unexpected param
        assert!(result
            .signals
            .iter()
            .any(|s| s.signal_type == AnomalySignalType::UnexpectedParam));
    }

    // ========================================================================
    // Configurable Threshold Tests
    // ========================================================================

    #[test]
    fn test_configurable_z_threshold() {
        // Use a higher threshold that won't flag our test case
        let config = ProfilerConfig {
            enabled: true,
            max_profiles: 100,
            max_schemas: 50,
            min_samples_for_validation: 10,
            payload_z_threshold: 10.0, // Very high threshold
            ..Default::default()
        };
        let profiler = Profiler::new(config);
        let template = "/api/threshold";

        // Train with payload size ~100
        for _ in 0..50 {
            profiler.update_profile(template, 100, &[], None);
        }

        // Test with slightly larger payload - should NOT trigger with high threshold
        let result = profiler.analyze_request(template, 200, &[], None);

        // With z-threshold of 10.0, a 2x payload shouldn't trigger
        assert!(!result
            .signals
            .iter()
            .any(|s| s.signal_type == AnomalySignalType::PayloadSizeHigh));
    }

    #[test]
    fn test_analyze_request_redacts_pii_in_signals() {
        let mut config = default_config();
        config.redact_pii = true;
        let profiler = Profiler::new(config);
        let template = "/api/pii";

        // Train with normal values
        for i in 0..20 {
            // Introduce variance so stddev > 0
            let val = if i % 2 == 0 { "normal" } else { "standard" };
            profiler.update_profile(template, 100, &[("user", val)], None);
        }

        // Test with anomalous value containing PII
        let result = profiler.analyze_request(
            template,
            100,
            &[(
                "user",
                "very-long-email-address-that-is-clearly-anomalous@example.com",
            )],
            None,
        );

        // Signal detail should be redacted
        let signal = result
            .signals
            .iter()
            .find(|s| {
                s.signal_type == AnomalySignalType::ParamValueAnomaly
                    || s.signal_type == AnomalySignalType::UnexpectedParam
            })
            .unwrap();
        assert!(signal.detail.contains("ve***om") || signal.detail.contains("****"));
        assert!(!signal.detail.contains("@example.com"));
    }

    #[test]
    fn test_frozen_baseline_prevents_response_updates() {
        let config = ProfilerConfig {
            enabled: true,
            freeze_after_samples: 5,
            ..Default::default()
        };
        let profiler = Profiler::new(config);
        let template = "/api/resp-frozen";

        // Add 5 samples to freeze
        for _i in 0..5 {
            profiler.update_profile(template, 100, &[], None);
            profiler.update_response_profile(template, 200, 200, None);
        }

        assert!(profiler.is_profile_frozen(template));
        let profile_before = profiler.get_profile(template).unwrap();

        // Attempt update after freeze
        profiler.update_response_profile(template, 10000, 500, None);

        let profile_after = profiler.get_profile(template).unwrap();
        assert_eq!(
            profile_before.response_size.mean(),
            profile_after.response_size.mean()
        );
    }

    #[test]
    fn test_get_or_create_profile_returns_none_at_capacity() {
        let config = ProfilerConfig {
            max_profiles: 2,
            ..Default::default()
        };
        let profiler = Profiler::new(config);

        profiler.get_or_create_profile("/a");
        profiler.get_or_create_profile("/b");

        // Third unique profile should be rejected
        let result = profiler.get_or_create_profile("/c");
        assert!(result.is_none());
    }

    #[test]
    fn test_analyze_response_size_anomaly_detected() {
        let profiler = Profiler::new(default_config());
        let template = "/api/resp-size";

        // Train with request samples to reach maturity (sample_count >= 10)
        for _ in 0..15 {
            profiler.update_profile(template, 100, &[], None);
        }

        // Train with small responses and some variance
        for i in 0..20 {
            let size = if i % 2 == 0 { 100 } else { 110 };
            profiler.update_response_profile(template, size, 200, None);
        }

        // Test with massive response
        let result = profiler.analyze_response(template, 10000, 200, None);

        assert!(result
            .signals
            .iter()
            .any(|s| s.signal_type == AnomalySignalType::PayloadSizeHigh));
    }

    #[test]
    fn test_analyze_request_payload_size_low_detected() {
        let profiler = Profiler::new(default_config());
        let template = "/api/small-payload";

        // Train with large payloads and some variance
        for i in 0..20 {
            let size = if i % 2 == 0 { 1000 } else { 1100 };
            profiler.update_profile(template, size, &[], None);
        }

        // Test with very small payload
        let result = profiler.analyze_request(template, 10, &[], None);

        assert!(result
            .signals
            .iter()
            .any(|s| s.signal_type == AnomalySignalType::PayloadSizeLow));
    }
}