Skip to main content

vellaveto_types/
etdi.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4//
5// Copyright 2026 Paolo Vella
6// SPDX-License-Identifier: MPL-2.0
7
8//! ETDI (Enhanced Tool Definition Interface) types — cryptographic verification
9//! of MCP tool definitions based on arxiv:2506.01333.
10
11use serde::{Deserialize, Serialize};
12use std::fmt;
13
14/// Signature algorithm for tool definitions (ETDI).
15#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
16#[serde(rename_all = "snake_case")]
17pub enum SignatureAlgorithm {
18    /// Ed25519 signatures (recommended, default).
19    #[default]
20    Ed25519,
21    /// ECDSA with P-256 curve.
22    EcdsaP256,
23}
24
25impl fmt::Display for SignatureAlgorithm {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            SignatureAlgorithm::Ed25519 => write!(f, "ed25519"),
29            SignatureAlgorithm::EcdsaP256 => write!(f, "ecdsa_p256"),
30        }
31    }
32}
33
34/// SECURITY (FIND-R51-002): Validate that a string is a well-formed ISO 8601
35/// basic timestamp in the format `YYYY-MM-DDTHH:MM:SSZ`.
36///
37/// Checks structure, character classes, and value ranges for all components.
38/// Returns `false` for any malformed input, which callers use for fail-closed
39/// behavior (treating malformed timestamps as expired).
40fn is_valid_iso8601_basic(s: &str) -> bool {
41    // Must be exactly 20 bytes: "YYYY-MM-DDTHH:MM:SSZ"
42    if s.len() != 20 {
43        return false;
44    }
45    let b = s.as_bytes();
46
47    // Structural checks: separators at fixed positions
48    if b[4] != b'-'
49        || b[7] != b'-'
50        || b[10] != b'T'
51        || b[13] != b':'
52        || b[16] != b':'
53        || b[19] != b'Z'
54    {
55        return false;
56    }
57
58    // All digit positions must be ASCII digits
59    let digit_positions = [0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 14, 15, 17, 18];
60    for &pos in &digit_positions {
61        if !b[pos].is_ascii_digit() {
62            return false;
63        }
64    }
65
66    // Parse and validate numeric ranges
67    // Safe: we verified all positions are ASCII digits above, so from_utf8 and parse cannot fail.
68    let year: u16 = s[0..4].parse().unwrap_or(0);
69    let month: u8 = s[5..7].parse().unwrap_or(0);
70    let day: u8 = s[8..10].parse().unwrap_or(0);
71    let hour: u8 = s[11..13].parse().unwrap_or(0);
72    let minute: u8 = s[14..16].parse().unwrap_or(0);
73    let second: u8 = s[17..19].parse().unwrap_or(0);
74
75    if year < 1970 {
76        return false;
77    }
78    if !(1..=12).contains(&month) {
79        return false;
80    }
81    // R231-TYP-1: Calendar-aware day-of-month validation.
82    let max_day = match month {
83        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
84        4 | 6 | 9 | 11 => 30,
85        2 => {
86            if (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400) {
87                29
88            } else {
89                28
90            }
91        }
92        _ => return false,
93    };
94    if !(1..=max_day).contains(&day) {
95        return false;
96    }
97    if hour > 23 {
98        return false;
99    }
100    if minute > 59 {
101        return false;
102    }
103    if second > 59 {
104        return false;
105    }
106
107    true
108}
109
110/// A cryptographic signature on a tool definition.
111///
112/// Part of the ETDI (Enhanced Tool Definition Interface) system.
113/// Tool providers sign their tool definitions, and Vellaveto verifies
114/// these signatures before allowing tool registration.
115#[derive(Clone, Serialize, Deserialize, PartialEq)]
116#[serde(deny_unknown_fields)]
117pub struct ToolSignature {
118    /// Unique identifier for this signature.
119    pub signature_id: String,
120    /// Hex-encoded cryptographic signature.
121    pub signature: String,
122    /// Algorithm used to create the signature.
123    pub algorithm: SignatureAlgorithm,
124    /// Hex-encoded public key of the signer.
125    pub public_key: String,
126    /// Optional fingerprint of the public key (for key management).
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub key_fingerprint: Option<String>,
129    /// ISO 8601 timestamp when the signature was created.
130    pub signed_at: String,
131    /// ISO 8601 timestamp when the signature expires (optional).
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub expires_at: Option<String>,
134    /// SPIFFE ID of the signer for workload identity (optional).
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub signer_spiffe_id: Option<String>,
137    /// Optional Rekor transparency log entry for tool provenance (Phase 23.4).
138    /// Contains a serialized `RekorEntry` for offline inclusion proof verification.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub rekor_entry: Option<serde_json::Value>,
141}
142
143// SECURITY (FIND-R52-016): Custom Debug to redact signature and public_key.
144impl std::fmt::Debug for ToolSignature {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        f.debug_struct("ToolSignature")
147            .field("signature_id", &self.signature_id)
148            .field("signature", &"[REDACTED]")
149            .field("algorithm", &self.algorithm)
150            .field("public_key", &"[REDACTED]")
151            .field("key_fingerprint", &self.key_fingerprint)
152            .field("signed_at", &self.signed_at)
153            .field("expires_at", &self.expires_at)
154            .field("signer_spiffe_id", &self.signer_spiffe_id)
155            .field(
156                "rekor_entry",
157                &self.rekor_entry.as_ref().map(|_| "[PRESENT]"),
158            )
159            .finish()
160    }
161}
162
163impl ToolSignature {
164    /// Maximum serialized size of `rekor_entry` in bytes.
165    pub const MAX_REKOR_ENTRY_SIZE: usize = 65_536;
166
167    /// Maximum length for `signature_id` (bytes).
168    const MAX_SIGNATURE_ID_LEN: usize = 256;
169    /// Maximum length for `signature` hex string (bytes).
170    const MAX_SIGNATURE_LEN: usize = 512;
171    /// Maximum length for `public_key` hex string (bytes).
172    const MAX_PUBLIC_KEY_LEN: usize = 512;
173    /// Maximum length for ISO 8601 timestamp fields (`signed_at`, `expires_at`).
174    const MAX_TIMESTAMP_LEN: usize = 64;
175    /// Maximum length for `key_fingerprint` (bytes).
176    const MAX_KEY_FINGERPRINT_LEN: usize = 256;
177    /// Maximum length for `signer_spiffe_id` URI (bytes).
178    const MAX_SPIFFE_ID_LEN: usize = 2048;
179
180    /// Validate structural bounds on all string fields.
181    ///
182    /// SECURITY (FIND-R52-002): Prevents memory exhaustion from oversized
183    /// signature payloads deserialized from untrusted input.
184    pub fn validate(&self) -> Result<(), String> {
185        // SECURITY (FIND-R52-002): Validate all string field lengths.
186        if self.signature_id.len() > Self::MAX_SIGNATURE_ID_LEN {
187            return Err(format!(
188                "ToolSignature signature_id length {} exceeds max {}",
189                self.signature_id.len(),
190                Self::MAX_SIGNATURE_ID_LEN,
191            ));
192        }
193        if self.signature.len() > Self::MAX_SIGNATURE_LEN {
194            return Err(format!(
195                "ToolSignature signature length {} exceeds max {}",
196                self.signature.len(),
197                Self::MAX_SIGNATURE_LEN,
198            ));
199        }
200        if self.public_key.len() > Self::MAX_PUBLIC_KEY_LEN {
201            return Err(format!(
202                "ToolSignature public_key length {} exceeds max {}",
203                self.public_key.len(),
204                Self::MAX_PUBLIC_KEY_LEN,
205            ));
206        }
207        // SECURITY (FIND-R196-006): Validate that signature and public_key contain
208        // only hex characters. These fields are documented as "Hex-encoded" — accepting
209        // non-hex content could cause downstream parsing failures or be used for
210        // injection if the values are logged or interpolated without sanitization.
211        if !self.signature.is_empty() && !self.signature.bytes().all(|b| b.is_ascii_hexdigit()) {
212            return Err("ToolSignature signature contains non-hex characters".to_string());
213        }
214        if !self.public_key.is_empty() && !self.public_key.bytes().all(|b| b.is_ascii_hexdigit()) {
215            return Err("ToolSignature public_key contains non-hex characters".to_string());
216        }
217        if self.signed_at.len() > Self::MAX_TIMESTAMP_LEN {
218            return Err(format!(
219                "ToolSignature signed_at length {} exceeds max {}",
220                self.signed_at.len(),
221                Self::MAX_TIMESTAMP_LEN,
222            ));
223        }
224        if let Some(ref ea) = self.expires_at {
225            if ea.len() > Self::MAX_TIMESTAMP_LEN {
226                return Err(format!(
227                    "ToolSignature expires_at length {} exceeds max {}",
228                    ea.len(),
229                    Self::MAX_TIMESTAMP_LEN,
230                ));
231            }
232        }
233        if let Some(ref kf) = self.key_fingerprint {
234            if kf.len() > Self::MAX_KEY_FINGERPRINT_LEN {
235                return Err(format!(
236                    "ToolSignature key_fingerprint length {} exceeds max {}",
237                    kf.len(),
238                    Self::MAX_KEY_FINGERPRINT_LEN,
239                ));
240            }
241        }
242        if let Some(ref spiffe) = self.signer_spiffe_id {
243            if spiffe.len() > Self::MAX_SPIFFE_ID_LEN {
244                return Err(format!(
245                    "ToolSignature signer_spiffe_id length {} exceeds max {}",
246                    spiffe.len(),
247                    Self::MAX_SPIFFE_ID_LEN,
248                ));
249            }
250        }
251        if let Some(ref entry) = self.rekor_entry {
252            let size = serde_json::to_string(entry)
253                .map_err(|e| format!("rekor_entry serialization failed: {e}"))?
254                .len();
255            if size > Self::MAX_REKOR_ENTRY_SIZE {
256                return Err(format!(
257                    "rekor_entry serialized size {} exceeds max {}",
258                    size,
259                    Self::MAX_REKOR_ENTRY_SIZE
260                ));
261            }
262        }
263        // SECURITY (FIND-R141-003): Validate control and Unicode format characters
264        // in all string fields. Without this, a signature_id containing newlines could
265        // cause log injection, and a signer_spiffe_id with zero-width chars could bypass
266        // SPIFFE-based identity matching. This matches the pattern in ToolVersionPin::validate().
267        for (name, value) in [
268            ("signature_id", Some(&self.signature_id)),
269            ("signed_at", Some(&self.signed_at)),
270        ] {
271            if let Some(v) = value {
272                if v.chars()
273                    .any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
274                {
275                    return Err(format!(
276                        "ToolSignature {name} contains control or format characters"
277                    ));
278                }
279            }
280        }
281        for (name, value) in [
282            ("expires_at", self.expires_at.as_ref()),
283            ("key_fingerprint", self.key_fingerprint.as_ref()),
284            ("signer_spiffe_id", self.signer_spiffe_id.as_ref()),
285        ] {
286            if let Some(v) = value {
287                if v.chars()
288                    .any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
289                {
290                    return Err(format!(
291                        "ToolSignature {name} contains control or format characters"
292                    ));
293                }
294            }
295        }
296        Ok(())
297    }
298
299    /// Returns true if the signature has expired.
300    ///
301    /// SAFETY: Lexicographic comparison is correct for ISO 8601 timestamps
302    /// in the canonical format `YYYY-MM-DDTHH:MM:SSZ` because:
303    /// - All fields are fixed-width with zero-padding
304    /// - Fields are ordered from most significant (year) to least (second)
305    /// - The character ordering of digits matches numeric ordering
306    ///
307    /// This holds for any consistent ISO 8601 format (with or without 'Z',
308    /// with or without fractional seconds) as long as both timestamps use
309    /// the same format and timezone.
310    pub fn is_expired(&self, now: &str) -> bool {
311        // SECURITY (FIND-R49-004): Reject non-UTC timestamps as expired (fail-closed).
312        if !now.ends_with('Z') {
313            return true;
314        }
315        // SECURITY (FIND-R51-002): Reject malformed `now` timestamps as expired (fail-closed).
316        if !is_valid_iso8601_basic(now) {
317            return true;
318        }
319        self.expires_at.as_ref().is_some_and(|exp| {
320            if !exp.ends_with('Z') {
321                return true;
322            }
323            // SECURITY (FIND-R51-002): Reject malformed `expires_at` as expired (fail-closed).
324            if !is_valid_iso8601_basic(exp) {
325                return true;
326            }
327            now >= exp.as_str()
328        })
329    }
330}
331
332/// Verification result for a tool signature.
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
334#[serde(deny_unknown_fields)]
335pub struct SignatureVerification {
336    /// Whether the cryptographic signature is valid.
337    pub valid: bool,
338    /// Whether the signer is in the trusted signers list.
339    pub signer_trusted: bool,
340    /// Whether the signature has expired.
341    pub expired: bool,
342    /// Human-readable message about the verification result.
343    pub message: String,
344}
345
346impl SignatureVerification {
347    /// Maximum length for `message` field (bytes).
348    const MAX_MESSAGE_LEN: usize = 4096;
349
350    /// Returns true if the signature passes all checks.
351    pub fn is_fully_verified(&self) -> bool {
352        self.valid && self.signer_trusted && !self.expired
353    }
354
355    /// Validate structural bounds on string fields.
356    ///
357    /// SECURITY (FIND-R146-TE-002): Prevents memory exhaustion from oversized
358    /// message fields and control/format character injection from untrusted payloads.
359    pub fn validate(&self) -> Result<(), String> {
360        if self.message.len() > Self::MAX_MESSAGE_LEN {
361            return Err(format!(
362                "SignatureVerification message length {} exceeds max {}",
363                self.message.len(),
364                Self::MAX_MESSAGE_LEN,
365            ));
366        }
367        if crate::core::has_dangerous_chars(&self.message) {
368            return Err(
369                "SignatureVerification message contains control or format characters".to_string(),
370            );
371        }
372        Ok(())
373    }
374}
375
376/// An attestation record in a tool's provenance chain.
377///
378/// Attestations form a chain of custody for tool definitions,
379/// allowing verification that a tool has not been modified
380/// since it was first registered.
381#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
382#[serde(deny_unknown_fields)]
383pub struct ToolAttestation {
384    /// Unique identifier for this attestation.
385    pub attestation_id: String,
386    /// Type of attestation (e.g., "initial", "version_update", "security_audit").
387    pub attestation_type: String,
388    /// Entity that created this attestation.
389    pub attester: String,
390    /// ISO 8601 timestamp when the attestation was created.
391    pub timestamp: String,
392    /// SHA-256 hash of the tool definition at attestation time.
393    pub tool_hash: String,
394    /// ID of the previous attestation in the chain (None for first attestation).
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub previous_attestation: Option<String>,
397    /// Cryptographic signature on this attestation.
398    pub signature: ToolSignature,
399    /// Optional reference to a transparency log entry.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub transparency_log_entry: Option<String>,
402}
403
404impl ToolAttestation {
405    /// Maximum attestation chain depth to prevent DoS during chain traversal.
406    pub const MAX_ATTESTATION_CHAIN_DEPTH: usize = 64;
407
408    /// Maximum length for `attestation_id`.
409    const MAX_ATTESTATION_ID_LEN: usize = 256;
410    /// Maximum length for `attestation_type`.
411    const MAX_ATTESTATION_TYPE_LEN: usize = 128;
412    /// Maximum length for `attester`.
413    const MAX_ATTESTER_LEN: usize = 512;
414    /// Maximum length for ISO 8601 timestamp fields.
415    const MAX_TIMESTAMP_LEN: usize = 64;
416    /// Maximum length for `tool_hash` (hex-encoded SHA-256 = 64 chars).
417    const MAX_TOOL_HASH_LEN: usize = 256;
418    /// Maximum length for `previous_attestation` ID.
419    const MAX_PREV_ATTESTATION_LEN: usize = 256;
420    /// Maximum length for `transparency_log_entry` reference.
421    const MAX_LOG_ENTRY_LEN: usize = 2048;
422
423    /// Validate structural bounds on string fields and the nested signature.
424    ///
425    /// SECURITY: Prevents memory exhaustion from oversized attestation payloads
426    /// deserialized from untrusted input. Delegates to [`ToolSignature::validate()`]
427    /// for the inner signature.
428    pub fn validate(&self) -> Result<(), String> {
429        if self.attestation_id.len() > Self::MAX_ATTESTATION_ID_LEN {
430            return Err(format!(
431                "ToolAttestation attestation_id length {} exceeds max {}",
432                self.attestation_id.len(),
433                Self::MAX_ATTESTATION_ID_LEN,
434            ));
435        }
436        if self.attestation_type.len() > Self::MAX_ATTESTATION_TYPE_LEN {
437            return Err(format!(
438                "ToolAttestation attestation_type length {} exceeds max {}",
439                self.attestation_type.len(),
440                Self::MAX_ATTESTATION_TYPE_LEN,
441            ));
442        }
443        if self.attester.len() > Self::MAX_ATTESTER_LEN {
444            return Err(format!(
445                "ToolAttestation attester length {} exceeds max {}",
446                self.attester.len(),
447                Self::MAX_ATTESTER_LEN,
448            ));
449        }
450        if self.timestamp.len() > Self::MAX_TIMESTAMP_LEN {
451            return Err(format!(
452                "ToolAttestation timestamp length {} exceeds max {}",
453                self.timestamp.len(),
454                Self::MAX_TIMESTAMP_LEN,
455            ));
456        }
457        if self.tool_hash.len() > Self::MAX_TOOL_HASH_LEN {
458            return Err(format!(
459                "ToolAttestation tool_hash length {} exceeds max {}",
460                self.tool_hash.len(),
461                Self::MAX_TOOL_HASH_LEN,
462            ));
463        }
464        if let Some(ref prev) = self.previous_attestation {
465            if prev.len() > Self::MAX_PREV_ATTESTATION_LEN {
466                return Err(format!(
467                    "ToolAttestation previous_attestation length {} exceeds max {}",
468                    prev.len(),
469                    Self::MAX_PREV_ATTESTATION_LEN,
470                ));
471            }
472        }
473        if let Some(ref entry) = self.transparency_log_entry {
474            if entry.len() > Self::MAX_LOG_ENTRY_LEN {
475                return Err(format!(
476                    "ToolAttestation transparency_log_entry length {} exceeds max {}",
477                    entry.len(),
478                    Self::MAX_LOG_ENTRY_LEN,
479                ));
480            }
481        }
482        // SECURITY (FIND-R141-004): Validate control and Unicode format characters
483        // in all string fields. Without this, an attestation_id or attester with
484        // newlines could cause log injection, and a tool_hash with zero-width chars
485        // could cause integrity check inconsistencies. Matches ToolVersionPin::validate() pattern.
486        for (name, value) in [
487            ("attestation_id", &self.attestation_id as &str),
488            ("attestation_type", &self.attestation_type),
489            ("attester", &self.attester),
490            ("timestamp", &self.timestamp),
491            ("tool_hash", &self.tool_hash),
492        ] {
493            if value
494                .chars()
495                .any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
496            {
497                return Err(format!(
498                    "ToolAttestation {name} contains control or format characters"
499                ));
500            }
501        }
502        for (name, value) in [
503            ("previous_attestation", self.previous_attestation.as_ref()),
504            (
505                "transparency_log_entry",
506                self.transparency_log_entry.as_ref(),
507            ),
508        ] {
509            if let Some(v) = value {
510                if v.chars()
511                    .any(|c| c.is_control() || crate::core::is_unicode_format_char(c))
512                {
513                    return Err(format!(
514                        "ToolAttestation {name} contains control or format characters"
515                    ));
516                }
517            }
518        }
519        self.signature.validate()?;
520        Ok(())
521    }
522
523    /// Returns true if this is the first attestation in the chain.
524    pub fn is_initial(&self) -> bool {
525        self.previous_attestation.is_none()
526    }
527}
528
529/// Version pinning record for a tool.
530///
531/// Pins allow administrators to lock tools to specific versions
532/// or version constraints, preventing unauthorized updates.
533#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
534#[serde(deny_unknown_fields)]
535pub struct ToolVersionPin {
536    /// Name of the tool being pinned.
537    pub tool_name: String,
538    /// Exact version to pin to (e.g., "1.2.3").
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub pinned_version: Option<String>,
541    /// Semver constraint (e.g., "^1.2.0", ">=1.0,<2.0").
542    #[serde(default, skip_serializing_if = "Option::is_none")]
543    pub version_constraint: Option<String>,
544    /// SHA-256 hash of the pinned tool definition.
545    pub definition_hash: String,
546    /// ISO 8601 timestamp when the pin was created.
547    pub pinned_at: String,
548    /// Identity of who created this pin.
549    pub pinned_by: String,
550}
551
552impl ToolVersionPin {
553    /// Maximum length for `tool_name` (bytes).
554    const MAX_TOOL_NAME_LEN: usize = 256;
555    /// Maximum length for `pinned_version` (bytes).
556    const MAX_VERSION_LEN: usize = 128;
557    /// Maximum length for `version_constraint` (bytes).
558    const MAX_CONSTRAINT_LEN: usize = 256;
559    /// Maximum length for `definition_hash` (bytes).
560    const MAX_HASH_LEN: usize = 256;
561    /// Maximum length for ISO 8601 timestamp fields (bytes).
562    const MAX_TIMESTAMP_LEN: usize = 64;
563    /// Maximum length for `pinned_by` (bytes).
564    const MAX_PINNED_BY_LEN: usize = 256;
565
566    /// Returns true if the pin uses an exact version match.
567    pub fn is_exact(&self) -> bool {
568        self.pinned_version.is_some()
569    }
570
571    /// Returns true if the pin uses a constraint.
572    pub fn is_constraint(&self) -> bool {
573        self.version_constraint.is_some()
574    }
575
576    /// Validate structural bounds on fields.
577    ///
578    /// SECURITY (FIND-R53-P3-008): Prevents memory exhaustion and control character
579    /// injection from untrusted `ToolVersionPin` payloads.
580    pub fn validate(&self) -> Result<(), String> {
581        if self.tool_name.is_empty() {
582            return Err("ToolVersionPin tool_name must not be empty".to_string());
583        }
584        if self.tool_name.len() > Self::MAX_TOOL_NAME_LEN {
585            return Err(format!(
586                "ToolVersionPin tool_name length {} exceeds max {}",
587                self.tool_name.len(),
588                Self::MAX_TOOL_NAME_LEN,
589            ));
590        }
591        if crate::core::has_dangerous_chars(&self.tool_name) {
592            return Err(
593                "ToolVersionPin tool_name contains control or format characters".to_string(),
594            );
595        }
596        if let Some(ref ver) = self.pinned_version {
597            if ver.len() > Self::MAX_VERSION_LEN {
598                return Err(format!(
599                    "ToolVersionPin pinned_version length {} exceeds max {}",
600                    ver.len(),
601                    Self::MAX_VERSION_LEN,
602                ));
603            }
604            // SECURITY: Reject control/format chars in pinned_version to prevent
605            // version comparison bypass via zero-width characters.
606            if crate::core::has_dangerous_chars(ver) {
607                return Err(
608                    "ToolVersionPin pinned_version contains control or format characters"
609                        .to_string(),
610                );
611            }
612        }
613        if let Some(ref constraint) = self.version_constraint {
614            if constraint.len() > Self::MAX_CONSTRAINT_LEN {
615                return Err(format!(
616                    "ToolVersionPin version_constraint length {} exceeds max {}",
617                    constraint.len(),
618                    Self::MAX_CONSTRAINT_LEN,
619                ));
620            }
621            // SECURITY: Reject control/format chars in version_constraint to prevent
622            // constraint parsing bypass via invisible characters.
623            if crate::core::has_dangerous_chars(constraint) {
624                return Err(
625                    "ToolVersionPin version_constraint contains control or format characters"
626                        .to_string(),
627                );
628            }
629        }
630        if self.definition_hash.len() > Self::MAX_HASH_LEN {
631            return Err(format!(
632                "ToolVersionPin definition_hash length {} exceeds max {}",
633                self.definition_hash.len(),
634                Self::MAX_HASH_LEN,
635            ));
636        }
637        // SECURITY: Reject control/format chars in definition_hash to prevent
638        // integrity check inconsistencies via zero-width characters in hash comparison.
639        if crate::core::has_dangerous_chars(&self.definition_hash) {
640            return Err(
641                "ToolVersionPin definition_hash contains control or format characters".to_string(),
642            );
643        }
644        if self.pinned_at.len() > Self::MAX_TIMESTAMP_LEN {
645            return Err(format!(
646                "ToolVersionPin pinned_at length {} exceeds max {}",
647                self.pinned_at.len(),
648                Self::MAX_TIMESTAMP_LEN,
649            ));
650        }
651        // SECURITY: Reject control/format chars in pinned_at to prevent
652        // log injection and timestamp comparison bypass.
653        if crate::core::has_dangerous_chars(&self.pinned_at) {
654            return Err(
655                "ToolVersionPin pinned_at contains control or format characters".to_string(),
656            );
657        }
658        if self.pinned_by.is_empty() {
659            return Err("ToolVersionPin pinned_by must not be empty".to_string());
660        }
661        if self.pinned_by.len() > Self::MAX_PINNED_BY_LEN {
662            return Err(format!(
663                "ToolVersionPin pinned_by length {} exceeds max {}",
664                self.pinned_by.len(),
665                Self::MAX_PINNED_BY_LEN,
666            ));
667        }
668        if crate::core::has_dangerous_chars(&self.pinned_by) {
669            return Err(
670                "ToolVersionPin pinned_by contains control or format characters".to_string(),
671            );
672        }
673        Ok(())
674    }
675}
676
677/// Result of version drift detection.
678///
679/// Generated when a tool's version or definition changes
680/// from the pinned state.
681#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
682#[serde(deny_unknown_fields)]
683pub struct VersionDriftAlert {
684    /// Name of the tool with drift.
685    pub tool: String,
686    /// Expected version string or definition hash from the pin.
687    ///
688    /// When `drift_type` is `"version_mismatch"`, this holds the pinned semver
689    /// version (e.g., `"1.2.3"`). When `drift_type` is `"hash_mismatch"`, this
690    /// holds the pinned SHA-256 definition hash.
691    pub expected_version: String,
692    /// Actual version string or definition hash observed at evaluation time.
693    ///
694    /// Interpretation depends on `drift_type` — see [`Self::expected_version`].
695    pub actual_version: String,
696    /// Type of drift detected: `"version_mismatch"` (semver changed) or
697    /// `"hash_mismatch"` (definition content changed while version stayed the same).
698    pub drift_type: String,
699    /// Whether this drift should block the tool from being used.
700    pub blocking: bool,
701    /// ISO 8601 timestamp when the drift was detected.
702    pub detected_at: String,
703}
704
705impl VersionDriftAlert {
706    /// Maximum length for string fields (`tool`, `expected_version`,
707    /// `actual_version`, `drift_type`, `detected_at`).
708    const MAX_FIELD_LEN: usize = 512;
709
710    /// Validate structural bounds on all string fields.
711    ///
712    /// SECURITY (FIND-R146-TE-001): Prevents memory exhaustion from oversized
713    /// fields and control/format character injection from untrusted payloads.
714    pub fn validate(&self) -> Result<(), String> {
715        for (name, value) in [
716            ("tool", &self.tool),
717            ("expected_version", &self.expected_version),
718            ("actual_version", &self.actual_version),
719            ("drift_type", &self.drift_type),
720            ("detected_at", &self.detected_at),
721        ] {
722            if value.is_empty() {
723                return Err(format!("VersionDriftAlert {name} must not be empty"));
724            }
725            if value.len() > Self::MAX_FIELD_LEN {
726                return Err(format!(
727                    "VersionDriftAlert {} length {} exceeds max {}",
728                    name,
729                    value.len(),
730                    Self::MAX_FIELD_LEN,
731                ));
732            }
733            if crate::core::has_dangerous_chars(value) {
734                return Err(format!(
735                    "VersionDriftAlert {name} contains control or format characters"
736                ));
737            }
738        }
739        Ok(())
740    }
741
742    /// Create a version mismatch alert.
743    pub fn version_mismatch(
744        tool: impl Into<String>,
745        expected: impl Into<String>,
746        actual: impl Into<String>,
747        blocking: bool,
748        detected_at: impl Into<String>,
749    ) -> Self {
750        Self {
751            tool: tool.into(),
752            expected_version: expected.into(),
753            actual_version: actual.into(),
754            drift_type: "version_mismatch".to_string(),
755            blocking,
756            detected_at: detected_at.into(),
757        }
758    }
759
760    /// Create a hash mismatch alert.
761    pub fn hash_mismatch(
762        tool: impl Into<String>,
763        expected_hash: impl Into<String>,
764        actual_hash: impl Into<String>,
765        blocking: bool,
766        detected_at: impl Into<String>,
767    ) -> Self {
768        Self {
769            tool: tool.into(),
770            expected_version: expected_hash.into(),
771            actual_version: actual_hash.into(),
772            drift_type: "hash_mismatch".to_string(),
773            blocking,
774            detected_at: detected_at.into(),
775        }
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782
783    #[test]
784    fn test_r231_iso8601_rejects_feb_31() {
785        assert!(!is_valid_iso8601_basic("2026-02-31T00:00:00Z"));
786    }
787
788    #[test]
789    fn test_r231_iso8601_rejects_feb_30_non_leap() {
790        assert!(!is_valid_iso8601_basic("2025-02-30T00:00:00Z"));
791    }
792
793    #[test]
794    fn test_r231_iso8601_rejects_feb_29_non_leap() {
795        assert!(!is_valid_iso8601_basic("2025-02-29T00:00:00Z"));
796    }
797
798    #[test]
799    fn test_r231_iso8601_accepts_feb_29_leap() {
800        assert!(is_valid_iso8601_basic("2024-02-29T00:00:00Z"));
801    }
802
803    #[test]
804    fn test_r231_iso8601_accepts_feb_28_non_leap() {
805        assert!(is_valid_iso8601_basic("2025-02-28T12:30:45Z"));
806    }
807
808    #[test]
809    fn test_r231_iso8601_rejects_apr_31() {
810        assert!(!is_valid_iso8601_basic("2026-04-31T00:00:00Z"));
811    }
812
813    #[test]
814    fn test_r231_iso8601_accepts_apr_30() {
815        assert!(is_valid_iso8601_basic("2026-04-30T00:00:00Z"));
816    }
817
818    #[test]
819    fn test_r231_iso8601_rejects_jun_31() {
820        assert!(!is_valid_iso8601_basic("2026-06-31T10:00:00Z"));
821    }
822
823    #[test]
824    fn test_r231_iso8601_accepts_jan_31() {
825        assert!(is_valid_iso8601_basic("2026-01-31T23:59:59Z"));
826    }
827
828    #[test]
829    fn test_r231_iso8601_century_leap_year() {
830        // 2000 is divisible by 400 → leap
831        assert!(is_valid_iso8601_basic("2000-02-29T00:00:00Z"));
832        // 1900 is divisible by 100 but not 400 → NOT leap
833        // But year < 1970 is rejected separately
834    }
835}