Skip to main content

lenso_process_protocol/
lib.rs

1//! Language-neutral source types for `lenso-process-jsonrpc-http-v1`.
2
3use 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
12/// Runtime-neutral values shared by Authoring V2 execution profiles.
13///
14/// This module does not define a transport envelope. Process and Bun adapters
15/// wrap these values in their own versioned protocols.
16pub 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
23/// Exact Process Protocol profile selected by an Adapter.
24pub const PROCESS_PROFILE: &str = "lenso-process-jsonrpc-http-v1";
25/// Portable JSON value profile used by request payloads.
26pub const VALUE_PROFILE: &str = "lenso-json-value-v1";
27/// Mandatory child-provides-request interaction profile.
28pub const PROVIDE_REQUEST_PROFILE: &str = "provide-request-v1";
29/// Control method used once during process startup.
30pub const HANDSHAKE_METHOD: &str = "lenso.process.v1.handshake";
31/// Data method used for one request interaction.
32pub const REQUEST_METHOD: &str = "lenso.process.v1.request";
33/// Control method used for idempotent cancellation.
34pub const CANCEL_METHOD: &str = "lenso.process.v1.cancel";
35/// Control method used for graceful child shutdown.
36pub const SHUTDOWN_METHOD: &str = "lenso.process.v1.shutdown";
37
38/// One bounded readiness record written on the dedicated inherited handle.
39#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
40#[serde(deny_unknown_fields)]
41pub struct ReadinessRecord {
42    /// Exact Process Protocol profile implemented by both listeners.
43    pub protocol: String,
44    /// Ephemeral loopback data-listener port.
45    pub data_port: u16,
46    /// Distinct ephemeral loopback control-listener port.
47    pub control_port: u16,
48}
49
50impl ReadinessRecord {
51    /// Validates the exact profile and two non-zero, distinct ports.
52    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/// Error returned when a Process Protocol document is malformed or inconsistent.
66#[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    /// Returns the stable human-readable validation detail.
79    #[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/// Peer-confirmed limits that must match exactly during handshake.
94#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96pub struct PeerLimits {
97    /// Maximum encoded data request or response body.
98    pub max_http_body_bytes: u64,
99    /// Maximum encoded control request or response body.
100    pub max_control_http_body_bytes: u64,
101    /// Maximum concurrently active request handlers.
102    pub max_concurrent_requests: u32,
103    /// Maximum queued child data requests.
104    pub child_request_queue_capacity: u32,
105    /// Maximum completed correlation IDs retained in one process session.
106    pub max_retired_correlation_ids: u32,
107    /// Maximum queued control requests, with at least one reserved handler.
108    pub control_queue_capacity: u32,
109}
110
111impl PeerLimits {
112    /// Returns the V1 defaults.
113    #[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    /// Enforces non-zero V1 hard maxima.
126    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/// One exact provided operation in handshake identity.
157#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
158#[serde(deny_unknown_fields)]
159pub struct OperationDescriptor {
160    /// Stable operation name.
161    pub operation: String,
162    /// Exact interaction kind. V1 supports request provision only.
163    pub interaction: InteractionKind,
164}
165
166/// Interaction kinds admitted by the base V1 profile.
167#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
168#[serde(rename_all = "snake_case")]
169pub enum InteractionKind {
170    /// One request with one terminal outcome.
171    Request,
172}
173
174/// One exact provided Capability Descriptor.
175#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
176#[serde(deny_unknown_fields)]
177pub struct CapabilityDescriptor {
178    /// Stable `namespace.name@major` identity.
179    pub capability_id: String,
180    /// Exact Descriptor semantic version.
181    pub descriptor_version: String,
182    /// Canonical Descriptor SHA-256 digest.
183    pub descriptor_digest: String,
184    /// Canonical-sorted operation table.
185    pub operations: Vec<OperationDescriptor>,
186}
187
188/// One exact outbound binding exposed only by a selected consume profile.
189#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
190#[serde(deny_unknown_fields)]
191pub struct OutboundBindingDescriptor {
192    /// Stable binding identity within the Plugin Instance.
193    pub binding_id: String,
194    /// Required Capability identity.
195    pub capability_id: String,
196    /// Exact Descriptor version.
197    pub descriptor_version: String,
198    /// Canonical Descriptor digest.
199    pub descriptor_digest: String,
200    /// Explicit provider Plugin Instance key.
201    pub provider_instance: String,
202}
203
204/// Immutable identity the child must echo exactly during handshake.
205#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
206#[serde(deny_unknown_fields)]
207pub struct HandshakeIdentity {
208    /// Exact transport profile.
209    pub protocol_profile: String,
210    /// Exact portable value profile.
211    pub value_profile: String,
212    /// App-local Plugin Instance key.
213    pub plugin_instance: String,
214    /// Canonical decimal Plugin generation.
215    pub plugin_generation: String,
216    /// Exact App Generation Spec digest.
217    pub generation_spec_digest: String,
218    /// Exact executable Artifact digest.
219    pub artifact_digest: String,
220    /// Exact Effective Host Grant Set digest.
221    pub effective_host_grant_set_digest: String,
222    /// Canonical-sorted exact interaction profiles.
223    pub interaction_profiles: Vec<String>,
224    /// Canonical-sorted provided Capability Descriptors.
225    pub provided_capabilities: Vec<CapabilityDescriptor>,
226    /// Canonical-sorted explicit outbound bindings.
227    pub outbound_bindings: Vec<OutboundBindingDescriptor>,
228    /// Limits both peers must confirm exactly.
229    pub peer_limits: PeerLimits,
230}
231
232/// Host-to-child handshake params.
233#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
234#[serde(deny_unknown_fields)]
235pub struct HandshakeParams {
236    /// Exact identity to admit.
237    pub identity: HandshakeIdentity,
238    /// Canonical base64url encoding of 32 random bytes.
239    pub host_nonce: String,
240    /// Canonical base64url HMAC output.
241    pub host_proof: String,
242}
243
244/// Child-to-host accepted handshake result.
245#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
246#[serde(deny_unknown_fields)]
247pub struct HandshakeResult {
248    /// Exact admitted identity echoed from the request.
249    pub identity: HandshakeIdentity,
250    /// Canonical base64url encoding of 32 random bytes.
251    pub session: String,
252    /// Canonical base64url HMAC output.
253    pub child_proof: String,
254}
255
256/// Portable invocation extension transported without domain interpretation.
257#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct InvocationExtension {
260    /// Stable unique extension key.
261    pub key: String,
262    /// Canonical padded Base64 bytes.
263    pub value: String,
264    /// Optional issuing authority.
265    #[serde(skip_serializing_if = "Option::is_none")]
266    pub issuer: Option<String>,
267    /// Canonical-sorted declared audiences.
268    #[serde(default, skip_serializing_if = "Vec::is_empty")]
269    pub audience: Vec<String>,
270    /// Optional opaque proof.
271    #[serde(skip_serializing_if = "Option::is_none")]
272    pub proof: Option<String>,
273    /// Whether the extension value is sealed for its audience.
274    #[serde(default, skip_serializing_if = "is_false")]
275    pub sealed: bool,
276}
277
278/// Host-to-child request params for `provide-request-v1`.
279#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
280#[serde(deny_unknown_fields)]
281pub struct RequestParams {
282    /// Authenticated process session.
283    pub session: String,
284    /// Opaque canonical decimal-string correlation ID.
285    pub correlation_id: String,
286    /// Selected Capability identity.
287    pub capability_id: String,
288    /// Exact selected Descriptor version.
289    pub descriptor_version: String,
290    /// Exact selected Descriptor digest.
291    pub descriptor_digest: String,
292    /// Selected operation.
293    pub operation: String,
294    /// Exact request interaction marker.
295    pub interaction: InteractionKind,
296    /// Host-established caller Plugin Instance, or `null` for host ingress.
297    pub caller_instance: Option<String>,
298    /// Relative remaining budget as decimal nanoseconds, or `null` for none.
299    pub remaining_timeout_nanos: Option<String>,
300    /// Structurally validated portable invocation extensions.
301    #[serde(default)]
302    pub extensions: Vec<InvocationExtension>,
303    /// Capability-defined portable JSON payload.
304    pub payload: Value,
305}
306
307/// Child-to-host request result.
308#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
309#[serde(deny_unknown_fields)]
310pub struct RequestResult {
311    /// Authenticated process session.
312    pub session: String,
313    /// Correlation ID echoed from the request.
314    pub correlation_id: String,
315    /// Exactly one terminal application outcome.
316    pub outcome: ProcessOutcome,
317}
318
319/// Child-originated request outcomes allowed by V1.
320#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
321#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
322pub enum ProcessOutcome {
323    /// Capability success payload.
324    Success { value: Value },
325    /// Capability-defined Domain Error payload.
326    Domain { error: Value },
327    /// Narrow child-originated Runtime Failure.
328    Runtime { failure: ChildRuntimeFailure },
329}
330
331/// Runtime Failures the child is permitted to originate.
332#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
333#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
334pub enum ChildRuntimeFailure {
335    /// The child cannot admit this operation within its declared bound.
336    ResourceExhausted { operation: String },
337    /// The Plugin generation is no longer trustworthy and must be retired.
338    PluginFailure { detail: String },
339}
340
341/// Idempotent cancel params.
342#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
343#[serde(deny_unknown_fields)]
344pub struct CancelParams {
345    /// Authenticated process session.
346    pub session: String,
347    /// Active, retired, or unknown correlation ID.
348    pub correlation_id: String,
349}
350
351/// Graceful shutdown params.
352#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
353#[serde(deny_unknown_fields)]
354pub struct ShutdownParams {
355    /// Authenticated process session.
356    pub session: String,
357}
358
359/// Successful cancel or shutdown acknowledgement.
360#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
361#[serde(deny_unknown_fields)]
362pub struct ControlAck {
363    /// Authenticated process session.
364    pub session: String,
365    /// Always true; cancel does not reveal correlation existence.
366    pub accepted: bool,
367}
368
369/// Strict JSON-RPC request envelope.
370#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
371#[serde(deny_unknown_fields)]
372pub struct JsonRpcRequest<T> {
373    /// Must equal `2.0`.
374    pub jsonrpc: String,
375    /// Canonical decimal-string JSON-RPC ID.
376    pub id: String,
377    /// Exact versioned method.
378    pub method: String,
379    /// Strict method params object.
380    pub params: T,
381}
382
383/// Strict successful JSON-RPC response envelope.
384#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
385#[serde(deny_unknown_fields)]
386pub struct JsonRpcSuccess<T> {
387    /// Must equal `2.0`.
388    pub jsonrpc: String,
389    /// Exact request ID.
390    pub id: String,
391    /// Strict method result object.
392    pub result: T,
393}
394
395/// Strict JSON-RPC 2.0 error object used before a method result exists.
396#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
397#[serde(deny_unknown_fields)]
398pub struct JsonRpcErrorObject {
399    /// Standard JSON-RPC error code.
400    pub code: i32,
401    /// Stable public error message without host or child internals.
402    pub message: String,
403}
404
405/// Strict JSON-RPC 2.0 error response. Parse/invalid-request errors use a null ID.
406#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct JsonRpcError {
409    /// Must equal `2.0`.
410    pub jsonrpc: String,
411    /// Exact request ID, or null when the request ID could not be authenticated.
412    pub id: Option<String>,
413    /// Standard error object.
414    pub error: JsonRpcErrorObject,
415}
416
417impl HandshakeIdentity {
418    /// Validates exact profiles, digests, canonical ordering, and V1 limits.
419    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    /// Validates identity, nonce, and proof encoding.
484    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    /// Validates the child echo and proof encoding against the expected identity.
494    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    /// Validates host-owned request envelope fields before payload Schema decoding.
507    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    /// Validates session, correlation, and bounded child Runtime Failure fields.
550    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    /// Validates the authenticated cancel identity.
573    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    /// Validates the authenticated shutdown identity.
581    pub fn validate(&self) -> Result<(), ProtocolError> {
582        decode_base64url_32("session", &self.session)?;
583        Ok(())
584    }
585}
586
587impl ControlAck {
588    /// Validates an authenticated, affirmative control acknowledgement.
589    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    /// Validates the base JSON-RPC envelope and exact expected method.
602    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    /// Validates the base JSON-RPC success envelope and expected request ID.
616    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    /// Validates the closed V1 JSON-RPC error surface and optional request ID.
630    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}