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
//! High-level request proof building (Phase 3-B).
//!
//! `build_request_proof()` orchestrates existing Core primitives in a
//! fixed execution order. No new logic — only assembly.
//!
//! ## Why This Exists
//!
//! Before this function, every client SDK reimplemented the same multi-step
//! pipeline: normalize binding → hash body → derive client secret →
//! build proof → assemble headers. Each reimplementation introduced
//! divergence (different validation ordering, different normalization paths).
//!
//! Now the client SDK reduces to:
//! ```text
//! canonical_body = canonicalize(body, content_type)
//! result = build_request_proof(input)
//! set_header("x-ash-ts", result.timestamp)
//! set_header("x-ash-nonce", result.nonce)
//! set_header("x-ash-body-hash", result.body_hash)
//! set_header("x-ash-proof", result.proof)
//! ```
//!
//! ## Execution Order (Locked)
//!
//! The following order is fixed and must not change:
//!
//! 1. Validate nonce format
//! 2. Validate timestamp format
//! 3. Normalize binding (method + path + query)
//! 4. Hash canonical body
//! 5. Derive client secret (nonce + context_id + binding)
//! 6. Build proof (client_secret + timestamp + binding + body_hash)
//! 7. Return assembled result

use crate::errors::AshError;
use crate::proof::{
    ash_build_proof, ash_build_proof_scoped, ash_build_proof_unified, ash_derive_client_secret,
    ash_hash_body, ash_validate_timestamp_format,
};
use crate::validate::ash_validate_nonce;

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

/// Input for high-level request proof building.
///
/// The client SDK is responsible for:
/// - Obtaining `nonce` and `context_id` from the server
/// - Canonicalizing the body (based on content type)
/// - Generating a current timestamp
///
/// The builder handles everything else: nonce validation, timestamp
/// validation, binding normalization, body hashing, secret derivation,
/// and proof computation.
#[derive(Debug)]
pub struct BuildRequestInput<'a> {
    /// 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 context response)
    pub nonce: &'a str,

    /// Context ID (from context response)
    pub context_id: &'a str,

    /// Unix timestamp as string (caller generates current time)
    pub timestamp: &'a str,

    /// Optional: scope fields for scoped proof (e.g., &["amount", "recipient"])
    pub scope: Option<&'a [&'a str]>,

    /// Optional: previous proof hex for request chaining
    pub previous_proof: Option<&'a str>,
}

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

/// Result of high-level request proof building.
///
/// Contains all values the client needs to set as HTTP headers.
#[derive(Debug)]
pub struct BuildRequestResult {
    /// The cryptographic proof (64-char lowercase hex)
    pub proof: String,

    /// The body hash (64-char lowercase hex)
    pub body_hash: String,

    /// The normalized binding string (METHOD|PATH|CANONICAL_QUERY)
    pub binding: String,

    /// The timestamp used (echoed back for header)
    pub timestamp: String,

    /// The nonce used (echoed back for header)
    pub nonce: String,

    /// Scope hash (empty string if no scoping)
    pub scope_hash: String,

    /// Chain hash (empty string if no chaining)
    pub chain_hash: String,

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

/// Non-normative debug metadata. Must not contain secrets.
#[derive(Debug)]
pub struct BuildMeta {
    /// The canonical query string that was computed
    pub canonical_query: String,
}

// ── Build Function ───────────────────────────────────────────────────

/// Build an HTTP request proof using ASH protocol.
///
/// Orchestrates all Core primitives in a fixed execution order.
/// Returns the first error encountered (no error accumulation).
///
/// # Execution Order (locked)
///
/// 1. Validate nonce format (length, hex charset)
/// 2. Validate timestamp format (digits, no leading zeros, within bounds)
/// 3. Normalize binding (METHOD|PATH|CANONICAL_QUERY)
/// 4. Hash canonical body → body_hash
/// 5. Derive client secret (nonce + context_id + binding)
/// 6. Build proof (client_secret + timestamp + binding + body_hash)
/// 7. Return result with all header values
///
/// # Proof Modes
///
/// - **Basic**: `scope` is None, `previous_proof` is None → standard proof
/// - **Scoped**: `scope` is Some → scoped proof with scope_hash
/// - **Unified**: `scope` is Some and/or `previous_proof` is Some → unified proof
///
/// # Example
///
/// ```rust
/// use ash_core::build::{build_request_proof, BuildRequestInput};
///
/// let input = BuildRequestInput {
///     method: "POST",
///     path: "/api/transfer",
///     raw_query: "",
///     canonical_body: r#"{"amount":100,"recipient":"alice"}"#,
///     nonce: "0123456789abcdef0123456789abcdef",
///     context_id: "ctx_abc123",
///     timestamp: "1700000000",
///     scope: None,
///     previous_proof: None,
/// };
///
/// let result = build_request_proof(&input).unwrap();
/// assert_eq!(result.body_hash.len(), 64);
/// assert_eq!(result.proof.len(), 64);
/// assert_eq!(result.binding, "POST|/api/transfer|");
/// ```
pub fn build_request_proof(input: &BuildRequestInput<'_>) -> Result<BuildRequestResult, AshError> {
    // ── Step 1: Validate nonce format ─────────────────────────────────
    ash_validate_nonce(input.nonce)?;

    // ── Step 2: Validate timestamp format ─────────────────────────────
    ash_validate_timestamp_format(input.timestamp)?;

    // ── Step 3: Normalize binding ─────────────────────────────────────
    let binding =
        crate::ash_normalize_binding(input.method, input.path, input.raw_query)?;

    // ── Step 4: Hash canonical body ───────────────────────────────────
    let body_hash = ash_hash_body(input.canonical_body);

    // ── Step 5: Derive client secret ──────────────────────────────────
    let client_secret = ash_derive_client_secret(input.nonce, input.context_id, &binding)?;

    // ── Step 6: Build proof ───────────────────────────────────────────
    let (proof, scope_hash, chain_hash) = match (input.scope, input.previous_proof) {
        // Unified: scope and/or chain
        (Some(scope), Some(prev)) => {
            let r = ash_build_proof_unified(
                &client_secret,
                input.timestamp,
                &binding,
                input.canonical_body,
                scope,
                Some(prev),
            )?;
            (r.proof, r.scope_hash, r.chain_hash)
        }
        // Unified with chain only (no scope)
        (None, Some(prev)) => {
            let r = ash_build_proof_unified(
                &client_secret,
                input.timestamp,
                &binding,
                input.canonical_body,
                &[],
                Some(prev),
            )?;
            (r.proof, r.scope_hash, r.chain_hash)
        }
        // Scoped only (no chain)
        (Some(scope), None) if !scope.is_empty() => {
            let (proof, scope_hash) = ash_build_proof_scoped(
                &client_secret,
                input.timestamp,
                &binding,
                input.canonical_body,
                scope,
            )?;
            (proof, scope_hash, String::new())
        }
        // Basic proof (no scope, no chain)
        _ => {
            let proof = ash_build_proof(&client_secret, input.timestamp, &binding, &body_hash)?;
            (proof, String::new(), String::new())
        }
    };

    // ── Step 7: Assemble result ───────────────────────────────────────
    let canonical_query = if binding.contains('|') {
        // Extract query part from binding (METHOD|PATH|QUERY)
        binding.rsplitn(2, '|').next().unwrap_or("").to_string()
    } else {
        String::new()
    };

    let meta = if cfg!(debug_assertions) {
        Some(BuildMeta { canonical_query })
    } else {
        None
    };

    Ok(BuildRequestResult {
        proof,
        body_hash,
        binding,
        timestamp: input.timestamp.to_string(),
        nonce: input.nonce.to_string(),
        scope_hash,
        chain_hash,
        meta,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::{AshErrorCode, InternalReason};

    #[test]
    fn test_basic_build_succeeds() {
        let input = BuildRequestInput {
            method: "POST",
            path: "/api/transfer",
            raw_query: "",
            canonical_body: r#"{"amount":100}"#,
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test123",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        };

        let result = build_request_proof(&input).unwrap();
        assert_eq!(result.proof.len(), 64);
        assert_eq!(result.body_hash.len(), 64);
        assert_eq!(result.binding, "POST|/api/transfer|");
        assert_eq!(result.timestamp, "1700000000");
        assert_eq!(result.nonce, "0123456789abcdef0123456789abcdef");
        assert!(result.scope_hash.is_empty());
        assert!(result.chain_hash.is_empty());
    }

    #[test]
    fn test_build_normalizes_method() {
        let input = BuildRequestInput {
            method: "post",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        };

        let result = build_request_proof(&input).unwrap();
        assert!(result.binding.starts_with("POST|"));
    }

    #[test]
    fn test_build_normalizes_path() {
        let input = BuildRequestInput {
            method: "GET",
            path: "/api//users/",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        };

        let result = build_request_proof(&input).unwrap();
        assert_eq!(result.binding, "GET|/api/users|");
    }

    #[test]
    fn test_build_canonicalizes_query() {
        let input = BuildRequestInput {
            method: "GET",
            path: "/api/search",
            raw_query: "z=3&a=1",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        };

        let result = build_request_proof(&input).unwrap();
        assert_eq!(result.binding, "GET|/api/search|a=1&z=3");
    }

    #[test]
    fn test_build_bad_nonce_fails_first() {
        let input = BuildRequestInput {
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "short",
            context_id: "ctx_test",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        };

        let err = build_request_proof(&input).unwrap_err();
        assert_eq!(err.code(), AshErrorCode::ValidationError);
        assert_eq!(err.reason(), InternalReason::NonceTooShort);
    }

    #[test]
    fn test_build_bad_timestamp_fails_second() {
        let input = BuildRequestInput {
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            timestamp: "not_a_number",
            scope: None,
            previous_proof: None,
        };

        let err = build_request_proof(&input).unwrap_err();
        assert_eq!(err.code(), AshErrorCode::TimestampInvalid);
    }

    #[test]
    fn test_build_bad_path_fails() {
        let input = BuildRequestInput {
            method: "POST",
            path: "no_leading_slash",
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        };

        let err = build_request_proof(&input).unwrap_err();
        assert_eq!(err.code(), AshErrorCode::ValidationError);
    }

    #[test]
    fn test_build_verify_roundtrip() {
        // Build a proof, then verify it matches what verify_incoming_request expects
        let nonce = "0123456789abcdef0123456789abcdef";
        let context_id = "ctx_roundtrip";
        let canonical_body = r#"{"amount":100}"#;
        let timestamp = "1700000000";

        let build_result = build_request_proof(&BuildRequestInput {
            method: "POST",
            path: "/api/transfer",
            raw_query: "sort=name",
            canonical_body,
            nonce,
            context_id,
            timestamp,
            scope: None,
            previous_proof: None,
        })
        .unwrap();

        // Re-derive and verify manually using low-level primitives
        let client_secret =
            ash_derive_client_secret(nonce, context_id, &build_result.binding).unwrap();
        let expected_proof =
            ash_build_proof(&client_secret, timestamp, &build_result.binding, &build_result.body_hash)
                .unwrap();

        assert_eq!(build_result.proof, expected_proof);
    }

    #[test]
    fn test_build_scoped_proof() {
        let input = BuildRequestInput {
            method: "POST",
            path: "/api/transfer",
            raw_query: "",
            canonical_body: r#"{"amount":100,"recipient":"alice"}"#,
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_scoped",
            timestamp: "1700000000",
            scope: Some(&["amount", "recipient"]),
            previous_proof: None,
        };

        let result = build_request_proof(&input).unwrap();
        assert_eq!(result.proof.len(), 64);
        assert!(!result.scope_hash.is_empty());
        assert!(result.chain_hash.is_empty());
    }

    #[test]
    fn test_build_chained_proof() {
        // First build a basic proof
        let first = build_request_proof(&BuildRequestInput {
            method: "POST",
            path: "/api/step1",
            raw_query: "",
            canonical_body: r#"{"step":1}"#,
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_chain",
            timestamp: "1700000000",
            scope: None,
            previous_proof: None,
        })
        .unwrap();

        // Then build a chained proof
        let second = build_request_proof(&BuildRequestInput {
            method: "POST",
            path: "/api/step2",
            raw_query: "",
            canonical_body: r#"{"step":2}"#,
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_chain",
            timestamp: "1700000001",
            scope: None,
            previous_proof: Some(&first.proof),
        })
        .unwrap();

        assert_eq!(second.proof.len(), 64);
        assert!(!second.chain_hash.is_empty());
        // Chain hash should be SHA-256 of previous proof
        assert_eq!(second.chain_hash.len(), 64);
    }

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

    #[test]
    fn precedence_bad_nonce_before_bad_timestamp() {
        let input = BuildRequestInput {
            method: "POST",
            path: "/api/test",
            raw_query: "",
            canonical_body: "{}",
            nonce: "short",           // bad nonce
            context_id: "ctx_test",
            timestamp: "not_a_number", // bad timestamp
            scope: None,
            previous_proof: None,
        };

        let err = build_request_proof(&input).unwrap_err();
        // Nonce validation happens before timestamp (step 1 vs step 2)
        assert_eq!(err.reason(), InternalReason::NonceTooShort);
    }

    #[test]
    fn precedence_bad_timestamp_before_bad_path() {
        let input = BuildRequestInput {
            method: "POST",
            path: "no_slash",           // bad path
            raw_query: "",
            canonical_body: "{}",
            nonce: "0123456789abcdef0123456789abcdef",
            context_id: "ctx_test",
            timestamp: "not_a_number",  // bad timestamp
            scope: None,
            previous_proof: None,
        };

        let err = build_request_proof(&input).unwrap_err();
        // Timestamp validation happens before binding (step 2 vs step 3)
        assert_eq!(err.code(), AshErrorCode::TimestampInvalid);
    }
}