atomic_lib 0.40.0

Library for creating, storing, querying, validating and converting Atomic Data.
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Describe changes / mutations to data

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use urls::{SET, SIGNER};

use crate::{
    agents::{decode_base64, encode_base64},
    datatype::DataType,
    errors::AtomicResult,
    resources::PropVals,
    urls,
    values::SubResource,
    Atom, Resource, Storelike, Value,
};

/// The `resource_new`, `resource_old` and `commit_resource` fields are only created if the Commit is persisted.
/// When the Db is only notifying other of changes (e.g. if a new Message was added to a ChatRoom), these fields are not created.
/// When deleting a resource, the `resource_new` field is None.
#[derive(Clone, Debug)]
pub struct CommitResponse {
    pub commit: Commit,
    pub commit_resource: Resource,
    pub resource_new: Option<Resource>,
    pub resource_old: Option<Resource>,
    pub add_atoms: Vec<Atom>,
    pub remove_atoms: Vec<Atom>,
}

pub struct CommitApplied {
    /// The resource before the Commit was applied
    pub resource_old: Resource,
    /// The modified resources where the commit has been applied to
    pub resource_new: Resource,
    /// The atoms that should be added to the store (for updating indexes)
    pub add_atoms: Vec<Atom>,
    /// The atoms that should be removed from the store (for updating indexes)
    pub remove_atoms: Vec<Atom>,
}

#[derive(Clone, Debug)]
/// Describes options for applying a Commit.
/// Skip the checks you don't need to get better performance, or if you want to break the rules a little.
pub struct CommitOpts {
    /// Makes sure all `required` properties are present.
    pub validate_schema: bool,
    /// Checks the public key and the signature of the Commit.
    pub validate_signature: bool,
    /// Checks whether the Commit isn't too old, or has been created in the future.
    pub validate_timestamp: bool,
    /// Checks whether the creator of the Commit has the rights to edit the Resource.
    pub validate_rights: bool,
    /// Checks whether the previous Commit applied to the resource matches the one mentioned in the Commit/
    /// This makes sure that the Commit is not applied twice, or that the one creating it had a faulty state.
    pub validate_previous_commit: bool,
    /// Updates the indexes in the Store. Is a bit more costly.
    pub update_index: bool,
    /// For who the right checks will be perormed. If empty, the signer of the Commit will be used.
    pub validate_for_agent: Option<String>,
}

impl CommitOpts {
    pub fn no_validations_no_index() -> Self {
        Self {
            validate_schema: false,
            validate_signature: false,
            validate_timestamp: false,
            validate_rights: false,
            validate_previous_commit: false,
            update_index: false,
            validate_for_agent: None,
        }
    }
}

/// A Commit is a set of changes to a Resource.
/// Use CommitBuilder if you're programmatically constructing a Delta.
#[derive(Clone, Debug, Serialize)]
pub struct Commit {
    /// The subject URL that is to be modified by this Delta
    #[serde(rename = "https://atomicdata.dev/properties/subject")]
    pub subject: String,
    /// The date it was created, as a unix timestamp
    #[serde(rename = "https://atomicdata.dev/properties/createdAt")]
    pub created_at: i64,
    /// The URL of the one signing this Commit
    #[serde(rename = "https://atomicdata.dev/properties/signer")]
    pub signer: String,
    /// The set of PropVals that need to be added.
    /// Overwrites existing values
    #[serde(rename = "https://atomicdata.dev/properties/set")]
    pub set: Option<std::collections::HashMap<String, Value>>,
    /// The set of property URLs that need to be removed
    #[serde(rename = "https://atomicdata.dev/properties/remove")]
    pub remove: Option<Vec<String>>,
    /// If set to true, deletes the entire resource
    #[serde(rename = "https://atomicdata.dev/properties/destroy")]
    pub destroy: Option<bool>,
    /// Base64 encoded signature of the JSON serialized Commit
    #[serde(rename = "https://atomicdata.dev/properties/signature")]
    pub signature: Option<String>,
    /// List of Properties and Arrays to be appended to them
    #[serde(rename = "https://atomicdata.dev/properties/push")]
    pub push: Option<std::collections::HashMap<String, Value>>,
    /// The previously applied commit to this Resource.
    #[serde(rename = "https://atomicdata.dev/properties/previousCommit")]
    pub previous_commit: Option<String>,
    /// The URL of the Commit
    pub url: Option<String>,
}

impl Commit {
    /// Throws an error if the parent is set to itself
    pub fn check_for_circular_parents(&self) -> AtomicResult<()> {
        // Check if the set hashset has a parent property and if it matches with this subject.
        if let Some(set) = self.set.clone() {
            if let Some(parent) = set.get(urls::PARENT) {
                if parent.to_string() == self.subject {
                    return Err("Circular parent reference".into());
                }
            }
        }

        // TODO: Check for circular parents by going up the parent tree.
        Ok(())
    }

    pub fn validate_previous_commit(
        &self,
        resource_old: &Resource,
        subject_url: &str,
    ) -> AtomicResult<()> {
        let commit = self;
        if let Ok(last_commit_val) = resource_old.get(urls::LAST_COMMIT) {
            let last_commit = last_commit_val.to_string();

            if let Some(prev_commit) = commit.previous_commit.clone() {
                // TODO: try auto merge
                if last_commit != prev_commit {
                    return Err(format!(
                        "previousCommit mismatch. Had lastCommit '{}' in Resource {}, but got in Commit '{}'. Perhaps you created the Commit based on an outdated version of the Resource.",
                        last_commit, subject_url, prev_commit,
                    )
                    .into());
                }
            } else {
                return Err(format!("Missing `previousCommit`. Resource {} already exists, and it has a `lastCommit` field, so a `previousCommit` field is required in your Commit.", commit.subject).into());
            }
        } else {
            // If there is no lastCommit in the Resource, we'll accept the Commit.
            tracing::warn!("No `lastCommit` in Resource. This can be a bug, or it could be that the resource was never properly updated.");
        }
        Ok(())
    }

    /// Check if the Commit's signature matches the signer's public key.
    pub fn validate_signature(&self, store: &impl Storelike) -> AtomicResult<()> {
        let commit = self;
        let signature = match commit.signature.as_ref() {
            Some(sig) => sig,
            None => return Err("No signature set".into()),
        };
        let pubkey_b64 = store
            .get_resource(&commit.signer)?
            .get(urls::PUBLIC_KEY)?
            .to_string();
        let agent_pubkey = decode_base64(&pubkey_b64)?;
        let stringified_commit = commit.serialize_deterministically_json_ad(store)?;
        let peer_public_key =
            ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, agent_pubkey);
        let signature_bytes = decode_base64(signature)?;
        peer_public_key
            .verify(stringified_commit.as_bytes(), &signature_bytes)
            .map_err(|_e| {
                format!(
                    "Incorrect signature for Commit. This could be due to an error during signing or serialization of the commit. Compare this to the serialized commit in the client: {}",
                    stringified_commit,
                )
            })?;
        Ok(())
    }

    /// Performs the checks specified in CommitOpts and constructs a new Resource.
    /// Warning: Does not save the new resource to the Store - doet not delete if it `destroy: true`.
    /// Use [Storelike::apply_commit] to save the resource to the Store.
    pub fn validate_and_build_response(
        self,
        opts: &CommitOpts,
        store: &impl Storelike,
    ) -> AtomicResult<CommitResponse> {
        let commit = self;
        let subject_url = url::Url::parse(&commit.subject)
            .map_err(|e| format!("Subject '{}' is not a URL. {}", commit.subject, e))?;

        if subject_url.query().is_some() {
            return Err("Subject URL cannot have query parameters".into());
        }

        if opts.validate_signature {
            commit.validate_signature(store)?;
        }
        if opts.validate_timestamp {
            commit.validate_timestamp()?;
        }

        commit.check_for_circular_parents()?;
        let mut is_new = false;
        // Create a new resource if it doesn't exist yet
        let mut resource_old = match store.get_resource(&commit.subject) {
            Ok(rs) => rs,
            Err(_) => {
                is_new = true;
                Resource::new(commit.subject.clone())
            }
        };

        // Make sure the one creating the commit had the same idea of what the current state is.
        if !is_new && opts.validate_previous_commit {
            commit.validate_previous_commit(&resource_old, subject_url.as_str())?;
        };

        let mut applied = commit
            .apply_changes(resource_old.clone(), store)
            .map_err(|e| {
                format!(
                    "Error applying changes to Resource {}. {}",
                    commit.subject, e
                )
            })?;

        if opts.validate_rights {
            let validate_for = opts.validate_for_agent.as_ref().unwrap_or(&commit.signer);
            if is_new {
                crate::hierarchy::check_append(store, &applied.resource_new, &validate_for.into())?;
            } else {
                // Set a parent only if the rights checks are to be validated.
                // If there is no explicit parent set on the previous resource, use a default.
                // Unless it's a Drive!
                if resource_old.get(urls::PARENT).is_err() {
                    let default_parent = store.get_self_url().ok_or("There is no self_url set, and no parent in the Commit. The commit can not be applied.")?;
                    resource_old.set(
                        urls::PARENT.into(),
                        Value::AtomicUrl(default_parent),
                        store,
                    )?;
                }
                // This should use the _old_ resource, no the new one, as the new one might maliciously give itself write rights.
                crate::hierarchy::check_write(store, &resource_old, &validate_for.into())?;
            }
        };
        // Check if all required props are there
        if opts.validate_schema {
            applied.resource_new.check_required_props(store)?;
        }

        let commit_resource: Resource = commit.into_resource(store)?;

        // Set the `lastCommit` to the newly created Commit
        applied.resource_new.set(
            urls::LAST_COMMIT.to_string(),
            Value::AtomicUrl(commit_resource.get_subject().into()),
            store,
        )?;

        let destroyed = commit.destroy.unwrap_or(false);

        Ok(CommitResponse {
            commit,
            add_atoms: applied.add_atoms,
            remove_atoms: applied.remove_atoms,
            commit_resource,
            resource_new: if destroyed {
                None
            } else {
                Some(applied.resource_new)
            },
            resource_old: if is_new {
                None
            } else {
                Some(applied.resource_old)
            },
        })
    }

    /// Checks if the Commit has been created in the future or if it is expired.
    #[tracing::instrument(skip_all)]
    pub fn validate_timestamp(&self) -> AtomicResult<()> {
        crate::utils::check_timestamp_in_past(self.created_at, ACCEPTABLE_TIME_DIFFERENCE)
    }

    /// Updates the values in the Resource according to the `set`, `remove`, `push`, and `destroy` attributes in the Commit.
    /// Optionally also returns the updated Atoms.
    #[tracing::instrument(skip(store))]
    pub fn apply_changes(
        &self,
        mut resource: Resource,
        store: &impl Storelike,
    ) -> AtomicResult<CommitApplied> {
        let resource_unedited = resource.clone();

        let mut remove_atoms: Vec<Atom> = Vec::new();
        let mut add_atoms: Vec<Atom> = Vec::new();

        if let Some(remove) = self.remove.clone() {
            for prop in remove.iter() {
                resource.remove_propval(prop);

                if let Ok(val) = resource_unedited.get(prop) {
                    let atom = Atom::new(resource.get_subject().clone(), prop.into(), val.clone());
                    remove_atoms.push(atom);
                } else {
                    // The property does not exist, so nothing to remove.
                    //
                    // This may happen if another concurrent commit has removed it first, or
                    // client removed it without validating it exists. (Currently rust and
                    // typescript clients do not validate that.)
                }
            }
        }
        if let Some(set) = self.set.clone() {
            for (prop, new_val) in set.iter() {
                resource
                    .set(prop.into(), new_val.to_owned(), store)
                    .map_err(|e| {
                        format!(
                            "Failed to set property '{}' to '{}' in Commit. Error: {}",
                            prop, new_val, e
                        )
                    })?;

                let new_atom =
                    Atom::new(resource.get_subject().clone(), prop.into(), new_val.clone());
                if let Ok(old_val) = resource_unedited.get(prop) {
                    let old_atom =
                        Atom::new(resource.get_subject().clone(), prop.into(), old_val.clone());
                    remove_atoms.push(old_atom);
                }
                add_atoms.push(new_atom);
            }
        }
        if let Some(push) = self.push.clone() {
            for (prop, vec) in push.iter() {
                let mut old_vec = match resource.get(prop) {
                    Ok(val) => match val {
                        Value::ResourceArray(res_arr) => res_arr.clone(),
                        _other => return Err("Wrong datatype when pushing to array".into()),
                    },
                    Err(_) => Vec::new(),
                };
                let new_vec = match vec {
                    Value::ResourceArray(res_arr) => res_arr.clone(),
                    _other => return Err("Wrong datatype when pushing to array".into()),
                };
                old_vec.append(&mut new_vec.clone());
                resource.set_unsafe(prop.into(), old_vec.into());
                for added_resource in new_vec {
                    let atom = Atom::new(
                        resource.get_subject().clone(),
                        prop.into(),
                        added_resource.into(),
                    );
                    add_atoms.push(atom);
                }
            }
        }
        // Remove all atoms from index if destroy
        if let Some(destroy) = self.destroy {
            if destroy {
                for atom in resource.to_atoms().into_iter() {
                    remove_atoms.push(atom);
                }
            }
        }

        Ok(CommitApplied {
            resource_old: resource_unedited,
            resource_new: resource,
            add_atoms,
            remove_atoms,
        })
    }

    /// Converts a Resource of a Commit into a Commit
    #[tracing::instrument]
    pub fn from_resource(resource: Resource) -> AtomicResult<Commit> {
        let subject = resource.get(urls::SUBJECT)?.to_string();
        let created_at = resource.get(urls::CREATED_AT)?.to_int()?;
        let signer = resource.get(SIGNER)?.to_string();
        let set = match resource.get(SET) {
            Ok(found) => Some(found.to_nested()?.to_owned()),
            Err(_) => None,
        };
        let push = match resource.get(urls::PUSH) {
            Ok(found) => Some(found.to_nested()?.to_owned()),
            Err(_) => None,
        };
        let remove = match resource.get(urls::REMOVE) {
            Ok(found) => Some(found.to_subjects(None)?),
            Err(_) => None,
        };
        let destroy = match resource.get(urls::DESTROY) {
            Ok(found) => Some(found.to_bool()?),
            Err(_) => None,
        };
        let previous_commit = match resource.get(urls::PREVIOUS_COMMIT) {
            Ok(found) => Some(found.to_string()),
            Err(_) => None,
        };
        let signature = resource.get(urls::SIGNATURE)?.to_string();
        let url = Some(resource.get_subject().into());

        Ok(Commit {
            subject,
            created_at,
            signer,
            set,
            push,
            remove,
            destroy,
            previous_commit,
            signature: Some(signature),
            url,
        })
    }

    /// Converts the Commit into a Resource with Atomic Values.
    /// Creates an identifier using the server_url
    /// Works for both Signed and Unsigned Commits
    #[tracing::instrument(skip(store))]
    pub fn into_resource(&self, store: &impl Storelike) -> AtomicResult<Resource> {
        let commit_subject = match self.signature.as_ref() {
            Some(sig) => format!("{}/commits/{}", store.get_server_url(), sig),
            None => {
                let now = crate::utils::now();
                format!("{}/commitsUnsigned/{}", store.get_server_url(), now)
            }
        };
        let mut resource = Resource::new_instance(urls::COMMIT, store)?;
        resource.set_subject(commit_subject);
        resource.set_unsafe(
            urls::SUBJECT.into(),
            Value::new(&self.subject, &DataType::AtomicUrl)?,
        );
        let classes = vec![urls::COMMIT.to_string()];
        resource.set_unsafe(urls::IS_A.into(), classes.into());
        resource.set_unsafe(
            urls::CREATED_AT.into(),
            Value::new(&self.created_at.to_string(), &DataType::Timestamp)?,
        );
        resource.set_unsafe(
            SIGNER.into(),
            Value::new(&self.signer, &DataType::AtomicUrl)?,
        );
        if let Some(set) = &self.set {
            let mut newset = PropVals::new();
            for (prop, val) in set {
                newset.insert(prop.into(), val.clone());
            }
            resource.set_unsafe(urls::SET.into(), newset.into());
        };
        if let Some(remove) = &self.remove {
            if !remove.is_empty() {
                resource.set_unsafe(urls::REMOVE.into(), remove.clone().into());
            }
        };
        if let Some(destroy) = self.destroy {
            if destroy {
                resource.set_unsafe(urls::DESTROY.into(), true.into());
            }
        }
        if let Some(previous_commit) = &self.previous_commit {
            resource.set_unsafe(
                urls::PREVIOUS_COMMIT.into(),
                Value::AtomicUrl(previous_commit.into()),
            );
        }
        resource.set_unsafe(
            SIGNER.into(),
            Value::new(&self.signer, &DataType::AtomicUrl)?,
        );
        if let Some(signature) = &self.signature {
            resource.set_unsafe(urls::SIGNATURE.into(), signature.clone().into());
        }
        if let Some(push) = &self.push {
            if !push.is_empty() {
                resource.set_unsafe(urls::PUSH.into(), push.clone().into());
            }
        }
        Ok(resource)
    }

    pub fn get_subject(&self) -> &str {
        &self.subject
    }

    /// Generates a deterministic serialized JSON-AD representation of the Commit.
    /// Removes the signature from the object before serializing, since this function is used to check if the signature is correct.
    #[tracing::instrument(skip(store))]
    pub fn serialize_deterministically_json_ad(
        &self,
        store: &impl Storelike,
    ) -> AtomicResult<String> {
        let mut commit_resource = self.into_resource(store)?;
        // A deterministic serialization should not contain the hash (signature), since that would influence the hash.
        commit_resource.remove_propval(urls::SIGNATURE);
        let json_obj =
            crate::serialize::propvals_to_json_ad_map(commit_resource.get_propvals(), None)?;
        let json = serde_jcs::to_string(&json_obj)
            .map_err(|e| format!("Failed to serialize Commit: {}", e))?;
        Ok(json)
    }
}

/// Use this for creating Commits.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommitBuilder {
    /// The subject URL that is to be modified by this Delta.
    /// Not the URL of the Commit itself.
    /// https://atomicdata.dev/properties/subject
    subject: String,
    /// The set of PropVals that need to be added.
    /// Overwrites existing values
    /// https://atomicdata.dev/properties/set
    set: std::collections::HashMap<String, Value>,
    /// The set of PropVals that need to be appended to resource arrays.
    push: std::collections::HashMap<String, Value>,
    /// The set of property URLs that need to be removed
    /// https://atomicdata.dev/properties/remove
    remove: HashSet<String>,
    /// If set to true, deletes the entire resource
    /// https://atomicdata.dev/properties/destroy
    destroy: bool,
    // pub signature: String,
    /// The previous Commit that was applied to the target resource (the subject) of this Commit. You should be able to follow these from Commit to Commit to establish an audit trail.
    /// https://atomicdata.dev/properties/previousCommit
    previous_commit: Option<String>,
}

impl CommitBuilder {
    /// Start constructing a Commit.
    pub fn new(subject: String) -> Self {
        CommitBuilder {
            push: HashMap::new(),
            subject,
            set: HashMap::new(),
            remove: HashSet::new(),
            destroy: false,
            previous_commit: None,
        }
    }

    /// Appends a URL or (nested anonymous) Resource to a ResourceArray.
    pub fn push_propval(&mut self, property: &str, value: SubResource) -> AtomicResult<()> {
        let mut vec = match self.push.get(property) {
            Some(val) => match val {
                Value::ResourceArray(resources) => resources.to_owned(),
                other => {
                    return Err(
                        format!("Expected ResourceArray in push_propval, got {}", other).into(),
                    )
                }
            },
            None => Vec::new(),
        };
        vec.push(value);
        self.push.insert(property.into(), Value::ResourceArray(vec));
        Ok(())
    }

    /// Creates the Commit and signs it using a signature.
    /// Does not send it - see [atomic_lib::client::post_commit].
    /// Private key is the base64 encoded pkcs8 for the signer.
    /// Sets the `previousCommit` using the `lastCommit`.
    pub fn sign(
        mut self,
        agent: &crate::agents::Agent,
        store: &impl Storelike,
        resource: &Resource,
    ) -> AtomicResult<Commit> {
        if let Ok(last) = resource.get(urls::LAST_COMMIT) {
            self.previous_commit = Some(last.to_string());
        }

        let now = crate::utils::now();
        sign_at(self, agent, now, store)
    }

    /// Set Property / Value combinations that will either be created or overwritten.
    pub fn set(&mut self, prop: String, val: Value) {
        self.set.insert(prop, val);
    }

    /// Set a new subject for this Commit
    pub fn set_subject(&mut self, subject: String) {
        self.subject = subject;
    }

    /// Set Property URLs which values to be removed
    pub fn remove(&mut self, prop: String) {
        self.remove.insert(prop);
    }

    /// Whether the resource needs to be removed fully
    pub fn destroy(&mut self, destroy: bool) {
        self.destroy = destroy
    }
}

/// Signs a CommitBuilder at a specific unix timestamp.
#[tracing::instrument(skip(store))]
fn sign_at(
    commitbuilder: CommitBuilder,
    agent: &crate::agents::Agent,
    sign_date: i64,
    store: &impl Storelike,
) -> AtomicResult<Commit> {
    let mut commit = Commit {
        subject: commitbuilder.subject,
        signer: agent.subject.clone(),
        set: Some(commitbuilder.set),
        remove: Some(commitbuilder.remove.into_iter().collect()),
        destroy: Some(commitbuilder.destroy),
        created_at: sign_date,
        previous_commit: commitbuilder.previous_commit,
        signature: None,
        push: Some(commitbuilder.push),
        url: None,
    };
    let stringified = commit
        .serialize_deterministically_json_ad(store)
        .map_err(|e| format!("Failed serializing commit: {}", e))?;
    let private_key = agent.private_key.clone().ok_or("No private key in agent")?;
    let signature = sign_message(&stringified, &private_key, &agent.public_key).map_err(|e| {
        format!(
            "Failed to sign message for resource {} with agent {}: {}",
            commit.subject, agent.subject, e
        )
    })?;
    commit.signature = Some(signature);
    Ok(commit)
}

/// Signs a string using a base64 encoded ed25519 private key. Outputs a base64 encoded ed25519 signature.
#[tracing::instrument]
pub fn sign_message(message: &str, private_key: &str, public_key: &str) -> AtomicResult<String> {
    let private_key_bytes = decode_base64(private_key)
        .map_err(|e| format!("Failed decoding private key {}: {}", private_key, e))?;
    let public_key_bytes = decode_base64(public_key)
        .map_err(|e| format!("Failed decoding public key {}: {}", public_key, e))?;
    let key_pair = ring::signature::Ed25519KeyPair::from_seed_and_public_key(
        &private_key_bytes,
        &public_key_bytes,
    )
    .map_err(|_| "Can't create Ed25519 keypair from Agent's Private Key.")?;
    let message_bytes = message.as_bytes();
    let signature = key_pair.sign(message_bytes);
    Ok(encode_base64(signature.as_ref()))
}

/// The amount of milliseconds that a Commit signature is valid for.
const ACCEPTABLE_TIME_DIFFERENCE: i64 = 10000;

#[cfg(test)]
mod test {
    lazy_static::lazy_static! {
        pub static ref OPTS: CommitOpts = CommitOpts {
            validate_schema: true,
            validate_signature: true,
            validate_timestamp: true,
            validate_previous_commit: true,
            validate_rights: false,
            validate_for_agent: None,
            update_index: true,
        };
    }

    use super::*;
    use crate::{agents::Agent, Storelike};

    #[test]
    fn agent_and_commit() {
        let store = crate::Store::init().unwrap();
        store.populate().unwrap();
        let agent = store.create_agent(Some("test_actor")).unwrap();
        let subject = "https://localhost/new_thing";
        let resource = Resource::new(subject.into());
        let mut commitbuiler = crate::commit::CommitBuilder::new(subject.into());
        let property1 = crate::urls::DESCRIPTION;
        let value1 = Value::new("Some value", &DataType::Markdown).unwrap();
        commitbuiler.set(property1.into(), value1.clone());
        let property2 = crate::urls::SHORTNAME;
        let value2 = Value::new("someval", &DataType::Slug).unwrap();
        commitbuiler.set(property2.into(), value2);
        let commit = commitbuiler.sign(&agent, &store, &resource).unwrap();
        let commit_subject = commit.get_subject().to_string();
        let _created_resource = store.apply_commit(commit, &OPTS).unwrap();

        let resource = store.get_resource(subject).unwrap();
        assert!(resource.get(property1).unwrap().to_string() == value1.to_string());
        let found_commit = store.get_resource(&commit_subject).unwrap();
        println!("{}", found_commit.get_subject());

        assert!(
            found_commit
                .get_shortname("description", &store)
                .unwrap()
                .to_string()
                == value1.to_string()
        );
    }

    #[test]
    fn serialize_commit() {
        let store = crate::Store::init().unwrap();
        store.populate().unwrap();
        let mut set: HashMap<String, Value> = HashMap::new();
        let shortname = Value::new("shortname", &DataType::String).unwrap();
        let description = Value::new("Some description", &DataType::String).unwrap();
        set.insert(urls::SHORTNAME.into(), shortname);
        set.insert(urls::DESCRIPTION.into(), description);
        let remove = vec![String::from(urls::IS_A)];
        let destroy = false;
        let commit = Commit {
            subject: String::from("https://localhost/test"),
            created_at: 1603638837,
            signer: String::from("https://localhost/author"),
            set: Some(set),
            push: None,
            remove: Some(remove),
            previous_commit: None,
            destroy: Some(destroy),
            signature: None,
            url: None,
        };
        let serialized = commit.serialize_deterministically_json_ad(&store).unwrap();
        let should_be = "{\"https://atomicdata.dev/properties/createdAt\":1603638837,\"https://atomicdata.dev/properties/isA\":[\"https://atomicdata.dev/classes/Commit\"],\"https://atomicdata.dev/properties/remove\":[\"https://atomicdata.dev/properties/isA\"],\"https://atomicdata.dev/properties/set\":{\"https://atomicdata.dev/properties/description\":\"Some description\",\"https://atomicdata.dev/properties/shortname\":\"shortname\"},\"https://atomicdata.dev/properties/signer\":\"https://localhost/author\",\"https://atomicdata.dev/properties/subject\":\"https://localhost/test\"}";
        assert_eq!(serialized, should_be)
    }

    #[test]
    fn signature_matches() {
        let private_key = "CapMWIhFUT+w7ANv9oCPqrHrwZpkP2JhzF9JnyT6WcI=";
        let store = crate::Store::init().unwrap();
        store.populate().unwrap();
        let agent = Agent::new_from_private_key(None, &store, private_key);
        assert_eq!(
            &agent.subject,
            "local:store/agents/7LsjMW5gOfDdJzK/atgjQ1t20J/rw8MjVg6xwqm+h8U="
        );
        store.add_resource(&agent.to_resource().unwrap()).unwrap();
        let subject = "https://localhost/new_thing";
        let mut commitbuilder = crate::commit::CommitBuilder::new(subject.into());
        let property1 = crate::urls::DESCRIPTION;
        let value1 = Value::new("Some value", &DataType::String).unwrap();
        commitbuilder.set(property1.into(), value1);
        let property2 = crate::urls::SHORTNAME;
        let value2 = Value::new("someval", &DataType::String).unwrap();
        commitbuilder.set(property2.into(), value2);
        let commit = sign_at(commitbuilder, &agent, 0, &store).unwrap();
        let signature = commit.signature.clone().unwrap();
        let serialized = commit.serialize_deterministically_json_ad(&store).unwrap();

        assert_eq!(serialized, "{\"https://atomicdata.dev/properties/createdAt\":0,\"https://atomicdata.dev/properties/isA\":[\"https://atomicdata.dev/classes/Commit\"],\"https://atomicdata.dev/properties/set\":{\"https://atomicdata.dev/properties/description\":\"Some value\",\"https://atomicdata.dev/properties/shortname\":\"someval\"},\"https://atomicdata.dev/properties/signer\":\"local:store/agents/7LsjMW5gOfDdJzK/atgjQ1t20J/rw8MjVg6xwqm+h8U=\",\"https://atomicdata.dev/properties/subject\":\"https://localhost/new_thing\"}");
        assert_eq!(signature, "JOGRyp1NCulc0RNuuNozgIagQPRoZy0Y5+mbSpHY2DKiN3vqUNYLjXbAPYT6Cga6vSG9zztEIa/ZcbQPo7wgBg==");
    }

    #[test]
    fn signature_basics() {
        let private_key = "CapMWIhFUT+w7ANv9oCPqrHrwZpkP2JhzF9JnyT6WcI=";
        let public_key = "7LsjMW5gOfDdJzK/atgjQ1t20J/rw8MjVg6xwqm+h8U=";
        let signature_expected = "YtDR/xo0272LHNBQtDer4LekzdkfUANFTI0eHxZhITXnbC3j0LCqDWhr6itNvo4tFnep6DCbev5OKAHH89+TDA==";
        let message = "val";
        let signature = sign_message(message, private_key, public_key).unwrap();
        assert_eq!(signature, signature_expected);
    }

    #[test]

    fn invalid_subjects() {
        let store = crate::Store::init().unwrap();
        store.populate().unwrap();
        let agent = store.create_agent(Some("test_actor")).unwrap();
        let resource = Resource::new("https://localhost/test_resource".into());

        {
            let subject = "invalid URL";
            let commitbuiler = crate::commit::CommitBuilder::new(subject.into());
            let _ = commitbuiler.sign(&agent, &store, &resource).unwrap_err();
        }
        {
            let subject = "https://localhost/?q=invalid";
            let commitbuiler = crate::commit::CommitBuilder::new(subject.into());
            let commit = commitbuiler.sign(&agent, &store, &resource).unwrap();
            store.apply_commit(commit, &OPTS).unwrap_err();
        }
        {
            let subject = "https://localhost/valid";
            let commitbuiler = crate::commit::CommitBuilder::new(subject.into());
            let commit = commitbuiler.sign(&agent, &store, &resource).unwrap();
            store.apply_commit(commit, &OPTS).unwrap();
        }
    }
}