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
//! Documentation Examples Tests for ASH Rust SDK
//!
//! Tests that all code examples in documentation actually work.

use ash_core::{
    ash_build_proof, ash_verify_proof, ash_derive_client_secret,
    ash_canonicalize_json, ash_canonicalize_query, ash_canonicalize_urlencoded,
    ash_hash_body, ash_normalize_binding,
    ash_build_proof_scoped, ash_verify_proof_scoped,
    ash_build_proof_unified, ash_verify_proof_unified,
    ash_generate_nonce, ash_generate_context_id,
    ash_validate_timestamp, ash_timing_safe_equal,
};

// =========================================================================
// README QUICK START EXAMPLES
// =========================================================================

mod quick_start {
    use super::*;

    #[test]
    fn test_quick_start_example() {
        // Generate a cryptographic nonce
        let nonce = ash_generate_nonce(32).unwrap();
        assert_eq!(nonce.len(), 64);

        // Generate a context ID
        let context_id = ash_generate_context_id().unwrap();
        assert!(context_id.starts_with("ash_"));

        // Define the request binding
        let binding = ash_normalize_binding("POST", "/api/users", "").unwrap();
        assert_eq!(binding, "POST|/api/users|");

        // Derive the client secret
        let secret = ash_derive_client_secret(&nonce, &context_id, &binding).unwrap();
        assert_eq!(secret.len(), 64);

        // Hash the request body
        let body = r#"{"name":"John"}"#;
        let body_hash = ash_hash_body(body);
        assert_eq!(body_hash.len(), 64);

        // Build the proof
        let timestamp = chrono::Utc::now().timestamp().to_string();
        let proof = ash_build_proof(&secret, &timestamp, &binding, &body_hash).unwrap();
        assert_eq!(proof.len(), 64);

        // Verify the proof (server-side)
        let valid = ash_verify_proof(&nonce, &context_id, &binding, &timestamp, &body_hash, &proof).unwrap();
        assert!(valid);
    }
}

// =========================================================================
// BASIC USAGE EXAMPLES
// =========================================================================

mod basic_usage {
    use super::*;

    #[test]
    fn test_json_canonicalization_example() {
        // Canonicalize JSON (RFC 8785 compliant)
        let json = r#"{"z":1,"a":2,"nested":{"b":3,"a":4}}"#;
        let canonical = ash_canonicalize_json(json).unwrap();

        // Keys are sorted alphabetically
        assert_eq!(canonical, r#"{"a":2,"nested":{"a":4,"b":3},"z":1}"#);
    }

    #[test]
    fn test_query_string_canonicalization_example() {
        // Canonicalize query string
        let query = "z=3&a=1&b=2";
        let canonical = ash_canonicalize_query(query).unwrap();

        // Parameters are sorted by key
        assert_eq!(canonical, "a=1&b=2&z=3");
    }

    #[test]
    fn test_binding_normalization_example() {
        // Normalize request binding
        let binding = ash_normalize_binding("post", "/api/users/", "page=1&limit=10").unwrap();

        // Method is uppercased, trailing slash removed, query sorted
        assert!(binding.starts_with("POST|"));
        assert!(binding.contains("/api/users|"));
    }

    #[test]
    fn test_body_hashing_example() {
        // Hash request body
        let body = r#"{"user":"john","action":"login"}"#;
        let hash = ash_hash_body(body);

        // SHA-256 hash, 64 hex characters
        assert_eq!(hash.len(), 64);
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
    }
}

// =========================================================================
// PROOF LIFECYCLE EXAMPLE
// =========================================================================

mod proof_lifecycle {
    use super::*;

    #[test]
    fn test_full_proof_lifecycle_example() {
        // === CLIENT SIDE ===

        // 1. Generate nonce (should be done by server and sent to client)
        let nonce = ash_generate_nonce(32).unwrap();

        // 2. Generate context ID (unique per request context)
        let context_id = ash_generate_context_id().unwrap();

        // 3. Define the request
        let method = "POST";
        let path = "/api/transfer";
        let query = "confirm=true";
        let body = r#"{"from":"acc1","to":"acc2","amount":100}"#;

        // 4. Create binding
        let binding = ash_normalize_binding(method, path, query).unwrap();

        // 5. Derive client secret
        let secret = ash_derive_client_secret(&nonce, &context_id, &binding).unwrap();

        // 6. Hash body
        let body_hash = ash_hash_body(body);

        // 7. Get current timestamp
        let timestamp = chrono::Utc::now().timestamp().to_string();

        // 8. Build proof
        let proof = ash_build_proof(&secret, &timestamp, &binding, &body_hash).unwrap();

        // === SERVER SIDE ===

        // 1. Receive request with proof, timestamp, context_id headers
        // 2. Look up nonce by context_id from store

        // 3. Validate timestamp freshness
        let ts_valid = ash_validate_timestamp(&timestamp, 300, 60);
        assert!(ts_valid.is_ok());

        // 4. Reconstruct binding from request
        let server_binding = ash_normalize_binding(method, path, query).unwrap();

        // 5. Hash received body
        let server_body_hash = ash_hash_body(body);

        // 6. Verify proof
        let valid = ash_verify_proof(&nonce, &context_id, &server_binding, &timestamp, &server_body_hash, &proof).unwrap();
        assert!(valid);

        // 7. Mark context as consumed (single-use)
        // store.consume(context_id)
    }
}

// =========================================================================
// SCOPED PROOFS EXAMPLE
// =========================================================================

mod scoped_proofs {
    use super::*;

    #[test]
    fn test_scoped_proof_example() {
        // Scoped proofs protect only specified fields
        let nonce = ash_generate_nonce(32).unwrap();
        let context_id = ash_generate_context_id().unwrap();
        let binding = ash_normalize_binding("POST", "/api/payment", "").unwrap();

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

        // Full payload
        let payload = r#"{"amount":100,"currency":"USD","memo":"Payment for order #123"}"#;

        // Only protect amount and currency (memo can change)
        let scope = vec!["amount", "currency"];

        let timestamp = chrono::Utc::now().timestamp().to_string();

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

        // Verify with original payload
        let valid = ash_verify_proof_scoped(&nonce, &context_id, &binding, &timestamp, payload, &scope, &scope_hash, &proof).unwrap();
        assert!(valid);

        // Verify with modified memo (should still pass)
        let modified_payload = r#"{"amount":100,"currency":"USD","memo":"Updated memo"}"#;
        let valid_modified = ash_verify_proof_scoped(&nonce, &context_id, &binding, &timestamp, modified_payload, &scope, &scope_hash, &proof).unwrap();
        assert!(valid_modified, "Modified non-scoped field should verify");

        // Verify with modified amount (should fail)
        let tampered_payload = r#"{"amount":10000,"currency":"USD","memo":"Payment for order #123"}"#;
        let invalid = ash_verify_proof_scoped(&nonce, &context_id, &binding, &timestamp, tampered_payload, &scope, &scope_hash, &proof).unwrap();
        assert!(!invalid, "Modified scoped field should fail");
    }
}

// =========================================================================
// CHAINED PROOFS EXAMPLE
// =========================================================================

mod chained_proofs {
    use super::*;

    #[test]
    fn test_chained_proof_example() {
        // Chained proofs link multiple requests together
        let nonce = ash_generate_nonce(32).unwrap();
        let context_id = ash_generate_context_id().unwrap();
        let timestamp = chrono::Utc::now().timestamp().to_string();

        // Step 1: Initiate transfer
        let binding1 = ash_normalize_binding("POST", "/api/transfer/init", "").unwrap();
        let secret1 = ash_derive_client_secret(&nonce, &context_id, &binding1).unwrap();
        let payload1 = r#"{"from":"acc1","to":"acc2","amount":100}"#;

        let result1 = ash_build_proof_unified(&secret1, &timestamp, &binding1, payload1, &["amount"], None).unwrap();

        // Step 2: Confirm transfer (chained to step 1)
        let binding2 = ash_normalize_binding("POST", "/api/transfer/confirm", "").unwrap();
        let secret2 = ash_derive_client_secret(&nonce, &context_id, &binding2).unwrap();
        let payload2 = r#"{"confirmed":true}"#;

        // Chain to previous proof
        let result2 = ash_build_proof_unified(&secret2, &timestamp, &binding2, payload2, &[], Some(&result1.proof)).unwrap();

        // Verify step 2 includes chain to step 1
        assert!(!result2.chain_hash.is_empty());

        // Verify the chain
        let valid = ash_verify_proof_unified(
            &nonce, &context_id, &binding2, &timestamp, payload2,
            &result2.proof, &[], &result2.scope_hash,
            Some(&result1.proof), &result2.chain_hash
        ).unwrap();
        assert!(valid);
    }
}

// =========================================================================
// ERROR HANDLING EXAMPLE
// =========================================================================

mod error_handling {
    use super::*;

    #[test]
    fn test_error_handling_example() {
        // Invalid nonce (too short)
        let result = ash_derive_client_secret("short", "ctx", "GET|/|");
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(!error.to_string().is_empty());

        // Invalid JSON
        let result = ash_canonicalize_json("not json");
        assert!(result.is_err());

        // Expired timestamp
        let old_ts = (chrono::Utc::now().timestamp() - 3600).to_string();
        let result = ash_validate_timestamp(&old_ts, 300, 60);
        assert!(result.is_err());
    }
}

// =========================================================================
// URL-ENCODED FORMS EXAMPLE
// =========================================================================

mod urlencoded_forms {
    use super::*;

    #[test]
    fn test_form_data_example() {
        // Handle URL-encoded form data
        let form_data = "username=john&password=secret123&remember=true";
        let canonical = ash_canonicalize_urlencoded(form_data).unwrap();

        // Parameters are sorted
        assert!(canonical.starts_with("password="));
        assert!(canonical.contains("&remember="));
        assert!(canonical.contains("&username="));
    }
}

// =========================================================================
// TIMING SAFE COMPARISON EXAMPLE
// =========================================================================

mod timing_safe {
    use super::*;

    #[test]
    fn test_timing_safe_comparison_example() {
        // Always use timing-safe comparison for secrets
        let secret1 = "a".repeat(64);
        let secret2 = "a".repeat(64);
        let secret3 = "b".repeat(64);

        // Same secrets
        assert!(ash_timing_safe_equal(secret1.as_bytes(), secret2.as_bytes()));

        // Different secrets
        assert!(!ash_timing_safe_equal(secret1.as_bytes(), secret3.as_bytes()));
    }
}

// =========================================================================
// COMPLETE API FLOW EXAMPLE
// =========================================================================

mod complete_flow {
    use super::*;

    #[test]
    fn test_complete_api_flow_example() {
        // This demonstrates a complete real-world flow

        // === SETUP (one-time) ===
        // Server generates and stores nonce, sends to client

        // === CLIENT REQUEST ===
        let nonce = "a".repeat(64);  // Would come from server
        let context_id = "ctx_user123_req456";

        // Request details
        let method = "POST";
        let path = "/api/orders";
        let query = "";
        let body = r#"{"product_id":"prod_abc","quantity":2,"price":29.99}"#;

        // Build binding
        let binding = ash_normalize_binding(method, path, query).unwrap();

        // Derive secret and build proof
        let secret = ash_derive_client_secret(&nonce, &context_id, &binding).unwrap();
        let body_hash = ash_hash_body(body);
        let timestamp = chrono::Utc::now().timestamp().to_string();
        let proof = ash_build_proof(&secret, &timestamp, &binding, &body_hash).unwrap();

        // Client sends:
        // - Headers: X-ASH-Proof, X-ASH-Timestamp, X-ASH-Context-Id
        // - Body: the JSON payload

        // === SERVER VERIFICATION ===

        // 1. Validate timestamp
        let _ = ash_validate_timestamp(&timestamp, 300, 60).unwrap();

        // 2. Lookup nonce by context_id (from secure store)
        // let nonce = store.get_nonce(context_id);

        // 3. Reconstruct binding from request
        let server_binding = ash_normalize_binding(method, path, query).unwrap();

        // 4. Hash received body
        let server_body_hash = ash_hash_body(body);

        // 5. Verify proof
        let valid = ash_verify_proof(&nonce, &context_id, &server_binding, &timestamp, &server_body_hash, &proof).unwrap();

        assert!(valid, "Proof should be valid");

        // 6. Process request if valid
        // 7. Mark context as consumed
    }
}

// =========================================================================
// NESTED FIELD SCOPING EXAMPLE
// =========================================================================

mod nested_scoping {
    use super::*;

    #[test]
    fn test_nested_field_scoping_example() {
        let nonce = ash_generate_nonce(32).unwrap();
        let context_id = ash_generate_context_id().unwrap();
        let binding = ash_normalize_binding("POST", "/api/user", "").unwrap();
        let timestamp = chrono::Utc::now().timestamp().to_string();

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

        // Complex nested payload
        let payload = r#"{
            "user": {
                "name": "John",
                "email": "john@example.com",
                "preferences": {
                    "theme": "dark",
                    "notifications": true
                }
            },
            "action": "update"
        }"#;

        // Scope nested fields using dot notation
        let scope = vec!["user.email", "action"];

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

        // Verify
        let valid = ash_verify_proof_scoped(&nonce, &context_id, &binding, &timestamp, payload, &scope, &scope_hash, &proof).unwrap();
        assert!(valid);
    }
}