1pub mod blob;
158pub mod commit;
159pub mod context;
160pub mod context_frame;
161pub mod decision;
162pub mod evidence;
163pub mod integrity;
164pub mod intent;
165pub mod intent_event;
166pub mod note;
167pub mod patchset;
168pub mod plan;
169pub mod plan_step_event;
170pub mod provenance;
171pub mod run;
172pub mod run_event;
173pub mod run_usage;
174pub mod signature;
175pub mod tag;
176pub mod task;
177pub mod task_event;
178pub mod tool;
179pub mod tree;
180pub mod types;
181pub mod utils;
182
183use std::{
184 fmt::Display,
185 io::{BufRead, Read},
186};
187
188use crate::{
189 errors::GitError,
190 hash::{HashError, HashKind, ObjectHash, get_hash_kind},
191 internal::{object::types::ObjectType, zlib::stream::inflate::ReadBoxed},
192};
193
194pub trait ObjectTrait: Send + Sync + Display {
214 fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
216 where
217 Self: Sized;
218
219 fn from_buf_read_with_kind<R: BufRead>(
228 read: &mut ReadBoxed<R>,
229 size: usize,
230 kind: HashKind,
231 ) -> Result<Self, GitError>
232 where
233 Self: Sized,
234 {
235 let mut content: Vec<u8> = Vec::with_capacity(size);
236 read.read_to_end(&mut content)?;
237 let hasher = read.hash.clone();
238 let actual = hasher.kind();
239 if actual != kind {
240 return Err(HashError::KindMismatch {
241 operation: "from_buf_read_with_kind",
242 expected: kind,
243 actual,
244 expected_len: kind.size(),
245 actual_len: actual.size(),
246 }
247 .into());
248 }
249 let hash = hasher.finalize_object_hash();
250 Self::from_bytes(&content, hash)
251 }
252
253 fn from_buf_read<R: BufRead>(read: &mut ReadBoxed<R>, size: usize) -> Self
264 where
265 Self: Sized,
266 {
267 Self::from_buf_read_with_kind(read, size, get_hash_kind()).unwrap()
268 }
269
270 fn get_type(&self) -> ObjectType;
272
273 fn get_size(&self) -> usize;
274
275 fn to_data(&self) -> Result<Vec<u8>, GitError>;
276
277 fn object_hash_for_kind(&self, kind: HashKind) -> Result<ObjectHash, GitError> {
281 let data = self.to_data()?;
282 Ok(ObjectHash::from_type_and_data_for_kind(
283 kind,
284 self.get_type(),
285 &data,
286 )?)
287 }
288
289 fn object_hash(&self) -> Result<ObjectHash, GitError> {
293 self.object_hash_for_kind(get_hash_kind())
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use std::io::{self, Write};
300
301 use flate2::{Compression, write::ZlibEncoder};
302
303 use super::*;
304 use crate::{
305 hash::set_hash_kind_for_test,
306 internal::object::{
307 blob::Blob,
308 commit::Commit,
309 note::Note,
310 provenance::Provenance,
311 signature::{Signature, SignatureType},
312 tag::Tag,
313 tree::{Tree, TreeItem, TreeItemMode},
314 types::{ActorKind, ActorRef},
315 },
316 };
317
318 const KINDS: [(HashKind, HashKind); 4] = [
321 (HashKind::Sha1, HashKind::Sha256),
322 (HashKind::Sha256, HashKind::Sha1),
323 (HashKind::Blake3, HashKind::Sha256),
324 (HashKind::Sha256, HashKind::Blake3),
325 ];
326 const HELLO: &[u8] = b"Hello, world!";
327 const HELLO_BLOB_SHA1: &str = "5dd01c177f5d7d1be5346a5bc18a569a7410c2ef";
328 const HELLO_BLOB_SHA256: &str =
329 "178b5fbed164aee269fee7323badf7269cca0eed0875717b0d2d4f9819164c3f";
330
331 fn zlib(data: &[u8]) -> Vec<u8> {
332 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
333 enc.write_all(data).unwrap();
334 enc.finish().unwrap()
335 }
336
337 fn signature(role: SignatureType) -> Signature {
338 Signature::new(role, "tester".to_string(), "tester@example.com".to_string())
339 }
340
341 #[test]
344 fn object_hash_context_explicit_kind_ignores_thread_local() {
345 for (kind, other) in KINDS {
346 let _guard = set_hash_kind_for_test(other);
347
348 let blob = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
350 assert_eq!(blob.id.kind(), kind);
351 assert_eq!(blob.object_hash_for_kind(kind).unwrap(), blob.id);
352 let via_thread_local = blob.object_hash().unwrap();
353 assert_eq!(via_thread_local.kind(), other);
354 assert_ne!(via_thread_local, blob.id);
355
356 let actor = ActorRef::new(ActorKind::Agent, "agent-1").unwrap();
358 let provenance =
359 Provenance::new(actor, uuid::Uuid::now_v7(), "provider", "model").unwrap();
360 assert_eq!(provenance.object_hash_for_kind(kind).unwrap().kind(), kind);
361 assert_eq!(
362 provenance.object_hash_for_kind(other).unwrap().kind(),
363 other
364 );
365 assert_eq!(provenance.object_hash().unwrap().kind(), other);
366
367 let compressed = zlib(HELLO);
369 let mut reader = ReadBoxed::new_with_kind(
370 io::Cursor::new(&compressed),
371 ObjectType::Blob,
372 HELLO.len(),
373 kind,
374 )
375 .unwrap();
376 let loaded = Blob::from_buf_read_with_kind(&mut reader, HELLO.len(), kind).unwrap();
377 assert_eq!(loaded.id, blob.id);
378 assert_eq!(loaded.data, HELLO);
379
380 let tree = Tree::from_tree_items_with_kind(
383 kind,
384 vec![TreeItem::new(
385 TreeItemMode::Blob,
386 blob.id,
387 "hello.txt".to_string(),
388 )],
389 )
390 .unwrap();
391 let tree_bytes = tree.to_data().unwrap();
392 let mut reader = ReadBoxed::new_with_kind(
393 io::Cursor::new(zlib(&tree_bytes)),
394 ObjectType::Tree,
395 tree_bytes.len(),
396 kind,
397 )
398 .unwrap();
399 let loaded_tree =
400 Tree::from_buf_read_with_kind(&mut reader, tree_bytes.len(), kind).unwrap();
401 assert_eq!(loaded_tree.id, tree.id);
402 assert_eq!(loaded_tree.tree_items, tree.tree_items);
403 assert_eq!(loaded_tree.tree_items[0].id.kind(), kind);
404
405 let mut reader = ReadBoxed::new_with_kind(
407 io::Cursor::new(&compressed),
408 ObjectType::Blob,
409 HELLO.len(),
410 kind,
411 )
412 .unwrap();
413 let err = Blob::from_buf_read_with_kind(&mut reader, HELLO.len(), other).unwrap_err();
414 match err {
415 GitError::InvalidHashValue(msg) => {
416 assert!(msg.contains("from_buf_read_with_kind"), "{msg}");
417 assert!(
418 msg.contains(kind.as_str()) && msg.contains(other.as_str()),
419 "{msg}"
420 );
421 }
422 other_err => panic!("unexpected error: {other_err:?}"),
423 }
424 }
425 }
426
427 #[test]
430 fn object_hash_context_rejects_delta_reader() {
431 let _guard = set_hash_kind_for_test(HashKind::Sha1);
432 let err = ReadBoxed::new_with_kind(
433 io::Cursor::new(Vec::new()),
434 ObjectType::OffsetDelta,
435 7,
436 HashKind::Sha256,
437 )
438 .err()
439 .expect("delta type must be rejected");
440 match err {
441 GitError::InvalidHashValue(msg) => {
442 assert!(msg.contains("ReadBoxed::new_with_kind"), "{msg}");
443 assert!(
444 msg.contains("sha256") && msg.contains("OffsetDelta"),
445 "{msg}"
446 );
447 assert!(
448 msg.contains("32") && msg.contains("payload 7 bytes"),
449 "{msg}"
450 );
451 }
452 other => panic!("unexpected error: {other:?}"),
453 }
454 }
455
456 #[test]
458 fn blob_hash_for_kind_known_vectors() {
459 for (kind, other, expected) in [
460 (HashKind::Sha1, HashKind::Sha256, HELLO_BLOB_SHA1),
461 (HashKind::Sha256, HashKind::Sha1, HELLO_BLOB_SHA256),
462 ] {
463 let _guard = set_hash_kind_for_test(other);
464 let from_bytes = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
465 let from_str = Blob::from_content_with_kind(kind, "Hello, world!").unwrap();
466 assert_eq!(from_bytes.id.to_string(), expected);
467 assert_eq!(from_str.id, from_bytes.id);
468 assert_eq!(from_bytes.id.kind(), kind);
469 {
470 let _same = set_hash_kind_for_test(kind);
471 assert_eq!(Blob::from_content_bytes(HELLO.to_vec()).id, from_bytes.id);
472 }
473 }
474 }
475
476 #[test]
479 fn derived_id_for_kind_matches_explicit_hash() {
480 for (kind, other) in KINDS {
481 let _guard = set_hash_kind_for_test(other);
482
483 let blob = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
484 let item = TreeItem::new(TreeItemMode::Blob, blob.id, "hello.txt".to_string());
485 let mut tree = Tree::from_tree_items_with_kind(kind, vec![item]).unwrap();
486 assert_eq!(tree.id.kind(), kind);
487 assert_eq!(
488 tree.id,
489 ObjectHash::from_type_and_data_for_kind(
490 kind,
491 ObjectType::Tree,
492 &tree.to_data().unwrap()
493 )
494 .unwrap()
495 );
496 let before = tree.id;
497 tree.tree_items.push(TreeItem::new(
498 TreeItemMode::Blob,
499 blob.id,
500 "again.txt".to_string(),
501 ));
502 tree.rehash_with_kind(kind).unwrap();
503 assert_ne!(tree.id, before);
504 assert_eq!(tree.id.kind(), kind);
505 assert_eq!(tree.object_hash_for_kind(kind).unwrap(), tree.id);
506
507 let commit = Commit::new_with_kind(
508 kind,
509 signature(SignatureType::Author),
510 signature(SignatureType::Committer),
511 tree.id,
512 vec![],
513 "initial",
514 )
515 .unwrap();
516 assert_eq!(commit.id.kind(), kind);
517 assert_eq!(commit.object_hash_for_kind(kind).unwrap(), commit.id);
518 let child =
519 Commit::from_tree_id_with_kind(kind, tree.id, vec![commit.id], "child").unwrap();
520 assert_eq!(child.id.kind(), kind);
521 assert_eq!(child.parent_commit_ids, vec![commit.id]);
522 assert_eq!(child.object_hash_for_kind(kind).unwrap(), child.id);
523
524 let tag = Tag::new_with_kind(
525 kind,
526 commit.id,
527 ObjectType::Commit,
528 "v1".to_string(),
529 signature(SignatureType::Tagger),
530 "release".to_string(),
531 )
532 .unwrap();
533 assert_eq!(tag.id.kind(), kind);
534 assert_eq!(tag.object_hash_for_kind(kind).unwrap(), tag.id);
535
536 let note = Note::new_with_kind(kind, commit.id, "note body".to_string()).unwrap();
537 assert_eq!(note.id.kind(), kind);
538 assert_eq!(note.target_object_id, commit.id);
539 assert_eq!(note.object_hash_for_kind(kind).unwrap(), note.id);
540 let placeholder = Note::from_content_with_kind(kind, "note body").unwrap();
541 assert_eq!(placeholder.id, note.id);
542 assert_eq!(
543 placeholder.target_object_id,
544 ObjectHash::zero_for_kind(kind)
545 );
546 assert_eq!(placeholder.target_object_id.kind(), kind);
547 }
548 }
549
550 #[test]
553 fn derived_id_for_kind_rejects_cross_kind_references() {
554 for (own, foreign) in [
555 (HashKind::Sha1, HashKind::Sha256),
556 (HashKind::Sha256, HashKind::Blake3),
557 (HashKind::Blake3, HashKind::Sha256),
558 ] {
559 reject_cross_kind_references(own, foreign);
560 }
561 }
562
563 fn reject_cross_kind_references(own: HashKind, foreign: HashKind) {
564 let _guard = set_hash_kind_for_test(own);
565 let sha1_blob = Blob::from_content_bytes_with_kind(own, HELLO.to_vec()).unwrap();
566 let sha256_blob = Blob::from_content_bytes_with_kind(foreign, HELLO.to_vec()).unwrap();
567 assert_eq!(sha1_blob.id.kind(), own);
568 assert_eq!(sha256_blob.id.kind(), foreign);
569
570 let is_kind_mismatch = |err: GitError| match err {
571 GitError::InvalidHashValue(msg) => msg.contains("hash kind mismatch"),
572 _ => false,
573 };
574
575 let item = TreeItem::new(TreeItemMode::Blob, sha256_blob.id, "x".to_string());
576 assert!(is_kind_mismatch(
577 Tree::from_tree_items_with_kind(own, vec![item]).unwrap_err()
578 ));
579 let mut tree = Tree::from_tree_items_with_kind(
580 own,
581 vec![TreeItem::new(
582 TreeItemMode::Blob,
583 sha1_blob.id,
584 "x".to_string(),
585 )],
586 )
587 .unwrap();
588 tree.tree_items[0].id = sha256_blob.id;
589 assert!(is_kind_mismatch(tree.rehash_with_kind(own).unwrap_err()));
590
591 assert!(is_kind_mismatch(
592 Commit::from_tree_id_with_kind(own, sha256_blob.id, vec![], "m").unwrap_err()
593 ));
594 assert!(is_kind_mismatch(
595 Commit::from_tree_id_with_kind(own, sha1_blob.id, vec![sha256_blob.id], "m")
596 .unwrap_err()
597 ));
598 assert!(is_kind_mismatch(
599 Tag::new_with_kind(
600 own,
601 sha256_blob.id,
602 ObjectType::Blob,
603 "t".to_string(),
604 signature(SignatureType::Tagger),
605 "m".to_string(),
606 )
607 .unwrap_err()
608 ));
609 assert!(is_kind_mismatch(
610 Note::new_with_kind(own, sha256_blob.id, "n".to_string()).unwrap_err()
611 ));
612 }
613
614 #[test]
617 fn reference_parse_context_follows_hash_kind() {
618 for (kind, other) in KINDS {
619 let _guard = set_hash_kind_for_test(other);
620
621 let blob = Blob::from_content_bytes_with_kind(kind, HELLO.to_vec()).unwrap();
622 let tree = Tree::from_tree_items_with_kind(
623 kind,
624 vec![TreeItem::new(
625 TreeItemMode::Blob,
626 blob.id,
627 "hello.txt".to_string(),
628 )],
629 )
630 .unwrap();
631 let root = Commit::from_tree_id_with_kind(kind, tree.id, vec![], "root").unwrap();
632 let child = Commit::new_with_kind(
633 kind,
634 signature(SignatureType::Author),
635 signature(SignatureType::Committer),
636 tree.id,
637 vec![root.id, root.id],
638 "child\n\nbody",
639 )
640 .unwrap();
641
642 let parsed = Commit::from_bytes(&child.to_data().unwrap(), child.id).unwrap();
643 assert_eq!(parsed.tree_id, tree.id);
644 assert_eq!(parsed.tree_id.kind(), kind);
645 assert_eq!(parsed.parent_commit_ids, vec![root.id, root.id]);
646 assert!(parsed.parent_commit_ids.iter().all(|p| p.kind() == kind));
647 assert_eq!(parsed.message, "child\n\nbody");
648 assert_eq!(parsed.to_data().unwrap(), child.to_data().unwrap());
649
650 let tag = Tag::new_with_kind(
651 kind,
652 child.id,
653 ObjectType::Commit,
654 "v1".to_string(),
655 signature(SignatureType::Tagger),
656 "release".to_string(),
657 )
658 .unwrap();
659 let parsed = Tag::from_bytes(&tag.to_data().unwrap(), tag.id).unwrap();
660 assert_eq!(parsed.object_hash, child.id);
661 assert_eq!(parsed.object_hash.kind(), kind);
662
663 let note = Note::new_with_kind(kind, child.id, "annotation".to_string()).unwrap();
664 let parsed = Note::from_bytes(¬e.to_data().unwrap(), note.id).unwrap();
665 assert_eq!(parsed.target_object_id, ObjectHash::zero_for_kind(kind));
666 assert_eq!(parsed.target_object_id.kind(), kind);
667 assert_eq!(parsed.content, "annotation");
668 }
669 }
670
671 #[test]
674 fn reference_parse_context_rejects_cross_kind_and_malformed() {
675 let _guard = set_hash_kind_for_test(HashKind::Sha1);
676 let sha1_id = ObjectHash::new_for_kind(HashKind::Sha1, b"x");
677 let sha256_id = ObjectHash::new_for_kind(HashKind::Sha256, b"x");
678 let author = signature(SignatureType::Author).to_data().unwrap();
679 let committer = signature(SignatureType::Committer).to_data().unwrap();
680 let body = |tree: &str, parent: Option<&str>| {
681 let mut v = format!("tree {tree}\n").into_bytes();
682 if let Some(p) = parent {
683 v.extend(format!("parent {p}\n").into_bytes());
684 }
685 v.extend(&author);
686 v.push(b'\n');
687 v.extend(&committer);
688 v.extend(b"\nmsg");
689 v
690 };
691 let hash_msg = |err: GitError| match err {
692 GitError::InvalidHashValue(msg) => msg,
693 other => panic!("expected InvalidHashValue, got {other:?}"),
694 };
695
696 let msg =
698 hash_msg(Commit::from_bytes(&body(&sha1_id.to_string(), None), sha256_id).unwrap_err());
699 assert!(msg.contains("tree") && msg.contains("sha256"), "{msg}");
700 assert!(
701 msg.contains("expected 64") && msg.contains("got 40"),
702 "{msg}"
703 );
704
705 let msg = hash_msg(
707 Commit::from_bytes(
708 &body(&sha1_id.to_string(), Some(&sha256_id.to_string())),
709 sha1_id,
710 )
711 .unwrap_err(),
712 );
713 assert!(
714 msg.contains("parent") && msg.contains("expected 40") && msg.contains("got 64"),
715 "{msg}"
716 );
717
718 let msg = hash_msg(Commit::from_bytes(&body(&"zz".repeat(20), None), sha1_id).unwrap_err());
720 assert!(msg.contains("tree") && msg.contains("hex"), "{msg}");
721
722 assert!(matches!(
724 Commit::from_bytes(b"tree abc", sha1_id),
725 Err(GitError::InvalidCommitObject)
726 ));
727 assert!(matches!(
728 Commit::from_bytes(format!("tree {sha1_id}\n").as_bytes(), sha1_id),
729 Err(GitError::InvalidCommitObject)
730 ));
731 assert!(matches!(
732 Commit::from_bytes(format!("blob {sha1_id}\n").as_bytes(), sha1_id),
733 Err(GitError::InvalidCommitObject)
734 ));
735 let mut no_committer = format!("tree {sha1_id}\n").into_bytes();
736 no_committer.extend(&author);
737 assert!(matches!(
738 Commit::from_bytes(&no_committer, sha1_id),
739 Err(GitError::InvalidCommitObject)
740 ));
741
742 for bad_sig in [
744 "author",
745 "author name-without-email 1 +0000",
746 "author name <mail 1 +0000",
747 "author name <mail>",
748 "author name <mail> notanumber +0000",
749 "author name <mail> 1",
750 "author name <mail> 1 ",
751 "author name <mail>1 +0000",
752 "author name <mail>x1 +0000",
753 "author name <mail> 1 +08 00",
754 "author name<mail> 1 +0000",
755 "author name <mail> 1 garbage",
756 "author name <mail> 1 0800",
757 "author name <mail> 1 +12345",
758 "author name <mail> 1 +0a00",
759 "committer name <mail> 1 +0000",
760 "xauthor name <mail> 1 +0000",
761 "encoding utf-8",
762 ] {
763 let mut body = format!("tree {sha1_id}\n{bad_sig}\n").into_bytes();
764 body.extend(&committer);
765 body.extend(b"\nmsg");
766 match Commit::from_bytes(&body, sha1_id) {
767 Err(GitError::InvalidSignatureType(_)) | Err(GitError::InvalidCommitObject) => {}
768 Err(GitError::ConversionError(_)) => {}
769 other => panic!("expected a parse error for {bad_sig:?}, got {other:?}"),
770 }
771 }
772 let mut empty_name = format!("tree {sha1_id}\nauthor <mail> 1 +0000\n").into_bytes();
775 empty_name.extend(&committer);
776 empty_name.extend(b"\nmsg");
777 let parsed = Commit::from_bytes(&empty_name, sha1_id).unwrap();
778 assert_eq!(parsed.author.name, "");
779 assert_eq!(parsed.author.email, "mail");
780 assert_eq!(parsed.author.timestamp, 1);
781 assert_eq!(parsed.author.timezone, "+0000");
782 let mut negative_tz = format!("tree {sha1_id}\nauthor a b <m> 7 -0530\n").into_bytes();
783 negative_tz.extend(&committer);
784 negative_tz.extend(b"\nmsg");
785 let parsed = Commit::from_bytes(&negative_tz, sha1_id).unwrap();
786 assert_eq!(parsed.author.name, "a b");
787 assert_eq!(parsed.author.timezone, "-0530");
788 let mut two_authors = format!("tree {sha1_id}\n").into_bytes();
790 two_authors.extend(&author);
791 two_authors.push(b'\n');
792 two_authors.extend(&author);
793 two_authors.extend(b"\nmsg");
794 assert!(matches!(
795 Commit::from_bytes(&two_authors, sha1_id),
796 Err(GitError::InvalidCommitObject)
797 ));
798 let mut non_utf8 = format!("tree {sha1_id}\nauthor ").into_bytes();
799 non_utf8.extend_from_slice(&[0xff, 0xfe]);
800 non_utf8.extend(b" <m> 1 +0000\n");
801 non_utf8.extend(&committer);
802 non_utf8.extend(b"\nmsg");
803 assert!(matches!(
804 Commit::from_bytes(&non_utf8, sha1_id),
805 Err(GitError::InvalidSignatureType(_))
806 ));
807
808 let tag_body = format!(
810 "object {sha1_id}\ntype commit\ntag v1\n{}\n\nmsg",
811 String::from_utf8(signature(SignatureType::Tagger).to_data().unwrap()).unwrap()
812 );
813 match Tag::from_bytes(tag_body.as_bytes(), sha256_id) {
814 Err(GitError::InvalidTagObject(msg)) => {
815 assert!(
816 msg.contains("sha256") && msg.contains("expected 64"),
817 "{msg}"
818 )
819 }
820 other => panic!("expected InvalidTagObject, got {other:?}"),
821 }
822 let mut raw_tag = b"object ".to_vec();
824 raw_tag.extend_from_slice(&[0xffu8; 40]);
825 raw_tag.extend(b"\ntype commit\ntag v1\n");
826 match Tag::from_bytes(&raw_tag, sha1_id) {
827 Err(GitError::InvalidTagObject(msg)) => {
828 assert!(
829 msg.contains("sha1")
830 && msg.contains("expected 40")
831 && msg.contains("got 40 bytes"),
832 "{msg}"
833 )
834 }
835 other => panic!("expected InvalidTagObject, got {other:?}"),
836 }
837 }
838}