1use serde::{Deserialize, Serialize};
12use std::fmt;
13
14#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
16#[serde(rename_all = "snake_case")]
17pub enum SignatureAlgorithm {
18 #[default]
20 Ed25519,
21 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
34fn is_valid_iso8601_basic(s: &str) -> bool {
41 if s.len() != 20 {
43 return false;
44 }
45 let b = s.as_bytes();
46
47 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 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 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 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#[derive(Clone, Serialize, Deserialize, PartialEq)]
116#[serde(deny_unknown_fields)]
117pub struct ToolSignature {
118 pub signature_id: String,
120 pub signature: String,
122 pub algorithm: SignatureAlgorithm,
124 pub public_key: String,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub key_fingerprint: Option<String>,
129 pub signed_at: String,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub expires_at: Option<String>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub signer_spiffe_id: Option<String>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub rekor_entry: Option<serde_json::Value>,
141}
142
143impl 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 pub const MAX_REKOR_ENTRY_SIZE: usize = 65_536;
166
167 const MAX_SIGNATURE_ID_LEN: usize = 256;
169 const MAX_SIGNATURE_LEN: usize = 512;
171 const MAX_PUBLIC_KEY_LEN: usize = 512;
173 const MAX_TIMESTAMP_LEN: usize = 64;
175 const MAX_KEY_FINGERPRINT_LEN: usize = 256;
177 const MAX_SPIFFE_ID_LEN: usize = 2048;
179
180 pub fn validate(&self) -> Result<(), String> {
185 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 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 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 pub fn is_expired(&self, now: &str) -> bool {
311 if !now.ends_with('Z') {
313 return true;
314 }
315 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 if !is_valid_iso8601_basic(exp) {
325 return true;
326 }
327 now >= exp.as_str()
328 })
329 }
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
334#[serde(deny_unknown_fields)]
335pub struct SignatureVerification {
336 pub valid: bool,
338 pub signer_trusted: bool,
340 pub expired: bool,
342 pub message: String,
344}
345
346impl SignatureVerification {
347 const MAX_MESSAGE_LEN: usize = 4096;
349
350 pub fn is_fully_verified(&self) -> bool {
352 self.valid && self.signer_trusted && !self.expired
353 }
354
355 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
382#[serde(deny_unknown_fields)]
383pub struct ToolAttestation {
384 pub attestation_id: String,
386 pub attestation_type: String,
388 pub attester: String,
390 pub timestamp: String,
392 pub tool_hash: String,
394 #[serde(default, skip_serializing_if = "Option::is_none")]
396 pub previous_attestation: Option<String>,
397 pub signature: ToolSignature,
399 #[serde(default, skip_serializing_if = "Option::is_none")]
401 pub transparency_log_entry: Option<String>,
402}
403
404impl ToolAttestation {
405 pub const MAX_ATTESTATION_CHAIN_DEPTH: usize = 64;
407
408 const MAX_ATTESTATION_ID_LEN: usize = 256;
410 const MAX_ATTESTATION_TYPE_LEN: usize = 128;
412 const MAX_ATTESTER_LEN: usize = 512;
414 const MAX_TIMESTAMP_LEN: usize = 64;
416 const MAX_TOOL_HASH_LEN: usize = 256;
418 const MAX_PREV_ATTESTATION_LEN: usize = 256;
420 const MAX_LOG_ENTRY_LEN: usize = 2048;
422
423 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 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 pub fn is_initial(&self) -> bool {
525 self.previous_attestation.is_none()
526 }
527}
528
529#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
534#[serde(deny_unknown_fields)]
535pub struct ToolVersionPin {
536 pub tool_name: String,
538 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub pinned_version: Option<String>,
541 #[serde(default, skip_serializing_if = "Option::is_none")]
543 pub version_constraint: Option<String>,
544 pub definition_hash: String,
546 pub pinned_at: String,
548 pub pinned_by: String,
550}
551
552impl ToolVersionPin {
553 const MAX_TOOL_NAME_LEN: usize = 256;
555 const MAX_VERSION_LEN: usize = 128;
557 const MAX_CONSTRAINT_LEN: usize = 256;
559 const MAX_HASH_LEN: usize = 256;
561 const MAX_TIMESTAMP_LEN: usize = 64;
563 const MAX_PINNED_BY_LEN: usize = 256;
565
566 pub fn is_exact(&self) -> bool {
568 self.pinned_version.is_some()
569 }
570
571 pub fn is_constraint(&self) -> bool {
573 self.version_constraint.is_some()
574 }
575
576 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 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 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 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 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
682#[serde(deny_unknown_fields)]
683pub struct VersionDriftAlert {
684 pub tool: String,
686 pub expected_version: String,
692 pub actual_version: String,
696 pub drift_type: String,
699 pub blocking: bool,
701 pub detected_at: String,
703}
704
705impl VersionDriftAlert {
706 const MAX_FIELD_LEN: usize = 512;
709
710 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 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 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 assert!(is_valid_iso8601_basic("2000-02-29T00:00:00Z"));
832 }
835}