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