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
//! Security Audit Tests for ASH Rust SDK
//!
//! Tests security vulnerabilities, attack vectors, and hardening measures.
//! Based on TEST-DOCUMENTATION.md security requirements.

use ash_core::{
    ash_build_proof, ash_verify_proof, ash_derive_client_secret,
    ash_canonicalize_json, ash_canonicalize_query,
    ash_hash_body, ash_timing_safe_equal, ash_normalize_binding,
    ash_build_proof_scoped, ash_verify_proof_scoped,
    ash_build_proof_unified, ash_verify_proof_unified,
    ash_extract_scoped_fields, ash_validate_timestamp,
};
use std::collections::HashSet;

// =========================================================================
// INPUT VALIDATION SECURITY
// =========================================================================

#[test]
fn test_rejects_empty_nonce() {
    let result = ash_derive_client_secret("", "ctx_test", "POST|/api|");
    assert!(result.is_err());
}

#[test]
fn test_rejects_short_nonce() {
    // Nonce must be at least 32 hex chars (16 bytes)
    let result = ash_derive_client_secret("abcd1234", "ctx_test", "POST|/api|");
    assert!(result.is_err());
}

#[test]
fn test_rejects_non_hex_nonce() {
    let result = ash_derive_client_secret("ghijklmnopqrstuvwxyz123456789012", "ctx_test", "POST|/api|");
    assert!(result.is_err());
}

#[test]
fn test_rejects_empty_context_id() {
    let nonce = "a".repeat(64);
    let result = ash_derive_client_secret(&nonce, "", "POST|/api|");
    assert!(result.is_err());
}

#[test]
fn test_rejects_empty_binding() {
    let nonce = "a".repeat(64);
    // PT-001: ash_derive_client_secret now validates empty binding
    let result = ash_derive_client_secret(&nonce, "ctx_test", "");
    assert!(result.is_err());
    assert!(result.unwrap_err().message().contains("binding"));
}

#[test]
fn test_rejects_invalid_json() {
    let result = ash_canonicalize_json("not valid json");
    assert!(result.is_err());
}

#[test]
fn test_rejects_json_with_nan() {
    // NaN is not valid JSON per RFC 8785
    let result = ash_canonicalize_json(r#"{"value": NaN}"#);
    assert!(result.is_err());
}

#[test]
fn test_rejects_json_with_infinity() {
    let result = ash_canonicalize_json(r#"{"value": Infinity}"#);
    assert!(result.is_err());
}

// =========================================================================
// INJECTION PREVENTION
// =========================================================================

#[test]
fn test_json_injection_prevented() {
    // Attempting to inject via special characters
    let payload = r#"{"key": "value\", \"injected\": \"true"}"#;
    let result = ash_canonicalize_json(payload);
    // Should either fail or properly escape
    if let Ok(canonical) = result {
        // If it succeeds, verify no injection occurred
        assert!(!canonical.contains(r#""injected""#));
    }
}

#[test]
fn test_prototype_pollution_in_scope() {
    // Note: Rust SDK doesn't specifically reject __proto__ as dangerous
    // It treats it like any other field name
    let payload = serde_json::json!({"__proto__": {"polluted": true}, "safe": 1});
    let result = ash_extract_scoped_fields(&payload, &["__proto__"]);
    // In Rust, this is OK - the field is extracted if it exists
    assert!(result.is_ok());
    // The field should be in the result
    let extracted = result.unwrap();
    assert!(extracted.get("__proto__").is_some());
}

#[test]
fn test_constructor_field_in_scope() {
    // Note: Rust SDK doesn't specifically reject constructor as dangerous
    // It treats it like any other field name
    let payload = serde_json::json!({"constructor": {"polluted": true}, "safe": 1});
    let result = ash_extract_scoped_fields(&payload, &["constructor"]);
    // In Rust, this is OK - the field is extracted if it exists
    assert!(result.is_ok());
    let extracted = result.unwrap();
    assert!(extracted.get("constructor").is_some());
}

#[test]
fn test_path_traversal_in_scope_prevented() {
    let payload = serde_json::json!({"data": {"nested": 1}});
    // Path traversal attempts should be handled safely
    let result = ash_extract_scoped_fields(&payload, &["../etc/passwd"]);
    // Should either fail or return empty (field not found)
    // Value doesn't have is_empty, check as_object
    if let Ok(extracted) = result {
        let is_empty = extracted.as_object().map(|o| o.is_empty()).unwrap_or(true);
        assert!(is_empty);
    }
}

// =========================================================================
// CRYPTOGRAPHIC SECURITY
// =========================================================================

#[test]
fn test_nonce_uniqueness() {
    // Generate many nonces and ensure uniqueness
    let mut nonces = HashSet::new();
    for _ in 0..1000 {
        let nonce = format!("{:064x}", rand::random::<u128>());
        nonces.insert(nonce);
    }
    assert_eq!(nonces.len(), 1000, "Nonces should be unique");
}

#[test]
fn test_proof_is_deterministic() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = "1700000000";
    let body_hash = "b".repeat(64);

    let secret = ash_derive_client_secret(&nonce, context_id, binding).unwrap();

    let proof1 = ash_build_proof(&secret, timestamp, binding, &body_hash).unwrap();
    let proof2 = ash_build_proof(&secret, timestamp, binding, &body_hash).unwrap();

    assert_eq!(proof1, proof2, "Same inputs should produce same proof");
}

#[test]
fn test_different_inputs_produce_different_proofs() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = "1700000000";

    let secret = ash_derive_client_secret(&nonce, context_id, binding).unwrap();

    let proof1 = ash_build_proof(&secret, timestamp, binding, &"a".repeat(64)).unwrap();
    let proof2 = ash_build_proof(&secret, timestamp, binding, &"b".repeat(64)).unwrap();

    assert_ne!(proof1, proof2, "Different inputs should produce different proofs");
}

#[test]
fn test_timing_safe_comparison() {
    // Verify timing-safe comparison works correctly
    assert!(ash_timing_safe_equal(b"abc", b"abc"));
    assert!(!ash_timing_safe_equal(b"abc", b"abd"));
    assert!(!ash_timing_safe_equal(b"abc", b"abcd"));
    assert!(!ash_timing_safe_equal(b"", b"a"));
}

// =========================================================================
// REPLAY PREVENTION
// =========================================================================

#[test]
fn test_timestamp_validation_rejects_old() {
    // Timestamp from 1 hour ago should be rejected
    let old_timestamp = (chrono::Utc::now().timestamp() - 3600).to_string();
    let result = ash_validate_timestamp(&old_timestamp, 300, 60);
    assert!(result.is_err());
}

#[test]
fn test_timestamp_validation_rejects_future() {
    // Timestamp 1 hour in future should be rejected
    let future_timestamp = (chrono::Utc::now().timestamp() + 3600).to_string();
    let result = ash_validate_timestamp(&future_timestamp, 300, 60);
    assert!(result.is_err());
}

#[test]
fn test_timestamp_validation_accepts_current() {
    let current_timestamp = chrono::Utc::now().timestamp().to_string();
    let result = ash_validate_timestamp(&current_timestamp, 300, 60);
    assert!(result.is_ok());
}

// =========================================================================
// INFORMATION DISCLOSURE PREVENTION
// =========================================================================

#[test]
fn test_error_messages_do_not_leak_secrets() {
    let nonce = "secret_nonce_".to_string() + &"a".repeat(51);

    // Try to use invalid nonce
    let result = ash_derive_client_secret(&nonce, "ctx", "POST|/|");

    if let Err(e) = result {
        let error_msg = e.to_string();
        assert!(!error_msg.contains("secret_nonce_"),
            "Error message should not contain the nonce");
    }
}

#[test]
fn test_verification_failure_does_not_leak_expected_proof() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();
    let body_hash = "b".repeat(64);
    let wrong_proof = "c".repeat(64);

    let result = ash_verify_proof(&nonce, context_id, binding, &timestamp, &body_hash, &wrong_proof);

    // Should return false, not error with expected proof
    assert!(result.is_ok());
    assert!(!result.unwrap());
}

// =========================================================================
// SIZE LIMIT ENFORCEMENT
// =========================================================================

#[test]
fn test_rejects_oversized_json() {
    // Create JSON larger than 10MB limit
    let large_data = "x".repeat(11 * 1024 * 1024);
    let large_json = format!(r#"{{"data": "{}"}}"#, large_data);

    let result = ash_canonicalize_json(&large_json);
    assert!(result.is_err());
}

#[test]
fn test_rejects_deeply_nested_json() {
    // Create deeply nested JSON (> 64 levels)
    let mut json = String::from("1");
    for _ in 0..100 {
        json = format!(r#"{{"a": {}}}"#, json);
    }

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

#[test]
fn test_rejects_oversized_nonce() {
    // Nonce longer than max allowed (MAX_NONCE_LENGTH = 512 hex chars)
    let long_nonce = "a".repeat(513);
    let result = ash_derive_client_secret(&long_nonce, "ctx", "POST|/|");
    assert!(result.is_err());
}

#[test]
fn test_rejects_oversized_binding() {
    // Binding longer than 8KB - size limit is checked in ash_derive_client_secret/ash_build_proof
    let long_path = "/".to_string() + &"a".repeat(9000);
    let binding = ash_normalize_binding("POST", &long_path, "").unwrap();

    // ash_derive_client_secret enforces the 8KB limit
    let nonce = "a".repeat(64);
    let result = ash_derive_client_secret(&nonce, "ctx", &binding);
    assert!(result.is_err());
}

// =========================================================================
// SCOPE SECURITY
// =========================================================================

#[test]
fn test_scope_rejects_too_many_fields() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();

    let secret = ash_derive_client_secret(&nonce, context_id, binding).unwrap();

    // Create payload with many fields
    let mut payload_map = serde_json::Map::new();
    for i in 0..150 {
        payload_map.insert(format!("field{}", i), serde_json::json!(i));
    }
    let payload = serde_json::Value::Object(payload_map);
    let payload_str = serde_json::to_string(&payload).unwrap();

    // Create scope with too many fields
    let scope: Vec<&str> = (0..150).map(|i| Box::leak(format!("field{}", i).into_boxed_str()) as &str).collect();

    let result = ash_build_proof_scoped(&secret, &timestamp, binding, &payload_str, &scope);
    assert!(result.is_err());
}

#[test]
fn test_scope_field_name_length_limit() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();

    let secret = ash_derive_client_secret(&nonce, context_id, binding).unwrap();

    // Field name longer than 64 chars
    let long_field = "a".repeat(100);
    let payload = serde_json::json!({&long_field: 1});
    let payload_str = serde_json::to_string(&payload).unwrap();

    let result = ash_build_proof_scoped(&secret, &timestamp, binding, &payload_str, &[&long_field]);
    assert!(result.is_err());
}

// =========================================================================
// ENCODING ATTACKS
// =========================================================================

#[test]
fn test_double_encoding_handled() {
    // %252F is double-encoded /
    let query = "key=%252F";
    let result = ash_canonicalize_query(query);
    assert!(result.is_ok());
    // Should preserve double encoding, not decode twice
    assert!(result.unwrap().contains("%252F"));
}

#[test]
fn test_mixed_case_hex_normalized() {
    // Mix of uppercase and lowercase hex should normalize
    let query = "key=%2f";  // lowercase
    let canonical = ash_canonicalize_query(query).unwrap();
    assert!(canonical.contains("%2F"), "Should uppercase hex digits");
}

#[test]
fn test_unicode_normalization_nfc() {
    // NFD form (e + combining accent) should normalize to NFC (é)
    let nfd = r#"{"text": "cafe\u0301"}"#;  // café in NFD
    let nfc = r#"{"text": "café"}"#;         // café in NFC

    let canonical_nfd = ash_canonicalize_json(nfd).unwrap();
    let canonical_nfc = ash_canonicalize_json(nfc).unwrap();

    assert_eq!(canonical_nfd, canonical_nfc, "Unicode should normalize to NFC");
}

// =========================================================================
// VERIFICATION SECURITY
// =========================================================================

#[test]
fn test_verify_rejects_tampered_binding() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();
    let body_hash = ash_hash_body("{}");

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

    // Try to verify with different binding
    let tampered_binding = "POST|/api/admin|";
    let result = ash_verify_proof(&nonce, context_id, tampered_binding, &timestamp, &body_hash, &proof).unwrap();

    assert!(!result, "Tampered binding should fail verification");
}

#[test]
fn test_verify_rejects_tampered_body() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();
    let body_hash = ash_hash_body(r#"{"amount": 100}"#);

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

    // Try to verify with different body
    let tampered_body_hash = ash_hash_body(r#"{"amount": 10000}"#);
    let result = ash_verify_proof(&nonce, context_id, binding, &timestamp, &tampered_body_hash, &proof).unwrap();

    assert!(!result, "Tampered body should fail verification");
}

#[test]
fn test_verify_rejects_wrong_proof_format() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();
    let body_hash = "b".repeat(64);

    // Wrong length proof
    let short_proof = "abc123";
    let result = ash_verify_proof(&nonce, context_id, binding, &timestamp, &body_hash, short_proof);
    assert!(result.is_err() || !result.unwrap());

    // Non-hex proof
    let invalid_proof = "g".repeat(64);
    let result = ash_verify_proof(&nonce, context_id, binding, &timestamp, &body_hash, &invalid_proof);
    assert!(result.is_err() || !result.unwrap());
}

// =========================================================================
// SCOPED PROOF SECURITY
// =========================================================================

#[test]
fn test_scoped_proof_protects_specified_fields() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let binding = "POST|/api/test|";
    let timestamp = chrono::Utc::now().timestamp().to_string();

    let secret = ash_derive_client_secret(&nonce, context_id, binding).unwrap();

    let payload = r#"{"amount": 100, "memo": "test"}"#;
    let scope = vec!["amount"];

    let (proof, scope_hash) = ash_build_proof_scoped(&secret, &timestamp, binding, payload, &scope).unwrap();

    // Modify memo (unscoped) - should still verify
    let modified_payload = r#"{"amount": 100, "memo": "modified"}"#;
    let result = ash_verify_proof_scoped(&nonce, context_id, binding, &timestamp, modified_payload, &scope, &scope_hash, &proof).unwrap();
    assert!(result, "Unscoped field change should verify");

    // Modify amount (scoped) - should fail
    let tampered_payload = r#"{"amount": 10000, "memo": "test"}"#;
    let result = ash_verify_proof_scoped(&nonce, context_id, binding, &timestamp, tampered_payload, &scope, &scope_hash, &proof).unwrap();
    assert!(!result, "Scoped field change should fail verification");
}

// =========================================================================
// CHAINED PROOF SECURITY
// =========================================================================

#[test]
fn test_chained_proof_integrity() {
    let nonce = "a".repeat(64);
    let context_id = "ctx_test";
    let timestamp = chrono::Utc::now().timestamp().to_string();

    // Step 1
    let binding1 = "POST|/api/step1|";
    let secret1 = ash_derive_client_secret(&nonce, context_id, binding1).unwrap();
    let payload1 = r#"{"step": 1}"#;
    let result1 = ash_build_proof_unified(&secret1, &timestamp, binding1, payload1, &[], None).unwrap();

    // Step 2 chained to step 1
    let binding2 = "POST|/api/step2|";
    let secret2 = ash_derive_client_secret(&nonce, context_id, binding2).unwrap();
    let payload2 = r#"{"step": 2}"#;
    let result2 = ash_build_proof_unified(&secret2, &timestamp, binding2, payload2, &[], Some(&result1.proof)).unwrap();

    // Verify step 2 with correct chain
    let scope: &[&str] = &[];
    let valid = ash_verify_proof_unified(
        &nonce, context_id, binding2, &timestamp, payload2,
        &result2.proof, scope, &result2.scope_hash,
        Some(&result1.proof), &result2.chain_hash
    ).unwrap();
    assert!(valid, "Valid chain should verify");

    // Verify step 2 with wrong previous proof
    let wrong_proof = "d".repeat(64);
    let invalid = ash_verify_proof_unified(
        &nonce, context_id, binding2, &timestamp, payload2,
        &result2.proof, scope, &result2.scope_hash,
        Some(&wrong_proof), &result2.chain_hash
    ).unwrap();
    assert!(!invalid, "Wrong chain should fail verification");
}