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
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
//! # ASH Core
//!
//! **ASH (Anti-tamper Security Hash)** is a request integrity and anti-replay protection library
//!
//! ## Safety
//!
//! This crate uses `#![forbid(unsafe_code)]` to guarantee 100% safe Rust.
//! that ensures HTTP requests have not been tampered with in transit.
//!
//! ## What ASH Does
//!
//! ASH provides cryptographic proof that:
//! - The **payload** has not been modified
//! - The request is for the **correct endpoint** (method + path + query)
//! - The request is **not a replay** of a previous request
//! - Optionally, only **specific fields** are protected (scoping)
//!
//! ## What ASH Does NOT Do
//!
//! ASH verifies **what** is being submitted, not **who** is submitting it.
//! Use alongside authentication systems (JWT, OAuth, API keys, etc.).
//!
//! ## Quick Start
//!
//! ```rust
//! use ash_core::{
//!     ash_canonicalize_json, ash_derive_client_secret,
//!     ash_build_proof, ash_verify_proof, ash_hash_body,
//! };
//!
//! // 1. Server provides nonce and context_id to client
//! let nonce = "0123456789abcdef0123456789abcdef"; // 32+ hex chars
//! let context_id = "ctx_abc123";
//! let binding = "POST|/api/transfer|";
//!
//! // 2. Client canonicalizes payload
//! let payload = r#"{"amount":100,"recipient":"alice"}"#;
//! let canonical = ash_canonicalize_json(payload).unwrap();
//!
//! // 3. Client derives secret and builds proof
//! let client_secret = ash_derive_client_secret(nonce, context_id, binding).unwrap();
//! let body_hash = ash_hash_body(&canonical);
//! let timestamp = "1704067200";
//! let proof = ash_build_proof(&client_secret, timestamp, binding, &body_hash).unwrap();
//!
//! // 4. Server verifies proof (re-derives secret from nonce internally)
//! let valid = ash_verify_proof(nonce, context_id, binding, timestamp, &body_hash, &proof).unwrap();
//! assert!(valid);
//! ```
//!
//! ## Features
//!
//! | Feature | Description |
//! |---------|-------------|
//! | **Tamper Detection** | HMAC-SHA256 proof ensures payload integrity |
//! | **Replay Prevention** | One-time contexts prevent request replay |
//! | **Deterministic** | Byte-identical output across all platforms |
//! | **Field Scoping** | Protect specific fields while allowing others to change |
//! | **Request Chaining** | Link sequential requests cryptographically |
//! | **WASM Compatible** | Works in browsers and server environments |
//!
//! ## Module Overview
//!
//! | Module | Purpose |
//! |--------|---------|
//! | [`proof`](crate::proof) | Core proof generation and verification |
//! | [`canonicalize`](crate::canonicalize) | Deterministic JSON/URL-encoded serialization |
//! | [`compare`](crate::compare) | Constant-time comparison functions |
//! | [`config`](crate::config) | Scope policy configuration |
//! | [`errors`](crate::errors) | Error types and codes |
//!
//! ## Security Considerations
//!
//! - **Nonce entropy**: Use 32+ hex characters (128+ bits) for nonces
//! - **Timestamp validation**: Reject requests older than 5 minutes
//! - **HTTPS required**: ASH does not encrypt data, only signs it
//! - **Context isolation**: Never reuse context_id across requests
//!
//! ## Protocol Version
//!
//! This library implements ASH Protocol v2.1 with extensions:
//! - v2.2: Field-level scoping
//! - v2.3: Request chaining
//! - v2.3.2: Binding normalization (METHOD|PATH|QUERY format)
//! - v2.3.4: Bug fixes (BUG-020 through BUG-034)
//! - v2.3.5: Security hardening (SEC-AUDIT-005 through SEC-AUDIT-007)

#![forbid(unsafe_code)]
#![forbid(clippy::undocumented_unsafe_blocks)]

mod canonicalize;
mod compare;
pub mod config;
mod errors;
pub mod headers;
mod proof;
mod types;
pub mod binding;
pub mod enriched;
mod validate;
pub mod build;
pub mod testkit;
pub mod verify;

pub use canonicalize::{ash_canonicalize_json, ash_canonicalize_json_value, ash_canonicalize_json_value_with_size_check, ash_canonicalize_query, ash_canonicalize_urlencoded};
pub use compare::{ash_timing_safe_equal, ash_timing_safe_compare};
pub use errors::{AshError, AshErrorCode, InternalReason};
pub use headers::{HeaderMapView, HeaderBundle, ash_extract_headers};
pub use validate::ash_validate_nonce;
pub use proof::{
    // Core proof functions
    ash_build_proof,
    ash_verify_proof,
    ash_verify_proof_with_freshness,
    ash_derive_client_secret,
    // Scoped proof functions
    ash_build_proof_scoped,
    ash_verify_proof_scoped,
    ash_extract_scoped_fields,
    ash_extract_scoped_fields_strict,
    // Unified proof functions (scoping + chaining)
    ash_build_proof_unified,
    ash_verify_proof_unified,
    UnifiedProofResult,
    // Hash functions
    ash_hash_body,
    ash_hash_proof,
    ash_hash_scope,
    ash_hash_scoped_body,
    ash_hash_scoped_body_strict,
    // Nonce and context generation
    ash_generate_nonce,
    ash_generate_nonce_or_panic,
    ash_generate_context_id,
    ash_generate_context_id_256,
    // Timestamp validation
    ash_validate_timestamp,
    ash_validate_timestamp_format,
    DEFAULT_MAX_TIMESTAMP_AGE_SECONDS,
    DEFAULT_CLOCK_SKEW_SECONDS,
    // Version constants
    ASH_SDK_VERSION,
    ASH_VERSION_PREFIX,
};
pub use types::{AshMode, BuildProofInput, VerifyInput};
pub use binding::{ash_normalize_binding_value, BindingType, NormalizedBindingValue, MAX_BINDING_VALUE_LENGTH};
pub use build::{build_request_proof, BuildRequestInput, BuildRequestResult, BuildMeta};
pub use enriched::{
    ash_canonicalize_query_enriched, CanonicalQueryResult,
    ash_hash_body_enriched, BodyHashResult,
    ash_normalize_binding_enriched, ash_parse_binding, NormalizedBinding,
};
pub use testkit::{load_vectors, load_vectors_from_file, run_vectors, AshAdapter, AdapterResult, TestReport, VectorResult, Vector, VectorFile};
pub use verify::{verify_incoming_request, VerifyRequestInput, VerifyResult, VerifyMeta};

/// Normalize a binding string to canonical form (v2.3.2+ format).
///
/// Bindings are in the format: `METHOD|PATH|CANONICAL_QUERY`
///
/// # Normalization Rules
/// - Method is uppercased
/// - Path must start with `/`
/// - Path must not contain `?` (use `normalize_binding_from_url` for combined path+query)
/// - Path is percent-decoded, normalized, then re-encoded (BUG-025 fix)
/// - Path has duplicate slashes collapsed (after decoding)
/// - Trailing slash is removed (except for root `/`)
/// - Query string is canonicalized (sorted, normalized)
/// - Parts are joined with `|` (pipe) separator
///
/// # Path Normalization (BUG-025)
///
/// Paths are decoded before normalization to handle cases like:
/// - `/api/%2F%2F/users` → decoded → `/api///users` → normalized → `/api/users`
/// - `/api/caf%C3%A9` → decoded → `/api/café` → re-encoded → `/api/caf%C3%A9`
///
/// # Error on Embedded Query
///
/// If the `path` parameter contains a `?`, an error is returned to prevent
/// silent data loss. Use [`normalize_binding_from_url`] if you have a combined
/// path+query string.
///
/// # Example
///
/// ```rust
/// use ash_core::ash_normalize_binding;
///
/// let binding = ash_normalize_binding("post", "/api//users/", "").unwrap();
/// assert_eq!(binding, "POST|/api/users|");
///
/// let binding_with_query = ash_normalize_binding("GET", "/api/users", "page=1&sort=name").unwrap();
/// assert_eq!(binding_with_query, "GET|/api/users|page=1&sort=name");
///
/// // Error if path contains '?'
/// assert!(ash_normalize_binding("GET", "/api/users?old=query", "new=query").is_err());
/// ```
pub fn ash_normalize_binding(method: &str, path: &str, query: &str) -> Result<String, AshError> {
    // Validate method
    let method = method.trim();
    if method.is_empty() {
        return Err(AshError::new(
            AshErrorCode::ValidationError,
            "Method cannot be empty",
        ));
    }

    // BUG-042: Use ASCII-only uppercase to ensure cross-platform consistency
    // Unicode uppercase rules can vary across platforms/versions
    if !method.is_ascii() {
        return Err(AshError::new(
            AshErrorCode::ValidationError,
            "Method must contain only ASCII characters",
        ));
    }
    let method = method.to_ascii_uppercase();

    // Validate path starts with /
    let path = path.trim();
    if !path.starts_with('/') {
        return Err(AshError::new(
            AshErrorCode::ValidationError,
            "Path must start with /",
        ));
    }

    // BUG-025: Percent-decode the path before normalization
    let decoded_path = ash_percent_decode_path(path)?;

    // BUG-009 & BUG-027: Error if path contains '?' AFTER decoding to catch encoded %3F
    // This prevents silent data loss and encoded query delimiter bypass
    if decoded_path.contains('?') {
        return Err(AshError::new(
            AshErrorCode::ValidationError,
            "Path must not contain '?' (including encoded %3F) - use normalize_binding_from_url for combined path+query",
        ));
    }

    // BUG-035: Normalize path segments including . and ..
    let normalized_path = ash_normalize_path_segments(&decoded_path);

    // Ensure path still starts with / after normalization
    if normalized_path.is_empty() || !normalized_path.starts_with('/') {
        return Err(AshError::new(
            AshErrorCode::ValidationError,
            "Path normalization resulted in invalid path",
        ));
    }

    // BUG-025: Re-encode the normalized path (only encode characters that need encoding)
    let encoded_path = ash_percent_encode_path(&normalized_path);

    // BUG-043: Trim whitespace from query string before canonicalization
    // Whitespace-only query should be treated as empty
    let query = query.trim();
    let canonical_query = if query.is_empty() {
        String::new()
    } else {
        canonicalize::ash_canonicalize_query(query)?
    };

    // v2.3.2 format: METHOD|PATH|CANONICAL_QUERY
    Ok(format!(
        "{}|{}|{}",
        method, encoded_path, canonical_query
    ))
}

/// Percent-decode a URL path segment.
/// BUG-025: Decodes %XX sequences to their character equivalents.
fn ash_percent_decode_path(input: &str) -> Result<String, AshError> {
    let mut bytes = Vec::with_capacity(input.len());
    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '%' {
            // Read two hex digits
            let hex: String = chars.by_ref().take(2).collect();
            if hex.len() != 2 {
                return Err(AshError::new(
                    AshErrorCode::ValidationError,
                    "Invalid percent encoding in path",
                ));
            }
            let byte = u8::from_str_radix(&hex, 16).map_err(|_| {
                AshError::new(
                    AshErrorCode::ValidationError,
                    "Invalid percent encoding hex in path",
                )
            })?;
            bytes.push(byte);
        } else {
            // Encode character directly to UTF-8 bytes
            let mut buf = [0u8; 4];
            let encoded = ch.encode_utf8(&mut buf);
            bytes.extend_from_slice(encoded.as_bytes());
        }
    }

    // Convert bytes to UTF-8 string
    String::from_utf8(bytes).map_err(|_| {
        AshError::new(
            AshErrorCode::ValidationError,
            "Invalid UTF-8 in percent-decoded path",
        )
    })
}

/// Normalize path segments, handling `.`, `..`, duplicate slashes, and trailing slashes.
/// BUG-035: Properly resolves `.` (current dir) and `..` (parent dir) segments.
///
/// # Rules
/// - `.` segments are removed
/// - `..` segments remove the preceding segment (if any)
/// - Duplicate slashes are collapsed
/// - Trailing slash is removed (except for root `/`)
/// - `..` at root level is ignored (can't go above root)
fn ash_normalize_path_segments(path: &str) -> String {
    let mut segments: Vec<&str> = Vec::new();

    for segment in path.split('/') {
        match segment {
            "" | "." => {
                // Empty segment (from // or leading /) or current dir - skip
                continue;
            }
            ".." => {
                // Parent dir - pop last segment if any
                segments.pop();
            }
            s => {
                segments.push(s);
            }
        }
    }

    // Reconstruct path with leading slash
    if segments.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", segments.join("/"))
    }
}

/// Percent-encode a URL path, preserving safe characters.
/// BUG-025: Only encodes characters that are not allowed in URL paths.
fn ash_percent_encode_path(input: &str) -> String {
    let mut result = String::with_capacity(input.len() * 3);

    for ch in input.chars() {
        match ch {
            // Unreserved characters (RFC 3986)
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => {
                result.push(ch);
            }
            // Path separators and sub-delimiters that are safe in paths
            '/' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | ':' | '@' => {
                result.push(ch);
            }
            _ => {
                // Encode all other characters
                let mut buf = [0u8; 4];
                let encoded = ch.encode_utf8(&mut buf);
                for byte in encoded.as_bytes() {
                    use std::fmt::Write;
                    write!(result, "%{:02X}", byte).unwrap();
                }
            }
        }
    }

    result
}

/// Normalize a binding from a full URL path (including query string).
///
/// This is a convenience function that extracts the query string from the path.
///
/// # Example
///
/// ```rust
/// use ash_core::ash_normalize_binding_from_url;
///
/// let binding = ash_normalize_binding_from_url("GET", "/api/users?page=1&sort=name").unwrap();
/// assert_eq!(binding, "GET|/api/users|page=1&sort=name");
/// ```
pub fn ash_normalize_binding_from_url(method: &str, full_path: &str) -> Result<String, AshError> {
    let (path, query) = match full_path.find('?') {
        Some(pos) => (&full_path[..pos], &full_path[pos + 1..]),
        None => (full_path, ""),
    };
    ash_normalize_binding(method, path, query)
}

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

    // v2.3.2 Binding Format Tests (METHOD|PATH|CANONICAL_QUERY)

    #[test]
    fn test_normalize_binding_basic() {
        assert_eq!(
            ash_normalize_binding("POST", "/api/users", "").unwrap(),
            "POST|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_lowercase_method() {
        assert_eq!(
            ash_normalize_binding("post", "/api/users", "").unwrap(),
            "POST|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_duplicate_slashes() {
        assert_eq!(
            ash_normalize_binding("GET", "/api//users///profile", "").unwrap(),
            "GET|/api/users/profile|"
        );
    }

    #[test]
    fn test_normalize_binding_trailing_slash() {
        assert_eq!(
            ash_normalize_binding("PUT", "/api/users/", "").unwrap(),
            "PUT|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_root() {
        assert_eq!(ash_normalize_binding("GET", "/", "").unwrap(), "GET|/|");
    }

    #[test]
    fn test_normalize_binding_with_query() {
        assert_eq!(
            ash_normalize_binding("GET", "/api/users", "page=1&sort=name").unwrap(),
            "GET|/api/users|page=1&sort=name"
        );
    }

    #[test]
    fn test_normalize_binding_query_sorted() {
        assert_eq!(
            ash_normalize_binding("GET", "/api/users", "z=3&a=1&b=2").unwrap(),
            "GET|/api/users|a=1&b=2&z=3"
        );
    }

    #[test]
    fn test_normalize_binding_from_url_basic() {
        assert_eq!(
            ash_normalize_binding_from_url("GET", "/api/users?page=1&sort=name").unwrap(),
            "GET|/api/users|page=1&sort=name"
        );
    }

    #[test]
    fn test_normalize_binding_from_url_no_query() {
        assert_eq!(
            ash_normalize_binding_from_url("POST", "/api/users").unwrap(),
            "POST|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_from_url_query_sorted() {
        assert_eq!(
            ash_normalize_binding_from_url("GET", "/api/search?z=last&a=first").unwrap(),
            "GET|/api/search|a=first&z=last"
        );
    }

    #[test]
    fn test_normalize_binding_empty_method() {
        assert!(ash_normalize_binding("", "/api", "").is_err());
    }

    #[test]
    fn test_normalize_binding_no_leading_slash() {
        assert!(ash_normalize_binding("GET", "api/users", "").is_err());
    }

    // Version Constants Tests

    #[test]
    fn test_version_constants() {
        use crate::{ASH_SDK_VERSION, ASH_VERSION_PREFIX};

        assert_eq!(ASH_SDK_VERSION, "2.3.5");
        assert_eq!(ASH_VERSION_PREFIX, "ASHv2.1");
    }

    // v2.3.1 Query Canonicalization in Binding Tests

    #[test]
    fn test_normalize_binding_strips_fragment() {
        // Fragment should be stripped from query string
        assert_eq!(
            ash_normalize_binding("GET", "/api/search", "q=test#section").unwrap(),
            "GET|/api/search|q=test"
        );
    }

    #[test]
    fn test_normalize_binding_plus_literal() {
        // + is literal plus in query strings, not space
        assert_eq!(
            ash_normalize_binding("GET", "/api/search", "q=a+b").unwrap(),
            "GET|/api/search|q=a%2Bb"
        );
    }

    // BUG-025: Path percent-encoding normalization tests

    #[test]
    fn test_normalize_binding_encoded_slashes() {
        // BUG-025: Encoded slashes should be decoded and collapsed
        assert_eq!(
            ash_normalize_binding("GET", "/api/%2F%2F/users", "").unwrap(),
            "GET|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_encoded_double_slash() {
        // Encoded double slash should be collapsed to single slash
        assert_eq!(
            ash_normalize_binding("GET", "/api%2F%2Fusers", "").unwrap(),
            "GET|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_unicode_path() {
        // Unicode characters should be preserved (encoded in output)
        let result = ash_normalize_binding("GET", "/api/café", "").unwrap();
        assert!(result.starts_with("GET|/api/caf"));
        // The é should be percent-encoded
        assert!(result.contains("%C3%A9") || result.contains("é"));
    }

    #[test]
    fn test_normalize_binding_mixed_encoding() {
        // Mix of encoded and unencoded should normalize consistently
        let result1 = ash_normalize_binding("GET", "/api/%2Ftest", "").unwrap();
        let result2 = ash_normalize_binding("GET", "/api//test", "").unwrap();
        // Both should collapse to /api/test
        assert_eq!(result1, result2);
    }

    #[test]
    fn test_normalize_binding_encoded_trailing_slash() {
        // Encoded trailing slash should be removed
        assert_eq!(
            ash_normalize_binding("GET", "/api/users%2F", "").unwrap(),
            "GET|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_special_chars_preserved() {
        // Special characters that are valid in paths should be preserved
        let result = ash_normalize_binding("GET", "/api/users/@me", "").unwrap();
        assert_eq!(result, "GET|/api/users/@me|");
    }

    // BUG-027: Encoded query delimiter tests

    #[test]
    fn test_normalize_binding_rejects_encoded_question_mark() {
        // BUG-027: Encoded %3F (?) should be rejected after decoding
        let result = ash_normalize_binding("GET", "/api/users%3Fid=5", "");
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("?"));
    }

    #[test]
    fn test_normalize_binding_rejects_doubly_encoded_question_mark() {
        // BUG-027: Doubly encoded %253F decodes to %3F, then to ? - should be rejected
        // Note: %253F -> %3F after first decode, but we only do one decode pass,
        // so %253F -> %3F (stays as-is), which doesn't contain literal ?
        // This is acceptable as it's an unusual edge case
        let result = ash_normalize_binding("GET", "/api/users%253F", "");
        // This should succeed because %253F decodes to "%3F" (literal chars), not "?"
        assert!(result.is_ok());
    }

    #[test]
    fn test_normalize_binding_allows_other_encoded_chars() {
        // Other encoded characters should be allowed
        // %20 = space, %2B = +
        let result = ash_normalize_binding("GET", "/api/hello%20world", "").unwrap();
        assert!(result.contains("/api/hello%20world"));
    }

    // BUG-035: Path segment normalization tests

    #[test]
    fn test_normalize_binding_dot_segment() {
        // BUG-035: Single dot should be removed
        assert_eq!(
            ash_normalize_binding("GET", "/api/./users", "").unwrap(),
            "GET|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_double_dot_segment() {
        // BUG-035: Double dot should go up one level
        assert_eq!(
            ash_normalize_binding("GET", "/api/v1/../users", "").unwrap(),
            "GET|/api/users|"
        );
    }

    #[test]
    fn test_normalize_binding_multiple_dots() {
        // BUG-035: Multiple dot segments
        assert_eq!(
            ash_normalize_binding("GET", "/api/v1/./users/../admin", "").unwrap(),
            "GET|/api/v1/admin|"
        );
    }

    #[test]
    fn test_normalize_binding_dots_at_root() {
        // BUG-035: Can't go above root
        assert_eq!(
            ash_normalize_binding("GET", "/../api", "").unwrap(),
            "GET|/api|"
        );
    }

    #[test]
    fn test_normalize_binding_only_dots() {
        // BUG-035: Path with only dots should become root
        assert_eq!(
            ash_normalize_binding("GET", "/./.", "").unwrap(),
            "GET|/|"
        );
    }

    // BUG-042: ASCII method validation tests

    #[test]
    fn test_normalize_binding_rejects_unicode_method() {
        // BUG-042: Non-ASCII method should be rejected
        let result = ash_normalize_binding("GËṪ", "/api", "");
        assert!(result.is_err());
        assert!(result.unwrap_err().message().contains("ASCII"));
    }

    #[test]
    fn test_normalize_binding_ascii_method_uppercased() {
        // BUG-042: ASCII method should be uppercased consistently
        assert_eq!(
            ash_normalize_binding("get", "/api", "").unwrap(),
            "GET|/api|"
        );
        assert_eq!(
            ash_normalize_binding("Post", "/api", "").unwrap(),
            "POST|/api|"
        );
    }

    // BUG-043: Whitespace query string tests

    #[test]
    fn test_normalize_binding_whitespace_only_query() {
        // BUG-043: Whitespace-only query should be treated as empty
        assert_eq!(
            ash_normalize_binding("GET", "/api", "   ").unwrap(),
            "GET|/api|"
        );
        assert_eq!(
            ash_normalize_binding("GET", "/api", "\t\n").unwrap(),
            "GET|/api|"
        );
    }

    #[test]
    fn test_normalize_binding_query_with_leading_trailing_whitespace() {
        // BUG-043: Query should be trimmed before processing
        assert_eq!(
            ash_normalize_binding("GET", "/api", "  a=1  ").unwrap(),
            "GET|/api|a=1"
        );
    }
}