ash-core 2.3.6

DEPRECATED — Use `ashcore` instead. This crate is End of Life (EOL).
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
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
//! Comprehensive Stress and Performance Tests
//!
//! These tests verify system behavior under load:
//! - High volume operations
//! - Concurrent operations
//! - Memory safety
//! - Large payload handling

use ash_core::{
    ash_build_proof, ash_verify_proof, ash_derive_client_secret,
    ash_canonicalize_json, ash_canonicalize_query,
    ash_hash_body, ash_normalize_binding,
};
use std::thread;
use std::sync::Arc;

const TEST_NONCE: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const TEST_BODY_HASH: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

// =========================================================================
// HIGH VOLUME TESTS
// =========================================================================

mod high_volume {
    use super::*;

    #[test]
    fn test_10000_canonicalizations() {
        for i in 0..10000 {
            let json = format!(r#"{{"index":{},"value":"test_{}" }}"#, i, i);
            let result = ash_canonicalize_json(&json);
            assert!(result.is_ok(), "Failed at iteration {}", i);
        }
    }

    #[test]
    fn test_10000_hash_operations() {
        for i in 0..10000 {
            let body = format!("body_content_{}_with_some_data", i);
            let hash = ash_hash_body(&body);
            assert_eq!(hash.len(), 64, "Invalid hash at iteration {}", i);
        }
    }

    #[test]
    fn test_5000_secret_derivations() {
        for i in 0..5000 {
            let context_id = format!("ctx_{}", i);
            let secret = ash_derive_client_secret(TEST_NONCE, &context_id, "GET|/|");
            assert!(secret.is_ok(), "Failed at iteration {}", i);
        }
    }

    #[test]
    fn test_5000_proof_generations() {
        let secret = ash_derive_client_secret(TEST_NONCE, "ctx_volume", "POST|/|").unwrap();

        for i in 0..5000 {
            let timestamp = (1700000000 + i).to_string();
            let proof = ash_build_proof(&secret, &timestamp, "POST|/|", TEST_BODY_HASH);
            assert!(proof.is_ok(), "Failed at iteration {}", i);
        }
    }

    #[test]
    fn test_5000_verifications() {
        let context_id = "ctx_verify_volume";
        let binding = "POST|/api|";
        let timestamp = "1700000000";

        let secret = ash_derive_client_secret(TEST_NONCE, context_id, binding).unwrap();
        let proof = ash_build_proof(&secret, timestamp, binding, TEST_BODY_HASH).unwrap();

        for i in 0..5000 {
            let valid = ash_verify_proof(TEST_NONCE, context_id, binding, timestamp, TEST_BODY_HASH, &proof);
            assert!(valid.is_ok() && valid.unwrap(), "Failed at iteration {}", i);
        }
    }

    #[test]
    fn test_10000_binding_normalizations() {
        for i in 0..10000 {
            let path = format!("/api/resource/{}", i);
            let result = ash_normalize_binding("GET", &path, "");
            assert!(result.is_ok(), "Failed at iteration {}", i);
        }
    }

    #[test]
    fn test_10000_query_canonicalizations() {
        for i in 0..10000 {
            let query = format!("page={}&limit=10&sort=name", i);
            let result = ash_canonicalize_query(&query);
            assert!(result.is_ok(), "Failed at iteration {}", i);
        }
    }
}

// =========================================================================
// CONCURRENT OPERATION TESTS
// =========================================================================

mod concurrent {
    use super::*;

    #[test]
    fn test_concurrent_hashing_20_threads() {
        let mut handles = vec![];

        for thread_id in 0..20 {
            let handle = thread::spawn(move || {
                for i in 0..500 {
                    let body = format!("thread_{}_iteration_{}", thread_id, i);
                    let hash = ash_hash_body(&body);
                    assert_eq!(hash.len(), 64);
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("Thread panicked");
        }
    }

    #[test]
    fn test_concurrent_canonicalization_20_threads() {
        let mut handles = vec![];

        for thread_id in 0..20 {
            let handle = thread::spawn(move || {
                for i in 0..500 {
                    let json = format!(r#"{{"thread":{},"iter":{}}}"#, thread_id, i);
                    let result = ash_canonicalize_json(&json);
                    assert!(result.is_ok());
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("Thread panicked");
        }
    }

    #[test]
    fn test_concurrent_proof_generation_10_threads() {
        let mut handles = vec![];

        for thread_id in 0..10 {
            let handle = thread::spawn(move || {
                let context_id = format!("ctx_concurrent_{}", thread_id);
                let binding = "POST|/api/test|";
                let secret = ash_derive_client_secret(TEST_NONCE, &context_id, binding).unwrap();

                for i in 0..500 {
                    let timestamp = (1700000000 + thread_id * 1000 + i).to_string();
                    let proof = ash_build_proof(&secret, &timestamp, binding, TEST_BODY_HASH);
                    assert!(proof.is_ok());
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("Thread panicked");
        }
    }

    #[test]
    fn test_concurrent_verification_shared_proof() {
        let context_id = "ctx_shared_verify";
        let binding = "POST|/api/test|";
        let timestamp = "1700000000";

        let secret = ash_derive_client_secret(TEST_NONCE, context_id, binding).unwrap();
        let proof = Arc::new(ash_build_proof(&secret, timestamp, binding, TEST_BODY_HASH).unwrap());

        let mut handles = vec![];

        for _ in 0..10 {
            let proof_clone = Arc::clone(&proof);
            let handle = thread::spawn(move || {
                for _ in 0..500 {
                    let valid = ash_verify_proof(
                        TEST_NONCE, context_id, binding, timestamp, TEST_BODY_HASH, &proof_clone
                    ).unwrap();
                    assert!(valid);
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("Thread panicked");
        }
    }

    #[test]
    fn test_concurrent_mixed_operations() {
        let mut handles = vec![];

        // Hash threads
        for i in 0..5 {
            let handle = thread::spawn(move || {
                for j in 0..200 {
                    let body = format!("hash_thread_{}_iter_{}", i, j);
                    let _ = ash_hash_body(&body);
                }
            });
            handles.push(handle);
        }

        // Canonicalize threads
        for i in 0..5 {
            let handle = thread::spawn(move || {
                for j in 0..200 {
                    let json = format!(r#"{{"t":{},"i":{}}}"#, i, j);
                    let _ = ash_canonicalize_json(&json);
                }
            });
            handles.push(handle);
        }

        // Proof threads
        for i in 0..5 {
            let handle = thread::spawn(move || {
                let ctx = format!("ctx_mixed_{}", i);
                let secret = ash_derive_client_secret(TEST_NONCE, &ctx, "GET|/|").unwrap();
                for j in 0..200 {
                    let ts = (1700000000 + j).to_string();
                    let _ = ash_build_proof(&secret, &ts, "GET|/|", TEST_BODY_HASH);
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().expect("Thread panicked");
        }
    }
}

// =========================================================================
// LARGE PAYLOAD TESTS
// =========================================================================

mod large_payloads {
    use super::*;

    #[test]
    fn test_1kb_json_payload() {
        let large_value = "x".repeat(1000);
        let json = format!(r#"{{"data":"{}"}}"#, large_value);

        let result = ash_canonicalize_json(&json);
        assert!(result.is_ok());

        let hash = ash_hash_body(&result.unwrap());
        assert_eq!(hash.len(), 64);
    }

    #[test]
    fn test_100kb_json_payload() {
        let large_value = "x".repeat(100_000);
        let json = format!(r#"{{"data":"{}"}}"#, large_value);

        let result = ash_canonicalize_json(&json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_1mb_json_payload() {
        let large_value = "x".repeat(1_000_000);
        let json = format!(r#"{{"data":"{}"}}"#, large_value);

        let result = ash_canonicalize_json(&json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_many_keys_object() {
        let mut json = String::from("{");
        for i in 0..1000 {
            if i > 0 { json.push(','); }
            json.push_str(&format!(r#""key{}":{}"#, i, i));
        }
        json.push('}');

        let result = ash_canonicalize_json(&json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_deeply_nested_but_valid() {
        // 50 levels of nesting (within limit)
        let mut json = String::new();
        for _ in 0..50 {
            json.push_str(r#"{"a":"#);
        }
        json.push_str("1");
        for _ in 0..50 {
            json.push('}');
        }

        let result = ash_canonicalize_json(&json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_large_array() {
        let mut json = String::from("[");
        for i in 0..10000 {
            if i > 0 { json.push(','); }
            json.push_str(&i.to_string());
        }
        json.push(']');

        let result = ash_canonicalize_json(&json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_long_query_string() {
        let params: String = (0..500)
            .map(|i| format!("param{}=value{}", i, i))
            .collect::<Vec<_>>()
            .join("&");

        let result = ash_canonicalize_query(&params);
        assert!(result.is_ok());
    }

    #[test]
    fn test_very_long_path() {
        let long_segment = "a".repeat(1000);
        let path = format!("/api/{}/resource", long_segment);

        let result = ash_normalize_binding("GET", &path, "");
        assert!(result.is_ok());
    }
}

// =========================================================================
// MEMORY SAFETY TESTS
// =========================================================================

mod memory_safety {
    use super::*;

    #[test]
    fn test_repeated_allocation_and_release() {
        for _ in 0..1000 {
            let large_value = "x".repeat(10_000);
            let json = format!(r#"{{"data":"{}"}}"#, large_value);
            let result = ash_canonicalize_json(&json);
            assert!(result.is_ok());
            // Result goes out of scope and is freed
        }
    }

    #[test]
    fn test_interleaved_allocations() {
        let mut results = Vec::new();

        for i in 0..100 {
            let json = format!(r#"{{"iteration":{}}}"#, i);
            results.push(ash_canonicalize_json(&json).unwrap());
        }

        // All results should still be valid
        for (i, result) in results.iter().enumerate() {
            assert!(result.contains(&format!("\"iteration\":{}", i)));
        }
    }

    #[test]
    fn test_string_with_special_allocation_sizes() {
        // Test various sizes that might trigger different allocation strategies
        let sizes = [0, 1, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128, 255, 256, 511, 512, 1023, 1024];

        for size in sizes {
            let value = "x".repeat(size);
            let json = format!(r#"{{"data":"{}"}}"#, value);
            let result = ash_canonicalize_json(&json);
            assert!(result.is_ok(), "Failed for size {}", size);
        }
    }

    #[test]
    fn test_hash_many_unique_inputs() {
        // Generate many unique inputs to test hash table behavior
        let mut hashes = Vec::with_capacity(10000);

        for i in 0..10000 {
            let body = format!("unique_body_content_{}_with_extra_data", i);
            hashes.push(ash_hash_body(&body));
        }

        // Verify all hashes are present
        assert_eq!(hashes.len(), 10000);
    }
}

// =========================================================================
// PERFORMANCE CONSISTENCY TESTS
// =========================================================================

mod performance_consistency {
    use super::*;
    use std::time::Instant;

    #[test]
    fn test_consistent_canonicalization_time() {
        let json = r#"{"z":26,"a":1,"m":13,"nested":{"x":24,"y":25}}"#;

        let mut times = Vec::new();

        for _ in 0..100 {
            let start = Instant::now();
            for _ in 0..1000 {
                let _ = ash_canonicalize_json(json);
            }
            times.push(start.elapsed());
        }

        // Check that times are relatively consistent (within 5x of median)
        // Note: Using 5x threshold to accommodate CI environment variability
        times.sort();
        let median = times[times.len() / 2];
        let min = times[0];
        let max = times[times.len() - 1];

        assert!(
            max <= median * 5,
            "Performance inconsistent: median={:?}, max={:?}",
            median, max
        );
        assert!(
            min >= median / 5,
            "Performance inconsistent: median={:?}, min={:?}",
            median, min
        );
    }

    #[test]
    fn test_consistent_hashing_time() {
        let body = "test body for hashing performance";

        let mut times = Vec::new();

        for _ in 0..100 {
            let start = Instant::now();
            for _ in 0..1000 {
                let _ = ash_hash_body(body);
            }
            times.push(start.elapsed());
        }

        times.sort();
        let median = times[times.len() / 2];
        let max = times[times.len() - 1];

        // Note: Using 5x threshold to accommodate CI environment variability
        assert!(
            max <= median * 5,
            "Hash performance inconsistent: median={:?}, max={:?}",
            median, max
        );
    }

    #[test]
    fn test_scaling_with_input_size() {
        let sizes = [100, 1000, 10000];
        let mut timings = Vec::new();

        for size in sizes {
            let body = "x".repeat(size);
            let start = Instant::now();
            for _ in 0..100 {
                let _ = ash_hash_body(&body);
            }
            timings.push((size, start.elapsed()));
        }

        // Verify roughly linear scaling (10x size should be < 20x time)
        let (s1, t1) = timings[0];
        let (s3, t3) = timings[2];

        let size_ratio = s3 as f64 / s1 as f64;
        let time_ratio = t3.as_nanos() as f64 / t1.as_nanos() as f64;

        assert!(
            time_ratio < size_ratio * 2.0,
            "Scaling worse than expected: size {}x, time {}x",
            size_ratio, time_ratio
        );
    }
}

// =========================================================================
// ERROR RECOVERY TESTS
// =========================================================================

mod error_recovery {
    use super::*;

    #[test]
    fn test_continue_after_invalid_json() {
        // Process invalid JSON
        let result = ash_canonicalize_json("invalid{json");
        assert!(result.is_err());

        // Should still be able to process valid JSON after error
        let result = ash_canonicalize_json(r#"{"valid":"json"}"#);
        assert!(result.is_ok());
    }

    #[test]
    fn test_continue_after_invalid_nonce() {
        // Try invalid nonce
        let result = ash_derive_client_secret("short", "ctx", "GET|/|");
        assert!(result.is_err());

        // Should still work with valid nonce
        let result = ash_derive_client_secret(TEST_NONCE, "ctx", "GET|/|");
        assert!(result.is_ok());
    }

    #[test]
    fn test_interleaved_valid_invalid() {
        for i in 0..100 {
            // Alternate between valid and invalid inputs
            if i % 2 == 0 {
                let json = format!(r#"{{"index":{}}}"#, i);
                let result = ash_canonicalize_json(&json);
                assert!(result.is_ok());
            } else {
                let invalid = format!("invalid_json_{}", i);
                let result = ash_canonicalize_json(&invalid);
                assert!(result.is_err());
            }
        }
    }
}