canaad-core 0.2.0

Core library for AAD canonicalization per RFC 8785
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
//! Test vectors from Section 10 of the AAD specification.
//!
//! These tests validate that the implementation correctly handles all
//! specified test vectors, including edge cases for JCS serialization.

use crate::{canonicalize_string, parse, AadContext, AadError};
use sha2::{Digest, Sha256};

/// Computes SHA-256 hash of the canonical output and returns it as hex.
fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    hex::encode(hasher.finalize())
}

// =============================================================================
// Section 10.1: Minimal Required Fields
// =============================================================================

#[test]
fn test_vector_10_1_minimal_fields() {
    let input = r#"{
        "v": 1,
        "tenant": "org_abc",
        "resource": "secrets/db",
        "purpose": "encryption"
    }"#;

    let expected_canonical =
        r#"{"purpose":"encryption","resource":"secrets/db","tenant":"org_abc","v":1}"#;

    // Correct SHA-256 from the implementation plan (spec has wrong hash)
    let expected_sha256 = "03fdc63d2f82815eb0a97e6f1a02890e152c021a795142b9c22e2b31a3bd83eb";

    let expected_hex = "7b22707572706f7365223a22656e6372797074696f6e222c227265736f75726365223a22736563726574732f6462222c2274656e616e74223a226f72675f616263222c2276223a317d";

    // Parse and canonicalize
    let canonical = canonicalize_string(input).expect("should parse and canonicalize");
    assert_eq!(canonical, expected_canonical);

    // Verify UTF-8 hex encoding
    let utf8_hex = hex::encode(canonical.as_bytes());
    assert_eq!(utf8_hex, expected_hex);

    // Verify SHA-256
    let sha256 = sha256_hex(canonical.as_bytes());
    assert_eq!(sha256, expected_sha256);
}

#[test]
fn test_vector_10_1_via_builder() {
    let ctx =
        AadContext::new("org_abc", "secrets/db", "encryption").expect("should create context");

    let canonical = ctx.canonicalize_string().expect("should canonicalize");
    let expected = r#"{"purpose":"encryption","resource":"secrets/db","tenant":"org_abc","v":1}"#;

    assert_eq!(canonical, expected);
}

// =============================================================================
// Section 10.2: All Fields Including Optional
// =============================================================================

#[test]
fn test_vector_10_2_all_fields() {
    let input = r#"{
        "v": 1,
        "tenant": "org_abc",
        "resource": "secrets/db/prod",
        "purpose": "encryption-at-rest",
        "ts": 1706400000
    }"#;

    let expected_canonical = r#"{"purpose":"encryption-at-rest","resource":"secrets/db/prod","tenant":"org_abc","ts":1706400000,"v":1}"#;

    let canonical = canonicalize_string(input).expect("should parse and canonicalize");
    assert_eq!(canonical, expected_canonical);
}

#[test]
fn test_vector_10_2_via_builder() {
    let ctx = AadContext::new("org_abc", "secrets/db/prod", "encryption-at-rest")
        .expect("should create context")
        .with_timestamp(1706400000)
        .expect("should add timestamp");

    let canonical = ctx.canonicalize_string().expect("should canonicalize");
    let expected = r#"{"purpose":"encryption-at-rest","resource":"secrets/db/prod","tenant":"org_abc","ts":1706400000,"v":1}"#;

    assert_eq!(canonical, expected);
}

// =============================================================================
// Section 10.3: Unicode in Values
// =============================================================================

#[test]
fn test_vector_10_3_unicode() {
    let input = r#"{
        "v": 1,
        "tenant": "组织_测试",
        "resource": "data/🔐/secret",
        "purpose": "encryption"
    }"#;

    let expected_canonical =
        r#"{"purpose":"encryption","resource":"data/🔐/secret","tenant":"组织_测试","v":1}"#;

    let canonical = canonicalize_string(input).expect("should parse and canonicalize");
    assert_eq!(canonical, expected_canonical);

    // Verify that Unicode characters are preserved, not escaped
    assert!(canonical.contains("组织_测试"));
    assert!(canonical.contains("🔐"));
}

#[test]
fn test_vector_10_3_via_builder() {
    let ctx = AadContext::new("组织_测试", "data/🔐/secret", "encryption")
        .expect("should create context");

    let canonical = ctx.canonicalize_string().expect("should canonicalize");

    assert!(canonical.contains("组织_测试"));
    assert!(canonical.contains("🔐"));
}

// =============================================================================
// Section 10.4: Extension Fields
// =============================================================================

#[test]
fn test_vector_10_4_extension_fields() {
    let input = r#"{
        "v": 1,
        "tenant": "org_abc",
        "resource": "vault/key",
        "purpose": "key-wrapping",
        "x_vault_cluster": "us-east-1"
    }"#;

    let expected_canonical = r#"{"purpose":"key-wrapping","resource":"vault/key","tenant":"org_abc","v":1,"x_vault_cluster":"us-east-1"}"#;

    let canonical = canonicalize_string(input).expect("should parse and canonicalize");
    assert_eq!(canonical, expected_canonical);
}

#[test]
fn test_vector_10_4_via_builder() {
    let ctx = AadContext::new("org_abc", "vault/key", "key-wrapping")
        .expect("should create context")
        .with_string_extension("x_vault_cluster", "us-east-1")
        .expect("should add extension");

    let canonical = ctx.canonicalize_string().expect("should canonicalize");
    let expected = r#"{"purpose":"key-wrapping","resource":"vault/key","tenant":"org_abc","v":1,"x_vault_cluster":"us-east-1"}"#;

    assert_eq!(canonical, expected);
}

// =============================================================================
// Section 10.5: JCS Edge Cases
// =============================================================================

#[test]
fn test_vector_10_5_jcs_edge_cases() {
    // Input uses \u000A for newline and has escaped quotes
    let input = r#"{
        "v": 1,
        "tenant": "org\u000Atest",
        "resource": "path/with\"quotes",
        "purpose": "test",
        "ts": 9007199254740991
    }"#;

    // Canonical output should use \n not \u000A, and preserve escaped quotes
    let expected_canonical = r#"{"purpose":"test","resource":"path/with\"quotes","tenant":"org\ntest","ts":9007199254740991,"v":1}"#;

    let canonical = canonicalize_string(input).expect("should parse and canonicalize");
    assert_eq!(canonical, expected_canonical);

    // Verify: control character newline is escaped as \n
    assert!(canonical.contains(r#"\n"#));

    // Verify: quote escaping within strings
    assert!(canonical.contains(r#"\""#));

    // Verify: integer at precision boundary (2^53-1)
    assert!(canonical.contains("9007199254740991"));
}

#[test]
fn test_vector_10_5_max_safe_integer() {
    // Test the maximum safe integer value
    let ctx = AadContext::new("org", "res", "test")
        .expect("should create context")
        .with_timestamp(9007199254740991)
        .expect("should accept max safe integer");

    let canonical = ctx.canonicalize_string().expect("should canonicalize");
    assert!(canonical.contains("9007199254740991"));
}

// =============================================================================
// Negative Tests
// =============================================================================

#[test]
fn test_negative_integer_above_max_safe() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","ts":9007199254740992}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::IntegerOutOfRange { .. })));
}

#[test]
fn test_negative_integer_value() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","ts":-1}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::NegativeInteger { .. })));
}

#[test]
fn test_negative_empty_tenant() {
    let input = r#"{"v":1,"tenant":"","resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::FieldTooShort { field: "tenant", .. })));
}

#[test]
fn test_negative_nul_byte_in_tenant() {
    // NUL byte encoded as \u0000
    let input = r#"{"v":1,"tenant":"org\u0000abc","resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::NulByteInValue { field: "tenant" })));
}

#[test]
fn test_negative_unknown_field() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","unknown":"value"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::UnknownField { .. })));
}

#[test]
fn test_negative_missing_required_field() {
    // Missing purpose
    let input = r#"{"v":1,"tenant":"org","resource":"res"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::MissingRequiredField { field: "purpose" })));
}

#[test]
fn test_negative_duplicate_key() {
    let input = r#"{"v":1,"tenant":"org","tenant":"other","resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::DuplicateKey { .. })));
}

#[test]
fn test_negative_invalid_extension_key_single_underscore() {
    // x_foo is missing the second underscore
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","x_foo":"value"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::InvalidExtensionKeyFormat { .. })));
}

#[test]
fn test_negative_invalid_extension_key_empty_app() {
    // x__field has empty app part
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","x__field":"value"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::InvalidExtensionKeyFormat { .. })));
}

#[test]
fn test_negative_invalid_extension_key_empty_field() {
    // x_app_ has empty field part
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","x_app_":"value"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::InvalidExtensionKeyFormat { .. })));
}

#[test]
fn test_negative_unsupported_version() {
    let input = r#"{"v":2,"tenant":"org","resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::UnsupportedVersion { version: 2 })));
}

#[test]
fn test_negative_version_zero() {
    let input = r#"{"v":0,"tenant":"org","resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::UnsupportedVersion { version: 0 })));
}

#[test]
fn test_negative_wrong_field_type_version() {
    let input = r#"{"v":"1","tenant":"org","resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::WrongFieldType { field: "v", .. })));
}

#[test]
fn test_negative_wrong_field_type_tenant() {
    let input = r#"{"v":1,"tenant":123,"resource":"res","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::WrongFieldType { field: "tenant", .. })));
}

#[test]
fn test_negative_wrong_field_type_ts() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","ts":"1706400000"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::WrongFieldType { field: "ts", .. })));
}

#[test]
fn test_negative_invalid_json() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test""#; // Missing closing brace
    let result = parse(input);
    assert!(matches!(result, Err(AadError::InvalidJson { .. })));
}

#[test]
fn test_negative_not_an_object() {
    let input = r#"["v", 1, "tenant", "org"]"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::InvalidJson { .. })));
}

// =============================================================================
// Additional Edge Cases
// =============================================================================

#[test]
fn test_extension_field_with_integer_value() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","x_app_count":42}"#;
    let result = parse(input);
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.extensions().len(), 1);
}

#[test]
fn test_multiple_extension_fields() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","x_app_field":"value","x_other_key":"data"}"#;
    let result = parse(input);
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.extensions().len(), 2);

    // Verify canonical ordering (extensions are sorted)
    let canonical = ctx.canonicalize_string().unwrap();
    let app_pos = canonical.find("x_app_field").unwrap();
    let other_pos = canonical.find("x_other_key").unwrap();
    assert!(app_pos < other_pos); // x_app_field comes before x_other_key
}

#[test]
fn test_extension_key_with_multiple_underscores_in_field() {
    // x_app_field_name is valid (field can contain underscores)
    let input =
        r#"{"v":1,"tenant":"org","resource":"res","purpose":"test","x_app_field_name":"value"}"#;
    let result = parse(input);
    assert!(result.is_ok());
}

#[test]
fn test_tenant_at_max_length() {
    let tenant = "a".repeat(256);
    let input = format!(r#"{{"v":1,"tenant":"{}","resource":"res","purpose":"test"}}"#, tenant);
    let result = parse(&input);
    assert!(result.is_ok());
}

#[test]
fn test_tenant_exceeds_max_length() {
    let tenant = "a".repeat(257);
    let input = format!(r#"{{"v":1,"tenant":"{}","resource":"res","purpose":"test"}}"#, tenant);
    let result = parse(&input);
    assert!(matches!(result, Err(AadError::FieldTooLong { field: "tenant", .. })));
}

#[test]
fn test_resource_at_max_length() {
    let resource = "a".repeat(1024);
    let input = format!(r#"{{"v":1,"tenant":"org","resource":"{}","purpose":"test"}}"#, resource);
    let result = parse(&input);
    assert!(result.is_ok());
}

#[test]
fn test_resource_exceeds_max_length() {
    let resource = "a".repeat(1025);
    let input = format!(r#"{{"v":1,"tenant":"org","resource":"{}","purpose":"test"}}"#, resource);
    let result = parse(&input);
    assert!(matches!(result, Err(AadError::FieldTooLong { field: "resource", .. })));
}

#[test]
fn test_whitespace_in_input_is_handled() {
    // Input with lots of whitespace
    let input = r#"
    {
        "v" : 1 ,
        "tenant" : "org" ,
        "resource" : "res" ,
        "purpose" : "test"
    }
    "#;

    let canonical = canonicalize_string(input).unwrap();

    // Canonical output should have no whitespace
    assert!(!canonical.contains(' '));
    assert!(!canonical.contains('\n'));
    assert_eq!(canonical, r#"{"purpose":"test","resource":"res","tenant":"org","v":1}"#);
}

#[test]
fn test_special_characters_in_strings() {
    let input = r#"{"v":1,"tenant":"org/abc","resource":"path\\to\\file","purpose":"test\ttab"}"#;
    let result = parse(input);
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.tenant(), "org/abc");
    assert_eq!(ctx.resource(), "path\\to\\file");
    assert_eq!(ctx.purpose(), "test\ttab");
}

#[test]
fn test_empty_resource() {
    let input = r#"{"v":1,"tenant":"org","resource":"","purpose":"test"}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::FieldTooShort { field: "resource", .. })));
}

#[test]
fn test_empty_purpose() {
    let input = r#"{"v":1,"tenant":"org","resource":"res","purpose":""}"#;
    let result = parse(input);
    assert!(matches!(result, Err(AadError::FieldTooShort { field: "purpose", .. })));
}