p2panda-rs 0.7.0

All the things a panda needs
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
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Collection of low-level validation methods for operations.
use crate::document::DocumentViewId;
use crate::entry::traits::{AsEncodedEntry, AsEntry};
use crate::entry::validate::{validate_log_integrity, validate_payload};
use crate::hash::Hash;
use crate::operation::error::ValidateOperationError;
use crate::operation::plain::{PlainFields, PlainOperation};
use crate::operation::traits::{Actionable, Schematic};
use crate::operation::{
    EncodedOperation, Operation, OperationAction, OperationId, OperationVersion,
};
use crate::schema::validate::{validate_all_fields, validate_only_given_fields};
use crate::schema::Schema;
use crate::Human;

/// Main method for complete verification of an operation and entry pair as per Bamboo and p2panda
/// specification.
///
/// Use this method for a complete check of all untrusted, incoming entries and operations. Since
/// this crate does not supply a persistence layer there are some preparations to be done by the
/// implementer to use this method:
///
/// 1. Decode the incoming entry
/// 2. Decode the incoming operation
/// 3. Look up a `Schema` instance (for example in a schema provider) via the schema id you
///    received from the decoded `PlainOperation`
/// 4. Look up `Entry` instances for the back- & skiplinks claimed by the decoded entry
/// 5. Use decoded and encoded data for this method to apply all checks which guarantees
///    authenticity, log integrity, correct operation format, schema validity etc. Returns
///    the operation and it's id.
///
/// This method applies the following validation steps:
///
/// 1. Correct hexadecimal entry encoding (when using human-readable encoding format) (#E1)
/// 2. Correct Bamboo encoding as per specification (#E2)
/// 3. Check if back- and skiplinks are correctly set for given sequence number (#E3)
/// 4. Verify log-integrity (matching back- & skiplink entries, author, log id) (#E4)
/// 5. Verify signature (#E5)
/// 6. Check if payload matches claimed hash and size (#E6)
/// 7. Correct hexadecimal operation encoding (when using human-readable encoding format) (#OP1)
/// 8. Correct operation format as per specification, including canonic format checks against
///    duplicate and unsorted operation fields (#OP2)
/// 9. Correctly formatted and canonic operation field values, like document view ids (no
///    duplicates, sorted, when no semantic value is given by that) as per specification (#OP3)
/// 10. Operation fields match the claimed schema (#OP4)
///
/// ```text
///                                                                  Look-Up
///
///             ┌────────────┐                       ┌─────┐    ┌─────┐    ┌─────┐
///  bytes ───► │EncodedEntry├────decode_entry()────►│Entry│    │Entry│    │Entry│
///             └──────┬─────┘                       └──┬──┘    └─────┘    └─────┘
///                    │                                │
///                    └───────────────────────────┐    │       Skiplink   Backlink
///                                                │    │          │          │
///             ┌────────────────┐                 │    │          │          │
///  bytes ───► │EncodedOperation├─────────────┐   │    │          │          │
///             └───────┬────────┘             │   │    │          │          │
///                     │                      │   │    │          │          │
///             decode_operation()             │   │    │          │          │
///                     │            Look-Up   │   │    │          │          │
///                     ▼                      │   │    │          │          │
///              ┌──────────────┐    ┌──────┐  │   │    │          │          │
///              │PlainOperation│    │Schema│  │   │    │          │          │
///              └──────┬───────┘    └──┬───┘  │   │    │          │          │
///                     │               │      │   │    │          │          │
///                     │               │      │   │    │          │          │
///                     │               │      │   │    │          │          │
///                     │               │      │   │    │          │          │
///                     │               ▼      ▼   ▼    ▼          ▼          │
///                     └───────────►  validate_operation_with_entry() ◄──────┘
//////////////////                                     ┌────────────────────────┐
///                                     │(Operation, OperationId)│
///                                     └────────────────────────┘
/// ```
#[allow(clippy::too_many_arguments)]
pub fn validate_operation_with_entry(
    entry: &impl AsEntry,
    entry_encoded: &impl AsEncodedEntry,
    skiplink: Option<(&impl AsEntry, &Hash)>,
    backlink: Option<(&impl AsEntry, &Hash)>,
    plain_operation: &PlainOperation,
    operation_encoded: &EncodedOperation,
    schema: &Schema,
) -> Result<(Operation, OperationId), ValidateOperationError> {
    // Verify that the entry belongs to this operation
    validate_payload(entry, operation_encoded)?;

    // Verify that the entries links are correct
    validate_log_integrity(entry, skiplink, backlink)?;

    // The operation id is the result of a hashing function over the entry bytes.
    let operation_id = entry_encoded.hash().into();

    // Validate and convert plain operation with the help of a schema
    let operation = validate_operation(plain_operation, schema)?;

    Ok((operation, operation_id))
}

/// Check the format of an operation-like data type.
///
/// This method checks against:
///
/// 1. Correct operation format (#OP2)
pub fn validate_operation_format(
    operation: &(impl Actionable + Schematic),
) -> Result<(), ValidateOperationError> {
    match operation.action() {
        OperationAction::Create => {
            // We don't want to return the fields here so we ignore them.
            let _ = validate_create_operation_format(operation.previous(), operation.fields())?;
            Ok(())
        }
        OperationAction::Update => {
            // We don't want to return the fields here so we ignore them.
            let _ = validate_update_operation_format(operation.previous(), operation.fields())?;
            Ok(())
        }
        OperationAction::Delete => {
            validate_delete_operation_format(operation.previous(), operation.fields())
        }
    }
}

/// Checks the fields and format of an operation-like data type against a schema.
///
/// This method checks against:
///
/// 1. Correct operation format (#OP2)
/// 2. Correct canonic operation field values, like document view ids of pinned relations (no
///    duplicates, sorted) (#OP3)
/// 3. Schema matches the given operation fields (#OP4)
pub fn validate_operation(
    operation: &(impl Actionable + Schematic),
    schema: &Schema,
) -> Result<Operation, ValidateOperationError> {
    let previous = operation.previous();
    let fields = operation.fields();

    // Make sure the schema id and given schema matches
    if operation.schema_id() != schema.id() {
        return Err(ValidateOperationError::SchemaNotMatching(
            operation.schema_id().display(),
            schema.id().display(),
        ));
    }

    match operation.action() {
        OperationAction::Create => validate_create_operation(previous, fields, schema),
        OperationAction::Update => validate_update_operation(previous, fields, schema),
        OperationAction::Delete => validate_delete_operation(previous, fields, schema),
    }
}

/// Validate the header fields of a CREATE operation.
///
/// Returns the unwrapped fields which we may wish to validate agains a schema in a
/// following step.
fn validate_create_operation_format(
    plain_previous_operations: Option<&DocumentViewId>,
    plain_fields: Option<PlainFields>,
) -> Result<PlainFields, ValidateOperationError> {
    match (plain_fields, plain_previous_operations) {
        (None, _) => Err(ValidateOperationError::ExpectedFields),
        (Some(_), Some(_)) => Err(ValidateOperationError::UnexpectedPreviousOperations),
        (Some(fields), None) => Ok(fields),
    }
}

/// Validate the header fields of a UPDATE operation.
///
/// Returns the unwrapped fields which we may wish to validate agains a schema in a
/// following step.
fn validate_update_operation_format(
    plain_previous_operations: Option<&DocumentViewId>,
    plain_fields: Option<PlainFields>,
) -> Result<PlainFields, ValidateOperationError> {
    match (plain_fields, plain_previous_operations) {
        (None, _) => Err(ValidateOperationError::ExpectedFields),
        (Some(_), None) => Err(ValidateOperationError::ExpectedPreviousOperations),
        (Some(fields), Some(_)) => Ok(fields),
    }
}

/// Validate the header fields of a DELETE operation.
fn validate_delete_operation_format(
    plain_previous_operations: Option<&DocumentViewId>,
    plain_fields: Option<PlainFields>,
) -> Result<(), ValidateOperationError> {
    match (plain_fields, plain_previous_operations) {
        (Some(_), _) => Err(ValidateOperationError::UnexpectedFields),
        (None, None) => Err(ValidateOperationError::ExpectedPreviousOperations),
        (None, Some(_)) => Ok(()),
    }
}

/// Validates a CREATE operation.
fn validate_create_operation(
    plain_previous_operations: Option<&DocumentViewId>,
    plain_fields: Option<PlainFields>,
    schema: &Schema,
) -> Result<Operation, ValidateOperationError> {
    let fields = validate_create_operation_format(plain_previous_operations, plain_fields)?;
    let validated_fields = validate_all_fields(&fields, schema)?;

    Ok(Operation {
        version: OperationVersion::V1,
        action: OperationAction::Create,
        schema_id: schema.id().to_owned(),
        previous: None,
        fields: Some(validated_fields),
    })
}

/// Validates an UPDATE operation.
fn validate_update_operation(
    plain_previous_operations: Option<&DocumentViewId>,
    plain_fields: Option<PlainFields>,
    schema: &Schema,
) -> Result<Operation, ValidateOperationError> {
    let fields = validate_update_operation_format(plain_previous_operations, plain_fields)?;
    let validated_fields = validate_only_given_fields(&fields, schema)?;

    Ok(Operation {
        version: OperationVersion::V1,
        action: OperationAction::Update,
        schema_id: schema.id().to_owned(),
        previous: plain_previous_operations.cloned(),
        fields: Some(validated_fields),
    })
}

/// Validates a DELETE operation.
fn validate_delete_operation(
    plain_previous_operations: Option<&DocumentViewId>,
    plain_fields: Option<PlainFields>,
    schema: &Schema,
) -> Result<Operation, ValidateOperationError> {
    validate_delete_operation_format(plain_previous_operations, plain_fields)?;

    Ok(Operation {
        version: OperationVersion::V1,
        action: OperationAction::Delete,
        schema_id: schema.id().to_owned(),
        previous: plain_previous_operations.cloned(),
        fields: None,
    })
}

#[cfg(test)]
mod tests {
    use ciborium::cbor;
    use ciborium::value::{Error, Value};
    use rstest::rstest;
    use rstest_reuse::apply;

    use crate::document::{DocumentId, DocumentViewId};
    use crate::operation::decode::decode_operation;
    use crate::operation::plain::PlainOperation;
    use crate::operation::{EncodedOperation, OperationAction, OperationBuilder};
    use crate::schema::{FieldType, Schema, SchemaId};
    use crate::test_utils::constants::{HASH, SCHEMA_ID};
    use crate::test_utils::fixtures::{document_id, document_view_id, schema, schema_id, Fixture};
    use crate::test_utils::templates::version_fixtures;

    use super::validate_operation;

    fn cbor_to_plain(value: Value) -> PlainOperation {
        let mut cbor_bytes = Vec::new();
        ciborium::ser::into_writer(&value, &mut cbor_bytes).unwrap();

        let encoded_operation = EncodedOperation::new(&cbor_bytes);
        decode_operation(&encoded_operation).unwrap()
    }

    #[rstest]
    #[case(
        vec![
            ("country", FieldType::Relation(schema_id.clone())),
            ("national_dish", FieldType::String),
            ("vegan_friendly", FieldType::Boolean),
            ("yummyness", FieldType::Integer),
            ("yumsimumsiness", FieldType::Float),
        ],
        cbor!([
            1, 0, SCHEMA_ID,
            {
                "country" => HASH,
                "national_dish" => "Pumpkin",
                "vegan_friendly" => true,
                "yummyness" => 8,
                "yumsimumsiness" => 7.2,
            },
        ]),
    )]
    fn valid_operations(
        #[from(schema_id)] schema_id: SchemaId,
        #[case] schema_fields: Vec<(&str, FieldType)>,
        #[case] cbor: Result<Value, Error>,
    ) {
        let schema = Schema::new(&schema_id, "Some schema description", &schema_fields)
            .expect("Could not create schema");

        let plain_operation = cbor_to_plain(cbor.expect("Invalid CBOR value"));
        assert!(validate_operation(&plain_operation, &schema).is_ok());
    }

    #[rstest]
    #[case::incomplete_hash(
        vec![
            ("country", FieldType::Relation(schema_id.clone())),
        ],
        cbor!([
            1, 0, SCHEMA_ID,
            {
                "country" => "0020",
            },
        ]),
        "field 'country' does not match schema: invalid hash length 2 bytes, expected 34 bytes"
    )]
    #[case::invalid_hex_encoding(
        vec![
            ("country", FieldType::Relation(schema_id.clone())),
        ],
        cbor!([
            1, 0, SCHEMA_ID,
            {
                "country" => "xyz",
            },
        ]),
        "field 'country' does not match schema: invalid hex encoding in hash string"
    )]
    #[case::missing_field(
        vec![
            ("national_dish", FieldType::String),
        ],
        cbor!([
            1, 0, SCHEMA_ID,
            {
                "vegan_friendly" => true,
            },
        ]),
        "field 'vegan_friendly' does not match schema: expected field name 'national_dish'"
    )]
    fn wrong_operation_fields(
        #[from(schema_id)] schema_id: SchemaId,
        #[case] schema_fields: Vec<(&str, FieldType)>,
        #[case] raw_operation: Result<Value, Error>,
        #[case] expected: &str,
    ) {
        let schema = Schema::new(&schema_id, "Some schema description", &schema_fields)
            .expect("Could not create schema");

        let plain_operation = cbor_to_plain(raw_operation.expect("Invalid CBOR value"));
        assert_eq!(
            validate_operation(&plain_operation, &schema)
                .expect_err("Expect error")
                .to_string(),
            expected
        );
    }

    #[apply(version_fixtures)]
    fn validate_fixture_operation(#[case] fixture: Fixture) {
        // Validating operation fixture against schema should succeed
        let plain_operation = decode_operation(&fixture.operation_encoded).unwrap();
        assert!(validate_operation(&plain_operation, &fixture.schema).is_ok());
    }

    #[rstest]
    fn operation_schema_validation(
        #[with(vec![
                ("firstname".into(), FieldType::String),
                ("year".into(), FieldType::Integer),
                ("is_cute".into(), FieldType::Boolean),
                ("address".into(), FieldType::Relation(schema_id(SCHEMA_ID))),
            ])]
        schema: Schema,
        document_id: DocumentId,
        document_view_id: DocumentViewId,
    ) {
        // Operation matches schema
        let operation = OperationBuilder::new(schema.id())
            .fields(&[
                ("firstname", "Peter".into()),
                ("year", 2020.into()),
                ("is_cute", false.into()),
                ("address", document_id.clone().into()),
            ])
            .build()
            .unwrap();

        assert!(validate_operation(&operation, &schema).is_ok());

        // Field ordering does not matter in builder
        let operation = OperationBuilder::new(schema.id())
            .fields(&[
                ("address", document_id.clone().into()),
                ("is_cute", false.into()),
                ("year", 2020.into()),
                ("firstname", "Peter".into()),
            ])
            .build()
            .unwrap();

        assert!(validate_operation(&operation, &schema).is_ok());

        // Field missing
        let operation = OperationBuilder::new(schema.id())
            .fields(&[
                ("firstname", "Peter".into()),
                ("is_cute", false.into()),
                ("address", document_id.clone().into()),
            ])
            .build()
            .unwrap();

        assert!(validate_operation(&operation, &schema).is_err());

        // Invalid type
        let operation = OperationBuilder::new(schema.id())
            .fields(&[
                ("firstname", "Peter".into()),
                ("year", "2020".into()),
                ("is_cute", false.into()),
                ("address", document_id.clone().into()),
            ])
            .build()
            .unwrap();

        assert!(validate_operation(&operation, &schema).is_err());

        // Correct UPDATE operation matching schema
        let operation = OperationBuilder::new(schema.id())
            .action(OperationAction::Update)
            .previous(&document_view_id)
            .fields(&[("address", document_id.into())])
            .build()
            .unwrap();

        assert!(validate_operation(&operation, &schema).is_ok());
    }
}