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