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