cdx-core 0.7.1

Core library for reading, writing, and validating Codex Document Format (.cdx) files
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
//! JSON Schema validation for Codex Document Format files.
//!
//! This module provides validation functions for the core CDX file types:
//! - Manifest (`manifest.json`)
//! - Content (`content/content.json`)
//! - Dublin Core metadata (`metadata/dublin-core.json`)
//!
//! # Feature Flag
//!
//! This module requires the `validation` feature:
//!
//! ```toml
//! [dependencies]
//! cdx-core = { version = "0.1", features = ["validation"] }
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use cdx_core::validation::{validate_manifest, validate_content};
//!
//! let manifest_json = r#"{"version": "0.1", "id": "sha256:abc..."}"#;
//! let errors = validate_manifest(manifest_json)?;
//! if errors.is_empty() {
//!     println!("Manifest is valid");
//! } else {
//!     for error in errors {
//!         println!("Validation error: {}", error);
//!     }
//! }
//! ```

use std::fmt;

/// JSON schema validation error for manifest and metadata files.
///
/// Reports type mismatches, missing required properties, and invalid
/// enum values when validating manifest, content, Dublin Core metadata,
/// block index, and signature JSON files against their schemas.
///
/// See also [`crate::content::ValidationError`] for content structure
/// validation (block hierarchy, unique IDs, etc.).
#[derive(Debug, Clone)]
pub struct SchemaValidationError {
    /// JSON path to the invalid element (empty for root-level errors).
    pub path: String,
    /// Description of the validation failure.
    pub message: String,
}

impl fmt::Display for SchemaValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path.is_empty() {
            write!(f, "{}", self.message)
        } else {
            write!(f, "{}: {}", self.path, self.message)
        }
    }
}

impl std::error::Error for SchemaValidationError {}

/// Result type for validation operations.
pub type ValidationResult = Result<Vec<SchemaValidationError>, crate::Error>;

/// Validate a manifest JSON string against the CDX manifest schema.
///
/// # Arguments
///
/// * `json` - The JSON string to validate
///
/// # Returns
///
/// A vector of validation errors. An empty vector means the JSON is valid.
///
/// # Errors
///
/// Returns an error if the JSON cannot be parsed.
pub fn validate_manifest(json: &str) -> ValidationResult {
    validate_json(json, SchemaType::Manifest)
}

/// Validate a content JSON string against the CDX content schema.
///
/// # Arguments
///
/// * `json` - The JSON string to validate
///
/// # Returns
///
/// A vector of validation errors. An empty vector means the JSON is valid.
///
/// # Errors
///
/// Returns an error if the JSON cannot be parsed.
pub fn validate_content(json: &str) -> ValidationResult {
    validate_json(json, SchemaType::Content)
}

/// Validate a Dublin Core metadata JSON string against the schema.
///
/// # Arguments
///
/// * `json` - The JSON string to validate
///
/// # Returns
///
/// A vector of validation errors. An empty vector means the JSON is valid.
///
/// # Errors
///
/// Returns an error if the JSON cannot be parsed.
pub fn validate_dublin_core(json: &str) -> ValidationResult {
    validate_json(json, SchemaType::DublinCore)
}

/// Validate a block index JSON string against the schema.
///
/// # Arguments
///
/// * `json` - The JSON string to validate
///
/// # Returns
///
/// A vector of validation errors. An empty vector means the JSON is valid.
///
/// # Errors
///
/// Returns an error if the JSON cannot be parsed.
pub fn validate_block_index(json: &str) -> ValidationResult {
    validate_json(json, SchemaType::BlockIndex)
}

/// Validate a signatures JSON string against the schema.
///
/// # Arguments
///
/// * `json` - The JSON string to validate
///
/// # Returns
///
/// A vector of validation errors. An empty vector means the JSON is valid.
///
/// # Errors
///
/// Returns an error if the JSON cannot be parsed.
pub fn validate_signatures(json: &str) -> ValidationResult {
    validate_json(json, SchemaType::Signatures)
}

/// Schema types for validation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SchemaType {
    Manifest,
    Content,
    DublinCore,
    BlockIndex,
    Signatures,
}

/// Internal validation function.
fn validate_json(json: &str, schema_type: SchemaType) -> ValidationResult {
    // Parse the JSON
    let type_name = match schema_type {
        SchemaType::Manifest => "manifest",
        SchemaType::Content => "content",
        SchemaType::DublinCore => "Dublin Core metadata",
        SchemaType::BlockIndex => "block index",
        SchemaType::Signatures => "signatures",
    };
    let value: serde_json::Value =
        serde_json::from_str(json).map_err(|e| crate::Error::ValidationFailed {
            reason: format!("Invalid {type_name} JSON: {e}"),
        })?;

    // Get the schema for this type
    let schema = get_schema(schema_type);

    // Validate against schema
    let mut errors = Vec::new();
    validate_value(&value, &schema, "", &mut errors);

    Ok(errors)
}

/// Get the schema definition for a given type.
fn get_schema(schema_type: SchemaType) -> Schema {
    match schema_type {
        SchemaType::Manifest => manifest_schema(),
        SchemaType::Content => content_schema(),
        SchemaType::DublinCore => dublin_core_schema(),
        SchemaType::BlockIndex => block_index_schema(),
        SchemaType::Signatures => signatures_schema(),
    }
}

/// Simple schema representation for validation.
#[derive(Debug, Clone)]
struct Schema {
    /// Required properties.
    required: Vec<&'static str>,
    /// Property schemas.
    properties: Vec<(&'static str, PropertySchema)>,
}

#[derive(Debug, Clone)]
enum PropertySchema {
    String,
    Object,
    Array,
    Any,
    StringEnum(Vec<&'static str>),
}

/// Validate a JSON value against a schema.
fn validate_value(
    value: &serde_json::Value,
    schema: &Schema,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    let Some(obj) = value.as_object() else {
        errors.push(SchemaValidationError {
            path: path.to_string(),
            message: "expected object".to_string(),
        });
        return;
    };

    // Check required properties
    for required in &schema.required {
        if !obj.contains_key(*required) {
            errors.push(SchemaValidationError {
                path: if path.is_empty() {
                    (*required).to_string()
                } else {
                    format!("{path}.{required}")
                },
                message: format!("missing required property '{required}'"),
            });
        }
    }

    // Validate property types
    for (prop_name, prop_schema) in &schema.properties {
        if let Some(prop_value) = obj.get(*prop_name) {
            let prop_path = if path.is_empty() {
                (*prop_name).to_string()
            } else {
                format!("{path}.{prop_name}")
            };
            validate_property(prop_value, prop_schema, &prop_path, errors);
        }
    }
}

/// Validate a property value against its schema.
fn validate_property(
    value: &serde_json::Value,
    schema: &PropertySchema,
    path: &str,
    errors: &mut Vec<SchemaValidationError>,
) {
    match schema {
        PropertySchema::String => {
            if !value.is_string() {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: format!("expected string, got {}", value_type_name(value)),
                });
            }
        }
        PropertySchema::Object => {
            if !value.is_object() {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: format!("expected object, got {}", value_type_name(value)),
                });
            }
        }
        PropertySchema::Array => {
            if !value.is_array() {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: format!("expected array, got {}", value_type_name(value)),
                });
            }
        }
        PropertySchema::Any => {
            // Any type is valid
        }
        PropertySchema::StringEnum(variants) => {
            if let Some(s) = value.as_str() {
                if !variants.contains(&s) {
                    errors.push(SchemaValidationError {
                        path: path.to_string(),
                        message: format!(
                            "invalid value '{}', expected one of: {}",
                            s,
                            variants.join(", ")
                        ),
                    });
                }
            } else {
                errors.push(SchemaValidationError {
                    path: path.to_string(),
                    message: format!("expected string, got {}", value_type_name(value)),
                });
            }
        }
    }
}

/// Get a human-readable type name for a JSON value.
fn value_type_name(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "null",
        serde_json::Value::Bool(_) => "boolean",
        serde_json::Value::Number(_) => "number",
        serde_json::Value::String(_) => "string",
        serde_json::Value::Array(_) => "array",
        serde_json::Value::Object(_) => "object",
    }
}

// Schema definitions

fn manifest_schema() -> Schema {
    Schema {
        required: vec!["version"],
        properties: vec![
            ("version", PropertySchema::String),
            ("id", PropertySchema::String),
            (
                "state",
                PropertySchema::StringEnum(vec!["draft", "review", "frozen", "published"]),
            ),
            ("created", PropertySchema::String),
            ("modified", PropertySchema::String),
            ("content", PropertySchema::Object),
            ("metadata", PropertySchema::Object),
            ("security", PropertySchema::Object),
            ("presentation", PropertySchema::Object),
            ("assets", PropertySchema::Object),
            ("lineage", PropertySchema::Object),
        ],
    }
}

fn content_schema() -> Schema {
    Schema {
        required: vec!["version", "blocks"],
        properties: vec![
            ("version", PropertySchema::String),
            ("blocks", PropertySchema::Array),
        ],
    }
}

fn dublin_core_schema() -> Schema {
    Schema {
        required: vec!["version"],
        properties: vec![
            ("version", PropertySchema::String),
            ("title", PropertySchema::String),
            ("creator", PropertySchema::Any), // Can be string or array
            ("subject", PropertySchema::Any),
            ("description", PropertySchema::String),
            ("publisher", PropertySchema::String),
            ("contributor", PropertySchema::Any),
            ("date", PropertySchema::String),
            ("type", PropertySchema::String),
            ("format", PropertySchema::String),
            ("identifier", PropertySchema::String),
            ("source", PropertySchema::String),
            ("language", PropertySchema::String),
            ("relation", PropertySchema::String),
            ("coverage", PropertySchema::String),
            ("rights", PropertySchema::String),
        ],
    }
}

fn block_index_schema() -> Schema {
    Schema {
        required: vec!["version", "algorithm", "root", "blocks"],
        properties: vec![
            ("version", PropertySchema::String),
            (
                "algorithm",
                PropertySchema::StringEnum(vec!["sha256", "sha384", "sha512", "blake3"]),
            ),
            ("root", PropertySchema::String),
            ("blocks", PropertySchema::Array),
        ],
    }
}

fn signatures_schema() -> Schema {
    Schema {
        required: vec!["version", "signatures"],
        properties: vec![
            ("version", PropertySchema::String),
            ("signatures", PropertySchema::Array),
        ],
    }
}

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

    #[test]
    fn test_validate_manifest_valid() {
        let json = r#"{
            "version": "0.1",
            "state": "draft",
            "created": "2024-01-01T00:00:00Z"
        }"#;

        let errors = validate_manifest(json).unwrap();
        assert!(errors.is_empty(), "Expected no errors: {errors:?}");
    }

    #[test]
    fn test_validate_manifest_missing_version() {
        let json = r#"{
            "state": "draft"
        }"#;

        let errors = validate_manifest(json).unwrap();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("version"));
    }

    #[test]
    fn test_validate_manifest_invalid_state() {
        let json = r#"{
            "version": "0.1",
            "state": "invalid"
        }"#;

        let errors = validate_manifest(json).unwrap();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("invalid"));
    }

    #[test]
    fn test_validate_manifest_wrong_type() {
        let json = r#"{
            "version": 123
        }"#;

        let errors = validate_manifest(json).unwrap();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("string"));
    }

    #[test]
    fn test_validate_content_valid() {
        let json = r#"{
            "version": "0.1",
            "blocks": []
        }"#;

        let errors = validate_content(json).unwrap();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_content_missing_blocks() {
        let json = r#"{
            "version": "0.1"
        }"#;

        let errors = validate_content(json).unwrap();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("blocks"));
    }

    #[test]
    fn test_validate_dublin_core_valid() {
        let json = r#"{
            "version": "0.1",
            "title": "Test Document",
            "creator": "Test Author"
        }"#;

        let errors = validate_dublin_core(json).unwrap();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_dublin_core_array_creator() {
        let json = r#"{
            "version": "0.1",
            "title": "Test Document",
            "creator": ["Author 1", "Author 2"]
        }"#;

        let errors = validate_dublin_core(json).unwrap();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_block_index_valid() {
        let json = r#"{
            "version": "0.1",
            "algorithm": "sha256",
            "root": "abc123",
            "blocks": []
        }"#;

        let errors = validate_block_index(json).unwrap();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_block_index_invalid_algorithm() {
        let json = r#"{
            "version": "0.1",
            "algorithm": "md5",
            "root": "abc123",
            "blocks": []
        }"#;

        let errors = validate_block_index(json).unwrap();
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("md5"));
    }

    #[test]
    fn test_validate_signatures_valid() {
        let json = r#"{
            "version": "0.1",
            "signatures": []
        }"#;

        let errors = validate_signatures(json).unwrap();
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_invalid_json() {
        let json = "not valid json";

        let result = validate_manifest(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_error_display() {
        let error = SchemaValidationError {
            path: "manifest.version".to_string(),
            message: "expected string".to_string(),
        };
        assert_eq!(error.to_string(), "manifest.version: expected string");
    }

    #[test]
    fn test_error_display_empty_path() {
        let error = SchemaValidationError {
            path: String::new(),
            message: "expected object".to_string(),
        };
        assert_eq!(error.to_string(), "expected object");
    }
}