1use std::cmp::Ordering;
4
5use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9mod proof;
10mod strict_json;
11
12pub use proof::{
13 canonicalize_proof_value, child_proof_message, handshake_params_digest, host_proof_message,
14};
15pub use strict_json::{decode_strict, encode_compact};
16
17pub const PROCESS_PROFILE: &str = "lenso-process-jsonrpc-http-v1";
19pub const VALUE_PROFILE: &str = "lenso-json-value-v1";
21pub const PROVIDE_REQUEST_PROFILE: &str = "provide-request-v1";
23pub const HANDSHAKE_METHOD: &str = "lenso.process.v1.handshake";
25pub const REQUEST_METHOD: &str = "lenso.process.v1.request";
27pub const CANCEL_METHOD: &str = "lenso.process.v1.cancel";
29pub const SHUTDOWN_METHOD: &str = "lenso.process.v1.shutdown";
31
32#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct ReadinessRecord {
36 pub protocol: String,
38 pub data_port: u16,
40 pub control_port: u16,
42}
43
44impl ReadinessRecord {
45 pub fn validate(&self) -> Result<(), ProtocolError> {
47 if self.protocol != PROCESS_PROFILE {
48 return Err(ProtocolError::new("unsupported Process Protocol profile"));
49 }
50 if self.data_port == 0 || self.control_port == 0 || self.data_port == self.control_port {
51 return Err(ProtocolError::new(
52 "readiness requires distinct non-zero data and control ports",
53 ));
54 }
55 Ok(())
56 }
57}
58
59#[derive(Clone, Debug, Eq, PartialEq)]
61pub struct ProtocolError {
62 detail: String,
63}
64
65impl ProtocolError {
66 fn new(detail: impl Into<String>) -> Self {
67 Self {
68 detail: detail.into(),
69 }
70 }
71
72 #[must_use]
74 pub fn detail(&self) -> &str {
75 &self.detail
76 }
77}
78
79impl std::fmt::Display for ProtocolError {
80 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 formatter.write_str(&self.detail)
82 }
83}
84
85impl std::error::Error for ProtocolError {}
86
87#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct PeerLimits {
91 pub max_http_body_bytes: u64,
93 pub max_control_http_body_bytes: u64,
95 pub max_concurrent_requests: u32,
97 pub child_request_queue_capacity: u32,
99 pub max_retired_correlation_ids: u32,
101 pub control_queue_capacity: u32,
103}
104
105impl PeerLimits {
106 #[must_use]
108 pub const fn v1_defaults() -> Self {
109 Self {
110 max_http_body_bytes: 65_536,
111 max_control_http_body_bytes: 16_384,
112 max_concurrent_requests: 32,
113 child_request_queue_capacity: 32,
114 max_retired_correlation_ids: 65_536,
115 control_queue_capacity: 32,
116 }
117 }
118
119 pub fn validate(&self) -> Result<(), ProtocolError> {
121 validate_limit("max_http_body_bytes", self.max_http_body_bytes, 1_048_576)?;
122 validate_limit(
123 "max_control_http_body_bytes",
124 self.max_control_http_body_bytes,
125 65_536,
126 )?;
127 validate_limit(
128 "max_concurrent_requests",
129 u64::from(self.max_concurrent_requests),
130 256,
131 )?;
132 validate_limit(
133 "child_request_queue_capacity",
134 u64::from(self.child_request_queue_capacity),
135 1_024,
136 )?;
137 validate_limit(
138 "max_retired_correlation_ids",
139 u64::from(self.max_retired_correlation_ids),
140 1_048_576,
141 )?;
142 validate_limit(
143 "control_queue_capacity",
144 u64::from(self.control_queue_capacity),
145 256,
146 )
147 }
148}
149
150#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
152#[serde(deny_unknown_fields)]
153pub struct OperationDescriptor {
154 pub operation: String,
156 pub interaction: InteractionKind,
158}
159
160#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
162#[serde(rename_all = "snake_case")]
163pub enum InteractionKind {
164 Request,
166}
167
168#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
170#[serde(deny_unknown_fields)]
171pub struct CapabilityDescriptor {
172 pub capability_id: String,
174 pub descriptor_version: String,
176 pub descriptor_digest: String,
178 pub operations: Vec<OperationDescriptor>,
180}
181
182#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
184#[serde(deny_unknown_fields)]
185pub struct OutboundBindingDescriptor {
186 pub binding_id: String,
188 pub capability_id: String,
190 pub descriptor_version: String,
192 pub descriptor_digest: String,
194 pub provider_instance: String,
196}
197
198#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
200#[serde(deny_unknown_fields)]
201pub struct HandshakeIdentity {
202 pub protocol_profile: String,
204 pub value_profile: String,
206 pub module_instance: String,
208 pub module_generation: String,
210 pub generation_spec_digest: String,
212 pub artifact_digest: String,
214 pub effective_host_grant_set_digest: String,
216 pub interaction_profiles: Vec<String>,
218 pub provided_capabilities: Vec<CapabilityDescriptor>,
220 pub outbound_bindings: Vec<OutboundBindingDescriptor>,
222 pub peer_limits: PeerLimits,
224}
225
226#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
228#[serde(deny_unknown_fields)]
229pub struct HandshakeParams {
230 pub identity: HandshakeIdentity,
232 pub host_nonce: String,
234 pub host_proof: String,
236}
237
238#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
240#[serde(deny_unknown_fields)]
241pub struct HandshakeResult {
242 pub identity: HandshakeIdentity,
244 pub session: String,
246 pub child_proof: String,
248}
249
250#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
252#[serde(deny_unknown_fields)]
253pub struct InvocationExtension {
254 pub key: String,
256 pub value: String,
258 #[serde(skip_serializing_if = "Option::is_none")]
260 pub issuer: Option<String>,
261 #[serde(default, skip_serializing_if = "Vec::is_empty")]
263 pub audience: Vec<String>,
264 #[serde(skip_serializing_if = "Option::is_none")]
266 pub proof: Option<String>,
267 #[serde(default, skip_serializing_if = "is_false")]
269 pub sealed: bool,
270}
271
272#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
274#[serde(deny_unknown_fields)]
275pub struct RequestParams {
276 pub session: String,
278 pub correlation_id: String,
280 pub capability_id: String,
282 pub descriptor_version: String,
284 pub descriptor_digest: String,
286 pub operation: String,
288 pub interaction: InteractionKind,
290 pub caller_instance: Option<String>,
292 pub remaining_timeout_nanos: Option<String>,
294 #[serde(default)]
296 pub extensions: Vec<InvocationExtension>,
297 pub payload: Value,
299}
300
301#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
303#[serde(deny_unknown_fields)]
304pub struct RequestResult {
305 pub session: String,
307 pub correlation_id: String,
309 pub outcome: ProcessOutcome,
311}
312
313#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
315#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
316pub enum ProcessOutcome {
317 Success { value: Value },
319 Domain { error: Value },
321 Runtime { failure: ChildRuntimeFailure },
323}
324
325#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
327#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
328pub enum ChildRuntimeFailure {
329 ResourceExhausted { operation: String },
331 ModuleFailure { detail: String },
333}
334
335#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
337#[serde(deny_unknown_fields)]
338pub struct CancelParams {
339 pub session: String,
341 pub correlation_id: String,
343}
344
345#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
347#[serde(deny_unknown_fields)]
348pub struct ShutdownParams {
349 pub session: String,
351}
352
353#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
355#[serde(deny_unknown_fields)]
356pub struct ControlAck {
357 pub session: String,
359 pub accepted: bool,
361}
362
363#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
365#[serde(deny_unknown_fields)]
366pub struct JsonRpcRequest<T> {
367 pub jsonrpc: String,
369 pub id: String,
371 pub method: String,
373 pub params: T,
375}
376
377#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
379#[serde(deny_unknown_fields)]
380pub struct JsonRpcSuccess<T> {
381 pub jsonrpc: String,
383 pub id: String,
385 pub result: T,
387}
388
389#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
391#[serde(deny_unknown_fields)]
392pub struct JsonRpcErrorObject {
393 pub code: i32,
395 pub message: String,
397}
398
399#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
401#[serde(deny_unknown_fields)]
402pub struct JsonRpcError {
403 pub jsonrpc: String,
405 pub id: Option<String>,
407 pub error: JsonRpcErrorObject,
409}
410
411impl HandshakeIdentity {
412 pub fn validate(&self) -> Result<(), ProtocolError> {
414 if self.protocol_profile != PROCESS_PROFILE {
415 return Err(ProtocolError::new("unsupported Process Protocol profile"));
416 }
417 if self.value_profile != VALUE_PROFILE {
418 return Err(ProtocolError::new("unsupported portable value profile"));
419 }
420 validate_token("module_instance", &self.module_instance)?;
421 validate_decimal("module_generation", &self.module_generation)?;
422 validate_digest("generation_spec_digest", &self.generation_spec_digest)?;
423 validate_digest("artifact_digest", &self.artifact_digest)?;
424 validate_digest(
425 "effective_host_grant_set_digest",
426 &self.effective_host_grant_set_digest,
427 )?;
428 validate_sorted_unique("interaction_profiles", &self.interaction_profiles, Ord::cmp)?;
429 if self.interaction_profiles.as_slice() != [PROVIDE_REQUEST_PROFILE] {
430 return Err(ProtocolError::new(
431 "V1 requires exactly the provide-request-v1 interaction profile",
432 ));
433 }
434 validate_sorted_unique(
435 "provided_capabilities",
436 &self.provided_capabilities,
437 |left, right| left.capability_id.cmp(&right.capability_id),
438 )?;
439 if self.provided_capabilities.is_empty() {
440 return Err(ProtocolError::new(
441 "at least one provided Capability is required",
442 ));
443 }
444 for descriptor in &self.provided_capabilities {
445 descriptor.validate()?;
446 }
447 if !self.outbound_bindings.is_empty() {
448 return Err(ProtocolError::new(
449 "outbound bindings require a selected consume profile",
450 ));
451 }
452 self.peer_limits.validate()
453 }
454}
455
456impl CapabilityDescriptor {
457 fn validate(&self) -> Result<(), ProtocolError> {
458 validate_token("capability_id", &self.capability_id)?;
459 validate_token("descriptor_version", &self.descriptor_version)?;
460 validate_digest("descriptor_digest", &self.descriptor_digest)?;
461 validate_sorted_unique("operations", &self.operations, |left, right| {
462 left.operation.cmp(&right.operation)
463 })?;
464 if self.operations.is_empty() {
465 return Err(ProtocolError::new(
466 "provided Capability operations cannot be empty",
467 ));
468 }
469 for operation in &self.operations {
470 validate_token("operation", &operation.operation)?;
471 }
472 Ok(())
473 }
474}
475
476impl HandshakeParams {
477 pub fn validate(&self) -> Result<(), ProtocolError> {
479 self.identity.validate()?;
480 decode_base64url_32("host_nonce", &self.host_nonce)?;
481 decode_base64url_32("host_proof", &self.host_proof)?;
482 Ok(())
483 }
484}
485
486impl HandshakeResult {
487 pub fn validate_against(&self, expected: &HandshakeIdentity) -> Result<(), ProtocolError> {
489 self.identity.validate()?;
490 if &self.identity != expected {
491 return Err(ProtocolError::new("child handshake identity mismatch"));
492 }
493 decode_base64url_32("session", &self.session)?;
494 decode_base64url_32("child_proof", &self.child_proof)?;
495 Ok(())
496 }
497}
498
499impl RequestParams {
500 pub fn validate(&self) -> Result<(), ProtocolError> {
502 decode_base64url_32("session", &self.session)?;
503 validate_decimal("correlation_id", &self.correlation_id)?;
504 validate_token("capability_id", &self.capability_id)?;
505 validate_token("descriptor_version", &self.descriptor_version)?;
506 validate_digest("descriptor_digest", &self.descriptor_digest)?;
507 validate_token("operation", &self.operation)?;
508 if let Some(caller) = &self.caller_instance {
509 validate_token("caller_instance", caller)?;
510 }
511 if let Some(timeout) = &self.remaining_timeout_nanos {
512 validate_decimal("remaining_timeout_nanos", timeout)?;
513 }
514 validate_sorted_unique("extensions", &self.extensions, |left, right| {
515 left.key.cmp(&right.key)
516 })?;
517 for extension in &self.extensions {
518 extension.validate()?;
519 }
520 Ok(())
521 }
522}
523
524impl InvocationExtension {
525 fn validate(&self) -> Result<(), ProtocolError> {
526 validate_token("extension key", &self.key)?;
527 let decoded = base64::engine::general_purpose::STANDARD
528 .decode(&self.value)
529 .map_err(|_| ProtocolError::new("extension value must be padded Base64"))?;
530 if base64::engine::general_purpose::STANDARD.encode(decoded) != self.value {
531 return Err(ProtocolError::new(
532 "extension value must use canonical padded Base64",
533 ));
534 }
535 validate_sorted_unique("extension audience", &self.audience, |left, right| {
536 left.cmp(right)
537 })?;
538 Ok(())
539 }
540}
541
542impl RequestResult {
543 pub fn validate(&self) -> Result<(), ProtocolError> {
545 decode_base64url_32("session", &self.session)?;
546 validate_decimal("correlation_id", &self.correlation_id)?;
547 if let ProcessOutcome::Runtime { failure } = &self.outcome {
548 match failure {
549 ChildRuntimeFailure::ResourceExhausted { operation } => {
550 validate_token("operation", operation)?;
551 }
552 ChildRuntimeFailure::ModuleFailure { detail } => {
553 if detail.is_empty() || detail.len() > 1_024 {
554 return Err(ProtocolError::new(
555 "Module Failure detail must contain 1..=1024 bytes",
556 ));
557 }
558 }
559 }
560 }
561 Ok(())
562 }
563}
564
565impl CancelParams {
566 pub fn validate(&self) -> Result<(), ProtocolError> {
568 decode_base64url_32("session", &self.session)?;
569 validate_decimal("correlation_id", &self.correlation_id).map(|_| ())
570 }
571}
572
573impl ShutdownParams {
574 pub fn validate(&self) -> Result<(), ProtocolError> {
576 decode_base64url_32("session", &self.session)?;
577 Ok(())
578 }
579}
580
581impl ControlAck {
582 pub fn validate(&self) -> Result<(), ProtocolError> {
584 decode_base64url_32("session", &self.session)?;
585 if !self.accepted {
586 return Err(ProtocolError::new(
587 "control acknowledgement must be accepted",
588 ));
589 }
590 Ok(())
591 }
592}
593
594impl<T> JsonRpcRequest<T> {
595 pub fn validate_envelope(&self, expected_method: &str) -> Result<(), ProtocolError> {
597 if self.jsonrpc != "2.0" {
598 return Err(ProtocolError::new("jsonrpc must equal 2.0"));
599 }
600 validate_decimal("JSON-RPC id", &self.id)?;
601 if self.method != expected_method {
602 return Err(ProtocolError::new("unexpected JSON-RPC method"));
603 }
604 Ok(())
605 }
606}
607
608impl<T> JsonRpcSuccess<T> {
609 pub fn validate_envelope(&self, expected_id: &str) -> Result<(), ProtocolError> {
611 if self.jsonrpc != "2.0" {
612 return Err(ProtocolError::new("jsonrpc must equal 2.0"));
613 }
614 validate_decimal("JSON-RPC id", &self.id)?;
615 if self.id != expected_id {
616 return Err(ProtocolError::new("JSON-RPC response id mismatch"));
617 }
618 Ok(())
619 }
620}
621
622impl JsonRpcError {
623 pub fn validate(&self) -> Result<(), ProtocolError> {
625 if self.jsonrpc != "2.0" {
626 return Err(ProtocolError::new("jsonrpc must equal 2.0"));
627 }
628 if let Some(id) = &self.id {
629 validate_decimal("JSON-RPC id", id)?;
630 }
631 if !matches!(self.error.code, -32700 | -32600 | -32601 | -32602 | -32603) {
632 return Err(ProtocolError::new("unsupported JSON-RPC error code"));
633 }
634 if self.error.message.is_empty() || self.error.message.len() > 256 {
635 return Err(ProtocolError::new(
636 "JSON-RPC error message must contain 1..=256 bytes",
637 ));
638 }
639 Ok(())
640 }
641}
642
643fn validate_limit(name: &str, value: u64, maximum: u64) -> Result<(), ProtocolError> {
644 if value == 0 || value > maximum {
645 return Err(ProtocolError::new(format!(
646 "{name} must be within 1..={maximum}"
647 )));
648 }
649 Ok(())
650}
651
652fn validate_token(name: &str, value: &str) -> Result<(), ProtocolError> {
653 if value.is_empty()
654 || value.len() > 256
655 || !value.bytes().all(|byte| {
656 byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'@' | b'/' | b':')
657 })
658 {
659 return Err(ProtocolError::new(format!(
660 "{name} must be a 1..=256 byte portable token"
661 )));
662 }
663 Ok(())
664}
665
666fn validate_decimal(name: &str, value: &str) -> Result<u64, ProtocolError> {
667 if value.is_empty()
668 || (value.len() > 1 && value.starts_with('0'))
669 || !value.bytes().all(|byte| byte.is_ascii_digit())
670 {
671 return Err(ProtocolError::new(format!(
672 "{name} must be a canonical non-negative decimal string"
673 )));
674 }
675 value.parse::<u64>().map_err(|_| {
676 ProtocolError::new(format!(
677 "{name} exceeds the unsigned 64-bit decimal profile"
678 ))
679 })
680}
681
682fn validate_digest(name: &str, value: &str) -> Result<(), ProtocolError> {
683 let Some(hex) = value.strip_prefix("sha256:") else {
684 return Err(ProtocolError::new(format!(
685 "{name} must use a sha256: prefix"
686 )));
687 };
688 if hex.len() != 64
689 || !hex
690 .bytes()
691 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
692 {
693 return Err(ProtocolError::new(format!(
694 "{name} must contain 64 lowercase hexadecimal characters"
695 )));
696 }
697 Ok(())
698}
699
700fn decode_base64url_32(name: &str, value: &str) -> Result<[u8; 32], ProtocolError> {
701 let decoded = URL_SAFE_NO_PAD
702 .decode(value)
703 .map_err(|_| ProtocolError::new(format!("{name} must be canonical base64url")))?;
704 let decoded: [u8; 32] = decoded
705 .try_into()
706 .map_err(|_| ProtocolError::new(format!("{name} must encode exactly 32 bytes")))?;
707 if URL_SAFE_NO_PAD.encode(decoded) != value {
708 return Err(ProtocolError::new(format!(
709 "{name} must be canonical unpadded base64url"
710 )));
711 }
712 Ok(decoded)
713}
714
715fn validate_sorted_unique<T>(
716 name: &str,
717 values: &[T],
718 compare: impl Fn(&T, &T) -> Ordering,
719) -> Result<(), ProtocolError> {
720 if values
721 .windows(2)
722 .any(|pair| compare(&pair[0], &pair[1]) != Ordering::Less)
723 {
724 return Err(ProtocolError::new(format!(
725 "{name} must be strictly canonical-sorted and unique"
726 )));
727 }
728 Ok(())
729}
730
731#[allow(clippy::trivially_copy_pass_by_ref)]
732const fn is_false(value: &bool) -> bool {
733 !*value
734}