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
//! High-level request verification (Phase 3-A).
//!
//! `verify_incoming_request()` orchestrates existing Core primitives in a
//! fixed execution order. No new logic — only assembly.
//!
//! ## Why This Exists
//!
//! Before this function, every middleware reimplemented the same multi-step
//! pipeline: extract headers → validate timestamp → normalize binding →
//! hash body → compare → verify proof. Each reimplementation introduced
//! divergence (different error ordering, different validation sequencing).
//!
//! Now the middleware reduces to:
//! ```text
//! context = store.lookup(context_id)
//! canonical_body = canonicalize(body, content_type)
//! result = verify_incoming_request(input)
//! if result.ok { proceed } else { return result.error.http_status }
//! ```
//!
//! ## Execution Order (Locked)
//!
//! The following order is fixed and must not change. It determines which
//! error is returned when multiple inputs are invalid.
//!
//! 1. Extract headers (ts, body-hash, proof from `HeaderMapView`)
//! 2. Validate timestamp format
//! 3. Validate timestamp freshness (skew)
//! 4. Validate nonce format
//! 5. Normalize binding (method + path + query)
//! 6. Hash canonical body
//! 7. Compare computed body hash with header body hash
//! 8. Verify proof (re-derives secret, HMAC comparison)
//! 9. Return ok

use crate::compare::ash_timing_safe_equal;
use crate::errors::{AshError, AshErrorCode, InternalReason};
use crate::headers::{HeaderMapView, HDR_BODY_HASH, HDR_PROOF, HDR_TIMESTAMP};
use crate::proof::{ash_build_proof, ash_derive_client_secret, ash_validate_timestamp_format};
use crate::validate::ash_validate_nonce;

// ── Input ─────────────────────────────────────────────────────────────

/// Input for high-level request verification.
///
/// The middleware is responsible for:
/// - Looking up the context in the store → providing `nonce` and `context_id`
/// - Reading the body and canonicalizing it (based on content type)
/// - Providing the raw HTTP headers via `HeaderMapView`
///
/// The verifier handles everything else: header extraction, validation,
/// binding normalization, body hash comparison, and proof verification.
pub struct VerifyRequestInput<'a, H: HeaderMapView> {
    /// HTTP headers (implements `HeaderMapView` for case-insensitive lookup)
    pub headers: &'a H,

    /// HTTP method (e.g., "POST", "GET")
    pub method: &'a str,

    /// URL path without query string (e.g., "/api/transfer")
    pub path: &'a str,

    /// Raw query string without leading `?` (e.g., "page=1&sort=name")
    pub raw_query: &'a str,

    /// Canonicalized body string (caller canonicalizes based on content type)
    pub canonical_body: &'a str,

    /// Server nonce (from store lookup, not from headers)
    pub nonce: &'a str,

    /// Context ID (from store lookup or header extraction)
    pub context_id: &'a str,

    /// Maximum allowed timestamp age in seconds (e.g., 300 = 5 minutes)
    pub max_age_seconds: u64,

    /// Clock skew tolerance in seconds (e.g., 60)
    pub clock_skew_seconds: u64,
}

// ── Output ────────────────────────────────────────────────────────────

/// Result of high-level request verification.
pub struct VerifyResult {
    /// Whether the request passed all checks
    pub ok: bool,

    /// The error if verification failed (None if ok)
    pub error: Option<AshError>,

    /// Debug metadata (only populated in debug builds)
    pub meta: Option<VerifyMeta>,
}

/// Non-normative debug metadata. Must not contain secrets.
pub struct VerifyMeta {
    /// The canonical query string that was computed
    pub canonical_query: String,

    /// The body hash that was computed from the canonical body
    pub computed_body_hash: String,

    /// The binding string that was assembled
    pub binding: String,
}

impl VerifyResult {
    fn fail(error: AshError) -> Self {
        Self {
            ok: false,
            error: Some(error),
            meta: None,
        }
    }

    fn success(meta: Option<VerifyMeta>) -> Self {
        Self {
            ok: true,
            error: None,
            meta,
        }
    }
}

// ── Verification Function ─────────────────────────────────────────────

/// Verify an incoming HTTP request using ASH protocol.
///
/// Orchestrates all Core primitives in a fixed execution order.
/// Returns the first error encountered (no error accumulation).
///
/// # Execution Order (locked)
///
/// 1. Extract `x-ash-ts`, `x-ash-body-hash`, `x-ash-proof` from headers
/// 2. Validate timestamp format (digits, no leading zeros, within bounds)
/// 3. Validate timestamp freshness (not expired, not future)
/// 4. Validate nonce format (length, hex charset)
/// 5. Normalize binding (METHOD|PATH|CANONICAL_QUERY)
/// 6. Hash canonical body → computed_body_hash
/// 7. Compare computed_body_hash with header body hash (timing-safe)
/// 8. Verify proof (re-derive secret, build expected proof, compare)
/// 9. Return ok
///
/// # Example
///
/// ```rust
/// use ash_core::headers::HeaderMapView;
/// use ash_core::verify::{verify_incoming_request, VerifyRequestInput};
///
/// struct MyHeaders(Vec<(String, String)>);
/// impl HeaderMapView for MyHeaders {
///     fn get_all_ci(&self, name: &str) -> Vec<&str> {
///         let n = name.to_ascii_lowercase();
///         self.0.iter()
///             .filter(|(k, _)| k.to_ascii_lowercase() == n)
///             .map(|(_, v)| v.as_str())
///             .collect()
///     }
/// }
///
/// // In a real middleware, these come from the request + store
/// let headers = MyHeaders(vec![
///     ("x-ash-ts".into(), "1700000000".into()),
///     ("x-ash-body-hash".into(), "some_hash".into()),
///     ("x-ash-proof".into(), "some_proof".into()),
/// ]);
///
/// let input = VerifyRequestInput {
///     headers: &headers,
///     method: "POST",
///     path: "/api/transfer",
///     raw_query: "",
///     canonical_body: "{}",
///     nonce: "0123456789abcdef0123456789abcdef",
///     context_id: "ctx_abc123",
///     max_age_seconds: 300,
///     clock_skew_seconds: 60,
/// };
///
/// let result = verify_incoming_request(&input);
/// // result.ok will be false because the proof won't match,
/// // but the pipeline executes correctly
/// ```
pub fn verify_incoming_request<H: HeaderMapView>(input: &VerifyRequestInput<'_, H>) -> VerifyResult {
    // ── Step 1: Extract required headers ──────────────────────────────
    let ts = match extract_single_header(input.headers, HDR_TIMESTAMP) {
        Ok(v) => v,
        Err(e) => return VerifyResult::fail(e),
    };

    let header_body_hash = match extract_single_header(input.headers, HDR_BODY_HASH) {
        Ok(v) => v,
        Err(e) => return VerifyResult::fail(e),
    };

    let proof = match extract_single_header(input.headers, HDR_PROOF) {
        Ok(v) => v,
        Err(e) => return VerifyResult::fail(e),
    };

    // ── Step 2: Validate timestamp format ─────────────────────────────
    if let Err(e) = ash_validate_timestamp_format(&ts) {
        return VerifyResult::fail(e);
    }

    // ── Step 3: Validate timestamp freshness ──────────────────────────
    if let Err(e) = validate_timestamp_with_reference(
        &ts,
        input.max_age_seconds,
        input.clock_skew_seconds,
    ) {
        return VerifyResult::fail(e);
    }

    // ── Step 4: Validate nonce format ─────────────────────────────────
    if let Err(e) = ash_validate_nonce(input.nonce) {
        return VerifyResult::fail(e);
    }

    // ── Step 5: Normalize binding ─────────────────────────────────────
    let binding = match crate::ash_normalize_binding(input.method, input.path, input.raw_query) {
        Ok(b) => b,
        Err(e) => return VerifyResult::fail(e),
    };

    // ── Step 6: Hash canonical body ───────────────────────────────────
    let computed_body_hash = crate::proof::ash_hash_body(input.canonical_body);

    // ── Step 7: Compare body hashes (timing-safe) ─────────────────────
    if !ash_timing_safe_equal(computed_body_hash.as_bytes(), header_body_hash.as_bytes()) {
        return VerifyResult::fail(AshError::with_reason(
            AshErrorCode::ValidationError,
            InternalReason::General,
            "Body hash mismatch",
        ));
    }

    // ── Step 8: Verify proof ──────────────────────────────────────────
    let client_secret = match ash_derive_client_secret(input.nonce, input.context_id, &binding) {
        Ok(s) => s,
        Err(e) => return VerifyResult::fail(e),
    };

    let expected_proof = match ash_build_proof(&client_secret, &ts, &binding, &computed_body_hash) {
        Ok(p) => p,
        Err(e) => return VerifyResult::fail(e),
    };

    if !ash_timing_safe_equal(expected_proof.as_bytes(), proof.as_bytes()) {
        return VerifyResult::fail(AshError::new(
            AshErrorCode::ProofInvalid,
            "Proof verification failed",
        ));
    }

    // ── Step 9: Success ───────────────────────────────────────────────
    let meta = if cfg!(debug_assertions) {
        Some(VerifyMeta {
            canonical_query: input.raw_query.to_string(),
            computed_body_hash,
            binding,
        })
    } else {
        None
    };

    VerifyResult::success(meta)
}

// ── Internal Helpers ──────────────────────────────────────────────────

/// Extract a single header value with validation.
/// Reuses the same logic as `ash_extract_headers` but for individual headers.
fn extract_single_header(h: &impl HeaderMapView, name: &'static str) -> Result<String, AshError> {
    let vals = h.get_all_ci(name);

    if vals.is_empty() {
        return Err(
            AshError::with_reason(
                AshErrorCode::ValidationError,
                InternalReason::HdrMissing,
                format!("Required header '{}' is missing", name),
            )
            .with_detail("header", name),
        );
    }
    if vals.len() > 1 {
        return Err(
            AshError::with_reason(
                AshErrorCode::ValidationError,
                InternalReason::HdrMultiValue,
                format!("Header '{}' must have exactly one value, got {}", name, vals.len()),
            )
            .with_detail("header", name)
            .with_detail("count", vals.len().to_string()),
        );
    }

    let v = vals[0].trim();
    if v.chars().any(|c| c == '\r' || c == '\n' || c.is_control()) {
        return Err(
            AshError::with_reason(
                AshErrorCode::ValidationError,
                InternalReason::HdrInvalidChars,
                format!("Header '{}' contains invalid characters", name),
            )
            .with_detail("header", name),
        );
    }

    Ok(v.to_string())
}

/// Validate timestamp freshness using system clock.
/// Wraps `ash_validate_timestamp` which uses `SystemTime::now()` internally.
fn validate_timestamp_with_reference(
    timestamp: &str,
    max_age_seconds: u64,
    clock_skew_seconds: u64,
) -> Result<(), AshError> {
    crate::proof::ash_validate_timestamp(timestamp, max_age_seconds, clock_skew_seconds)
}

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

    struct TestHeaders(Vec<(String, String)>);

    impl HeaderMapView for TestHeaders {
        fn get_all_ci(&self, name: &str) -> Vec<&str> {
            let n = name.to_ascii_lowercase();
            self.0
                .iter()
                .filter(|(k, _)| k.to_ascii_lowercase() == n)
                .map(|(_, v)| v.as_str())
                .collect()
        }
    }

    fn now_ts() -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            .to_string()
    }

    fn make_valid_request() -> (TestHeaders, String, String) {
        let nonce = "0123456789abcdef0123456789abcdef";
        let context_id = "ctx_test123";
        let binding = "POST|/api/transfer|";
        let timestamp = now_ts();
        let canonical_body = r#"{"amount":100}"#;
        let body_hash = crate::proof::ash_hash_body(canonical_body);

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

        let headers = TestHeaders(vec![
            ("x-ash-ts".into(), timestamp),
            ("x-ash-body-hash".into(), body_hash),
            ("x-ash-proof".into(), proof),
        ]);

        (headers, canonical_body.to_string(), nonce.to_string())
    }

    #[test]
    fn test_valid_request_passes() {
        let (headers, canonical_body, nonce) = make_valid_request();

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/transfer",
            raw_query: "",
            canonical_body: &canonical_body,
            nonce: &nonce,
            context_id: "ctx_test123",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(result.ok, "Expected ok, got error: {:?}", result.error);
    }

    #[test]
    fn test_missing_timestamp_fails() {
        let headers = TestHeaders(vec![
            ("x-ash-body-hash".into(), "a".repeat(64)),
            ("x-ash-proof".into(), "b".repeat(64)),
        ]);

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        let err = result.error.unwrap();
        assert_eq!(err.code(), AshErrorCode::ValidationError);
        assert_eq!(err.reason(), InternalReason::HdrMissing);
    }

    #[test]
    fn test_invalid_timestamp_format_fails() {
        let headers = TestHeaders(vec![
            ("x-ash-ts".into(), "not_a_number".into()),
            ("x-ash-body-hash".into(), "a".repeat(64)),
            ("x-ash-proof".into(), "b".repeat(64)),
        ]);

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        assert_eq!(result.error.unwrap().code(), AshErrorCode::TimestampInvalid);
    }

    #[test]
    fn test_expired_timestamp_fails() {
        let headers = TestHeaders(vec![
            ("x-ash-ts".into(), "1000000000".into()), // 2001, way expired
            ("x-ash-body-hash".into(), "a".repeat(64)),
            ("x-ash-proof".into(), "b".repeat(64)),
        ]);

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        assert_eq!(result.error.unwrap().code(), AshErrorCode::TimestampInvalid);
    }

    #[test]
    fn test_body_hash_mismatch_fails() {
        let (mut headers, _canonical_body, nonce) = make_valid_request();
        // Tamper with body-hash header
        for (k, v) in &mut headers.0 {
            if k.to_ascii_lowercase() == "x-ash-body-hash" {
                *v = "f".repeat(64); // wrong hash
            }
        }

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/transfer",
            raw_query: "",
            canonical_body: r#"{"amount":100}"#,
            nonce: &nonce,
            context_id: "ctx_test123",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        let err = result.error.unwrap();
        assert_eq!(err.code(), AshErrorCode::ValidationError);
        assert!(err.message().contains("Body hash"));
    }

    #[test]
    fn test_wrong_proof_fails() {
        let (mut headers, canonical_body, nonce) = make_valid_request();
        // Tamper with proof header
        for (k, v) in &mut headers.0 {
            if k.to_ascii_lowercase() == "x-ash-proof" {
                *v = "f".repeat(64); // wrong proof
            }
        }

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/transfer",
            raw_query: "",
            canonical_body: &canonical_body,
            nonce: &nonce,
            context_id: "ctx_test123",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        assert_eq!(result.error.unwrap().code(), AshErrorCode::ProofInvalid);
    }

    #[test]
    fn test_tampered_body_fails() {
        let (headers, _canonical_body, nonce) = make_valid_request();

        // Original body was {"amount":100}, send different body
        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/transfer",
            raw_query: "",
            canonical_body: r#"{"amount":999}"#, // tampered
            nonce: &nonce,
            context_id: "ctx_test123",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        // Should fail at body hash comparison (step 7)
        let err = result.error.unwrap();
        assert_eq!(err.code(), AshErrorCode::ValidationError);
    }

    // ── Precedence tests ──────────────────────────────────────────────

    #[test]
    fn precedence_missing_ts_before_body_hash_mismatch() {
        // Missing timestamp AND wrong body hash → timestamp error first
        let headers = TestHeaders(vec![
            // no x-ash-ts
            ("x-ash-body-hash".into(), "wrong".repeat(10)),
            ("x-ash-proof".into(), "b".repeat(64)),
        ]);

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        assert_eq!(result.error.unwrap().reason(), InternalReason::HdrMissing);
    }

    #[test]
    fn precedence_bad_ts_format_before_bad_nonce() {
        // Bad timestamp format AND bad nonce → timestamp error first
        let headers = TestHeaders(vec![
            ("x-ash-ts".into(), "not_number".into()),
            ("x-ash-body-hash".into(), "a".repeat(64)),
            ("x-ash-proof".into(), "b".repeat(64)),
        ]);

        let input = VerifyRequestInput {
            headers: &headers,
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "short", // bad nonce
            context_id: "ctx_test",
            max_age_seconds: 300,
            clock_skew_seconds: 60,
        };

        let result = verify_incoming_request(&input);
        assert!(!result.ok);
        assert_eq!(result.error.unwrap().code(), AshErrorCode::TimestampInvalid);
    }
}