tilo-actions 0.5.3

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! One invocation as its caller signed it: who asked for which action, on
//! which resource of which workspace, with which arguments.
//!
//! A host runs an action for a caller; the signature is what makes that
//! claim checkable by anyone, not only by the host that read the caller's
//! connection. The caller's key signs a statement binding the workspace, the
//! invocation id, the target (provider, resource and action), a BLAKE3 hash
//! of the canonical arguments, the invocation it continues
//! ([`InvokeRequest::on_behalf_of`]), the issue time and the signing key. The
//! envelope carries the signer's certificate (with the certificate that
//! issued it, for a key another key minted), so the statement checks against
//! the person's root and their revocations with nothing else at hand.
//!
//! This module holds the statement and its exact bytes. Signing with a device
//! key and checking the certificate are the identity layer's
//! (`tilo_server_protocol::invocation`): this crate sits below it.

use super::{InvokeArgument, InvokeRequest, RemoteActionTarget};
use crate::InvocationId;
use serde::{Deserialize, Serialize};

/// Domain separator for a caller's signature over one invocation.
pub const INVOCATION_SIGNATURE_DOMAIN: &[u8] = b"tilo-invocation-v1\0";

/// How far a signed invocation's issue time may lie from the verifier's
/// clock, either way. Wide enough for a retry after a reconnect and for the
/// clocks of a phone and a server to disagree; an older statement is refused
/// as stale, and within the window the invocation id names the one run.
pub const INVOCATION_SIGNATURE_TOLERANCE_NS: u64 = 5 * 60 * 1_000_000_000;

/// The largest signer certificate an envelope carries: a certificate and
/// its issuer's, with room for long labels.
pub const MAX_SIGNER_CERT_BYTES: usize = 4 * 1024;

/// What the caller's key states about one invocation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InvocationStatement {
    /// The workspace the invocation acts in, as its id's text.
    pub workspace: String,
    pub invocation: InvocationId,
    pub target: RemoteActionTarget,
    /// [`argument_hash`] of the request's argument.
    pub arguments: [u8; 32],
    pub on_behalf_of: Option<InvocationId>,
    /// The signer's clock when it signed, in ns since the epoch.
    pub issued_at_ns: u64,
    /// The key that signs: the one the carried certificate certifies.
    pub signer: [u8; 32],
}

/// Which part of a request its signed statement does not cover.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum StatementMismatch {
    #[error("the signed invocation names another workspace")]
    Workspace,
    #[error("the signed invocation names another invocation")]
    Invocation,
    #[error("the signed invocation names another action")]
    Target,
    #[error("the request's arguments are not the ones signed")]
    Arguments,
    #[error("the signed invocation continues another invocation")]
    OnBehalfOf,
}

impl InvocationStatement {
    /// The statement `signer` makes at `issued_at_ns` about `request` in
    /// `workspace`.
    #[must_use]
    pub fn of(
        workspace: &str,
        request: &InvokeRequest,
        issued_at_ns: u64,
        signer: [u8; 32],
    ) -> Self {
        Self {
            workspace: workspace.to_owned(),
            invocation: request.invocation,
            target: request.target.clone(),
            arguments: argument_hash(&request.argument),
            on_behalf_of: request.on_behalf_of,
            issued_at_ns,
            signer,
        }
    }

    /// Whether this statement covers `request` in `workspace`, and if not,
    /// the first part that differs.
    ///
    /// # Errors
    ///
    /// The [`StatementMismatch`] naming that part.
    pub fn covers(
        &self,
        workspace: &str,
        request: &InvokeRequest,
    ) -> Result<(), StatementMismatch> {
        if self.workspace != workspace {
            return Err(StatementMismatch::Workspace);
        }
        if self.invocation != request.invocation {
            return Err(StatementMismatch::Invocation);
        }
        if self.target != request.target {
            return Err(StatementMismatch::Target);
        }
        if self.arguments != argument_hash(&request.argument) {
            return Err(StatementMismatch::Arguments);
        }
        if self.on_behalf_of != request.on_behalf_of {
            return Err(StatementMismatch::OnBehalfOf);
        }
        Ok(())
    }

    /// This statement over `argument`'s parts hashed under `salt` rather than over the argument
    /// whole: its argument hash the root of the parts ([`super::argument_parts::root`]),
    /// everything else alike. What a caller signs besides its request, so each change the call
    /// writes keeps only the parts it holds and still checks against the caller's signature.
    #[must_use]
    pub fn over_parts(
        mut self,
        argument: &InvokeArgument,
        salt: &super::argument_parts::Salt,
    ) -> Self {
        self.arguments = super::argument_parts::root(argument, salt);
        self
    }

    /// The bytes the signer's key signs: the domain separator and the BLAKE3
    /// hash of the statement's exact encoding.
    #[must_use]
    pub fn signing_message(&self) -> Vec<u8> {
        let mut message = INVOCATION_SIGNATURE_DOMAIN.to_vec();
        message.extend_from_slice(blake3::hash(&self.encode()).as_bytes());
        message
    }

    /// Whether the issue time is within [`INVOCATION_SIGNATURE_TOLERANCE_NS`]
    /// of `now_ns`.
    #[must_use]
    pub const fn fresh_at(&self, now_ns: u64) -> bool {
        self.issued_at_ns.abs_diff(now_ns) <= INVOCATION_SIGNATURE_TOLERANCE_NS
    }

    /// The statement's one encoding: every field in order, each text length
    /// prefixed, so two statements encode alike only when they are alike.
    fn encode(&self) -> Vec<u8> {
        fn text(out: &mut Vec<u8>, text: &str) {
            out.extend_from_slice(&u64::try_from(text.len()).unwrap_or(u64::MAX).to_le_bytes());
            out.extend_from_slice(text.as_bytes());
        }
        let mut out = Vec::with_capacity(256);
        text(&mut out, &self.workspace);
        out.extend_from_slice(self.invocation.0.as_bytes());
        text(&mut out, &self.target.provider);
        text(&mut out, &self.target.address.resource);
        text(&mut out, &self.target.address.action);
        out.extend_from_slice(&self.arguments);
        match self.on_behalf_of {
            None => out.push(0),
            Some(original) => {
                out.push(1);
                out.extend_from_slice(original.0.as_bytes());
            }
        }
        out.extend_from_slice(&self.issued_at_ns.to_le_bytes());
        out.extend_from_slice(&self.signer);
        out
    }
}

/// The BLAKE3 hash of an invocation's argument in its canonical form: a tag
/// for which form it takes, then the text as is, or the argument object as JSON with
/// every object's keys sorted, so the same arguments hash alike however a
/// transport ordered them.
#[must_use]
pub fn argument_hash(argument: &InvokeArgument) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"tilo-invocation-arguments-v1\0");
    match argument {
        InvokeArgument::None => {
            hasher.update(&[0]);
        }
        InvokeArgument::Text(text) => {
            hasher.update(&[1]);
            hasher.update(text.as_bytes());
        }
        InvokeArgument::Json(object) => {
            hasher.update(&[2]);
            tilo_canonical_json::write_object_bytes(object, |chunk| {
                hasher.update(chunk);
            });
        }
    }
    *hasher.finalize().as_bytes()
}

/// An invocation's [`InvocationStatement`], the signer's signature over it,
/// and the signer's certificate. Decoded, it is only what it claims: nothing
/// in it is trusted until the identity layer verified the signature, the
/// certificate, its revocation and its freshness.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "SignedWire", into = "SignedWire")]
pub struct SignedInvocation {
    statement: InvocationStatement,
    signature: [u8; 64],
    signer_cert: Vec<u8>,
}

impl SignedInvocation {
    /// `statement` with the `signature` its signer made over
    /// [`InvocationStatement::signing_message`], and `signer_cert`, the
    /// signer's certificate in its binary encoding.
    #[must_use]
    pub const fn new(
        statement: InvocationStatement,
        signature: [u8; 64],
        signer_cert: Vec<u8>,
    ) -> Self {
        Self {
            statement,
            signature,
            signer_cert,
        }
    }

    /// What the signer claims to have asked. Trust it only once verified.
    #[must_use]
    pub const fn statement(&self) -> &InvocationStatement {
        &self.statement
    }

    #[must_use]
    pub const fn signature(&self) -> &[u8; 64] {
        &self.signature
    }

    /// The signer's certificate in its binary encoding, its issuer's within.
    #[must_use]
    pub fn signer_cert(&self) -> &[u8] {
        &self.signer_cert
    }

    /// Whether this is the invocation `request` serves rather than `request`'s own: a call an
    /// app makes while it runs this invocation names it as what it continues
    /// ([`InvokeRequest::on_behalf_of`]) and carries it as its proof.
    #[must_use]
    pub fn serves(&self, request: &InvokeRequest) -> bool {
        request.on_behalf_of == Some(self.statement.invocation)
            && request.invocation != self.statement.invocation
    }

    /// The workspace and the app the signer called: the app whose process runs this
    /// invocation, and the only one whose calls it proves. `None` where it called no app.
    #[must_use]
    pub fn called_app(&self) -> Option<(String, String)> {
        super::application_provider(&self.statement.target.provider)
            .map(|(workspace, app)| (workspace.to_owned(), app.to_owned()))
    }
}

/// The most of an invocation's argument a change keeps beside its signed
/// invocation, encoded: what the change already documents of its action
/// ([`crate::context::WHOLE_ACTION_BUDGET`]). A larger argument is left out,
/// and the change still says who asked for what.
pub const MAX_RECORDED_ARGUMENT_BYTES: usize = crate::context::WHOLE_ACTION_BUDGET;

/// An invocation as a change a host made for it keeps it: the caller's
/// [`SignedInvocation`] and the argument it signed. The host signs the change
/// as the one who ran it; this is what says who asked for it. A peer that
/// reads the change checks the signature and the certificate, and the
/// argument against the hash under the signature ([`Self::argument_signed`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedCall {
    pub signed: SignedInvocation,
    /// The argument as the caller sent it. `None` when it was larger than
    /// [`MAX_RECORDED_ARGUMENT_BYTES`]: the change then says who asked for
    /// which action, not with what.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub argument: Option<InvokeArgument>,
    /// How the host that carried the call out found it allowed for an agent: the person's yes,
    /// or the lasting grant that let the agent make it unasked. Not under the signature: it is
    /// the host's own word, kept beside the call in a record that host keeps, where the step it
    /// took is one the called action declares. `None` for a call a person made themselves.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowed: Option<CallAllowed>,
    /// The salt the argument's parts are hashed under, in hex, where the statement signs the
    /// root of the argument's parts ([`super::argument_parts`]) rather than one hash of it whole:
    /// a call on its way to the changes it writes, which keeps the whole argument to split.
    /// A change never keeps it: it keeps the call without its argument ([`Self::kept`]) and the
    /// parts it holds itself ([`crate::stamp::Stamp::parts`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub salt: Option<String>,
}

/// How a call an agent made was allowed, as the host that carried it out kept it beside the
/// call ([`SignedCall::allowed`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CallAllowed {
    /// Its person approved this very call: the asked record it was kept as.
    Asked(super::asked::RecordRef),
    /// A lasting grant of the workspace's let the agent make it unasked: the grant, by its id.
    Granted(String),
}

impl CallAllowed {
    /// How `request` was allowed, where its person approved it: the asked record it was kept as.
    #[must_use]
    pub fn asked(request: &InvokeRequest) -> Option<Self> {
        request
            .approval()
            .map(|approval| Self::Asked(approval.record.clone()))
    }
}

impl SignedCall {
    /// What a change made for `request` keeps of it: `None` for a request
    /// nobody signed. Where its caller signed its argument's parts too, the call in that form
    /// ([`Self::of_parts`]), which each change keeps only the parts of that it holds.
    #[must_use]
    pub fn of(request: &InvokeRequest) -> Option<Self> {
        Self::of_parts(request)
            .or_else(|| Some(Self::with(request, request.signed.as_deref()?.clone())))
    }

    /// What a change made for `request` keeps of it, as `signed` signed it: what [`Self::of`]
    /// keeps of a request that carries its signature, and what a host keeps of a call it signed
    /// itself as the device that carried it out.
    #[must_use]
    pub fn with(request: &InvokeRequest, signed: SignedInvocation) -> Self {
        let argument = serde_json::to_vec(&request.argument)
            .is_ok_and(|encoded| encoded.len() <= MAX_RECORDED_ARGUMENT_BYTES)
            .then(|| request.argument.clone());
        Self {
            signed,
            argument,
            allowed: None,
            salt: None,
        }
    }

    /// What the changes a host writes for `request` keep of it, where its caller also signed its
    /// argument's parts ([`Self::signed_over_parts`]): the call in that form, its whole argument and
    /// salt kept to split by what each change holds ([`Self::kept_parts`]). `None` for a request
    /// that carries no such signature, or one that does not cover it.
    #[must_use]
    pub fn of_parts(request: &InvokeRequest) -> Option<Self> {
        let over_parts = request.context.as_ref()?.signed.as_deref()?;
        let whole = request.signed.as_deref()?;
        over_parts
            .carries_parts_of(whole, &request.argument)
            .then(|| Self {
                signed: over_parts.signed.clone(),
                argument: Some(request.argument.clone()),
                allowed: None,
                salt: over_parts.salt.clone(),
            })
    }

    /// The call a caller hands the host beside its request, where it signs its argument's parts
    /// too: `signed`, the statement of its request with the root of the argument's parts hashed
    /// under `salt` ([`InvocationStatement::over_parts`]) and the caller's signature over it.
    /// It rides in the request's context ([`InvokeRequest::context`]), which grants nothing: a
    /// host reads it only as the form the changes it writes keep the call in.
    #[must_use]
    pub fn signed_over_parts(signed: SignedInvocation, salt: &super::argument_parts::Salt) -> Self {
        Self {
            signed,
            argument: None,
            allowed: None,
            salt: Some(hex::encode(salt)),
        }
    }

    /// Whether this is the call over its parts ([`Self::signed_over_parts`]) of `whole`, the request's own
    /// signed invocation, over `argument`: the same statement but for its argument hash, which
    /// is the root of `argument`'s parts under its salt, made under the same certificate. The
    /// signature itself is the identity layer's to check.
    #[must_use]
    pub fn carries_parts_of(&self, whole: &SignedInvocation, argument: &InvokeArgument) -> bool {
        let Some(salt) = self.salt_bytes() else {
            return false;
        };
        let parts = &self.signed.statement;
        self.argument.is_none()
            && self.signed.signer_cert == whole.signer_cert
            && *parts == whole.statement.clone().over_parts(argument, &salt)
    }

    /// The salt the argument's parts are hashed under, where this call carries one.
    fn salt_bytes(&self) -> Option<super::argument_parts::Salt> {
        let mut salt = [0; 32];
        hex::decode_to_slice(self.salt.as_deref()?, &mut salt).ok()?;
        Some(salt)
    }

    /// Whether this is a call on its way to the changes it writes, in the form whose statement
    /// signs its argument's parts: one a change never keeps as it is ([`Self::kept`]).
    #[must_use]
    pub const fn in_flight(&self) -> bool {
        self.salt.is_some()
    }

    /// This call as a change keeps it: in the form whose statement signs the argument's parts,
    /// without its argument or salt; any other as it is.
    #[must_use]
    pub fn kept(&self) -> Self {
        if !self.in_flight() {
            return self.clone();
        }
        Self {
            signed: self.signed.clone(),
            argument: None,
            allowed: self.allowed.clone(),
            salt: None,
        }
    }

    /// The parts of this call's argument a change that holds `held` keeps, with their proof:
    /// `None` for a call whose statement signs its argument whole.
    #[must_use]
    pub fn kept_parts(
        &self,
        held: &super::argument_parts::Held,
    ) -> Option<super::argument_parts::KeptParts> {
        let salt = self.salt_bytes()?;
        let argument = self.argument.as_ref()?;
        Some(super::argument_parts::KeptParts::of(
            argument,
            &salt,
            |value| held.holds(value),
        ))
    }

    /// What a change names this call by when another change of its document's write keeps the
    /// call itself ([`crate::stamp::Stamp::call`]): a BLAKE3 hash of the signed statement, its
    /// signature, the signer's certificate, the kept argument's hash and how the call was
    /// allowed. Two calls share it only when every part a holder reads of them is alike.
    #[must_use]
    pub fn digest(&self) -> [u8; 32] {
        fn bytes(hasher: &mut blake3::Hasher, bytes: &[u8]) {
            hasher.update(&u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_le_bytes());
            hasher.update(bytes);
        }
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"tilo-signed-call-v1\0");
        bytes(&mut hasher, &self.signed.statement.signing_message());
        hasher.update(&self.signed.signature);
        bytes(&mut hasher, &self.signed.signer_cert);
        match &self.argument {
            None => {
                hasher.update(&[0]);
            }
            Some(argument) => {
                hasher.update(&[1]);
                hasher.update(&argument_hash(argument));
            }
        }
        // Enums and strings only: its JSON reads the same however often it is written.
        let allowed = serde_json::to_vec(&self.allowed).unwrap_or_default();
        bytes(&mut hasher, &allowed);
        // A call kept in a change carries no salt: only one on its way there adds it.
        if let Some(salt) = &self.salt {
            bytes(&mut hasher, salt.as_bytes());
        }
        *hasher.finalize().as_bytes()
    }

    /// Whether the kept argument is the one signed: `None` when the change
    /// keeps none to compare.
    #[must_use]
    pub fn argument_signed(&self) -> Option<bool> {
        let argument = self.argument.as_ref()?;
        Some(match self.salt_bytes() {
            Some(salt) => {
                super::argument_parts::root(argument, &salt) == self.signed.statement.arguments
            }
            None if self.salt.is_some() => false,
            None => argument_hash(argument) == self.signed.statement.arguments,
        })
    }
}

/// The envelope on the wire: the statement's fields, the signature and the
/// certificate, the byte strings as lower-case hex so the envelope reads the
/// same in every encoding a frame travels in.
#[derive(Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SignedWire {
    workspace: String,
    invocation: InvocationId,
    target: RemoteActionTarget,
    arguments: String,
    on_behalf_of: Option<InvocationId>,
    issued_at_ns: u64,
    signer: String,
    signature: String,
    signer_cert: String,
}

impl From<SignedInvocation> for SignedWire {
    fn from(signed: SignedInvocation) -> Self {
        let InvocationStatement {
            workspace,
            invocation,
            target,
            arguments,
            on_behalf_of,
            issued_at_ns,
            signer,
        } = signed.statement;
        Self {
            workspace,
            invocation,
            target,
            arguments: hex::encode(arguments),
            on_behalf_of,
            issued_at_ns,
            signer: hex::encode(signer),
            signature: hex::encode(signed.signature),
            signer_cert: hex::encode(signed.signer_cert),
        }
    }
}

impl TryFrom<SignedWire> for SignedInvocation {
    type Error = String;

    fn try_from(wire: SignedWire) -> Result<Self, Self::Error> {
        fn bytes<const N: usize>(text: &str, what: &str) -> Result<[u8; N], String> {
            let mut out = [0; N];
            hex::decode_to_slice(text, &mut out)
                .map_err(|_| format!("a signed invocation's {what} is not {N} hex bytes"))?;
            Ok(out)
        }
        if wire.signer_cert.len() > 2 * MAX_SIGNER_CERT_BYTES {
            return Err("a signed invocation's certificate is too large".into());
        }
        let signer_cert = hex::decode(&wire.signer_cert)
            .map_err(|_| "a signed invocation's certificate is not hex".to_owned())?;
        Ok(Self {
            statement: InvocationStatement {
                workspace: wire.workspace,
                invocation: wire.invocation,
                target: wire.target,
                arguments: bytes(&wire.arguments, "argument hash")?,
                on_behalf_of: wire.on_behalf_of,
                issued_at_ns: wire.issued_at_ns,
                signer: bytes(&wire.signer, "signer")?,
            },
            signature: bytes(&wire.signature, "signature")?,
            signer_cert,
        })
    }
}

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

    fn request(argument: InvokeArgument) -> InvokeRequest {
        InvokeRequest {
            asks: false,
            invocation: InvocationId::new(),
            target: RemoteActionTarget {
                provider: "so.tilo.notes".into(),
                address: ActionAddress::new("note:1", "rename"),
            },
            argument,
            context: None,
            confirmation: None,
            revision: None,
            on_behalf_of: None,
            wait_ms: None,
            appearance: None,
            signed: None,
        }
    }

    fn object(json: &str) -> InvokeArgument {
        match serde_json::from_str(json).unwrap() {
            serde_json::Value::Object(object) => InvokeArgument::Json(object),
            _ => unreachable!(),
        }
    }

    #[test]
    fn arguments_hash_alike_in_any_key_order_and_unlike_once_a_value_changes() {
        let one = object(r#"{"title":"Plan","tags":["a",{"z":1,"y":2.5}]}"#);
        let reordered = object(r#"{"tags":["a",{"y":2.5,"z":1}],"title":"Plan"}"#);
        let changed = object(r#"{"title":"Plan!","tags":["a",{"z":1,"y":2.5}]}"#);
        assert_eq!(argument_hash(&one), argument_hash(&reordered));
        assert_ne!(argument_hash(&one), argument_hash(&changed));
        // A text and an object with the same characters are not one argument.
        assert_ne!(
            argument_hash(&InvokeArgument::Text("{}".into())),
            argument_hash(&object("{}"))
        );
        assert_ne!(
            argument_hash(&InvokeArgument::None),
            argument_hash(&InvokeArgument::Text(String::new()))
        );
    }

    #[test]
    fn a_statement_covers_its_request_and_names_the_first_part_another_changes() {
        let asked = request(object(r#"{"title":"Plan"}"#));
        let statement = InvocationStatement::of("w1", &asked, 7, [3; 32]);
        assert_eq!(statement.covers("w1", &asked), Ok(()));
        assert_eq!(
            statement.covers("w2", &asked),
            Err(StatementMismatch::Workspace)
        );
        let mut other = asked.clone();
        other.target.address.action = "delete".into();
        assert_eq!(
            statement.covers("w1", &other),
            Err(StatementMismatch::Target)
        );
        let mut other = asked.clone();
        other.argument = object(r#"{"title":"Other"}"#);
        assert_eq!(
            statement.covers("w1", &other),
            Err(StatementMismatch::Arguments)
        );
        let mut other = asked;
        other.on_behalf_of = Some(InvocationId::new());
        assert_eq!(
            statement.covers("w1", &other),
            Err(StatementMismatch::OnBehalfOf)
        );
        // Each field reaches the signed bytes.
        let mut later = statement.clone();
        later.issued_at_ns += 1;
        assert_ne!(statement.signing_message(), later.signing_message());
    }

    #[test]
    fn the_envelope_reads_back_the_same_from_json_and_postcard() {
        let statement = InvocationStatement::of("w1", &request(InvokeArgument::None), 9, [5; 32]);
        let signed = SignedInvocation::new(statement, [7; 64], vec![1, 2, 3]);
        let json = serde_json::to_string(&signed).unwrap();
        assert_eq!(
            serde_json::from_str::<SignedInvocation>(&json).unwrap(),
            signed
        );
        let binary = postcard::to_allocvec(&signed).unwrap();
        assert_eq!(
            postcard::from_bytes::<SignedInvocation>(&binary).unwrap(),
            signed
        );
        let short = json.replace(&hex::encode([7u8; 64]), "07");
        assert!(serde_json::from_str::<SignedInvocation>(&short).is_err());
    }

    const CANONICAL_JSON_CORPUS: &[(&str, &str, &[u8])] = &[
        (
            "nested_unsorted",
            r#"{"z":{"b":2,"a":1},"a":{"d":{"y":true,"x":false},"c":[3,2,1]},"m":0}"#,
            br#"{"a":{"c":[3,2,1],"d":{"x":false,"y":true}},"m":0,"z":{"a":1,"b":2}}"#,
        ),
        (
            "utf8_vs_utf16_key_order",
            r#"{"\uD83D\uDE00":4,"\uE000":3,"é":2,"z":1}"#,
            b"{\"z\":1,\"\xc3\xa9\":2,\"\xee\x80\x80\":3,\"\xf0\x9f\x98\x80\":4}",
        ),
        (
            "non_bmp_vs_bmp_high_key_order",
            r#"{"\uD83D\uDE80":1,"\uFFFF":2,"\uE000":3}"#,
            b"{\"\xee\x80\x80\":3,\"\xef\xbf\xbf\":2,\"\xf0\x9f\x9a\x80\":1}",
        ),
        (
            "ascii_empty_prefix_key_order",
            r#"{"b":1,"":2,"a":3,"ab":4,"B":5,"A":6}"#,
            br#"{"":2,"A":6,"B":5,"a":3,"ab":4,"b":1}"#,
        ),
        (
            "nested_ten_keys",
            r#"{"k9":9,"k8":8,"k7":{"j9":9,"j8":8,"j7":7,"j6":6,"j5":5,"j4":4,"j3":3,"j2":2,"j1":1,"j0":0},"k6":6,"k5":5,"k4":4,"k3":3,"k2":2,"k1":1,"k0":0}"#,
            br#"{"k0":0,"k1":1,"k2":2,"k3":3,"k4":4,"k5":5,"k6":6,"k7":{"j0":0,"j1":1,"j2":2,"j3":3,"j4":4,"j5":5,"j6":6,"j7":7,"j8":8,"j9":9},"k8":8,"k9":9}"#,
        ),
        ("empty_object", "{}", b"{}"),
        ("empty_array", "[]", b"[]"),
        ("empty_string", r#""""#, br#""""#),
        (
            "line_seps_fffd_and_solidus",
            r#""\u2028\u2029\ufffd/""#,
            b"\"\xe2\x80\xa8\xe2\x80\xa9\xef\xbf\xbd/\"",
        ),
        (
            "all_32_control_bytes_value",
            r#""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f""#,
            br#""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f""#,
        ),
        (
            "all_32_control_bytes_key",
            r#"{"a":2,"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f":1}"#,
            br#"{"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f":1,"a":2}"#,
        ),
        (
            "escaped_and_unicode_string",
            r#""q\"b\\c\u0000\u0001\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u001f\u007f café 日本語 🚀""#,
            b"\"q\\\"b\\\\c\\u0000\\u0001\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u001f\x7f caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xf0\x9f\x9a\x80\"",
        ),
        (
            "escaped_keys_object",
            r#"{"q\"b\\c\u0000\b\t\n\f\r\u001f\u007f":2,"a":1}"#,
            b"{\"a\":1,\"q\\\"b\\\\c\\u0000\\b\\t\\n\\f\\r\\u001f\x7f\":2}",
        ),
        ("i64_min", "-9223372036854775808", b"-9223372036854775808"),
        ("i64_max", "9223372036854775807", b"9223372036854775807"),
        (
            "u64_above_i64_max",
            "9223372036854775808",
            b"9223372036854775808",
        ),
        ("u64_max", "18446744073709551615", b"18446744073709551615"),
        ("zero", "0", b"0"),
        ("negative_zero", "-0.0", b"-0.0"),
        ("float_whole", "1.0", b"1.0"),
        ("float_tenth", "0.1", b"0.1"),
        ("float_1e20", "1e20", b"1e+20"),
        ("float_1e21", "1e21", b"1e+21"),
        ("float_1e_neg5", "1e-5", b"0.00001"),
        ("float_1e_neg7", "1e-7", b"1e-7"),
        ("float_min_subnormal", "5e-324", b"5e-324"),
        (
            "float_max_finite",
            "1.7976931348623157e308",
            b"1.7976931348623157e+308",
        ),
        ("float_1e15", "1e15", b"1000000000000000.0"),
        ("float_0_3_ulp", "0.30000000000000004", b"0.30000000000000004"),
        ("bool_true", "true", b"true"),
        ("bool_false", "false", b"false"),
        ("null", "null", b"null"),
        (
            "mixed_array",
            r#"[null,true,false,0,-1,1.0,0.1,-0.0,"a\"b",[],{},{"b":2,"a":1}]"#,
            br#"[null,true,false,0,-1,1.0,0.1,-0.0,"a\"b",[],{},{"a":1,"b":2}]"#,
        ),
    ];

    #[test]
    fn argument_hash_pins_canonical_bytes_for_shared_corpus() {
        const PINNED_NESTED_HASH: [u8; 32] = [
            0xda, 0x27, 0x10, 0xfd, 0x5e, 0x3c, 0xe4, 0x49, 0x6e, 0xd8, 0xa3, 0x94, 0x16, 0x6e,
            0x6d, 0x76, 0x7f, 0x43, 0x1b, 0xcd, 0x08, 0x53, 0xc1, 0xb7, 0x1a, 0x7e, 0x10, 0xa9,
            0x59, 0x37, 0x22, 0x44,
        ];

        for &(name, input, expected) in CANONICAL_JSON_CORPUS {
            let value: serde_json::Value = serde_json::from_str(input).unwrap();
            let (map, expected_bytes) = match value {
                serde_json::Value::Object(map) => (map, expected.to_vec()),
                other => {
                    let mut map = serde_json::Map::new();
                    map.insert("v".to_owned(), other);
                    let mut bytes = Vec::with_capacity(expected.len().saturating_add(6));
                    bytes.extend_from_slice(br#"{"v":"#);
                    bytes.extend_from_slice(expected);
                    bytes.push(b'}');
                    (map, bytes)
                }
            };
            let mut hasher = blake3::Hasher::new();
            hasher.update(b"tilo-invocation-arguments-v1\0");
            hasher.update(&[2]);
            hasher.update(&expected_bytes);
            assert_eq!(
                argument_hash(&InvokeArgument::Json(map)),
                *hasher.finalize().as_bytes(),
                "row {name}"
            );
        }
        assert_eq!(
            argument_hash(&object(CANONICAL_JSON_CORPUS[0].1)),
            PINNED_NESTED_HASH
        );
    }

    /// A call that writes many records keeps itself once, in its first change, and every other
    /// change names it by digest: read back through the change messages, the named one is the
    /// call whole; a change whose call is not kept with it, or not the one it names, is refused.
    #[test]
    fn a_call_named_by_digest_reads_back_whole_and_a_tampered_or_missing_one_is_refused() {
        use crate::stamp::{CallUnresolved, KeptCalls, Stamp};
        let asked = request(object(r#"{"titles":["one","two"]}"#));
        let statement = InvocationStatement::of("w1", &asked, 9, [5; 32]);
        let call = SignedCall::with(
            &asked,
            SignedInvocation::new(statement, [7; 64], vec![1; 64]),
        );
        let stamped = |kept: bool| {
            let mut stamp = Stamp {
                verb: "new_tasks".into(),
                invoker: "person".into(),
                signed: Some(Box::new(call.clone())),
                args: vec![serde_json::json!(["one", "two"])],
                ..Stamp::default()
            };
            stamp.name_call(kept);
            stamp.message()
        };
        let (first, later) = (stamped(false), stamped(true));
        assert!(
            later.len() < first.len() / 2,
            "{} of {}",
            later.len(),
            first.len()
        );

        // Unchanged, the digest verifies: the later change reads the call its write keeps.
        let calls = KeptCalls::of_messages([first.as_str(), later.as_str()]);
        let mut read = Stamp::of_message(&later).unwrap();
        assert_eq!(read.resolve(&calls), Ok(()));
        assert_eq!(read.signed.as_deref(), Some(&call));
        assert_eq!(read.args, [serde_json::json!(["one", "two"])]);
        let mut carrier = Stamp::of_message(&first).unwrap();
        assert_eq!(carrier.resolve(&calls), Ok(()));

        // Read without the change that keeps it, the call is missing.
        let mut alone = Stamp::of_message(&later).unwrap();
        assert_eq!(
            alone.resolve(&KeptCalls::default()),
            Err(CallUnresolved::Missing)
        );

        // A carrier whose call was changed keeps none under the digest it names, and itself
        // keeps another call than the one it names.
        let mut forged = Stamp::of_message(&first).unwrap();
        forged.signed.as_mut().unwrap().argument = Some(object(r#"{"titles":["other"]}"#));
        let calls = KeptCalls::of_messages([forged.message().as_str()]);
        assert!(calls.is_empty());
        let mut read = Stamp::of_message(&later).unwrap();
        assert_eq!(read.resolve(&calls), Err(CallUnresolved::Missing));
        assert_eq!(forged.resolve(&calls), Err(CallUnresolved::Mismatch));

        // A change that names its call keeps no arguments of its own.
        let calls = KeptCalls::of_messages([first.as_str()]);
        let mut reargued = Stamp::of_message(&later).unwrap();
        reargued.args = vec![serde_json::json!(["other"])];
        assert_eq!(reargued.resolve(&calls), Err(CallUnresolved::Mismatch));

        // A change naming another digest finds no call, even beside the real one.
        let mut renamed = Stamp::of_message(&later).unwrap();
        renamed.call = Some(hex::encode([0u8; 32]));
        let calls = KeptCalls::of_messages([first.as_str()]);
        assert_eq!(renamed.resolve(&calls), Err(CallUnresolved::Missing));
    }
}