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 execution_target;
10mod proof;
11mod strict_json;
12
13pub mod authoring;
18
19pub use execution_target::{
20 EXECUTION_TARGET_CAPABILITY_PROFILE, ExecutionTargetCapability,
21 ExecutionTargetCapabilityProfile,
22};
23pub use proof::{
24 AuthoringHandshakeProofInput, authoring_callback_proof_message, authoring_child_proof_message,
25 authoring_handshake_proof_payload, authoring_host_proof_message, canonicalize_proof_value,
26 child_proof_message, handshake_params_digest, host_proof_message,
27};
28pub use strict_json::{MAX_STRICT_JSON_NESTING, decode_strict, encode_compact};
29
30pub const PROCESS_PROFILE: &str = "lenso-process-jsonrpc-http-v1";
32pub const VALUE_PROFILE: &str = "lenso-json-value-v1";
34pub const PROVIDE_REQUEST_PROFILE: &str = "provide-request-v1";
36pub const HANDSHAKE_METHOD: &str = "lenso.process.v1.handshake";
38pub const REQUEST_METHOD: &str = "lenso.process.v1.request";
40pub const CANCEL_METHOD: &str = "lenso.process.v1.cancel";
42pub const SHUTDOWN_METHOD: &str = "lenso.process.v1.shutdown";
44
45#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct ReadinessRecord {
49 pub protocol: String,
51 pub data_port: u16,
53 pub control_port: u16,
55}
56
57impl ReadinessRecord {
58 pub fn validate(&self) -> Result<(), ProtocolError> {
60 if self.protocol != PROCESS_PROFILE {
61 return Err(ProtocolError::new("unsupported Process Protocol profile"));
62 }
63 if self.data_port == 0 || self.control_port == 0 || self.data_port == self.control_port {
64 return Err(ProtocolError::new(
65 "readiness requires distinct non-zero data and control ports",
66 ));
67 }
68 Ok(())
69 }
70}
71
72#[derive(Clone, Debug, Eq, PartialEq)]
74pub struct ProtocolError {
75 detail: String,
76}
77
78impl ProtocolError {
79 fn new(detail: impl Into<String>) -> Self {
80 Self {
81 detail: detail.into(),
82 }
83 }
84
85 #[must_use]
87 pub fn detail(&self) -> &str {
88 &self.detail
89 }
90}
91
92impl std::fmt::Display for ProtocolError {
93 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 formatter.write_str(&self.detail)
95 }
96}
97
98impl std::error::Error for ProtocolError {}
99
100#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
102#[serde(deny_unknown_fields)]
103pub struct PeerLimits {
104 pub max_http_body_bytes: u64,
106 pub max_control_http_body_bytes: u64,
108 pub max_concurrent_requests: u32,
110 pub child_request_queue_capacity: u32,
112 pub max_retired_correlation_ids: u32,
114 pub control_queue_capacity: u32,
116}
117
118impl PeerLimits {
119 #[must_use]
121 pub const fn v1_defaults() -> Self {
122 Self {
123 max_http_body_bytes: 65_536,
124 max_control_http_body_bytes: 16_384,
125 max_concurrent_requests: 32,
126 child_request_queue_capacity: 32,
127 max_retired_correlation_ids: 65_536,
128 control_queue_capacity: 32,
129 }
130 }
131
132 pub fn validate(&self) -> Result<(), ProtocolError> {
134 validate_limit("max_http_body_bytes", self.max_http_body_bytes, 1_048_576)?;
135 validate_limit(
136 "max_control_http_body_bytes",
137 self.max_control_http_body_bytes,
138 65_536,
139 )?;
140 validate_limit(
141 "max_concurrent_requests",
142 u64::from(self.max_concurrent_requests),
143 256,
144 )?;
145 validate_limit(
146 "child_request_queue_capacity",
147 u64::from(self.child_request_queue_capacity),
148 1_024,
149 )?;
150 validate_limit(
151 "max_retired_correlation_ids",
152 u64::from(self.max_retired_correlation_ids),
153 1_048_576,
154 )?;
155 validate_limit(
156 "control_queue_capacity",
157 u64::from(self.control_queue_capacity),
158 256,
159 )
160 }
161}
162
163#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
165#[serde(deny_unknown_fields)]
166pub struct OperationDescriptor {
167 pub operation: String,
169 pub interaction: InteractionKind,
171}
172
173#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case")]
176pub enum InteractionKind {
177 Request,
179}
180
181#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
183#[serde(deny_unknown_fields)]
184pub struct CapabilityDescriptor {
185 pub capability_id: String,
187 pub descriptor_version: String,
189 pub descriptor_digest: String,
191 pub operations: Vec<OperationDescriptor>,
193}
194
195#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct OutboundBindingDescriptor {
199 pub binding_id: String,
201 pub capability_id: String,
203 pub descriptor_version: String,
205 pub descriptor_digest: String,
207 pub provider_instance: String,
209}
210
211#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
213#[serde(deny_unknown_fields)]
214pub struct HandshakeIdentity {
215 pub protocol_profile: String,
217 pub value_profile: String,
219 pub plugin_instance: String,
221 pub plugin_generation: String,
223 pub generation_spec_digest: String,
225 pub artifact_digest: String,
227 pub effective_host_grant_set_digest: String,
229 pub interaction_profiles: Vec<String>,
231 pub provided_capabilities: Vec<CapabilityDescriptor>,
233 pub outbound_bindings: Vec<OutboundBindingDescriptor>,
235 pub peer_limits: PeerLimits,
237}
238
239#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
241#[serde(deny_unknown_fields)]
242pub struct HandshakeParams {
243 pub identity: HandshakeIdentity,
245 pub host_nonce: String,
247 pub host_proof: String,
249}
250
251#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct HandshakeResult {
255 pub identity: HandshakeIdentity,
257 pub session: String,
259 pub child_proof: String,
261}
262
263#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
265#[serde(deny_unknown_fields)]
266pub struct InvocationExtension {
267 pub key: String,
269 pub value: String,
271 #[serde(skip_serializing_if = "Option::is_none")]
273 pub issuer: Option<String>,
274 #[serde(default, skip_serializing_if = "Vec::is_empty")]
276 pub audience: Vec<String>,
277 #[serde(skip_serializing_if = "Option::is_none")]
279 pub proof: Option<String>,
280 #[serde(default, skip_serializing_if = "is_false")]
282 pub sealed: bool,
283}
284
285#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
287#[serde(deny_unknown_fields)]
288pub struct RequestParams {
289 pub session: String,
291 pub correlation_id: String,
293 pub capability_id: String,
295 pub descriptor_version: String,
297 pub descriptor_digest: String,
299 pub operation: String,
301 pub interaction: InteractionKind,
303 pub caller_instance: Option<String>,
305 pub remaining_timeout_nanos: Option<String>,
307 #[serde(default)]
309 pub extensions: Vec<InvocationExtension>,
310 pub payload: Value,
312}
313
314#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
316#[serde(deny_unknown_fields)]
317pub struct RequestResult {
318 pub session: String,
320 pub correlation_id: String,
322 pub outcome: ProcessOutcome,
324}
325
326#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
328#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
329pub enum ProcessOutcome {
330 Success { value: Value },
332 Domain { error: Value },
334 Runtime { failure: ChildRuntimeFailure },
336}
337
338#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
340#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
341pub enum ChildRuntimeFailure {
342 ResourceExhausted { operation: String },
344 PluginFailure { detail: String },
346}
347
348#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
350#[serde(deny_unknown_fields)]
351pub struct CancelParams {
352 pub session: String,
354 pub correlation_id: String,
356}
357
358#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
360#[serde(deny_unknown_fields)]
361pub struct ShutdownParams {
362 pub session: String,
364}
365
366#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct ControlAck {
370 pub session: String,
372 pub accepted: bool,
374}
375
376#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
378#[serde(deny_unknown_fields)]
379pub struct JsonRpcRequest<T> {
380 pub jsonrpc: String,
382 pub id: String,
384 pub method: String,
386 pub params: T,
388}
389
390#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
392#[serde(deny_unknown_fields)]
393pub struct JsonRpcSuccess<T> {
394 pub jsonrpc: String,
396 pub id: String,
398 pub result: T,
400}
401
402#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
404#[serde(deny_unknown_fields)]
405pub struct JsonRpcErrorObject {
406 pub code: i32,
408 pub message: String,
410}
411
412#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
414#[serde(deny_unknown_fields)]
415pub struct JsonRpcError {
416 pub jsonrpc: String,
418 pub id: Option<String>,
420 pub error: JsonRpcErrorObject,
422}
423
424impl HandshakeIdentity {
425 pub fn validate(&self) -> Result<(), ProtocolError> {
427 if self.protocol_profile != PROCESS_PROFILE {
428 return Err(ProtocolError::new("unsupported Process Protocol profile"));
429 }
430 if self.value_profile != VALUE_PROFILE {
431 return Err(ProtocolError::new("unsupported portable value profile"));
432 }
433 validate_token("plugin_instance", &self.plugin_instance)?;
434 validate_decimal("plugin_generation", &self.plugin_generation)?;
435 validate_digest("generation_spec_digest", &self.generation_spec_digest)?;
436 validate_digest("artifact_digest", &self.artifact_digest)?;
437 validate_digest(
438 "effective_host_grant_set_digest",
439 &self.effective_host_grant_set_digest,
440 )?;
441 validate_sorted_unique("interaction_profiles", &self.interaction_profiles, Ord::cmp)?;
442 if self.interaction_profiles.as_slice() != [PROVIDE_REQUEST_PROFILE] {
443 return Err(ProtocolError::new(
444 "V1 requires exactly the provide-request-v1 interaction profile",
445 ));
446 }
447 validate_sorted_unique(
448 "provided_capabilities",
449 &self.provided_capabilities,
450 |left, right| left.capability_id.cmp(&right.capability_id),
451 )?;
452 if self.provided_capabilities.is_empty() {
453 return Err(ProtocolError::new(
454 "at least one provided Capability is required",
455 ));
456 }
457 for descriptor in &self.provided_capabilities {
458 descriptor.validate()?;
459 }
460 if !self.outbound_bindings.is_empty() {
461 return Err(ProtocolError::new(
462 "outbound bindings require a selected consume profile",
463 ));
464 }
465 self.peer_limits.validate()
466 }
467}
468
469impl CapabilityDescriptor {
470 fn validate(&self) -> Result<(), ProtocolError> {
471 validate_token("capability_id", &self.capability_id)?;
472 validate_token("descriptor_version", &self.descriptor_version)?;
473 validate_digest("descriptor_digest", &self.descriptor_digest)?;
474 validate_sorted_unique("operations", &self.operations, |left, right| {
475 left.operation.cmp(&right.operation)
476 })?;
477 if self.operations.is_empty() {
478 return Err(ProtocolError::new(
479 "provided Capability operations cannot be empty",
480 ));
481 }
482 for operation in &self.operations {
483 validate_token("operation", &operation.operation)?;
484 }
485 Ok(())
486 }
487}
488
489impl HandshakeParams {
490 pub fn validate(&self) -> Result<(), ProtocolError> {
492 self.identity.validate()?;
493 decode_base64url_32("host_nonce", &self.host_nonce)?;
494 decode_base64url_32("host_proof", &self.host_proof)?;
495 Ok(())
496 }
497}
498
499impl HandshakeResult {
500 pub fn validate_against(&self, expected: &HandshakeIdentity) -> Result<(), ProtocolError> {
502 self.identity.validate()?;
503 if &self.identity != expected {
504 return Err(ProtocolError::new("child handshake identity mismatch"));
505 }
506 decode_base64url_32("session", &self.session)?;
507 decode_base64url_32("child_proof", &self.child_proof)?;
508 Ok(())
509 }
510}
511
512impl RequestParams {
513 pub fn validate(&self) -> Result<(), ProtocolError> {
515 decode_base64url_32("session", &self.session)?;
516 validate_decimal("correlation_id", &self.correlation_id)?;
517 validate_token("capability_id", &self.capability_id)?;
518 validate_token("descriptor_version", &self.descriptor_version)?;
519 validate_digest("descriptor_digest", &self.descriptor_digest)?;
520 validate_token("operation", &self.operation)?;
521 if let Some(caller) = &self.caller_instance {
522 validate_token("caller_instance", caller)?;
523 }
524 if let Some(timeout) = &self.remaining_timeout_nanos {
525 validate_decimal("remaining_timeout_nanos", timeout)?;
526 }
527 validate_sorted_unique("extensions", &self.extensions, |left, right| {
528 left.key.cmp(&right.key)
529 })?;
530 for extension in &self.extensions {
531 extension.validate()?;
532 }
533 Ok(())
534 }
535}
536
537impl InvocationExtension {
538 fn validate(&self) -> Result<(), ProtocolError> {
539 validate_token("extension key", &self.key)?;
540 let decoded = base64::engine::general_purpose::STANDARD
541 .decode(&self.value)
542 .map_err(|_| ProtocolError::new("extension value must be padded Base64"))?;
543 if base64::engine::general_purpose::STANDARD.encode(decoded) != self.value {
544 return Err(ProtocolError::new(
545 "extension value must use canonical padded Base64",
546 ));
547 }
548 validate_sorted_unique("extension audience", &self.audience, |left, right| {
549 left.cmp(right)
550 })?;
551 Ok(())
552 }
553}
554
555impl RequestResult {
556 pub fn validate(&self) -> Result<(), ProtocolError> {
558 decode_base64url_32("session", &self.session)?;
559 validate_decimal("correlation_id", &self.correlation_id)?;
560 if let ProcessOutcome::Runtime { failure } = &self.outcome {
561 match failure {
562 ChildRuntimeFailure::ResourceExhausted { operation } => {
563 validate_token("operation", operation)?;
564 }
565 ChildRuntimeFailure::PluginFailure { detail } => {
566 if detail.is_empty() || detail.len() > 1_024 {
567 return Err(ProtocolError::new(
568 "Plugin Failure detail must contain 1..=1024 bytes",
569 ));
570 }
571 }
572 }
573 }
574 Ok(())
575 }
576}
577
578impl CancelParams {
579 pub fn validate(&self) -> Result<(), ProtocolError> {
581 decode_base64url_32("session", &self.session)?;
582 validate_decimal("correlation_id", &self.correlation_id).map(|_| ())
583 }
584}
585
586impl ShutdownParams {
587 pub fn validate(&self) -> Result<(), ProtocolError> {
589 decode_base64url_32("session", &self.session)?;
590 Ok(())
591 }
592}
593
594impl ControlAck {
595 pub fn validate(&self) -> Result<(), ProtocolError> {
597 decode_base64url_32("session", &self.session)?;
598 if !self.accepted {
599 return Err(ProtocolError::new(
600 "control acknowledgement must be accepted",
601 ));
602 }
603 Ok(())
604 }
605}
606
607impl<T> JsonRpcRequest<T> {
608 pub fn validate_envelope(&self, expected_method: &str) -> Result<(), ProtocolError> {
610 if self.jsonrpc != "2.0" {
611 return Err(ProtocolError::new("jsonrpc must equal 2.0"));
612 }
613 validate_decimal("JSON-RPC id", &self.id)?;
614 if self.method != expected_method {
615 return Err(ProtocolError::new("unexpected JSON-RPC method"));
616 }
617 Ok(())
618 }
619}
620
621impl<T> JsonRpcSuccess<T> {
622 pub fn validate_envelope(&self, expected_id: &str) -> Result<(), ProtocolError> {
624 if self.jsonrpc != "2.0" {
625 return Err(ProtocolError::new("jsonrpc must equal 2.0"));
626 }
627 validate_decimal("JSON-RPC id", &self.id)?;
628 if self.id != expected_id {
629 return Err(ProtocolError::new("JSON-RPC response id mismatch"));
630 }
631 Ok(())
632 }
633}
634
635impl JsonRpcError {
636 pub fn validate(&self) -> Result<(), ProtocolError> {
638 if self.jsonrpc != "2.0" {
639 return Err(ProtocolError::new("jsonrpc must equal 2.0"));
640 }
641 if let Some(id) = &self.id {
642 validate_decimal("JSON-RPC id", id)?;
643 }
644 if !matches!(self.error.code, -32700 | -32600 | -32601 | -32602 | -32603) {
645 return Err(ProtocolError::new("unsupported JSON-RPC error code"));
646 }
647 if self.error.message.is_empty() || self.error.message.len() > 256 {
648 return Err(ProtocolError::new(
649 "JSON-RPC error message must contain 1..=256 bytes",
650 ));
651 }
652 Ok(())
653 }
654}
655
656fn validate_limit(name: &str, value: u64, maximum: u64) -> Result<(), ProtocolError> {
657 if value == 0 || value > maximum {
658 return Err(ProtocolError::new(format!(
659 "{name} must be within 1..={maximum}"
660 )));
661 }
662 Ok(())
663}
664
665fn validate_token(name: &str, value: &str) -> Result<(), ProtocolError> {
666 if value.is_empty()
667 || value.len() > 256
668 || !value.bytes().all(|byte| {
669 byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'@' | b'/' | b':')
670 })
671 {
672 return Err(ProtocolError::new(format!(
673 "{name} must be a 1..=256 byte portable token"
674 )));
675 }
676 Ok(())
677}
678
679fn validate_decimal(name: &str, value: &str) -> Result<u64, ProtocolError> {
680 if value.is_empty()
681 || (value.len() > 1 && value.starts_with('0'))
682 || !value.bytes().all(|byte| byte.is_ascii_digit())
683 {
684 return Err(ProtocolError::new(format!(
685 "{name} must be a canonical non-negative decimal string"
686 )));
687 }
688 value.parse::<u64>().map_err(|_| {
689 ProtocolError::new(format!(
690 "{name} exceeds the unsigned 64-bit decimal profile"
691 ))
692 })
693}
694
695fn validate_digest(name: &str, value: &str) -> Result<(), ProtocolError> {
696 let Some(hex) = value.strip_prefix("sha256:") else {
697 return Err(ProtocolError::new(format!(
698 "{name} must use a sha256: prefix"
699 )));
700 };
701 if hex.len() != 64
702 || !hex
703 .bytes()
704 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
705 {
706 return Err(ProtocolError::new(format!(
707 "{name} must contain 64 lowercase hexadecimal characters"
708 )));
709 }
710 Ok(())
711}
712
713fn decode_base64url_32(name: &str, value: &str) -> Result<[u8; 32], ProtocolError> {
714 let decoded = URL_SAFE_NO_PAD
715 .decode(value)
716 .map_err(|_| ProtocolError::new(format!("{name} must be canonical base64url")))?;
717 let decoded: [u8; 32] = decoded
718 .try_into()
719 .map_err(|_| ProtocolError::new(format!("{name} must encode exactly 32 bytes")))?;
720 if URL_SAFE_NO_PAD.encode(decoded) != value {
721 return Err(ProtocolError::new(format!(
722 "{name} must be canonical unpadded base64url"
723 )));
724 }
725 Ok(decoded)
726}
727
728fn validate_sorted_unique<T>(
729 name: &str,
730 values: &[T],
731 compare: impl Fn(&T, &T) -> Ordering,
732) -> Result<(), ProtocolError> {
733 if values
734 .windows(2)
735 .any(|pair| compare(&pair[0], &pair[1]) != Ordering::Less)
736 {
737 return Err(ProtocolError::new(format!(
738 "{name} must be strictly canonical-sorted and unique"
739 )));
740 }
741 Ok(())
742}
743
744#[allow(clippy::trivially_copy_pass_by_ref)]
745const fn is_false(value: &bool) -> bool {
746 !*value
747}