1use super::{InvokeArgument, InvokeRequest, RemoteActionTarget};
19use crate::InvocationId;
20use serde::{Deserialize, Serialize};
21
22pub const INVOCATION_SIGNATURE_DOMAIN: &[u8] = b"tilo-invocation-v1\0";
24
25pub const INVOCATION_SIGNATURE_TOLERANCE_NS: u64 = 5 * 60 * 1_000_000_000;
30
31pub const MAX_SIGNER_CERT_BYTES: usize = 4 * 1024;
34
35#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct InvocationStatement {
38 pub workspace: String,
40 pub invocation: InvocationId,
41 pub target: RemoteActionTarget,
42 pub arguments: [u8; 32],
44 pub on_behalf_of: Option<InvocationId>,
45 pub issued_at_ns: u64,
47 pub signer: [u8; 32],
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
53pub enum StatementMismatch {
54 #[error("the signed invocation names another workspace")]
55 Workspace,
56 #[error("the signed invocation names another invocation")]
57 Invocation,
58 #[error("the signed invocation names another action")]
59 Target,
60 #[error("the request's arguments are not the ones signed")]
61 Arguments,
62 #[error("the signed invocation continues another invocation")]
63 OnBehalfOf,
64}
65
66impl InvocationStatement {
67 #[must_use]
70 pub fn of(
71 workspace: &str,
72 request: &InvokeRequest,
73 issued_at_ns: u64,
74 signer: [u8; 32],
75 ) -> Self {
76 Self {
77 workspace: workspace.to_owned(),
78 invocation: request.invocation,
79 target: request.target.clone(),
80 arguments: argument_hash(&request.argument),
81 on_behalf_of: request.on_behalf_of,
82 issued_at_ns,
83 signer,
84 }
85 }
86
87 pub fn covers(
94 &self,
95 workspace: &str,
96 request: &InvokeRequest,
97 ) -> Result<(), StatementMismatch> {
98 if self.workspace != workspace {
99 return Err(StatementMismatch::Workspace);
100 }
101 if self.invocation != request.invocation {
102 return Err(StatementMismatch::Invocation);
103 }
104 if self.target != request.target {
105 return Err(StatementMismatch::Target);
106 }
107 if self.arguments != argument_hash(&request.argument) {
108 return Err(StatementMismatch::Arguments);
109 }
110 if self.on_behalf_of != request.on_behalf_of {
111 return Err(StatementMismatch::OnBehalfOf);
112 }
113 Ok(())
114 }
115
116 #[must_use]
119 pub fn signing_message(&self) -> Vec<u8> {
120 let mut message = INVOCATION_SIGNATURE_DOMAIN.to_vec();
121 message.extend_from_slice(blake3::hash(&self.encode()).as_bytes());
122 message
123 }
124
125 #[must_use]
128 pub const fn fresh_at(&self, now_ns: u64) -> bool {
129 self.issued_at_ns.abs_diff(now_ns) <= INVOCATION_SIGNATURE_TOLERANCE_NS
130 }
131
132 fn encode(&self) -> Vec<u8> {
135 fn text(out: &mut Vec<u8>, text: &str) {
136 out.extend_from_slice(&u64::try_from(text.len()).unwrap_or(u64::MAX).to_le_bytes());
137 out.extend_from_slice(text.as_bytes());
138 }
139 let mut out = Vec::with_capacity(256);
140 text(&mut out, &self.workspace);
141 out.extend_from_slice(self.invocation.0.as_bytes());
142 text(&mut out, &self.target.provider);
143 text(&mut out, &self.target.address.resource);
144 text(&mut out, &self.target.address.action);
145 out.extend_from_slice(&self.arguments);
146 match self.on_behalf_of {
147 None => out.push(0),
148 Some(original) => {
149 out.push(1);
150 out.extend_from_slice(original.0.as_bytes());
151 }
152 }
153 out.extend_from_slice(&self.issued_at_ns.to_le_bytes());
154 out.extend_from_slice(&self.signer);
155 out
156 }
157}
158
159#[must_use]
164pub fn argument_hash(argument: &InvokeArgument) -> [u8; 32] {
165 let mut hasher = blake3::Hasher::new();
166 hasher.update(b"tilo-invocation-arguments-v1\0");
167 match argument {
168 InvokeArgument::None => {
169 hasher.update(&[0]);
170 }
171 InvokeArgument::Text(text) => {
172 hasher.update(&[1]);
173 hasher.update(text.as_bytes());
174 }
175 InvokeArgument::Json(object) => {
176 hasher.update(&[2]);
177 tilo_canonical_json::write_object_bytes(object, |chunk| {
178 hasher.update(chunk);
179 });
180 }
181 }
182 *hasher.finalize().as_bytes()
183}
184
185#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(try_from = "SignedWire", into = "SignedWire")]
191pub struct SignedInvocation {
192 statement: InvocationStatement,
193 signature: [u8; 64],
194 signer_cert: Vec<u8>,
195}
196
197impl SignedInvocation {
198 #[must_use]
202 pub const fn new(
203 statement: InvocationStatement,
204 signature: [u8; 64],
205 signer_cert: Vec<u8>,
206 ) -> Self {
207 Self {
208 statement,
209 signature,
210 signer_cert,
211 }
212 }
213
214 #[must_use]
216 pub const fn statement(&self) -> &InvocationStatement {
217 &self.statement
218 }
219
220 #[must_use]
221 pub const fn signature(&self) -> &[u8; 64] {
222 &self.signature
223 }
224
225 #[must_use]
227 pub fn signer_cert(&self) -> &[u8] {
228 &self.signer_cert
229 }
230
231 #[must_use]
235 pub fn serves(&self, request: &InvokeRequest) -> bool {
236 request.on_behalf_of == Some(self.statement.invocation)
237 && request.invocation != self.statement.invocation
238 }
239
240 #[must_use]
243 pub fn called_app(&self) -> Option<(String, String)> {
244 super::application_provider(&self.statement.target.provider)
245 .map(|(workspace, app)| (workspace.to_owned(), app.to_owned()))
246 }
247}
248
249pub const MAX_RECORDED_ARGUMENT_BYTES: usize = crate::context::WHOLE_ACTION_BUDGET;
254
255#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
261pub struct SignedCall {
262 pub signed: SignedInvocation,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub argument: Option<InvokeArgument>,
268 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub allowed: Option<CallAllowed>,
274}
275
276#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(rename_all = "kebab-case")]
280pub enum CallAllowed {
281 Asked(super::asked::RecordRef),
283 Granted(String),
285}
286
287impl CallAllowed {
288 #[must_use]
290 pub fn asked(request: &InvokeRequest) -> Option<Self> {
291 request
292 .approval()
293 .map(|approval| Self::Asked(approval.record.clone()))
294 }
295}
296
297impl SignedCall {
298 #[must_use]
301 pub fn of(request: &InvokeRequest) -> Option<Self> {
302 Some(Self::with(request, request.signed.as_deref()?.clone()))
303 }
304
305 #[must_use]
309 pub fn with(request: &InvokeRequest, signed: SignedInvocation) -> Self {
310 let argument = serde_json::to_vec(&request.argument)
311 .is_ok_and(|encoded| encoded.len() <= MAX_RECORDED_ARGUMENT_BYTES)
312 .then(|| request.argument.clone());
313 Self {
314 signed,
315 argument,
316 allowed: None,
317 }
318 }
319
320 #[must_use]
323 pub fn argument_signed(&self) -> Option<bool> {
324 self.argument
325 .as_ref()
326 .map(|argument| argument_hash(argument) == self.signed.statement.arguments)
327 }
328}
329
330#[derive(Clone, Serialize, Deserialize)]
334#[serde(deny_unknown_fields)]
335struct SignedWire {
336 workspace: String,
337 invocation: InvocationId,
338 target: RemoteActionTarget,
339 arguments: String,
340 on_behalf_of: Option<InvocationId>,
341 issued_at_ns: u64,
342 signer: String,
343 signature: String,
344 signer_cert: String,
345}
346
347impl From<SignedInvocation> for SignedWire {
348 fn from(signed: SignedInvocation) -> Self {
349 let InvocationStatement {
350 workspace,
351 invocation,
352 target,
353 arguments,
354 on_behalf_of,
355 issued_at_ns,
356 signer,
357 } = signed.statement;
358 Self {
359 workspace,
360 invocation,
361 target,
362 arguments: hex::encode(arguments),
363 on_behalf_of,
364 issued_at_ns,
365 signer: hex::encode(signer),
366 signature: hex::encode(signed.signature),
367 signer_cert: hex::encode(signed.signer_cert),
368 }
369 }
370}
371
372impl TryFrom<SignedWire> for SignedInvocation {
373 type Error = String;
374
375 fn try_from(wire: SignedWire) -> Result<Self, Self::Error> {
376 fn bytes<const N: usize>(text: &str, what: &str) -> Result<[u8; N], String> {
377 let mut out = [0; N];
378 hex::decode_to_slice(text, &mut out)
379 .map_err(|_| format!("a signed invocation's {what} is not {N} hex bytes"))?;
380 Ok(out)
381 }
382 if wire.signer_cert.len() > 2 * MAX_SIGNER_CERT_BYTES {
383 return Err("a signed invocation's certificate is too large".into());
384 }
385 let signer_cert = hex::decode(&wire.signer_cert)
386 .map_err(|_| "a signed invocation's certificate is not hex".to_owned())?;
387 Ok(Self {
388 statement: InvocationStatement {
389 workspace: wire.workspace,
390 invocation: wire.invocation,
391 target: wire.target,
392 arguments: bytes(&wire.arguments, "argument hash")?,
393 on_behalf_of: wire.on_behalf_of,
394 issued_at_ns: wire.issued_at_ns,
395 signer: bytes(&wire.signer, "signer")?,
396 },
397 signature: bytes(&wire.signature, "signature")?,
398 signer_cert,
399 })
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406 use crate::ActionAddress;
407
408 fn request(argument: InvokeArgument) -> InvokeRequest {
409 InvokeRequest {
410 invocation: InvocationId::new(),
411 target: RemoteActionTarget {
412 provider: "so.tilo.notes".into(),
413 address: ActionAddress::new("note:1", "rename"),
414 },
415 argument,
416 context: None,
417 confirmation: None,
418 revision: None,
419 on_behalf_of: None,
420 wait_ms: None,
421 appearance: None,
422 signed: None,
423 }
424 }
425
426 fn object(json: &str) -> InvokeArgument {
427 match serde_json::from_str(json).unwrap() {
428 serde_json::Value::Object(object) => InvokeArgument::Json(object),
429 _ => unreachable!(),
430 }
431 }
432
433 #[test]
434 fn arguments_hash_alike_in_any_key_order_and_unlike_once_a_value_changes() {
435 let one = object(r#"{"title":"Plan","tags":["a",{"z":1,"y":2.5}]}"#);
436 let reordered = object(r#"{"tags":["a",{"y":2.5,"z":1}],"title":"Plan"}"#);
437 let changed = object(r#"{"title":"Plan!","tags":["a",{"z":1,"y":2.5}]}"#);
438 assert_eq!(argument_hash(&one), argument_hash(&reordered));
439 assert_ne!(argument_hash(&one), argument_hash(&changed));
440 assert_ne!(
442 argument_hash(&InvokeArgument::Text("{}".into())),
443 argument_hash(&object("{}"))
444 );
445 assert_ne!(
446 argument_hash(&InvokeArgument::None),
447 argument_hash(&InvokeArgument::Text(String::new()))
448 );
449 }
450
451 #[test]
452 fn a_statement_covers_its_request_and_names_the_first_part_another_changes() {
453 let asked = request(object(r#"{"title":"Plan"}"#));
454 let statement = InvocationStatement::of("w1", &asked, 7, [3; 32]);
455 assert_eq!(statement.covers("w1", &asked), Ok(()));
456 assert_eq!(
457 statement.covers("w2", &asked),
458 Err(StatementMismatch::Workspace)
459 );
460 let mut other = asked.clone();
461 other.target.address.action = "delete".into();
462 assert_eq!(
463 statement.covers("w1", &other),
464 Err(StatementMismatch::Target)
465 );
466 let mut other = asked.clone();
467 other.argument = object(r#"{"title":"Other"}"#);
468 assert_eq!(
469 statement.covers("w1", &other),
470 Err(StatementMismatch::Arguments)
471 );
472 let mut other = asked;
473 other.on_behalf_of = Some(InvocationId::new());
474 assert_eq!(
475 statement.covers("w1", &other),
476 Err(StatementMismatch::OnBehalfOf)
477 );
478 let mut later = statement.clone();
480 later.issued_at_ns += 1;
481 assert_ne!(statement.signing_message(), later.signing_message());
482 }
483
484 #[test]
485 fn the_envelope_reads_back_the_same_from_json_and_postcard() {
486 let statement = InvocationStatement::of("w1", &request(InvokeArgument::None), 9, [5; 32]);
487 let signed = SignedInvocation::new(statement, [7; 64], vec![1, 2, 3]);
488 let json = serde_json::to_string(&signed).unwrap();
489 assert_eq!(
490 serde_json::from_str::<SignedInvocation>(&json).unwrap(),
491 signed
492 );
493 let binary = postcard::to_allocvec(&signed).unwrap();
494 assert_eq!(
495 postcard::from_bytes::<SignedInvocation>(&binary).unwrap(),
496 signed
497 );
498 let short = json.replace(&hex::encode([7u8; 64]), "07");
499 assert!(serde_json::from_str::<SignedInvocation>(&short).is_err());
500 }
501
502 const CANONICAL_JSON_CORPUS: &[(&str, &str, &[u8])] = &[
503 (
504 "nested_unsorted",
505 r#"{"z":{"b":2,"a":1},"a":{"d":{"y":true,"x":false},"c":[3,2,1]},"m":0}"#,
506 br#"{"a":{"c":[3,2,1],"d":{"x":false,"y":true}},"m":0,"z":{"a":1,"b":2}}"#,
507 ),
508 (
509 "utf8_vs_utf16_key_order",
510 r#"{"\uD83D\uDE00":4,"\uE000":3,"é":2,"z":1}"#,
511 b"{\"z\":1,\"\xc3\xa9\":2,\"\xee\x80\x80\":3,\"\xf0\x9f\x98\x80\":4}",
512 ),
513 (
514 "non_bmp_vs_bmp_high_key_order",
515 r#"{"\uD83D\uDE80":1,"\uFFFF":2,"\uE000":3}"#,
516 b"{\"\xee\x80\x80\":3,\"\xef\xbf\xbf\":2,\"\xf0\x9f\x9a\x80\":1}",
517 ),
518 (
519 "ascii_empty_prefix_key_order",
520 r#"{"b":1,"":2,"a":3,"ab":4,"B":5,"A":6}"#,
521 br#"{"":2,"A":6,"B":5,"a":3,"ab":4,"b":1}"#,
522 ),
523 (
524 "nested_ten_keys",
525 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}"#,
526 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}"#,
527 ),
528 ("empty_object", "{}", b"{}"),
529 ("empty_array", "[]", b"[]"),
530 ("empty_string", r#""""#, br#""""#),
531 (
532 "line_seps_fffd_and_solidus",
533 r#""\u2028\u2029\ufffd/""#,
534 b"\"\xe2\x80\xa8\xe2\x80\xa9\xef\xbf\xbd/\"",
535 ),
536 (
537 "all_32_control_bytes_value",
538 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""#,
539 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""#,
540 ),
541 (
542 "all_32_control_bytes_key",
543 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}"#,
544 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}"#,
545 ),
546 (
547 "escaped_and_unicode_string",
548 r#""q\"b\\c\u0000\u0001\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u001f\u007f café 日本語 🚀""#,
549 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\"",
550 ),
551 (
552 "escaped_keys_object",
553 r#"{"q\"b\\c\u0000\b\t\n\f\r\u001f\u007f":2,"a":1}"#,
554 b"{\"a\":1,\"q\\\"b\\\\c\\u0000\\b\\t\\n\\f\\r\\u001f\x7f\":2}",
555 ),
556 ("i64_min", "-9223372036854775808", b"-9223372036854775808"),
557 ("i64_max", "9223372036854775807", b"9223372036854775807"),
558 (
559 "u64_above_i64_max",
560 "9223372036854775808",
561 b"9223372036854775808",
562 ),
563 ("u64_max", "18446744073709551615", b"18446744073709551615"),
564 ("zero", "0", b"0"),
565 ("negative_zero", "-0.0", b"-0.0"),
566 ("float_whole", "1.0", b"1.0"),
567 ("float_tenth", "0.1", b"0.1"),
568 ("float_1e20", "1e20", b"1e+20"),
569 ("float_1e21", "1e21", b"1e+21"),
570 ("float_1e_neg5", "1e-5", b"0.00001"),
571 ("float_1e_neg7", "1e-7", b"1e-7"),
572 ("float_min_subnormal", "5e-324", b"5e-324"),
573 (
574 "float_max_finite",
575 "1.7976931348623157e308",
576 b"1.7976931348623157e+308",
577 ),
578 ("float_1e15", "1e15", b"1000000000000000.0"),
579 ("float_0_3_ulp", "0.30000000000000004", b"0.30000000000000004"),
580 ("bool_true", "true", b"true"),
581 ("bool_false", "false", b"false"),
582 ("null", "null", b"null"),
583 (
584 "mixed_array",
585 r#"[null,true,false,0,-1,1.0,0.1,-0.0,"a\"b",[],{},{"b":2,"a":1}]"#,
586 br#"[null,true,false,0,-1,1.0,0.1,-0.0,"a\"b",[],{},{"a":1,"b":2}]"#,
587 ),
588 ];
589
590 #[test]
591 fn argument_hash_pins_canonical_bytes_for_shared_corpus() {
592 const PINNED_NESTED_HASH: [u8; 32] = [
593 0xda, 0x27, 0x10, 0xfd, 0x5e, 0x3c, 0xe4, 0x49, 0x6e, 0xd8, 0xa3, 0x94, 0x16, 0x6e,
594 0x6d, 0x76, 0x7f, 0x43, 0x1b, 0xcd, 0x08, 0x53, 0xc1, 0xb7, 0x1a, 0x7e, 0x10, 0xa9,
595 0x59, 0x37, 0x22, 0x44,
596 ];
597
598 for &(name, input, expected) in CANONICAL_JSON_CORPUS {
599 let value: serde_json::Value = serde_json::from_str(input).unwrap();
600 let (map, expected_bytes) = match value {
601 serde_json::Value::Object(map) => (map, expected.to_vec()),
602 other => {
603 let mut map = serde_json::Map::new();
604 map.insert("v".to_owned(), other);
605 let mut bytes = Vec::with_capacity(expected.len().saturating_add(6));
606 bytes.extend_from_slice(br#"{"v":"#);
607 bytes.extend_from_slice(expected);
608 bytes.push(b'}');
609 (map, bytes)
610 }
611 };
612 let mut hasher = blake3::Hasher::new();
613 hasher.update(b"tilo-invocation-arguments-v1\0");
614 hasher.update(&[2]);
615 hasher.update(&expected_bytes);
616 assert_eq!(
617 argument_hash(&InvokeArgument::Json(map)),
618 *hasher.finalize().as_bytes(),
619 "row {name}"
620 );
621 }
622 assert_eq!(
623 argument_hash(&object(CANONICAL_JSON_CORPUS[0].1)),
624 PINNED_NESTED_HASH
625 );
626 }
627}