Skip to main content

git_internal/protocol/
core.rs

1//! Core Git protocol implementation
2//!
3//! This module provides the main `GitProtocol` struct and `RepositoryAccess` trait
4//! that form the core interface of the git-internal library.
5use std::collections::HashMap;
6
7use async_trait::async_trait;
8use bytes::{BufMut, Bytes, BytesMut};
9use futures::stream::StreamExt;
10
11use crate::{
12    hash::{HashKind, ObjectHash, get_hash_kind},
13    internal::object::ObjectTrait,
14    protocol::{
15        smart::SmartProtocol,
16        types::{Capability, ProtocolError, ProtocolStream, ServiceType, SideBand},
17    },
18};
19
20/// Repository access trait for storage operations
21///
22/// This trait only handles storage-level operations, not Git protocol details.
23/// The git-internal library handles all Git protocol formatting and parsing.
24#[async_trait]
25pub trait RepositoryAccess: Send + Sync + Clone {
26    /// The object-ID hash kind of this repository.
27    ///
28    /// The default returns the thread-local [`HashKind`] so existing
29    /// implementors keep working unchanged; implementors that serve a
30    /// repository whose format is known (or that may be called from a thread
31    /// configured for another repository) should override it to return the
32    /// repository's real format. The default object accessors below parse
33    /// incoming hash strings against this kind and fail closed on a mismatch.
34    fn object_hash_kind(&self) -> HashKind {
35        get_hash_kind()
36    }
37
38    /// Get repository references as raw (name, hash) pairs
39    async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError>;
40
41    /// Check if an object exists in the repository
42    async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError>;
43
44    /// Get raw object data by hash
45    async fn get_object(&self, object_hash: &str) -> Result<Vec<u8>, ProtocolError>;
46
47    /// Store pack data in the repository
48    async fn store_pack_data(&self, pack_data: &[u8]) -> Result<(), ProtocolError>;
49
50    /// Update a single reference
51    async fn update_reference(
52        &self,
53        ref_name: &str,
54        old_hash: Option<&str>,
55        new_hash: &str,
56    ) -> Result<(), ProtocolError>;
57
58    /// Get objects needed for pack generation
59    async fn get_objects_for_pack(
60        &self,
61        wants: &[String],
62        haves: &[String],
63    ) -> Result<Vec<String>, ProtocolError>;
64
65    /// Check if repository has a default branch
66    async fn has_default_branch(&self) -> Result<bool, ProtocolError>;
67
68    /// Post-receive hook after successful push
69    async fn post_receive_hook(&self) -> Result<(), ProtocolError>;
70
71    /// Get blob data by hash
72    ///
73    /// Default implementation parses the object data using the internal object module.
74    /// Override this method if you need custom blob handling logic.
75    async fn get_blob(
76        &self,
77        object_hash: &str,
78    ) -> Result<crate::internal::object::blob::Blob, ProtocolError> {
79        // Resolve the repository kind before the first await: the default reads a
80
81        // thread-local, and the future may resume on another worker thread.
82
83        let kind = self.object_hash_kind();
84
85        let hash = ObjectHash::from_hex_for_kind(kind, object_hash)
86            .map_err(|e| ProtocolError::repository_error(format!("Invalid hash format: {e}")))?;
87        let data = self.get_object(object_hash).await?;
88
89        crate::internal::object::blob::Blob::from_bytes(&data, hash)
90            .map_err(|e| ProtocolError::repository_error(format!("Failed to parse blob: {e}")))
91    }
92
93    /// Get commit data by hash
94    ///
95    /// Default implementation parses the object data using the internal object module.
96    /// Override this method if you need custom commit handling logic.
97    async fn get_commit(
98        &self,
99        commit_hash: &str,
100    ) -> Result<crate::internal::object::commit::Commit, ProtocolError> {
101        // Resolve the repository kind before the first await: the default reads a
102
103        // thread-local, and the future may resume on another worker thread.
104
105        let kind = self.object_hash_kind();
106
107        let hash = ObjectHash::from_hex_for_kind(kind, commit_hash)
108            .map_err(|e| ProtocolError::repository_error(format!("Invalid hash format: {e}")))?;
109        let data = self.get_object(commit_hash).await?;
110
111        crate::internal::object::commit::Commit::from_bytes(&data, hash)
112            .map_err(|e| ProtocolError::repository_error(format!("Failed to parse commit: {e}")))
113    }
114
115    /// Get tree data by hash
116    ///
117    /// Default implementation parses the object data using the internal object module.
118    /// Override this method if you need custom tree handling logic.
119    async fn get_tree(
120        &self,
121        tree_hash: &str,
122    ) -> Result<crate::internal::object::tree::Tree, ProtocolError> {
123        // Resolve the repository kind before the first await: the default reads a
124
125        // thread-local, and the future may resume on another worker thread.
126
127        let kind = self.object_hash_kind();
128
129        let hash = ObjectHash::from_hex_for_kind(kind, tree_hash)
130            .map_err(|e| ProtocolError::repository_error(format!("Invalid hash format: {e}")))?;
131        let data = self.get_object(tree_hash).await?;
132
133        crate::internal::object::tree::Tree::from_bytes(&data, hash)
134            .map_err(|e| ProtocolError::repository_error(format!("Failed to parse tree: {e}")))
135    }
136
137    /// Check if a commit exists
138    ///
139    /// Default implementation checks object existence and validates it's a commit.
140    /// Override this method if you have more efficient commit existence checking.
141    async fn commit_exists(&self, commit_hash: &str) -> Result<bool, ProtocolError> {
142        match self.has_object(commit_hash).await {
143            Ok(exists) => {
144                if !exists {
145                    return Ok(false);
146                }
147
148                // Verify it's actually a commit by trying to parse it
149                match self.get_commit(commit_hash).await {
150                    Ok(_) => Ok(true),
151                    Err(_) => Ok(false), // Object exists but is not a valid commit
152                }
153            }
154            Err(e) => Err(e),
155        }
156    }
157
158    /// Handle pack objects after unpacking
159    ///
160    /// Default implementation stores each object individually using store_pack_data.
161    /// Override this method if you need batch processing or custom storage logic.
162    async fn handle_pack_objects(
163        &self,
164        commits: Vec<crate::internal::object::commit::Commit>,
165        trees: Vec<crate::internal::object::tree::Tree>,
166        blobs: Vec<crate::internal::object::blob::Blob>,
167    ) -> Result<(), ProtocolError> {
168        // Store blobs
169        for blob in blobs {
170            let data = blob.to_data().map_err(|e| {
171                ProtocolError::repository_error(format!("Failed to serialize blob: {e}"))
172            })?;
173            self.store_pack_data(&data).await.map_err(|e| {
174                ProtocolError::repository_error(format!("Failed to store blob {}: {}", blob.id, e))
175            })?;
176        }
177
178        // Store trees
179        for tree in trees {
180            let data = tree.to_data().map_err(|e| {
181                ProtocolError::repository_error(format!("Failed to serialize tree: {e}"))
182            })?;
183            self.store_pack_data(&data).await.map_err(|e| {
184                ProtocolError::repository_error(format!("Failed to store tree {}: {}", tree.id, e))
185            })?;
186        }
187
188        // Store commits
189        for commit in commits {
190            let data = commit.to_data().map_err(|e| {
191                ProtocolError::repository_error(format!("Failed to serialize commit: {e}"))
192            })?;
193            self.store_pack_data(&data).await.map_err(|e| {
194                ProtocolError::repository_error(format!(
195                    "Failed to store commit {}: {}",
196                    commit.id, e
197                ))
198            })?;
199        }
200
201        Ok(())
202    }
203}
204
205/// Authentication service trait
206#[async_trait]
207pub trait AuthenticationService: Send + Sync {
208    /// Authenticate HTTP request
209    async fn authenticate_http(
210        &self,
211        headers: &std::collections::HashMap<String, String>,
212    ) -> Result<(), ProtocolError>;
213
214    /// Authenticate SSH public key
215    async fn authenticate_ssh(
216        &self,
217        username: &str,
218        public_key: &[u8],
219    ) -> Result<(), ProtocolError>;
220}
221
222/// Transport-agnostic Git smart protocol handler
223/// Main Git protocol handler
224///
225/// This struct provides the core Git protocol implementation that works
226/// across HTTP, SSH, and other transports. It uses SmartProtocol internally
227/// to handle all Git protocol details.
228pub struct GitProtocol<R: RepositoryAccess, A: AuthenticationService> {
229    smart_protocol: SmartProtocol<R, A>,
230}
231
232impl<R: RepositoryAccess, A: AuthenticationService> GitProtocol<R, A> {
233    /// Create a new GitProtocol instance.
234    ///
235    /// The protocol is bound to `repo_access.object_hash_kind()`: info-refs advertises that
236    /// `object-format`, capability negotiation accepts only that value, and every operation
237    /// re-checks repository/local/wire kind consistency (see `SmartProtocol`).
238    pub fn new(repo_access: R, auth_service: A) -> Self {
239        Self {
240            smart_protocol: SmartProtocol::new(
241                super::types::TransportProtocol::Http,
242                repo_access,
243                auth_service,
244            ),
245        }
246    }
247
248    /// Authenticate HTTP request before serving Git operations
249    pub async fn authenticate_http(
250        &self,
251        headers: &HashMap<String, String>,
252    ) -> Result<(), ProtocolError> {
253        self.smart_protocol.authenticate_http(headers).await
254    }
255
256    /// Authenticate SSH session before serving Git operations
257    pub async fn authenticate_ssh(
258        &self,
259        username: &str,
260        public_key: &[u8],
261    ) -> Result<(), ProtocolError> {
262        self.smart_protocol
263            .authenticate_ssh(username, public_key)
264            .await
265    }
266
267    /// Set transport protocol (Http, Ssh, etc.)
268    pub fn set_transport(&mut self, protocol: super::types::TransportProtocol) {
269        self.smart_protocol.set_transport_protocol(protocol);
270    }
271
272    /// Handle git info-refs request
273    pub async fn info_refs(&self, service: &str) -> Result<Vec<u8>, ProtocolError> {
274        let service_type = match service {
275            "git-upload-pack" => ServiceType::UploadPack,
276            "git-receive-pack" => ServiceType::ReceivePack,
277            _ => return Err(ProtocolError::invalid_service(service)),
278        };
279
280        let bytes = self.smart_protocol.git_info_refs(service_type).await?;
281        Ok(bytes.to_vec())
282    }
283
284    /// Handle git-upload-pack request (for clone/fetch)
285    pub async fn upload_pack(
286        &mut self,
287        request_data: &[u8],
288    ) -> Result<ProtocolStream, ProtocolError> {
289        const SIDE_BAND_PACKET_LEN: usize = 1000;
290        const SIDE_BAND_64K_PACKET_LEN: usize = 65520;
291        const SIDE_BAND_HEADER_LEN: usize = 5; // 4-byte length + 1-byte band
292
293        let request_bytes = bytes::Bytes::from(request_data.to_vec());
294        let (pack_stream, protocol_buf) =
295            self.smart_protocol.git_upload_pack(request_bytes).await?;
296        let ack_bytes = protocol_buf.freeze();
297
298        let ack_stream: ProtocolStream = if ack_bytes.is_empty() {
299            Box::pin(futures::stream::empty::<Result<Bytes, ProtocolError>>())
300        } else {
301            Box::pin(futures::stream::once(async move { Ok(ack_bytes) }))
302        };
303
304        let sideband_max = if self
305            .smart_protocol
306            .capabilities
307            .contains(&Capability::SideBand64k)
308        {
309            Some(SIDE_BAND_64K_PACKET_LEN - SIDE_BAND_HEADER_LEN)
310        } else if self
311            .smart_protocol
312            .capabilities
313            .contains(&Capability::SideBand)
314        {
315            Some(SIDE_BAND_PACKET_LEN - SIDE_BAND_HEADER_LEN)
316        } else {
317            None
318        };
319
320        // Producer failures travel as `Err` items and are forwarded as protocol errors, in
321        // both the side-band and the raw framing.
322        let data_stream: ProtocolStream = if let Some(max_payload) = sideband_max {
323            let stream = pack_stream.flat_map(move |chunk| {
324                let packets: Vec<Result<Bytes, ProtocolError>> = match chunk {
325                    Ok(chunk) => build_side_band_packets(&chunk, max_payload)
326                        .into_iter()
327                        .map(Ok)
328                        .collect(),
329                    Err(e) => vec![Err(e)],
330                };
331                futures::stream::iter(packets)
332            });
333            let stream = stream.chain(futures::stream::once(async {
334                Ok(Bytes::from_static(b"0000"))
335            }));
336            Box::pin(stream)
337        } else {
338            Box::pin(pack_stream.map(|data| data.map(Bytes::from)))
339        };
340
341        Ok(Box::pin(ack_stream.chain(data_stream)))
342    }
343
344    /// Handle git-receive-pack request (for push)
345    pub async fn receive_pack(
346        &mut self,
347        request_stream: ProtocolStream,
348    ) -> Result<ProtocolStream, ProtocolError> {
349        const SIDE_BAND_PACKET_LEN: usize = 1000;
350        const SIDE_BAND_64K_PACKET_LEN: usize = 65520;
351        const SIDE_BAND_HEADER_LEN: usize = 5; // 4-byte length + 1-byte band
352
353        let result_bytes = self
354            .smart_protocol
355            .git_receive_pack_stream(request_stream)
356            .await?;
357
358        let sideband_max = if self
359            .smart_protocol
360            .capabilities
361            .contains(&Capability::SideBand64k)
362        {
363            Some(SIDE_BAND_64K_PACKET_LEN - SIDE_BAND_HEADER_LEN)
364        } else if self
365            .smart_protocol
366            .capabilities
367            .contains(&Capability::SideBand)
368        {
369            Some(SIDE_BAND_PACKET_LEN - SIDE_BAND_HEADER_LEN)
370        } else {
371            None
372        };
373
374        // Wrap report-status in side-band if negotiated by the client.
375        if let Some(max_payload) = sideband_max {
376            let packets = build_side_band_packets(result_bytes.as_ref(), max_payload);
377            let stream = futures::stream::iter(packets.into_iter().map(Ok)).chain(
378                futures::stream::once(async { Ok(Bytes::from_static(b"0000")) }),
379            );
380            Ok(Box::pin(stream))
381        } else {
382            // Return the report status as a single-chunk stream
383            Ok(Box::pin(futures::stream::once(async { Ok(result_bytes) })))
384        }
385    }
386}
387
388fn build_side_band_packets(chunk: &[u8], max_payload: usize) -> Vec<Bytes> {
389    if chunk.is_empty() {
390        return Vec::new();
391    }
392
393    let mut out = Vec::new();
394    let mut offset = 0;
395
396    while offset < chunk.len() {
397        let end = (offset + max_payload).min(chunk.len());
398        let payload = &chunk[offset..end];
399        let length = payload.len() + 5; // 4-byte length + 1-byte band
400        let mut pkt = BytesMut::with_capacity(length);
401        pkt.put(Bytes::from(format!("{length:04x}")));
402        pkt.put_u8(SideBand::PackfileData.value());
403        pkt.put(payload);
404        out.push(pkt.freeze());
405        offset = end;
406    }
407
408    out
409}
410
411#[cfg(test)]
412mod tests {
413    use async_trait::async_trait;
414    use bytes::{Bytes, BytesMut};
415    use futures::StreamExt;
416
417    use super::*;
418    use crate::{
419        hash::{HashKind, set_hash_kind_for_test},
420        internal::object::{
421            blob::Blob,
422            commit::Commit,
423            signature::{Signature, SignatureType},
424            tree::{Tree, TreeItem, TreeItemMode},
425        },
426        protocol::{types::TransportProtocol, utils},
427    };
428
429    /// Simple mock repository that serves fixed refs and echoes wants.
430    #[derive(Clone)]
431    struct MockRepo {
432        refs: Vec<(String, String)>,
433    }
434
435    #[async_trait]
436    impl RepositoryAccess for MockRepo {
437        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
438            Ok(self.refs.clone())
439        }
440        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
441            Ok(false)
442        }
443        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
444            Ok(Vec::new())
445        }
446        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
447            Ok(())
448        }
449        async fn update_reference(
450            &self,
451            _ref_name: &str,
452            _old_hash: Option<&str>,
453            _new_hash: &str,
454        ) -> Result<(), ProtocolError> {
455            Ok(())
456        }
457        async fn get_objects_for_pack(
458            &self,
459            wants: &[String],
460            _haves: &[String],
461        ) -> Result<Vec<String>, ProtocolError> {
462            Ok(wants.to_vec())
463        }
464        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
465            Ok(false)
466        }
467        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
468            Ok(())
469        }
470    }
471
472    /// No-op auth service for tests.
473    struct MockAuth;
474    #[async_trait]
475    impl AuthenticationService for MockAuth {
476        async fn authenticate_http(
477            &self,
478            _headers: &std::collections::HashMap<String, String>,
479        ) -> Result<(), ProtocolError> {
480            Ok(())
481        }
482        async fn authenticate_ssh(
483            &self,
484            _username: &str,
485            _public_key: &[u8],
486        ) -> Result<(), ProtocolError> {
487            Ok(())
488        }
489    }
490
491    /// Convenience builder for GitProtocol with mock repo/auth.
492    fn make_protocol() -> GitProtocol<MockRepo, MockAuth> {
493        GitProtocol::new(
494            MockRepo {
495                refs: vec![
496                    (
497                        "refs/heads/main".to_string(),
498                        ObjectHash::default().to_string(),
499                    ),
500                    ("HEAD".to_string(), ObjectHash::default().to_string()),
501                ],
502            },
503            MockAuth,
504        )
505    }
506
507    /// Mock repo that serves a single commit, tree, and blobs.
508    #[derive(Clone)]
509    struct SideBandRepo {
510        commit: Commit,
511        tree: Tree,
512        blobs: Vec<Blob>,
513    }
514    #[async_trait]
515    impl RepositoryAccess for SideBandRepo {
516        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
517            Ok(vec![(
518                "refs/heads/main".to_string(),
519                self.commit.id.to_string(),
520            )])
521        }
522
523        async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError> {
524            let known = object_hash == self.commit.id.to_string()
525                || object_hash == self.tree.id.to_string()
526                || self.blobs.iter().any(|b| b.id.to_string() == object_hash);
527            Ok(known)
528        }
529
530        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
531            Ok(Vec::new())
532        }
533
534        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
535            Ok(())
536        }
537
538        async fn update_reference(
539            &self,
540            _ref_name: &str,
541            _old_hash: Option<&str>,
542            _new_hash: &str,
543        ) -> Result<(), ProtocolError> {
544            Ok(())
545        }
546
547        async fn get_objects_for_pack(
548            &self,
549            _wants: &[String],
550            _haves: &[String],
551        ) -> Result<Vec<String>, ProtocolError> {
552            Ok(Vec::new())
553        }
554
555        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
556            Ok(true)
557        }
558
559        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
560            Ok(())
561        }
562
563        async fn get_commit(&self, commit_hash: &str) -> Result<Commit, ProtocolError> {
564            if commit_hash == self.commit.id.to_string() {
565                Ok(self.commit.clone())
566            } else {
567                Err(ProtocolError::ObjectNotFound(commit_hash.to_string()))
568            }
569        }
570
571        async fn get_tree(&self, tree_hash: &str) -> Result<Tree, ProtocolError> {
572            if tree_hash == self.tree.id.to_string() {
573                Ok(self.tree.clone())
574            } else {
575                Err(ProtocolError::ObjectNotFound(tree_hash.to_string()))
576            }
577        }
578
579        async fn get_blob(&self, blob_hash: &str) -> Result<Blob, ProtocolError> {
580            self.blobs
581                .iter()
582                .find(|b| b.id.to_string() == blob_hash)
583                .cloned()
584                .ok_or_else(|| ProtocolError::ObjectNotFound(blob_hash.to_string()))
585        }
586    }
587
588    fn build_repo_with_objects() -> (SideBandRepo, Commit) {
589        let blob = Blob::from_content("hello");
590        let item = TreeItem::new(TreeItemMode::Blob, blob.id, "hello.txt".to_string());
591        let tree = Tree::from_tree_items(vec![item]).unwrap();
592        let author = Signature::new(
593            SignatureType::Author,
594            "tester".to_string(),
595            "tester@example.com".to_string(),
596        );
597        let committer = Signature::new(
598            SignatureType::Committer,
599            "tester".to_string(),
600            "tester@example.com".to_string(),
601        );
602        let commit = Commit::new(author, committer, tree.id, vec![], "init commit");
603
604        let repo = SideBandRepo {
605            commit: commit.clone(),
606            tree,
607            blobs: vec![blob],
608        };
609
610        (repo, commit)
611    }
612
613    /// upload-pack should emit NAK before sending pack data.
614    #[tokio::test]
615    async fn upload_pack_emits_ack_before_pack() {
616        let _guard = set_hash_kind_for_test(HashKind::Sha1);
617        let (repo, commit) = build_repo_with_objects();
618        let mut proto = GitProtocol::new(repo, MockAuth);
619        let mut request = BytesMut::new();
620        utils::add_pkt_line_string(&mut request, format!("want {}\n", commit.id));
621        utils::add_pkt_line_string(&mut request, "done\n".to_string());
622
623        let mut stream = proto.upload_pack(&request).await.expect("upload-pack");
624        let mut out = BytesMut::new();
625        while let Some(chunk) = stream.next().await {
626            out.extend_from_slice(&chunk.expect("stream chunk"));
627        }
628
629        let mut out_bytes = out.freeze();
630        let (_len, line) = utils::read_pkt_line(&mut out_bytes);
631        assert_eq!(line, Bytes::from_static(b"NAK\n"));
632        assert!(
633            out_bytes.as_ref().starts_with(b"PACK"),
634            "pack should follow ack"
635        );
636    }
637
638    /// upload-pack with side-band should wrap pack data in side-band packets.
639    #[tokio::test]
640    async fn upload_pack_sideband_frames_pack() {
641        let _guard = set_hash_kind_for_test(HashKind::Sha1);
642        let (repo, commit) = build_repo_with_objects();
643
644        let mut proto = GitProtocol::new(repo, MockAuth);
645        let mut request = BytesMut::new();
646        utils::add_pkt_line_string(&mut request, format!("want {} side-band-64k\n", commit.id));
647        utils::add_pkt_line_string(&mut request, "done\n".to_string());
648
649        let mut stream = proto.upload_pack(&request).await.expect("upload-pack");
650        let mut out = BytesMut::new();
651        while let Some(chunk) = stream.next().await {
652            out.extend_from_slice(&chunk.expect("stream chunk"));
653        }
654
655        let mut out_bytes = out.freeze();
656        let (_len, line) = utils::read_pkt_line(&mut out_bytes);
657        assert_eq!(line, Bytes::from_static(b"NAK\n"));
658
659        let raw = out_bytes.as_ref();
660        assert!(raw.len() > 9, "side-band packet should include PACK header");
661        let len_hex = std::str::from_utf8(&raw[..4]).expect("hex length");
662        let pkt_len = usize::from_str_radix(len_hex, 16).expect("parse length");
663        assert!(pkt_len > 5, "side-band packet should contain data");
664        assert_eq!(raw[4], SideBand::PackfileData.value());
665        assert_eq!(&raw[5..9], b"PACK");
666        assert!(raw.ends_with(b"0000"), "side-band stream should flush");
667    }
668
669    /// info_refs should include refs, capabilities, and object-format.
670    #[tokio::test]
671    async fn info_refs_includes_refs_and_caps() {
672        let proto = make_protocol();
673        let bytes = proto.info_refs("git-upload-pack").await.expect("info_refs");
674        let text = String::from_utf8(bytes).expect("utf8");
675        assert!(text.contains("refs/heads/main"));
676        assert!(text.contains("capabilities"));
677        assert!(text.contains("object-format"));
678    }
679
680    /// Invalid service name should return InvalidService.
681    #[tokio::test]
682    async fn info_refs_invalid_service_errors() {
683        let proto = make_protocol();
684        let err = proto.info_refs("git-invalid").await.unwrap_err();
685        assert!(matches!(err, ProtocolError::InvalidService(_)));
686    }
687
688    /// Ensure set_transport can switch protocols without panic.
689    #[tokio::test]
690    async fn can_switch_transport() {
691        let mut proto = make_protocol();
692        proto.set_transport(TransportProtocol::Ssh);
693        // if set_transport did not panic, we consider this path covered
694    }
695
696    /// Wire hash kind expects SHA1 length; providing SHA256 refs should error.
697    #[tokio::test]
698    async fn info_refs_hash_length_mismatch_errors() {
699        let proto = GitProtocol::new(
700            MockRepo {
701                refs: vec![(
702                    "refs/heads/main".to_string(),
703                    "f".repeat(HashKind::Sha256.hex_len()),
704                )],
705            },
706            MockAuth,
707        );
708        let err = proto.info_refs("git-upload-pack").await.unwrap_err();
709        assert!(matches!(err, ProtocolError::InvalidRequest(_)));
710    }
711
712    /// Mock repo that reports a fixed object-hash kind and serves one blob.
713    #[derive(Clone)]
714    struct FixedKindRepo {
715        kind: HashKind,
716        blob: Blob,
717    }
718
719    #[async_trait]
720    impl RepositoryAccess for FixedKindRepo {
721        fn object_hash_kind(&self) -> HashKind {
722            self.kind
723        }
724        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
725            Ok(Vec::new())
726        }
727        async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError> {
728            Ok(object_hash == self.blob.id.to_string())
729        }
730        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
731            Ok(self.blob.data.clone())
732        }
733        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
734            Ok(())
735        }
736        async fn update_reference(
737            &self,
738            _ref_name: &str,
739            _old_hash: Option<&str>,
740            _new_hash: &str,
741        ) -> Result<(), ProtocolError> {
742            Ok(())
743        }
744        async fn get_objects_for_pack(
745            &self,
746            _wants: &[String],
747            _haves: &[String],
748        ) -> Result<Vec<String>, ProtocolError> {
749            Ok(Vec::new())
750        }
751        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
752            Ok(false)
753        }
754        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
755            Ok(())
756        }
757    }
758
759    /// `object_hash_kind()` defaults to the thread-local kind; an override drives the default
760    /// object accessors, which parse hashes against it and fail closed on a width mismatch.
761    #[tokio::test]
762    async fn repository_hash_kind_default_and_override() {
763        for (kind, other) in [
764            (HashKind::Sha1, HashKind::Sha256),
765            (HashKind::Sha256, HashKind::Sha1),
766        ] {
767            let _guard = set_hash_kind_for_test(kind);
768            // Default implementation follows the thread-local kind.
769            assert_eq!(MockRepo { refs: Vec::new() }.object_hash_kind(), kind);
770
771            // Override wins over the thread-local kind.
772            let blob = Blob::from_content_bytes_with_kind(other, b"hello".to_vec()).unwrap();
773            let repo = FixedKindRepo {
774                kind: other,
775                blob: blob.clone(),
776            };
777            assert_eq!(repo.object_hash_kind(), other);
778
779            let fetched = repo.get_blob(&blob.id.to_string()).await.unwrap();
780            assert_eq!(fetched.id, blob.id);
781            assert_eq!(fetched.id.kind(), other);
782
783            // A hash of the thread-local kind's width is rejected for this repository.
784            let wrong_width = ObjectHash::zero_for_kind(kind).to_string();
785            for err in [
786                repo.get_blob(&wrong_width).await.unwrap_err(),
787                repo.get_commit(&wrong_width).await.unwrap_err(),
788                repo.get_tree(&wrong_width).await.unwrap_err(),
789            ] {
790                let msg = err.to_string();
791                assert!(msg.contains("Invalid hash format"), "{msg}");
792                assert!(
793                    msg.contains(other.as_str())
794                        && msg.contains(&format!("expected {}", other.hex_len()))
795                        && msg.contains(&format!("got {}", kind.hex_len())),
796                    "{msg}"
797                );
798            }
799        }
800    }
801
802    /// `GitProtocol` follows the repository's `object_hash_kind()` end to end (BLAKE3 here,
803    /// while the thread-local kind stays SHA-1): info-refs advertises `object-format=blake3`
804    /// with a 64-hex zero ID, object access parses IDs as BLAKE3, upload-pack rejects a
805    /// SHA-1-width want line, and a repository whose kind diverges from the protocol's
806    /// binding is refused instead of served under another format.
807    #[tokio::test]
808    async fn hash_kind_context() {
809        let _guard = set_hash_kind_for_test(HashKind::Sha1);
810        let blob = Blob::from_content_bytes_with_kind(HashKind::Blake3, b"hello".to_vec()).unwrap();
811        let repo = FixedKindRepo {
812            kind: HashKind::Blake3,
813            blob: blob.clone(),
814        };
815        let mut proto = GitProtocol::new(repo.clone(), MockAuth);
816
817        let bytes = proto.info_refs("git-upload-pack").await.unwrap();
818        let text = String::from_utf8(bytes).unwrap();
819        assert!(text.contains(" object-format=blake3"), "{text}");
820        assert!(
821            text.contains(&format!("{} capabilities^{{}}", "0".repeat(64))),
822            "{text}"
823        );
824        assert!(!text.contains("object-format=sha"), "{text}");
825
826        // Object access uses the repository kind (64-hex BLAKE3 ID), not the thread-local one.
827        let fetched = repo.get_blob(&blob.id.to_string()).await.unwrap();
828        assert_eq!(fetched.id, blob.id);
829        assert_eq!(fetched.id.kind(), HashKind::Blake3);
830
831        // A SHA-1-width want line is a diagnosable error on the BLAKE3 wire.
832        let mut request = BytesMut::new();
833        crate::protocol::utils::add_pkt_line_string(
834            &mut request,
835            format!("want {}\n", "a".repeat(40)),
836        );
837        request.put(&crate::protocol::types::PKT_LINE_END_MARKER[..]);
838        let err = proto
839            .upload_pack(&request)
840            .await
841            .err()
842            .expect("SHA-1-width want on a BLAKE3 wire must fail");
843        assert!(matches!(err, ProtocolError::InvalidRequest(_)), "{err:?}");
844        assert!(err.to_string().contains("`want`"), "{err}");
845        assert!(err.to_string().contains("expected 64"), "{err}");
846
847        // A repository following the thread-local kind that changes after construction is
848        // refused (repository != local binding), never served as another format.
849        let dynamic = GitProtocol::new(MockRepo { refs: Vec::new() }, MockAuth);
850        {
851            let _inner = set_hash_kind_for_test(HashKind::Blake3);
852            let err = dynamic.info_refs("git-upload-pack").await.unwrap_err();
853            assert!(
854                err.to_string()
855                    .contains("wire=sha1 local=sha1 repository=blake3"),
856                "{err}"
857            );
858        }
859        assert!(dynamic.info_refs("git-upload-pack").await.is_ok());
860    }
861}