canaad-core 0.1.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
449
450
451
452
453
454
455
456
457
458
459
//! AAD context structure and builder.

use crate::canon::{canonicalize_context, canonicalize_context_string};
use crate::error::AadError;
use crate::parse::{parse_aad, ParsedAad, CURRENT_VERSION};
use crate::types::{ExtensionValue, Extensions, FieldKey, Purpose, Resource, SafeInt, Tenant};
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
use std::collections::BTreeMap;

/// AAD context with all validated fields.
///
/// This struct represents a fully validated AAD object that can be
/// serialized to canonical form for use with AEAD algorithms.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AadContext {
    /// Schema version (currently always 1)
    version: SafeInt,
    /// Tenant or user identifier
    tenant: Tenant,
    /// Resource path or identifier
    resource: Resource,
    /// Usage context
    purpose: Purpose,
    /// Optional Unix timestamp
    timestamp: Option<SafeInt>,
    /// Extension fields (x_<app>_<field>)
    extensions: Extensions,
}

impl AadContext {
    /// Creates a new `AadContext` with the required fields.
    ///
    /// # Arguments
    ///
    /// * `tenant` - Tenant identifier (1-256 bytes)
    /// * `resource` - Resource path (1-1024 bytes)
    /// * `purpose` - Usage context (1+ bytes)
    ///
    /// # Errors
    ///
    /// Returns validation errors if any field is invalid.
    ///
    /// # Example
    ///
    /// ```
    /// use canaad_core::AadContext;
    ///
    /// let ctx = AadContext::new("org_abc", "secrets/db", "encryption")?;
    /// # Ok::<(), canaad_core::AadError>(())
    /// ```
    pub fn new(
        tenant: impl Into<String>,
        resource: impl Into<String>,
        purpose: impl Into<String>,
    ) -> Result<Self, AadError> {
        Ok(Self {
            version: SafeInt::new(CURRENT_VERSION)?,
            tenant: Tenant::new(tenant)?,
            resource: Resource::new(resource)?,
            purpose: Purpose::new(purpose)?,
            timestamp: None,
            extensions: BTreeMap::new(),
        })
    }

    /// Creates a builder for constructing an `AadContext`.
    #[must_use]
    pub fn builder() -> AadContextBuilder {
        AadContextBuilder::new()
    }

    /// Adds a timestamp to the context.
    ///
    /// # Errors
    ///
    /// Returns `IntegerOutOfRange` if the timestamp exceeds 2^53-1.
    pub fn with_timestamp(mut self, ts: u64) -> Result<Self, AadError> {
        self.timestamp = Some(SafeInt::new(ts)?);
        Ok(self)
    }

    /// Adds an extension field to the context.
    ///
    /// # Arguments
    ///
    /// * `key` - Extension key (must match pattern `x_<app>_<field>`)
    /// * `value` - String or integer value
    ///
    /// # Errors
    ///
    /// Returns an error if the key format is invalid or the value is invalid.
    pub fn with_extension(
        mut self,
        key: impl Into<String>,
        value: ExtensionValue,
    ) -> Result<Self, AadError> {
        let key = FieldKey::new(key.into())?;
        key.validate_as_extension()?;
        self.extensions.insert(key, value);
        Ok(self)
    }

    /// Adds a string extension field.
    ///
    /// # Errors
    ///
    /// Returns an error if the key format is invalid or the value contains NUL bytes.
    pub fn with_string_extension(
        self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, AadError> {
        self.with_extension(key, ExtensionValue::string(value)?)
    }

    /// Adds an integer extension field.
    ///
    /// # Errors
    ///
    /// Returns an error if the key format is invalid or the value exceeds 2^53-1.
    pub fn with_int_extension(self, key: impl Into<String>, value: u64) -> Result<Self, AadError> {
        self.with_extension(key, ExtensionValue::integer(value)?)
    }

    /// Returns the schema version.
    #[must_use]
    pub const fn version(&self) -> u64 {
        self.version.value()
    }

    /// Returns the tenant identifier.
    #[must_use]
    pub fn tenant(&self) -> &str {
        self.tenant.as_str()
    }

    /// Returns the resource path.
    #[must_use]
    pub fn resource(&self) -> &str {
        self.resource.as_str()
    }

    /// Returns the purpose.
    #[must_use]
    pub fn purpose(&self) -> &str {
        self.purpose.as_str()
    }

    /// Returns the optional timestamp.
    #[must_use]
    pub fn timestamp(&self) -> Option<u64> {
        self.timestamp.map(|ts| ts.value())
    }

    /// Returns the extension fields.
    #[must_use]
    pub const fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    /// Canonicalizes this context to bytes according to RFC 8785.
    ///
    /// # Errors
    ///
    /// Returns `SerializedTooLarge` if the output exceeds 16 KiB.
    pub fn canonicalize(&self) -> Result<Vec<u8>, AadError> {
        canonicalize_context(self)
    }

    /// Canonicalizes this context to a UTF-8 string according to RFC 8785.
    ///
    /// # Errors
    ///
    /// Returns `SerializedTooLarge` if the output exceeds 16 KiB.
    pub fn canonicalize_string(&self) -> Result<String, AadError> {
        canonicalize_context_string(self)
    }
}

impl Serialize for AadContext {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Count fields: 4 required + optional ts + extensions
        let mut field_count = 4;
        if self.timestamp.is_some() {
            field_count += 1;
        }
        field_count += self.extensions.len();

        let mut map = serializer.serialize_map(Some(field_count))?;

        // Serialize in lexicographic order for canonical output
        // Required fields: purpose, resource, tenant, ts (if present), v, x_* extensions

        map.serialize_entry("purpose", self.purpose.as_str())?;
        map.serialize_entry("resource", self.resource.as_str())?;
        map.serialize_entry("tenant", self.tenant.as_str())?;

        if let Some(ts) = &self.timestamp {
            map.serialize_entry("ts", &ts.value())?;
        }

        map.serialize_entry("v", &self.version.value())?;

        // Extensions are in a BTreeMap so already sorted
        for (key, value) in &self.extensions {
            match value {
                ExtensionValue::String(s) => map.serialize_entry(key.as_str(), s)?,
                ExtensionValue::Integer(i) => map.serialize_entry(key.as_str(), &i.value())?,
            }
        }

        map.end()
    }
}

impl TryFrom<ParsedAad> for AadContext {
    type Error = AadError;

    fn try_from(parsed: ParsedAad) -> Result<Self, Self::Error> {
        Ok(Self {
            version: parsed.version,
            tenant: parsed.tenant,
            resource: parsed.resource,
            purpose: parsed.purpose,
            timestamp: parsed.timestamp,
            extensions: parsed.extensions,
        })
    }
}

/// Builder for constructing an `AadContext`.
#[derive(Debug, Default)]
pub struct AadContextBuilder {
    tenant: Option<String>,
    resource: Option<String>,
    purpose: Option<String>,
    timestamp: Option<u64>,
    extensions: Vec<(String, ExtensionValue)>,
}

impl AadContextBuilder {
    /// Creates a new builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the tenant identifier.
    #[must_use]
    pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
        self.tenant = Some(tenant.into());
        self
    }

    /// Sets the resource path.
    #[must_use]
    pub fn resource(mut self, resource: impl Into<String>) -> Self {
        self.resource = Some(resource.into());
        self
    }

    /// Sets the purpose.
    #[must_use]
    pub fn purpose(mut self, purpose: impl Into<String>) -> Self {
        self.purpose = Some(purpose.into());
        self
    }

    /// Sets the timestamp.
    #[must_use]
    pub const fn timestamp(mut self, ts: u64) -> Self {
        self.timestamp = Some(ts);
        self
    }

    /// Adds a string extension field.
    #[must_use]
    pub fn extension_string(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        if let Ok(v) = ExtensionValue::string(value) {
            self.extensions.push((key.into(), v));
        }
        self
    }

    /// Adds an integer extension field.
    #[must_use]
    pub fn extension_int(mut self, key: impl Into<String>, value: u64) -> Self {
        if let Ok(v) = ExtensionValue::integer(value) {
            self.extensions.push((key.into(), v));
        }
        self
    }

    /// Builds the `AadContext`.
    ///
    /// # Errors
    ///
    /// Returns an error if any required field is missing or invalid.
    pub fn build(self) -> Result<AadContext, AadError> {
        let tenant = self.tenant.ok_or(AadError::MissingRequiredField { field: "tenant" })?;
        let resource = self.resource.ok_or(AadError::MissingRequiredField { field: "resource" })?;
        let purpose = self.purpose.ok_or(AadError::MissingRequiredField { field: "purpose" })?;

        let mut ctx = AadContext::new(tenant, resource, purpose)?;

        if let Some(ts) = self.timestamp {
            ctx = ctx.with_timestamp(ts)?;
        }

        for (key, value) in self.extensions {
            ctx = ctx.with_extension(key, value)?;
        }

        Ok(ctx)
    }
}

/// Parses a JSON string into a validated `AadContext`.
///
/// # Errors
///
/// Returns an error if the JSON is invalid or violates AAD constraints.
pub fn parse(json: &str) -> Result<AadContext, AadError> {
    let parsed = parse_aad(json)?;
    AadContext::try_from(parsed)
}

/// Validates a JSON string as AAD and returns the context.
///
/// This is equivalent to `parse` - both perform full validation.
///
/// # Errors
///
/// Returns an error if the JSON is invalid or violates AAD constraints.
pub fn validate(json: &str) -> Result<AadContext, AadError> {
    parse(json)
}

/// Canonicalizes a JSON string to bytes.
///
/// This parses the JSON, validates it, and returns the canonical form.
///
/// # Errors
///
/// Returns an error if the JSON is invalid, violates AAD constraints,
/// or the canonical output exceeds 16 KiB.
pub fn canonicalize(json: &str) -> Result<Vec<u8>, AadError> {
    let ctx = parse(json)?;
    ctx.canonicalize()
}

/// Canonicalizes a JSON string to a UTF-8 string.
///
/// This parses the JSON, validates it, and returns the canonical form.
///
/// # Errors
///
/// Returns an error if the JSON is invalid, violates AAD constraints,
/// or the canonical output exceeds 16 KiB.
pub fn canonicalize_string(json: &str) -> Result<String, AadError> {
    let ctx = parse(json)?;
    ctx.canonicalize_string()
}

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

    #[test]
    fn test_context_new() {
        let ctx = AadContext::new("org_abc", "secrets/db", "encryption").unwrap();

        assert_eq!(ctx.version(), 1);
        assert_eq!(ctx.tenant(), "org_abc");
        assert_eq!(ctx.resource(), "secrets/db");
        assert_eq!(ctx.purpose(), "encryption");
        assert!(ctx.timestamp().is_none());
        assert!(ctx.extensions().is_empty());
    }

    #[test]
    fn test_context_with_timestamp() {
        let ctx =
            AadContext::new("org", "res", "test").unwrap().with_timestamp(1_706_400_000).unwrap();

        assert_eq!(ctx.timestamp(), Some(1_706_400_000));
    }

    #[test]
    fn test_context_with_extension() {
        let ctx = AadContext::new("org", "res", "test")
            .unwrap()
            .with_string_extension("x_vault_cluster", "us-east-1")
            .unwrap();

        assert_eq!(ctx.extensions().len(), 1);
    }

    #[test]
    fn test_builder() {
        let ctx = AadContext::builder()
            .tenant("org_abc")
            .resource("secrets/db")
            .purpose("encryption")
            .timestamp(1_706_400_000)
            .extension_string("x_app_field", "value")
            .build()
            .unwrap();

        assert_eq!(ctx.tenant(), "org_abc");
        assert_eq!(ctx.timestamp(), Some(1_706_400_000));
        assert_eq!(ctx.extensions().len(), 1);
    }

    #[test]
    fn test_builder_missing_required() {
        let result = AadContext::builder().tenant("org").resource("res").build();

        assert!(matches!(result, Err(AadError::MissingRequiredField { field: "purpose" })));
    }

    #[test]
    fn test_canonicalize_order() {
        let ctx = AadContext::new("org_abc", "secrets/db", "encryption").unwrap();
        let canonical = ctx.canonicalize_string().unwrap();

        // Fields should be in lexicographic order: purpose, resource, tenant, v
        assert_eq!(
            canonical,
            r#"{"purpose":"encryption","resource":"secrets/db","tenant":"org_abc","v":1}"#
        );
    }

    #[test]
    fn test_parse_and_canonicalize() {
        let json = r#"{"v":1,"tenant":"org_abc","resource":"secrets/db","purpose":"encryption"}"#;
        let canonical = canonicalize_string(json).unwrap();

        // Should be reordered
        assert_eq!(
            canonical,
            r#"{"purpose":"encryption","resource":"secrets/db","tenant":"org_abc","v":1}"#
        );
    }

    #[test]
    fn test_parse_roundtrip() {
        let original =
            r#"{"purpose":"encryption","resource":"secrets/db","tenant":"org_abc","v":1}"#;
        let ctx = parse(original).unwrap();
        let canonical = ctx.canonicalize_string().unwrap();

        assert_eq!(canonical, original);
    }
}