Skip to main content

git_internal/protocol/
smart.rs

1//! Implementation of the Git smart protocol state machine, handling capability negotiation, pkt
2//! exchanges, authentication delegation, and bridging repository storage to transport streams.
3
4use std::collections::HashMap;
5
6use bytes::{BufMut, Bytes, BytesMut};
7use tokio_stream::wrappers::ReceiverStream;
8
9use super::{
10    core::{AuthenticationService, RepositoryAccess},
11    pack::PackGenerator,
12    types::{
13        COMMON_CAP_LIST, Capability, LF, NUL, PKT_LINE_END_MARKER, ProtocolError, ProtocolStream,
14        RECEIVE_CAP_LIST, RefCommand, RefTypeEnum, SP, ServiceType, SideBand, TransportProtocol,
15        UPLOAD_CAP_LIST,
16    },
17    utils::{add_pkt_line_string, build_smart_reply, read_pkt_line, read_until_white_space},
18};
19use crate::hash::{HashKind, ObjectHash};
20/// Smart Git Protocol implementation
21///
22/// This struct handles the Git smart protocol operations for both HTTP and SSH transports.
23/// It uses trait abstractions to decouple from specific business logic implementations.
24pub struct SmartProtocol<R, A>
25where
26    R: RepositoryAccess,
27    A: AuthenticationService,
28{
29    pub transport_protocol: TransportProtocol,
30    pub capabilities: Vec<Capability>,
31    pub side_band: Option<SideBand>,
32    pub command_list: Vec<RefCommand>,
33    pub wire_hash_kind: HashKind,
34    pub local_hash_kind: HashKind,
35    pub zero_id: String,
36    // Trait-based dependencies
37    repo_storage: R,
38    auth_service: A,
39}
40
41impl<R, A> SmartProtocol<R, A>
42where
43    R: RepositoryAccess,
44    A: AuthenticationService,
45{
46    /// Set the wire hash kind (sha1, sha256 or blake3) and the matching zero ID.
47    ///
48    /// The wire kind must equal the repository's format
49    /// (`RepositoryAccess::object_hash_kind`) and `local_hash_kind`: every protocol
50    /// operation re-checks the three with [`SmartProtocol::ensure_hash_kind_consistency`]
51    /// and fails closed on a divergence, so this setter cannot be used to serve a
52    /// repository under another object format.
53    pub fn set_wire_hash_kind(&mut self, kind: HashKind) {
54        self.wire_hash_kind = kind;
55        self.zero_id = ObjectHash::zero_str(kind);
56    }
57
58    /// Create a new SmartProtocol instance.
59    ///
60    /// The local and wire hash kinds (and the zero ID) are bound to the repository's own
61    /// object format, `RepositoryAccess::object_hash_kind()` — which defaults to the
62    /// thread-local kind for implementors that do not override it — so a SHA-1, SHA-256 or
63    /// BLAKE3 (git-internal / Libra extension) repository advertises and accepts exactly its
64    /// own `object-format`. Nothing is inferred from ID widths.
65    pub fn new(transport_protocol: TransportProtocol, repo_storage: R, auth_service: A) -> Self {
66        let local_hash_kind = repo_storage.object_hash_kind();
67        Self {
68            transport_protocol,
69            capabilities: Vec::new(),
70            side_band: None,
71            command_list: Vec::new(),
72            repo_storage,
73            auth_service,
74            wire_hash_kind: local_hash_kind,
75            local_hash_kind,
76            zero_id: ObjectHash::zero_str(local_hash_kind),
77        }
78    }
79
80    /// Verify that the repository object format, the local kind bound at construction and
81    /// the negotiated wire kind agree (ADR-GI-B3-03).
82    ///
83    /// Every protocol operation calls this before touching refs, objects or pack bytes. A
84    /// divergence — a wire `object-format` that differs from the repository, a
85    /// [`SmartProtocol::set_wire_hash_kind`] override, or a `RepositoryAccess` whose kind
86    /// changed after construction — is a diagnosable `InvalidRequest` naming all three kinds;
87    /// there is no fallback to another format.
88    pub fn ensure_hash_kind_consistency(&self) -> Result<(), ProtocolError> {
89        let repository = self.repo_storage.object_hash_kind();
90        if repository != self.local_hash_kind || self.wire_hash_kind != self.local_hash_kind {
91            return Err(ProtocolError::object_format_mismatch(
92                self.wire_hash_kind,
93                self.local_hash_kind,
94                repository,
95            ));
96        }
97        // The (public) zero ID must be the wire kind's zero ID: create/delete semantics of
98        // receive-pack commands depend on it, so a tampered value fails closed too.
99        let expected_zero = ObjectHash::zero_str(self.wire_hash_kind);
100        if self.zero_id != expected_zero {
101            return Err(ProtocolError::invalid_request(&format!(
102                "zero ID `{}` does not match object-format {} (expected {} hex zeros)",
103                self.zero_id.chars().take(80).collect::<String>(),
104                self.wire_hash_kind.as_str(),
105                self.wire_hash_kind.hex_len()
106            )));
107        }
108        Ok(())
109    }
110
111    /// Parse a raw object ID received on the wire against the negotiated wire kind (GC-13).
112    ///
113    /// Exactly `wire_hash_kind.hex_len()` lowercase hex characters are accepted (fixed-length
114    /// check, then hex decode). A wrong width (for example a 40-hex SHA-1 ID on a BLAKE3
115    /// wire), uppercase or non-hex characters, or a tagged ID such as `blake3:HEX` is a
116    /// diagnosable `InvalidRequest` naming the pkt-line command. Returns the canonical raw hex.
117    fn parse_wire_id(&self, command: &str, id: &str) -> Result<String, ProtocolError> {
118        let hash = ObjectHash::from_hex_for_kind(self.wire_hash_kind, id)
119            .map_err(|e| ProtocolError::invalid_wire_id(command, id, &e))?;
120        if id.bytes().any(|b| b.is_ascii_uppercase()) {
121            return Err(ProtocolError::invalid_wire_id(
122                command,
123                id,
124                &format!(
125                    "object IDs on the wire must be raw lowercase hex (expected {} lowercase hex chars for {}, got uppercase characters)",
126                    self.wire_hash_kind.hex_len(),
127                    self.wire_hash_kind.as_str()
128                ),
129            ));
130        }
131        Ok(hash.to_string())
132    }
133
134    /// Authenticate an HTTP request using the injected auth service
135    pub async fn authenticate_http(
136        &self,
137        headers: &HashMap<String, String>,
138    ) -> Result<(), ProtocolError> {
139        self.auth_service.authenticate_http(headers).await
140    }
141
142    /// Authenticate an SSH session using username and public key
143    pub async fn authenticate_ssh(
144        &self,
145        username: &str,
146        public_key: &[u8],
147    ) -> Result<(), ProtocolError> {
148        self.auth_service
149            .authenticate_ssh(username, public_key)
150            .await
151    }
152
153    /// Set transport protocol (Http, Ssh, etc.)
154    pub fn set_transport_protocol(&mut self, protocol: TransportProtocol) {
155        self.transport_protocol = protocol;
156    }
157
158    /// Get git info refs for the repository, with explicit service type
159    pub async fn git_info_refs(
160        &self,
161        service_type: ServiceType,
162    ) -> Result<BytesMut, ProtocolError> {
163        // The advertised object-format is the repository's own format: refuse to advertise
164        // (or serve) anything else before touching the repository (ADR-GI-B3-03).
165        self.ensure_hash_kind_consistency()?;
166        let refs = self
167            .repo_storage
168            .get_repository_refs()
169            .await
170            .map_err(|e| ProtocolError::repository_error(format!("Failed to get refs: {e}")))?;
171        // Re-check after the await: the binding must still hold when the refs are advertised.
172        self.ensure_hash_kind_consistency()?;
173        let hex_len = self.wire_hash_kind.hex_len();
174        for (name, h) in &refs {
175            if h.len() != hex_len {
176                return Err(ProtocolError::invalid_request(&format!(
177                    "Hash length mismatch for ref {}: expected {}, got {}",
178                    name,
179                    hex_len,
180                    h.len()
181                )));
182            }
183            // Advertised IDs must be canonical raw lowercase hex of the wire kind (GC-13): a
184            // same-width ID of another namespace, a tagged ID or uppercase hex cannot be told
185            // apart by a peer, so it is refused here rather than advertised.
186            self.parse_wire_id("info-refs", h).map_err(|e| {
187                ProtocolError::invalid_request(&format!("Invalid hash for ref {name}: {e}"))
188            })?;
189        } // Ensure refs match the expected wire hash kind
190        // Convert to the expected format (head_hash, git_refs)
191        let head_hash = refs
192            .iter()
193            .find(|(name, _)| {
194                name == "HEAD" || name.ends_with("/main") || name.ends_with("/master")
195            })
196            .map(|(_, hash)| hash.clone())
197            .unwrap_or_else(|| self.zero_id.clone());
198
199        let git_refs: Vec<super::types::GitRef> = refs
200            .into_iter()
201            .map(|(name, hash)| super::types::GitRef { name, hash })
202            .collect();
203        // capability add object-format, declare the wire hash kind (single source:
204        // `HashKind::as_str`, no per-algorithm table here). `sha1`/`sha256` are the
205        // standard Git values; `blake3` is the git-internal / Libra extension.
206        let format_cap = format!(" object-format={}", self.wire_hash_kind.as_str());
207        // Determine capabilities based on service type
208        let cap_list = match service_type {
209            ServiceType::UploadPack => format!("{UPLOAD_CAP_LIST}{COMMON_CAP_LIST}{format_cap}"),
210            ServiceType::ReceivePack => format!("{RECEIVE_CAP_LIST}{COMMON_CAP_LIST}{format_cap}"),
211        };
212
213        // The stream MUST include capability declarations behind a NUL on the first ref.
214        let name = if head_hash == self.zero_id {
215            "capabilities^{}"
216        } else {
217            "HEAD"
218        };
219        let pkt_line = format!("{head_hash}{SP}{name}{NUL}{cap_list}{LF}");
220        let mut ref_list = vec![pkt_line];
221
222        for git_ref in git_refs {
223            let pkt_line = format!("{}{}{}{}", git_ref.hash, SP, git_ref.name, LF);
224            ref_list.push(pkt_line);
225        }
226
227        let pkt_line_stream =
228            build_smart_reply(self.transport_protocol, &ref_list, service_type.to_string());
229        tracing::debug!("git_info_refs, return: --------> {:?}", pkt_line_stream);
230        Ok(pkt_line_stream)
231    }
232
233    /// Handle git-upload-pack request.
234    ///
235    /// The returned pack stream carries `Result` items: a failure inside the pack producer
236    /// (encoder error, object of another format) arrives as an `Err` item so the transport
237    /// can report it, instead of an EOF that looks like a truncated pack.
238    pub async fn git_upload_pack(
239        &mut self,
240        upload_request: Bytes,
241    ) -> Result<(ReceiverStream<Result<Vec<u8>, ProtocolError>>, BytesMut), ProtocolError> {
242        self.capabilities.clear();
243        // Validate the current binding *before* touching anything: a wire kind that was driven
244        // away from the repository, or a repository whose kind changed, is an error — never
245        // silently re-bound. Capabilities may then confirm the repository kind, not change it.
246        self.ensure_hash_kind_consistency()?;
247        let mut upload_request = upload_request;
248        let mut want: Vec<String> = Vec::new();
249        let mut have: Vec<String> = Vec::new();
250        let mut last_common_commit = String::new();
251
252        let mut read_first_line = false;
253        loop {
254            let (bytes_take, pkt_line) = read_pkt_line(&mut upload_request);
255
256            if bytes_take == 0 {
257                break;
258            }
259
260            if pkt_line.is_empty() {
261                break;
262            }
263
264            let mut pkt_line = pkt_line;
265            let command = read_until_white_space(&mut pkt_line);
266
267            match command.as_str() {
268                "want" => {
269                    let hash = read_until_white_space(&mut pkt_line);
270                    if !read_first_line {
271                        // Capabilities first, so an object-format mismatch is reported as
272                        // such rather than as a malformed ID.
273                        let cap_str = String::from_utf8_lossy(&pkt_line).to_string();
274                        self.parse_capabilities(&cap_str)?;
275                        read_first_line = true;
276                    }
277                    want.push(self.parse_wire_id("want", &hash)?);
278                }
279                "have" => {
280                    let hash = read_until_white_space(&mut pkt_line);
281                    have.push(self.parse_wire_id("have", &hash)?);
282                }
283                "done" => {
284                    break;
285                }
286                _ => {
287                    tracing::warn!("Unknown upload-pack command: {}", command);
288                }
289            }
290        }
291
292        let mut protocol_buf = BytesMut::new();
293
294        // Create pack generator for this operation, bound to the kind validated above (the
295        // generator never re-reads `object_hash_kind()` after an `.await`).
296        let pack_generator =
297            PackGenerator::new_with_hash_kind(&self.repo_storage, self.local_hash_kind);
298
299        if have.is_empty() {
300            // Full pack
301            add_pkt_line_string(&mut protocol_buf, String::from("NAK\n"));
302            self.ensure_hash_kind_consistency()?;
303            let pack_stream = pack_generator.generate_full_pack(want).await?;
304            // Re-check after object collection: no drift during the awaits may reach the client.
305            self.ensure_hash_kind_consistency()?;
306            return Ok((pack_stream, protocol_buf));
307        }
308
309        // Check for common commits
310        for hash in &have {
311            let exists = self.repo_storage.commit_exists(hash).await.map_err(|e| {
312                ProtocolError::repository_error(format!("Failed to check commit existence: {e}"))
313            })?;
314            if exists {
315                add_pkt_line_string(&mut protocol_buf, format!("ACK {hash} common\n"));
316                if last_common_commit.is_empty() {
317                    last_common_commit = hash.clone();
318                }
319            }
320        }
321
322        // Re-check after the `commit_exists` awaits, before any pack is produced.
323        self.ensure_hash_kind_consistency()?;
324        if last_common_commit.is_empty() {
325            // No common commits found
326            add_pkt_line_string(&mut protocol_buf, String::from("NAK\n"));
327            let pack_stream = pack_generator.generate_full_pack(want).await?;
328            self.ensure_hash_kind_consistency()?;
329            return Ok((pack_stream, protocol_buf));
330        }
331
332        // Generate incremental pack
333        add_pkt_line_string(
334            &mut protocol_buf,
335            format!("ACK {last_common_commit} ready\n"),
336        );
337
338        let pack_stream = pack_generator.generate_incremental_pack(want, have).await?;
339        self.ensure_hash_kind_consistency()?;
340
341        Ok((pack_stream, protocol_buf))
342    }
343
344    /// Parse receive-pack commands from protocol bytes.
345    ///
346    /// Fails closed (`InvalidRequest`) on an object-format capability that is unknown or
347    /// differs from the repository, and on any command whose IDs are not raw lowercase hex
348    /// of the wire kind; `command_list` then holds the commands parsed so far.
349    pub fn parse_receive_pack_commands(
350        &mut self,
351        mut protocol_bytes: Bytes,
352    ) -> Result<(), ProtocolError> {
353        self.command_list.clear();
354        self.capabilities.clear();
355        // Validate before parsing (see `git_upload_pack`): no silent re-binding.
356        self.ensure_hash_kind_consistency()?;
357        let mut first_line = true;
358        loop {
359            let (bytes_take, pkt_line) = read_pkt_line(&mut protocol_bytes);
360
361            if bytes_take == 0 {
362                break;
363            }
364
365            if pkt_line.is_empty() {
366                break;
367            }
368
369            if first_line {
370                if let Some(pos) = pkt_line.iter().position(|b| *b == b'\0') {
371                    let caps = String::from_utf8_lossy(&pkt_line[(pos + 1)..]).to_string();
372                    self.parse_capabilities(&caps)?;
373                }
374                first_line = false;
375            }
376
377            let ref_command = self.parse_ref_command(&mut pkt_line.clone())?;
378            self.command_list.push(ref_command);
379        }
380        Ok(())
381    }
382
383    /// Handle git receive-pack operation (push)
384    pub async fn git_receive_pack_stream(
385        &mut self,
386        data_stream: ProtocolStream,
387    ) -> Result<Bytes, ProtocolError> {
388        // Fail closed before a single request byte is read: the binding must be consistent
389        // (repository == local == wire) before pack bytes or commands are accepted.
390        self.ensure_hash_kind_consistency()?;
391
392        // Collect all request data from stream
393        let mut request_data = BytesMut::new();
394        let mut stream = data_stream;
395
396        while let Some(chunk_result) = futures::StreamExt::next(&mut stream).await {
397            let chunk = chunk_result
398                .map_err(|e| ProtocolError::invalid_request(&format!("Stream error: {e}")))?;
399            request_data.extend_from_slice(&chunk);
400        }
401
402        let mut protocol_bytes = request_data.freeze();
403        self.command_list.clear();
404        self.capabilities.clear();
405        // Re-check after the awaited drain: the binding must still hold when commands are
406        // parsed (a repository following a drifting thread-local kind cannot slip through
407        // by omitting `object-format`).
408        self.ensure_hash_kind_consistency()?;
409        let mut first_line = true;
410        let mut saw_flush = false;
411        loop {
412            let (bytes_take, pkt_line) = read_pkt_line(&mut protocol_bytes);
413
414            if bytes_take == 0 {
415                if protocol_bytes.is_empty() {
416                    break;
417                }
418                return Err(ProtocolError::invalid_request(
419                    "Invalid pkt-line in receive-pack request",
420                ));
421            }
422
423            if pkt_line.is_empty() {
424                saw_flush = true;
425                break;
426            }
427
428            if first_line {
429                if let Some(pos) = pkt_line.iter().position(|b| *b == b'\0') {
430                    let caps = String::from_utf8_lossy(&pkt_line[(pos + 1)..]).to_string();
431                    self.parse_capabilities(&caps)?;
432                }
433                first_line = false;
434            }
435
436            let ref_command = self.parse_ref_command(&mut pkt_line.clone())?;
437            self.command_list.push(ref_command);
438        }
439
440        if !saw_flush {
441            return Err(ProtocolError::invalid_request(
442                "Missing flush before pack data",
443            ));
444        }
445
446        // Remaining bytes (if any) are pack data.
447        let pack_data = if protocol_bytes.is_empty() {
448            None
449        } else {
450            Some(protocol_bytes)
451        };
452
453        if let Some(pack_data) = pack_data {
454            // Create pack generator for unpacking, bound to the kind validated above; it
455            // decodes against that format (a pack of another kind fails closed at the
456            // trailer/ID check).
457            let pack_generator =
458                PackGenerator::new_with_hash_kind(&self.repo_storage, self.local_hash_kind);
459            // Unpack the received data
460            let (commits, trees, blobs) = pack_generator.unpack_stream(pack_data).await?;
461            // Re-check before the first side effect (storing objects).
462            self.ensure_hash_kind_consistency()?;
463
464            // Store the unpacked objects via the repository access trait
465            self.repo_storage
466                .handle_pack_objects(commits, trees, blobs)
467                .await
468                .map_err(|e| {
469                    ProtocolError::repository_error(format!("Failed to store pack objects: {e}"))
470                })?;
471        }
472
473        // Build status report
474        let mut report_status = BytesMut::new();
475        add_pkt_line_string(&mut report_status, "unpack ok\n".to_owned());
476
477        let mut default_exist = self.repo_storage.has_default_branch().await.map_err(|e| {
478            ProtocolError::repository_error(format!("Failed to check default branch: {e}"))
479        })?;
480
481        // Update refs with proper error handling. The binding is re-checked before *every*
482        // ref write (an `update_reference` may itself change the repository's reported kind)
483        // and once more after the last one, before the success report goes out.
484        let mut commands = std::mem::take(&mut self.command_list);
485        let mut update_result = Ok(());
486        for command in &mut commands {
487            if let Err(e) = self.ensure_hash_kind_consistency() {
488                update_result = Err(e);
489                break;
490            }
491            if command.ref_type == RefTypeEnum::Tag {
492                // Just update if refs type is tag
493                // Convert zero_id to None for old hash
494                let old_hash = if command.old_hash == self.zero_id {
495                    None
496                } else {
497                    Some(command.old_hash.as_str())
498                };
499                if let Err(e) = self
500                    .repo_storage
501                    .update_reference(&command.ref_name, old_hash, &command.new_hash)
502                    .await
503                {
504                    command.failed(e.to_string());
505                }
506            } else {
507                // Handle default branch setting for the first branch
508                if !default_exist {
509                    command.default_branch = true;
510                    default_exist = true;
511                }
512                // Convert zero_id to None for old hash
513                let old_hash = if command.old_hash == self.zero_id {
514                    None
515                } else {
516                    Some(command.old_hash.as_str())
517                };
518                if let Err(e) = self
519                    .repo_storage
520                    .update_reference(&command.ref_name, old_hash, &command.new_hash)
521                    .await
522                {
523                    command.failed(e.to_string());
524                }
525            }
526            add_pkt_line_string(&mut report_status, command.get_status());
527        }
528        self.command_list = commands;
529        update_result?;
530        self.ensure_hash_kind_consistency()?;
531
532        // Post-receive hook
533        self.repo_storage.post_receive_hook().await.map_err(|e| {
534            ProtocolError::repository_error(format!("Post-receive hook failed: {e}"))
535        })?;
536        // Final check after the last await: a drifted repository never gets a success report.
537        self.ensure_hash_kind_consistency()?;
538
539        report_status.put(&PKT_LINE_END_MARKER[..]);
540        Ok(report_status.freeze())
541    }
542
543    /// Builds the packet data in the sideband format if the SideBand/64k capability is enabled.
544    pub fn build_side_band_format(&self, from_bytes: BytesMut, length: usize) -> BytesMut {
545        let mut to_bytes = BytesMut::new();
546        if self.capabilities.contains(&Capability::SideBand)
547            || self.capabilities.contains(&Capability::SideBand64k)
548        {
549            let length = length + 5;
550            to_bytes.put(Bytes::from(format!("{length:04x}")));
551            to_bytes.put_u8(SideBand::PackfileData.value());
552            to_bytes.put(from_bytes);
553        } else {
554            to_bytes.put(from_bytes);
555        }
556        to_bytes
557    }
558
559    /// Parse the capability list of the first pkt-line of a request.
560    ///
561    /// `object-format=<name>` goes through the single `HashKind` parser (GC-02) as an exact
562    /// lowercase value (GC-13): `sha1` and `sha256` are the standard Git formats, `blake3` is
563    /// the git-internal / Libra extension. An unknown or non-canonical value, or a known
564    /// value that differs from the repository's format, is a diagnosable `InvalidRequest`
565    /// (fail-closed: no warn-and-ignore, no fallback); the wire kind and zero ID are only
566    /// updated on success. Other capabilities are recorded as before.
567    pub fn parse_capabilities(&mut self, cap_str: &str) -> Result<(), ProtocolError> {
568        // The current binding must already be consistent: a wire kind that was driven away
569        // from the repository is an error here too, never silently reset by a capability.
570        self.ensure_hash_kind_consistency()?;
571        for cap in cap_str.split_whitespace() {
572            if let Some(fmt) = cap.strip_prefix("object-format=") {
573                let kind = match fmt.parse::<HashKind>() {
574                    Ok(kind) if kind.as_str() == fmt => kind,
575                    _ => return Err(ProtocolError::unknown_object_format(fmt)),
576                };
577                // The peer's format must equal both the kind bound at construction and the
578                // repository's *current* kind, so a repository that changed kind after
579                // construction cannot be served through a stale capability.
580                let repository = self.repo_storage.object_hash_kind();
581                if kind != self.local_hash_kind || kind != repository {
582                    return Err(ProtocolError::object_format_mismatch(
583                        kind,
584                        self.local_hash_kind,
585                        repository,
586                    ));
587                }
588                self.set_wire_hash_kind(kind);
589                // Record the negotiated format alongside the other capabilities.
590                self.capabilities
591                    .push(Capability::ObjectFormat(kind.as_str().to_string()));
592                continue;
593            }
594            if let Ok(capability) = cap.parse::<Capability>() {
595                self.capabilities.push(capability);
596            }
597        }
598        Ok(())
599    }
600
601    /// Parse a reference command (`<old-id> <new-id> <ref-name>`) from a pkt-line.
602    ///
603    /// Both IDs must be raw lowercase hex of the wire kind (the zero ID included): a wrong
604    /// width (for example a 40-hex SHA-1 ID on a BLAKE3 wire), non-hex characters, a tagged
605    /// ID or a missing ref name is a diagnosable `InvalidRequest`.
606    pub fn parse_ref_command(&self, pkt_line: &mut Bytes) -> Result<RefCommand, ProtocolError> {
607        let old_id = read_until_white_space(pkt_line);
608        let new_id = read_until_white_space(pkt_line);
609        let ref_name = read_until_white_space(pkt_line);
610        let _capabilities = String::from_utf8_lossy(&pkt_line[..]).to_string();
611
612        let old_id = self.parse_wire_id("receive-pack old-id", &old_id)?;
613        let new_id = self.parse_wire_id("receive-pack new-id", &new_id)?;
614        if ref_name.is_empty() {
615            return Err(ProtocolError::invalid_request(
616                "receive-pack command is missing the ref name",
617            ));
618        }
619        Ok(RefCommand::new(old_id, new_id, ref_name))
620    }
621}
622
623#[cfg(test)]
624mod tests {
625    use std::sync::{
626        Arc, Mutex,
627        atomic::{AtomicBool, Ordering},
628    };
629
630    use async_trait::async_trait;
631    use bytes::BytesMut;
632    use futures;
633    use tokio::sync::mpsc;
634
635    use super::*;
636    use crate::protocol::utils; // import sibling module
637    use crate::{
638        hash::{HashKind, ObjectHash, set_hash_kind_for_test},
639        internal::{
640            metadata::{EntryMeta, MetaAttached},
641            object::{
642                blob::Blob,
643                commit::Commit,
644                signature::{Signature, SignatureType},
645                tree::{Tree, TreeItem, TreeItemMode},
646            },
647            pack::{encode::PackEncoder, entry::Entry},
648        },
649    };
650
651    // Simplify complex type via aliases to satisfy clippy::type_complexity
652    type UpdateRecord = (String, Option<String>, String);
653    type UpdateList = Vec<UpdateRecord>;
654    type SharedUpdates = Arc<Mutex<UpdateList>>;
655
656    /// Test repository access implementation for testing (SHA-1 by default; `with_kind`
657    /// serves a repository of another object format, independent of the thread-local kind).
658    #[derive(Clone)]
659    struct TestRepoAccess {
660        kind: HashKind,
661        updates: SharedUpdates,
662        stored_count: Arc<Mutex<usize>>,
663        default_branch_exists: Arc<Mutex<bool>>,
664        post_called: Arc<AtomicBool>,
665    }
666
667    impl TestRepoAccess {
668        fn new() -> Self {
669            Self::with_kind(HashKind::Sha1)
670        }
671
672        fn with_kind(kind: HashKind) -> Self {
673            Self {
674                kind,
675                updates: Arc::new(Mutex::new(vec![])),
676                stored_count: Arc::new(Mutex::new(0)),
677                default_branch_exists: Arc::new(Mutex::new(false)),
678                post_called: Arc::new(AtomicBool::new(false)),
679            }
680        }
681
682        fn recorded_updates(&self) -> UpdateList {
683            self.updates.lock().unwrap().clone()
684        }
685
686        fn updates_len(&self) -> usize {
687            self.updates.lock().unwrap().len()
688        }
689
690        fn post_hook_called(&self) -> bool {
691            self.post_called.load(Ordering::SeqCst)
692        }
693    }
694
695    #[async_trait]
696    impl RepositoryAccess for TestRepoAccess {
697        fn object_hash_kind(&self) -> HashKind {
698            self.kind
699        }
700
701        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
702            Ok(vec![
703                ("HEAD".to_string(), ObjectHash::zero_str(self.kind)),
704                (
705                    "refs/heads/main".to_string(),
706                    "1".repeat(self.kind.hex_len()),
707                ),
708            ])
709        }
710
711        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
712            Ok(true)
713        }
714
715        async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
716            Ok(vec![])
717        }
718
719        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
720            *self.stored_count.lock().unwrap() += 1;
721            Ok(())
722        }
723
724        async fn update_reference(
725            &self,
726            ref_name: &str,
727            old_hash: Option<&str>,
728            new_hash: &str,
729        ) -> Result<(), ProtocolError> {
730            self.updates.lock().unwrap().push((
731                ref_name.to_string(),
732                old_hash.map(|s| s.to_string()),
733                new_hash.to_string(),
734            ));
735            Ok(())
736        }
737
738        async fn get_objects_for_pack(
739            &self,
740            _wants: &[String],
741            _haves: &[String],
742        ) -> Result<Vec<String>, ProtocolError> {
743            Ok(vec![])
744        }
745
746        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
747            let mut exists = self.default_branch_exists.lock().unwrap();
748            let current = *exists;
749            *exists = true; // flip to true after first check
750            Ok(current)
751        }
752
753        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
754            self.post_called.store(true, Ordering::SeqCst);
755            Ok(())
756        }
757    }
758
759    /// Test authentication service implementation for testing
760    struct TestAuth;
761
762    #[async_trait]
763    impl AuthenticationService for TestAuth {
764        async fn authenticate_http(
765            &self,
766            _headers: &std::collections::HashMap<String, String>,
767        ) -> Result<(), ProtocolError> {
768            Ok(())
769        }
770
771        async fn authenticate_ssh(
772            &self,
773            _username: &str,
774            _public_key: &[u8],
775        ) -> Result<(), ProtocolError> {
776            Ok(())
777        }
778    }
779
780    /// Receive-pack stream decodes the pack, updates refs, and reports status (SHA-1).
781    #[tokio::test]
782    async fn test_receive_pack_stream_status_report() {
783        let _guard = set_hash_kind_for_test(HashKind::Sha1);
784        // Build simple objects
785        let blob1 = Blob::from_content("hello");
786        let blob2 = Blob::from_content("world");
787
788        let item1 = TreeItem::new(TreeItemMode::Blob, blob1.id, "hello.txt".to_string());
789        let item2 = TreeItem::new(TreeItemMode::Blob, blob2.id, "world.txt".to_string());
790        let tree = Tree::from_tree_items(vec![item1, item2]).unwrap();
791
792        let author = Signature::new(
793            SignatureType::Author,
794            "tester".to_string(),
795            "tester@example.com".to_string(),
796        );
797        let committer = Signature::new(
798            SignatureType::Committer,
799            "tester".to_string(),
800            "tester@example.com".to_string(),
801        );
802        let commit = Commit::new(author, committer, tree.id, vec![], "init commit");
803
804        // Encode pack bytes via PackEncoder
805        let (pack_tx, mut pack_rx) = mpsc::channel(1024);
806        let (entry_tx, entry_rx) = mpsc::channel(1024);
807        let mut encoder = PackEncoder::new(4, 10, pack_tx);
808
809        tokio::spawn(async move {
810            if let Err(e) = encoder.encode(entry_rx).await {
811                panic!("Failed to encode pack: {}", e);
812            }
813        });
814
815        let commit_clone = commit.clone();
816        let tree_clone = tree.clone();
817        let blob1_clone = blob1.clone();
818        let blob2_clone = blob2.clone();
819        tokio::spawn(async move {
820            let _ = entry_tx
821                .send(MetaAttached {
822                    inner: Entry::from(commit_clone),
823                    meta: EntryMeta::new(),
824                })
825                .await;
826            let _ = entry_tx
827                .send(MetaAttached {
828                    inner: Entry::from(tree_clone),
829                    meta: EntryMeta::new(),
830                })
831                .await;
832            let _ = entry_tx
833                .send(MetaAttached {
834                    inner: Entry::from(blob1_clone),
835                    meta: EntryMeta::new(),
836                })
837                .await;
838            let _ = entry_tx
839                .send(MetaAttached {
840                    inner: Entry::from(blob2_clone),
841                    meta: EntryMeta::new(),
842                })
843                .await;
844            // sender drop indicates end
845        });
846
847        let mut pack_bytes: Vec<u8> = Vec::new();
848        while let Some(chunk) = pack_rx.recv().await {
849            pack_bytes.extend_from_slice(&chunk);
850        }
851
852        // Prepare protocol and request
853        let repo_access = TestRepoAccess::new();
854        let auth = TestAuth;
855        let mut smart = SmartProtocol::new(TransportProtocol::Http, repo_access.clone(), auth);
856        smart.set_wire_hash_kind(HashKind::Sha1);
857
858        let mut request = BytesMut::new();
859        add_pkt_line_string(
860            &mut request,
861            format!(
862                "{} {} refs/heads/main\0report-status\n",
863                smart.zero_id, commit.id
864            ),
865        );
866        request.put(&PKT_LINE_END_MARKER[..]);
867        request.extend_from_slice(&pack_bytes);
868
869        // Create request stream
870        let request_stream = Box::pin(futures::stream::once(async { Ok(request.freeze()) }));
871
872        // Execute receive-pack
873        let result_bytes = smart
874            .git_receive_pack_stream(request_stream)
875            .await
876            .expect("receive-pack should succeed");
877
878        // Verify pkt-lines
879        let mut out = result_bytes.clone();
880        let (_c1, l1) = utils::read_pkt_line(&mut out);
881        assert_eq!(String::from_utf8(l1.to_vec()).unwrap(), "unpack ok\n");
882
883        let (_c2, l2) = utils::read_pkt_line(&mut out);
884        assert_eq!(
885            String::from_utf8(l2.to_vec()).unwrap(),
886            "ok refs/heads/main"
887        );
888
889        let (c3, l3) = utils::read_pkt_line(&mut out);
890        assert_eq!(c3, 4);
891        assert!(l3.is_empty());
892
893        // Verify side effects
894        assert_eq!(repo_access.updates_len(), 1);
895        assert!(repo_access.post_hook_called());
896    }
897
898    /// info-refs rejects SHA-256 wire format when repository refs are still SHA-1.
899    #[tokio::test]
900    async fn info_refs_rejects_sha256_with_sha1_refs() {
901        let _guard = set_hash_kind_for_test(HashKind::Sha1); // avoid thread-local contamination
902        let repo_access = TestRepoAccess::new(); // still returns 40-char strings
903        let auth = TestAuth;
904        let mut smart = SmartProtocol::new(TransportProtocol::Http, repo_access, auth);
905        smart.set_wire_hash_kind(HashKind::Sha256); // claims wire uses SHA-256
906        // expect failure because refs are SHA-1
907        let res = smart.git_info_refs(ServiceType::UploadPack).await;
908        assert!(res.is_err(), "expected failure when hash lengths mismatch");
909
910        smart.set_wire_hash_kind(HashKind::Sha1);
911
912        let res = smart.git_info_refs(ServiceType::UploadPack).await;
913        assert!(
914            res.is_ok(),
915            "expected SHA1 refs to be accepted when wire is SHA1"
916        );
917    }
918
919    fn blake3_repo_and_protocol() -> (TestRepoAccess, SmartProtocol<TestRepoAccess, TestAuth>) {
920        let repo = TestRepoAccess::with_kind(HashKind::Blake3);
921        let smart = SmartProtocol::new(TransportProtocol::Http, repo.clone(), TestAuth);
922        (repo, smart)
923    }
924
925    /// A BLAKE3 repository advertises and accepts `object-format=blake3` (git-internal /
926    /// Libra extension) with a 64-hex zero ID, independent of the thread-local kind; SHA-1
927    /// and SHA-256 repositories keep their existing capability output.
928    #[tokio::test]
929    async fn blake3_capability() {
930        let _guard = set_hash_kind_for_test(HashKind::Sha1);
931        let (_repo, mut smart) = blake3_repo_and_protocol();
932        assert_eq!(smart.wire_hash_kind, HashKind::Blake3);
933        assert_eq!(smart.local_hash_kind, HashKind::Blake3);
934        assert_eq!(smart.zero_id, "0".repeat(64));
935
936        let resp = smart.git_info_refs(ServiceType::UploadPack).await.unwrap();
937        let resp_str = String::from_utf8(resp.to_vec()).unwrap();
938        assert!(resp_str.contains(" object-format=blake3"), "{resp_str}");
939        assert!(
940            resp_str.contains(&format!("{} refs/heads/main", "1".repeat(64))),
941            "{resp_str}"
942        );
943        assert!(!resp_str.contains("object-format=sha"), "{resp_str}");
944
945        smart
946            .parse_capabilities("report-status object-format=blake3 side-band-64k")
947            .unwrap();
948        assert_eq!(smart.wire_hash_kind, HashKind::Blake3);
949        assert_eq!(smart.zero_id.len(), HashKind::Blake3.hex_len());
950        assert!(smart.capabilities.contains(&Capability::SideBand64k));
951        assert!(smart.capabilities.contains(&Capability::ReportStatus));
952        assert!(
953            smart
954                .capabilities
955                .contains(&Capability::ObjectFormat("blake3".to_string()))
956        );
957
958        // A ref whose ID is not canonical raw lowercase hex of the wire kind (same width,
959        // uppercase / non-hex / tagged) is refused instead of advertised.
960        for bad in [
961            "A".repeat(64),
962            "zz".repeat(32),
963            format!("blake3:{}", "1".repeat(57)),
964        ] {
965            let repo = BadRefRepo {
966                kind: HashKind::Blake3,
967                id: bad.clone(),
968            };
969            let smart = SmartProtocol::new(TransportProtocol::Http, repo, TestAuth);
970            let err = smart
971                .git_info_refs(ServiceType::UploadPack)
972                .await
973                .unwrap_err();
974            assert!(
975                matches!(err, ProtocolError::InvalidRequest(_)),
976                "{bad}: {err:?}"
977            );
978            assert!(
979                err.to_string().contains("Invalid hash for ref"),
980                "{bad}: {err}"
981            );
982        }
983
984        // Standard formats are unchanged: exact lowercase value, matching zero ID.
985        for kind in [HashKind::Sha1, HashKind::Sha256] {
986            let repo = TestRepoAccess::with_kind(kind);
987            let mut smart = SmartProtocol::new(TransportProtocol::Http, repo, TestAuth);
988            let resp = smart.git_info_refs(ServiceType::ReceivePack).await.unwrap();
989            let resp_str = String::from_utf8(resp.to_vec()).unwrap();
990            assert!(
991                resp_str.contains(&format!(" object-format={}", kind.as_str())),
992                "{resp_str}"
993            );
994            smart
995                .parse_capabilities(&format!("object-format={} side-band", kind.as_str()))
996                .unwrap();
997            assert_eq!(smart.wire_hash_kind, kind);
998            assert_eq!(smart.zero_id, ObjectHash::zero_str(kind));
999        }
1000    }
1001
1002    /// On a BLAKE3 wire the zero ID is 64 hex zeros: a create-ref command with it maps to
1003    /// `old_hash = None`, while the SHA-1 zero ID, a tagged ID, uppercase hex and a wrong
1004    /// width are rejected with diagnosable errors (GC-13).
1005    #[tokio::test]
1006    async fn blake3_zero_id() {
1007        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1008        let (repo, mut smart) = blake3_repo_and_protocol();
1009        let zero = smart.zero_id.clone();
1010        let new_id = "a".repeat(64);
1011
1012        let mut pkt = BytesMut::new();
1013        add_pkt_line_string(
1014            &mut pkt,
1015            format!("{zero} {new_id} refs/heads/main\0report-status object-format=blake3\n"),
1016        );
1017        add_pkt_line_string(&mut pkt, format!("{new_id} {zero} refs/tags/v1.0\n"));
1018        pkt.put(&PKT_LINE_END_MARKER[..]);
1019        smart
1020            .parse_receive_pack_commands(pkt.clone().freeze())
1021            .unwrap();
1022        assert_eq!(smart.command_list.len(), 2);
1023        assert_eq!(smart.command_list[0].old_hash, zero);
1024        assert_eq!(smart.command_list[0].new_hash, new_id);
1025        assert_eq!(smart.command_list[1].ref_name, "refs/tags/v1.0");
1026
1027        // Commands only (no pack payload): the BLAKE3 zero ID becomes `None` for the store.
1028        let request_stream = Box::pin(futures::stream::once(async { Ok(pkt.freeze()) }));
1029        let report = smart.git_receive_pack_stream(request_stream).await.unwrap();
1030        assert!(report.starts_with(b"000eunpack ok\n"), "{report:?}");
1031        assert_eq!(
1032            repo.recorded_updates(),
1033            vec![
1034                ("refs/heads/main".to_string(), None, new_id.clone()),
1035                (
1036                    "refs/tags/v1.0".to_string(),
1037                    Some(new_id.clone()),
1038                    zero.clone()
1039                ),
1040            ]
1041        );
1042
1043        let sha1_zero = ObjectHash::zero_str(HashKind::Sha1);
1044        let tagged = format!("blake3:{new_id}");
1045        let upper = new_id.to_uppercase();
1046        for (old, new, needle) in [
1047            (sha1_zero.as_str(), new_id.as_str(), "old-id"),
1048            (zero.as_str(), tagged.as_str(), "new-id"),
1049            (zero.as_str(), upper.as_str(), "lowercase"),
1050            (zero.as_str(), &new_id[..63], "expected 64"),
1051        ] {
1052            let mut pkt = BytesMut::new();
1053            add_pkt_line_string(&mut pkt, format!("{old} {new} refs/heads/main\n"));
1054            pkt.put(&PKT_LINE_END_MARKER[..]);
1055            let err = smart.parse_receive_pack_commands(pkt.freeze()).unwrap_err();
1056            assert!(matches!(err, ProtocolError::InvalidRequest(_)), "{err:?}");
1057            assert!(err.to_string().contains(needle), "{err}");
1058            assert!(smart.command_list.is_empty());
1059        }
1060    }
1061
1062    /// object-format negotiation fails closed: unknown or non-canonical values, a known
1063    /// value that differs from the repository, a wire kind overridden away from the
1064    /// repository, and want/have IDs of the wrong width or shape are diagnosable errors,
1065    /// never a warning or a fallback.
1066    #[tokio::test]
1067    async fn object_format_mismatch() {
1068        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1069        let mut smart =
1070            SmartProtocol::new(TransportProtocol::Http, TestRepoAccess::new(), TestAuth);
1071        for (caps, needle) in [
1072            (
1073                "object-format=SHA256 side-band-64k",
1074                "unknown object-format",
1075            ),
1076            ("object-format=md5", "unknown object-format"),
1077            (
1078                "object-format=sha256",
1079                "mismatch: wire=sha256 local=sha1 repository=sha1",
1080            ),
1081            (
1082                "object-format=blake3",
1083                "mismatch: wire=blake3 local=sha1 repository=sha1",
1084            ),
1085        ] {
1086            let err = smart.parse_capabilities(caps).unwrap_err();
1087            assert!(matches!(err, ProtocolError::InvalidRequest(_)), "{err:?}");
1088            assert!(err.to_string().contains(needle), "{err}");
1089            assert_eq!(smart.wire_hash_kind, HashKind::Sha1);
1090            assert_eq!(smart.zero_id, ObjectHash::zero_str(HashKind::Sha1));
1091        }
1092        smart.parse_capabilities("object-format=sha1").unwrap();
1093        assert_eq!(smart.wire_hash_kind, HashKind::Sha1);
1094
1095        // A BLAKE3 repository refuses the standard formats the same way.
1096        let (_repo, mut blake3) = blake3_repo_and_protocol();
1097        let err = blake3
1098            .parse_capabilities("object-format=sha256")
1099            .unwrap_err();
1100        assert!(
1101            err.to_string()
1102                .contains("wire=sha256 local=blake3 repository=blake3"),
1103            "{err}"
1104        );
1105
1106        // A wire kind overridden away from the repository is caught before any ref is
1107        // advertised, naming all three kinds.
1108        smart.set_wire_hash_kind(HashKind::Sha256);
1109        let err = smart
1110            .git_info_refs(ServiceType::UploadPack)
1111            .await
1112            .unwrap_err();
1113        assert!(
1114            err.to_string()
1115                .contains("wire=sha256 local=sha1 repository=sha1"),
1116            "{err}"
1117        );
1118        // upload-pack / receive-pack re-bind the wire kind to the repository and re-check.
1119        let sha1_id = "a".repeat(40);
1120        let mut req = BytesMut::new();
1121        add_pkt_line_string(&mut req, format!("want {sha1_id} object-format=sha256\n"));
1122        req.put(&PKT_LINE_END_MARKER[..]);
1123        let err = smart.git_upload_pack(req.freeze()).await.unwrap_err();
1124        assert!(err.to_string().contains("wire=sha256 local=sha1"), "{err}");
1125        // The divergent wire kind is reported, never silently re-bound to the repository.
1126        assert_eq!(smart.wire_hash_kind, HashKind::Sha256);
1127        smart.set_wire_hash_kind(HashKind::Sha1);
1128        // A wire kind driven away from the repository is not silently reset by a matching
1129        // capability: the divergence is reported first.
1130        smart.set_wire_hash_kind(HashKind::Sha256);
1131        let err = smart.parse_capabilities("object-format=sha1").unwrap_err();
1132        assert!(
1133            err.to_string()
1134                .contains("wire=sha256 local=sha1 repository=sha1"),
1135            "{err}"
1136        );
1137        assert_eq!(smart.wire_hash_kind, HashKind::Sha256);
1138        smart.set_wire_hash_kind(HashKind::Sha1);
1139        // A repository whose kind changed after construction cannot confirm a stale
1140        // capability either (both the bound kind and the current kind must match).
1141        {
1142            let repo = DriftingRepo::new();
1143            let mut dynamic = SmartProtocol::new(TransportProtocol::Http, repo.clone(), TestAuth);
1144            repo.set_kind(HashKind::Sha256);
1145            let err = dynamic
1146                .parse_capabilities("object-format=sha1")
1147                .unwrap_err();
1148            assert!(
1149                err.to_string()
1150                    .contains("wire=sha1 local=sha1 repository=sha256"),
1151                "{err}"
1152            );
1153        }
1154        // Uppercase IDs are diagnosed with the expected width and kind.
1155        let mut req = BytesMut::new();
1156        add_pkt_line_string(&mut req, format!("want {}\n", sha1_id.to_uppercase()));
1157        req.put(&PKT_LINE_END_MARKER[..]);
1158        let err = smart.git_upload_pack(req.freeze()).await.unwrap_err();
1159        assert!(
1160            err.to_string()
1161                .contains("expected 40 lowercase hex chars for sha1"),
1162            "{err}"
1163        );
1164
1165        // want/have IDs: wrong width, tagged and uppercase IDs are diagnosable errors.
1166        for (line, needle) in [
1167            (format!("want {} side-band-64k\n", "b".repeat(64)), "`want`"),
1168            (format!("want sha1:{sha1_id}\n"), "`want`"),
1169            (format!("want {sha1_id}\n"), "`have`"),
1170        ] {
1171            let mut req = BytesMut::new();
1172            add_pkt_line_string(&mut req, line);
1173            if needle == "`have`" {
1174                add_pkt_line_string(&mut req, format!("have {}\n", sha1_id.to_uppercase()));
1175            }
1176            req.put(&PKT_LINE_END_MARKER[..]);
1177            let err = smart.git_upload_pack(req.freeze()).await.unwrap_err();
1178            assert!(matches!(err, ProtocolError::InvalidRequest(_)), "{err:?}");
1179            assert!(err.to_string().contains(needle), "{err}");
1180        }
1181
1182        // A tampered public `zero_id` fails the consistency check (create/delete semantics
1183        // must not silently change).
1184        {
1185            let mut tampered =
1186                SmartProtocol::new(TransportProtocol::Http, TestRepoAccess::new(), TestAuth);
1187            tampered.zero_id = "0".repeat(64);
1188            let err = tampered
1189                .git_info_refs(ServiceType::UploadPack)
1190                .await
1191                .unwrap_err();
1192            assert!(err.to_string().contains("zero ID"), "{err}");
1193            assert!(err.to_string().contains("expected 40 hex zeros"), "{err}");
1194        }
1195
1196        // Kind drift *inside* `get_repository_refs` (after the await, before advertisement)
1197        // and *inside* object collection (after the await, before the pack is handed out) is
1198        // caught as well.
1199        {
1200            let flipping = SmartProtocol::new(
1201                TransportProtocol::Http,
1202                DriftingRepo::flipping_refs(),
1203                TestAuth,
1204            );
1205            let err = flipping
1206                .git_info_refs(ServiceType::UploadPack)
1207                .await
1208                .unwrap_err();
1209            assert!(
1210                err.to_string()
1211                    .contains("wire=sha1 local=sha1 repository=sha256"),
1212                "{err}"
1213            );
1214            let mut flipping = SmartProtocol::new(
1215                TransportProtocol::Http,
1216                DriftingRepo::flipping_has_object(),
1217                TestAuth,
1218            );
1219            // `have` drives `commit_exists` -> `has_object` (which flips the kind) before any
1220            // pack is produced; the re-check after those awaits refuses to continue.
1221            let mut req = BytesMut::new();
1222            add_pkt_line_string(&mut req, format!("want {}\n", "a".repeat(40)));
1223            add_pkt_line_string(&mut req, format!("have {}\n", "b".repeat(40)));
1224            add_pkt_line_string(&mut req, "done\n".to_string());
1225            let err = flipping.git_upload_pack(req.freeze()).await.unwrap_err();
1226            assert!(
1227                err.to_string()
1228                    .contains("wire=sha1 local=sha1 repository=sha256"),
1229                "{err}"
1230            );
1231        }
1232
1233        // Kind drift *during* the awaited request drain (a repository following the
1234        // thread-local kind, client omitting `object-format`) is caught before any command
1235        // or ref is accepted.
1236        {
1237            let repo = DriftingRepo::new();
1238            let mut drifting = SmartProtocol::new(TransportProtocol::Http, repo.clone(), TestAuth);
1239            let zero = ObjectHash::zero_str(HashKind::Sha1);
1240            let mut pkt = BytesMut::new();
1241            add_pkt_line_string(
1242                &mut pkt,
1243                format!("{zero} {} refs/heads/main\n", "a".repeat(40)),
1244            );
1245            pkt.put(&PKT_LINE_END_MARKER[..]);
1246            let bytes = pkt.freeze();
1247            let handle = repo.clone();
1248            let stream = Box::pin(futures::stream::once(async move {
1249                handle.set_kind(HashKind::Sha256);
1250                Ok(bytes)
1251            }));
1252            let err = drifting.git_receive_pack_stream(stream).await.unwrap_err();
1253            assert!(
1254                err.to_string()
1255                    .contains("wire=sha1 local=sha1 repository=sha256"),
1256                "{err}"
1257            );
1258            assert!(drifting.command_list.is_empty());
1259        }
1260
1261        // Kind drift *inside* `update_reference`: the second ref is never written, no success
1262        // report is produced, and the parsed commands are kept for diagnosis.
1263        {
1264            let repo = DriftingRepo::flipping_update_reference();
1265            let mut smart = SmartProtocol::new(TransportProtocol::Http, repo.clone(), TestAuth);
1266            let zero = ObjectHash::zero_str(HashKind::Sha1);
1267            let mut pkt = BytesMut::new();
1268            add_pkt_line_string(
1269                &mut pkt,
1270                format!("{zero} {} refs/heads/a\n", "a".repeat(40)),
1271            );
1272            add_pkt_line_string(
1273                &mut pkt,
1274                format!("{zero} {} refs/heads/b\n", "b".repeat(40)),
1275            );
1276            pkt.put(&PKT_LINE_END_MARKER[..]);
1277            let stream = Box::pin(futures::stream::once(async { Ok(pkt.freeze()) }));
1278            let err = smart.git_receive_pack_stream(stream).await.unwrap_err();
1279            assert!(
1280                err.to_string()
1281                    .contains("wire=sha1 local=sha1 repository=sha256"),
1282                "{err}"
1283            );
1284            assert_eq!(repo.inner.updates_len(), 1);
1285            assert_eq!(smart.command_list.len(), 2);
1286        }
1287
1288        // A repository whose reported kind changes after construction is refused too.
1289        let repo = DriftingRepo::new();
1290        let dynamic = SmartProtocol::new(TransportProtocol::Http, repo.clone(), TestAuth);
1291        assert_eq!(dynamic.local_hash_kind, HashKind::Sha1);
1292        repo.set_kind(HashKind::Sha256);
1293        let err = dynamic
1294            .git_info_refs(ServiceType::UploadPack)
1295            .await
1296            .unwrap_err();
1297        assert!(
1298            err.to_string()
1299                .contains("wire=sha1 local=sha1 repository=sha256"),
1300            "{err}"
1301        );
1302        repo.set_kind(HashKind::Sha1);
1303        assert!(dynamic.git_info_refs(ServiceType::UploadPack).await.is_ok());
1304    }
1305
1306    /// Repository serving real objects of one format from memory (content bytes, as the default
1307    /// `get_commit` / `get_tree` / `get_blob` accessors expect), advertising one branch.
1308    #[derive(Clone)]
1309    struct ObjectRepo {
1310        kind: HashKind,
1311        head: String,
1312        objects: Arc<std::collections::HashMap<String, Vec<u8>>>,
1313    }
1314
1315    #[async_trait]
1316    impl RepositoryAccess for ObjectRepo {
1317        fn object_hash_kind(&self) -> HashKind {
1318            self.kind
1319        }
1320        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
1321            Ok(vec![
1322                ("HEAD".to_string(), self.head.clone()),
1323                ("refs/heads/main".to_string(), self.head.clone()),
1324            ])
1325        }
1326        async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError> {
1327            Ok(self.objects.contains_key(object_hash))
1328        }
1329        async fn get_object(&self, object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
1330            self.objects
1331                .get(object_hash)
1332                .cloned()
1333                .ok_or_else(|| ProtocolError::ObjectNotFound(object_hash.to_string()))
1334        }
1335        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
1336            Ok(())
1337        }
1338        async fn update_reference(
1339            &self,
1340            _ref_name: &str,
1341            _old_hash: Option<&str>,
1342            _new_hash: &str,
1343        ) -> Result<(), ProtocolError> {
1344            Ok(())
1345        }
1346        async fn get_objects_for_pack(
1347            &self,
1348            _wants: &[String],
1349            _haves: &[String],
1350        ) -> Result<Vec<String>, ProtocolError> {
1351            Ok(vec![])
1352        }
1353        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
1354            Ok(true)
1355        }
1356        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
1357            Ok(())
1358        }
1359    }
1360
1361    /// want/have and receive-pack command parsing accept the repository's own IDs end to end
1362    /// for SHA-1, SHA-256 (GC-07: the standard formats keep working) and BLAKE3, the generated
1363    /// pack decodes under that format, and `have` produces the ACK path.
1364    #[tokio::test]
1365    async fn wire_ids_round_trip_for_every_kind() {
1366        use crate::internal::object::ObjectTrait;
1367        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1368        for kind in [HashKind::Sha1, HashKind::Sha256, HashKind::Blake3] {
1369            let blob = Blob::from_content_with_kind(kind, "wire").unwrap();
1370            let tree = Tree::from_tree_items_with_kind(
1371                kind,
1372                vec![TreeItem::new(
1373                    TreeItemMode::Blob,
1374                    blob.id,
1375                    "wire.txt".to_string(),
1376                )],
1377            )
1378            .unwrap();
1379            let commit = Commit::from_tree_id_with_kind(kind, tree.id, vec![], "wire ids").unwrap();
1380            let mut objects = std::collections::HashMap::new();
1381            objects.insert(blob.id.to_string(), blob.to_data().unwrap());
1382            objects.insert(tree.id.to_string(), tree.to_data().unwrap());
1383            objects.insert(commit.id.to_string(), commit.to_data().unwrap());
1384            let repo = ObjectRepo {
1385                kind,
1386                head: commit.id.to_string(),
1387                objects: Arc::new(objects),
1388            };
1389            let mut smart = SmartProtocol::new(TransportProtocol::Http, repo, TestAuth);
1390
1391            let resp = smart.git_info_refs(ServiceType::UploadPack).await.unwrap();
1392            let text = String::from_utf8(resp.to_vec()).unwrap();
1393            assert!(
1394                text.contains(&format!("{} HEAD", commit.id))
1395                    && text.contains(&format!(" object-format={}", kind.as_str())),
1396                "{kind:?}: {text}"
1397            );
1398
1399            // want (no have): NAK + a full pack that decodes under `kind`.
1400            let mut req = BytesMut::new();
1401            add_pkt_line_string(
1402                &mut req,
1403                format!(
1404                    "want {} side-band-64k object-format={}\n",
1405                    commit.id,
1406                    kind.as_str()
1407                ),
1408            );
1409            add_pkt_line_string(&mut req, "done\n".to_string());
1410            let (stream, buf) = smart.git_upload_pack(req.freeze()).await.unwrap();
1411            assert!(String::from_utf8_lossy(&buf).contains("NAK"), "{kind:?}");
1412            let mut stream = stream;
1413            let mut pack_bytes = Vec::new();
1414            while let Some(chunk) = futures::StreamExt::next(&mut stream).await {
1415                pack_bytes.extend(chunk.unwrap());
1416            }
1417            let tmp = tempfile::tempdir().unwrap();
1418            let mut pack = crate::internal::pack::Pack::new_with_hash_kind(
1419                kind,
1420                Some(1),
1421                None,
1422                Some(tmp.path().to_path_buf()),
1423                true,
1424            );
1425            let seen = Arc::new(Mutex::new(Vec::new()));
1426            let sink = seen.clone();
1427            pack.decode(
1428                &mut std::io::Cursor::new(&pack_bytes),
1429                move |entry| sink.lock().unwrap().push(entry.inner.hash),
1430                None::<fn(ObjectHash)>,
1431            )
1432            .unwrap();
1433            let seen: Vec<ObjectHash> = seen.lock().unwrap().clone();
1434            assert_eq!(seen.len(), 3, "{kind:?}");
1435            assert!(seen.contains(&commit.id) && seen.iter().all(|h| h.kind() == kind));
1436
1437            // have: the common commit is acknowledged.
1438            let mut req = BytesMut::new();
1439            add_pkt_line_string(&mut req, format!("want {}\n", commit.id));
1440            add_pkt_line_string(&mut req, format!("have {}\n", commit.id));
1441            add_pkt_line_string(&mut req, "done\n".to_string());
1442            let (stream, buf) = smart.git_upload_pack(req.freeze()).await.unwrap();
1443            assert!(
1444                String::from_utf8_lossy(&buf).contains(&format!("ACK {}", commit.id)),
1445                "{kind:?}"
1446            );
1447            // Nothing left to send: a valid empty pack (0 objects, trailer of `kind`).
1448            let mut stream = stream;
1449            let mut empty_pack = Vec::new();
1450            while let Some(chunk) = futures::StreamExt::next(&mut stream).await {
1451                empty_pack.extend(chunk.unwrap());
1452            }
1453            assert_eq!(empty_pack.len(), 12 + kind.size(), "{kind:?}");
1454            assert_eq!(&empty_pack[..4], b"PACK");
1455            assert_eq!(&empty_pack[8..12], &0u32.to_be_bytes());
1456            assert_eq!(
1457                ObjectHash::from_bytes_for_kind(kind, &empty_pack[12..]).unwrap(),
1458                ObjectHash::new_for_kind(kind, &empty_pack[..12])
1459            );
1460
1461            // receive-pack command with this kind's zero ID and commit ID.
1462            let zero = ObjectHash::zero_str(kind);
1463            let mut pkt = BytesMut::new();
1464            add_pkt_line_string(
1465                &mut pkt,
1466                format!(
1467                    "{zero} {} refs/heads/feature\0report-status object-format={}\n",
1468                    commit.id,
1469                    kind.as_str()
1470                ),
1471            );
1472            pkt.put(&PKT_LINE_END_MARKER[..]);
1473            smart.parse_receive_pack_commands(pkt.freeze()).unwrap();
1474            assert_eq!(smart.command_list.len(), 1);
1475            assert_eq!(smart.command_list[0].old_hash, zero);
1476            assert_eq!(smart.command_list[0].new_hash, commit.id.to_string());
1477            assert!(smart.capabilities.contains(&Capability::ReportStatus));
1478        }
1479    }
1480
1481    /// Repository advertising one ref with an arbitrary (possibly malformed) ID string.
1482    #[derive(Clone)]
1483    struct BadRefRepo {
1484        kind: HashKind,
1485        id: String,
1486    }
1487
1488    #[async_trait]
1489    impl RepositoryAccess for BadRefRepo {
1490        fn object_hash_kind(&self) -> HashKind {
1491            self.kind
1492        }
1493        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
1494            Ok(vec![("refs/heads/main".to_string(), self.id.clone())])
1495        }
1496        async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
1497            Ok(false)
1498        }
1499        async fn get_object(&self, object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
1500            Err(ProtocolError::ObjectNotFound(object_hash.to_string()))
1501        }
1502        async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
1503            Ok(())
1504        }
1505        async fn update_reference(
1506            &self,
1507            _ref_name: &str,
1508            _old_hash: Option<&str>,
1509            _new_hash: &str,
1510        ) -> Result<(), ProtocolError> {
1511            Ok(())
1512        }
1513        async fn get_objects_for_pack(
1514            &self,
1515            _wants: &[String],
1516            _haves: &[String],
1517        ) -> Result<Vec<String>, ProtocolError> {
1518            Ok(vec![])
1519        }
1520        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
1521            Ok(true)
1522        }
1523        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
1524            Ok(())
1525        }
1526    }
1527
1528    /// Repository whose reported kind is test-local shared state (no thread-local mutation):
1529    /// `set_kind` changes it at any time, and the flip flags make the refs / `has_object`
1530    /// accessors switch it to SHA-256 while they run (drift inside an awaited repository
1531    /// call). Refs and objects are served by a SHA-1 `TestRepoAccess`.
1532    #[derive(Clone)]
1533    struct DriftingRepo {
1534        inner: TestRepoAccess,
1535        kind: Arc<Mutex<HashKind>>,
1536        flip_in_refs: bool,
1537        flip_in_has_object: bool,
1538        flip_in_update_reference: bool,
1539    }
1540
1541    impl DriftingRepo {
1542        fn new() -> Self {
1543            Self {
1544                inner: TestRepoAccess::new(),
1545                kind: Arc::new(Mutex::new(HashKind::Sha1)),
1546                flip_in_refs: false,
1547                flip_in_has_object: false,
1548                flip_in_update_reference: false,
1549            }
1550        }
1551
1552        fn flipping_update_reference() -> Self {
1553            Self {
1554                flip_in_update_reference: true,
1555                ..Self::new()
1556            }
1557        }
1558
1559        fn flipping_refs() -> Self {
1560            Self {
1561                flip_in_refs: true,
1562                ..Self::new()
1563            }
1564        }
1565
1566        fn flipping_has_object() -> Self {
1567            Self {
1568                flip_in_has_object: true,
1569                ..Self::new()
1570            }
1571        }
1572
1573        fn set_kind(&self, kind: HashKind) {
1574            *self.kind.lock().unwrap() = kind;
1575        }
1576    }
1577
1578    #[async_trait]
1579    impl RepositoryAccess for DriftingRepo {
1580        fn object_hash_kind(&self) -> HashKind {
1581            *self.kind.lock().unwrap()
1582        }
1583        async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
1584            if self.flip_in_refs {
1585                self.set_kind(HashKind::Sha256);
1586            }
1587            self.inner.get_repository_refs().await
1588        }
1589        async fn has_object(&self, object_hash: &str) -> Result<bool, ProtocolError> {
1590            if self.flip_in_has_object {
1591                self.set_kind(HashKind::Sha256);
1592            }
1593            self.inner.has_object(object_hash).await
1594        }
1595        async fn get_object(&self, object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
1596            self.inner.get_object(object_hash).await
1597        }
1598        async fn store_pack_data(&self, pack_data: &[u8]) -> Result<(), ProtocolError> {
1599            self.inner.store_pack_data(pack_data).await
1600        }
1601        async fn update_reference(
1602            &self,
1603            ref_name: &str,
1604            old_hash: Option<&str>,
1605            new_hash: &str,
1606        ) -> Result<(), ProtocolError> {
1607            let result = self
1608                .inner
1609                .update_reference(ref_name, old_hash, new_hash)
1610                .await;
1611            if self.flip_in_update_reference {
1612                self.set_kind(HashKind::Sha256);
1613            }
1614            result
1615        }
1616        async fn get_objects_for_pack(
1617            &self,
1618            wants: &[String],
1619            haves: &[String],
1620        ) -> Result<Vec<String>, ProtocolError> {
1621            self.inner.get_objects_for_pack(wants, haves).await
1622        }
1623        async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
1624            self.inner.has_default_branch().await
1625        }
1626        async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
1627            self.inner.post_receive_hook().await
1628        }
1629    }
1630
1631    /// parse_capabilities should confirm the repository's wire hash kind and record declared
1632    /// capabilities (SHA-256 repository; thread-local kind is SHA-1 and does not matter).
1633    #[tokio::test]
1634    async fn parse_capabilities_updates_hash_and_caps() {
1635        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1636        let repo_access = TestRepoAccess::with_kind(HashKind::Sha256);
1637        let auth = TestAuth;
1638        let mut smart = SmartProtocol::new(TransportProtocol::Http, repo_access, auth);
1639
1640        smart
1641            .parse_capabilities("object-format=sha256 side-band-64k multi_ack")
1642            .unwrap();
1643
1644        assert_eq!(smart.wire_hash_kind, HashKind::Sha256);
1645        assert_eq!(smart.zero_id.len(), HashKind::Sha256.hex_len());
1646        assert!(
1647            smart.capabilities.contains(&Capability::SideBand64k),
1648            "side-band-64k should be recorded"
1649        );
1650    }
1651
1652    /// info-refs should accept SHA-256 refs and emit the matching object-format capability.
1653    #[tokio::test]
1654    async fn info_refs_accepts_sha256_refs_and_emits_capability() {
1655        // Define a repo access that returns SHA-256 refs
1656        #[derive(Clone)]
1657        struct Sha256Repo;
1658
1659        #[async_trait]
1660        impl RepositoryAccess for Sha256Repo {
1661            fn object_hash_kind(&self) -> HashKind {
1662                HashKind::Sha256
1663            }
1664            async fn get_repository_refs(&self) -> Result<Vec<(String, String)>, ProtocolError> {
1665                Ok(vec![
1666                    (
1667                        "HEAD".to_string(),
1668                        "0000000000000000000000000000000000000000000000000000000000000000"
1669                            .to_string(),
1670                    ),
1671                    (
1672                        "refs/heads/main".to_string(),
1673                        "1111111111111111111111111111111111111111111111111111111111111111"
1674                            .to_string(),
1675                    ),
1676                ])
1677            }
1678            async fn has_object(&self, _object_hash: &str) -> Result<bool, ProtocolError> {
1679                Ok(true)
1680            }
1681            async fn get_object(&self, _object_hash: &str) -> Result<Vec<u8>, ProtocolError> {
1682                Ok(vec![])
1683            }
1684            async fn store_pack_data(&self, _pack_data: &[u8]) -> Result<(), ProtocolError> {
1685                Ok(())
1686            }
1687            async fn update_reference(
1688                &self,
1689                _ref_name: &str,
1690                _old_hash: Option<&str>,
1691                _new_hash: &str,
1692            ) -> Result<(), ProtocolError> {
1693                Ok(())
1694            }
1695            async fn get_objects_for_pack(
1696                &self,
1697                _wants: &[String],
1698                _haves: &[String],
1699            ) -> Result<Vec<String>, ProtocolError> {
1700                Ok(vec![])
1701            }
1702            async fn has_default_branch(&self) -> Result<bool, ProtocolError> {
1703                Ok(false)
1704            }
1705            async fn post_receive_hook(&self) -> Result<(), ProtocolError> {
1706                Ok(())
1707            }
1708        }
1709
1710        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1711        let repo_access = Sha256Repo;
1712        let auth = TestAuth;
1713        let mut smart = SmartProtocol::new(TransportProtocol::Http, repo_access, auth);
1714        smart.set_wire_hash_kind(HashKind::Sha256);
1715
1716        let resp = smart
1717            .git_info_refs(ServiceType::UploadPack)
1718            .await
1719            .expect("sha256 refs should be accepted");
1720        let resp_str = String::from_utf8(resp.to_vec()).expect("pkt-line should be valid UTF-8");
1721        assert!(
1722            resp_str.contains("object-format=sha256"),
1723            "capability line should advertise sha256"
1724        );
1725    }
1726
1727    /// parse_receive_pack_commands should decode multiple pkt-lines into RefCommand list.
1728    #[tokio::test]
1729    async fn parse_receive_pack_commands_decodes_commands() {
1730        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1731        let repo_access = TestRepoAccess::new();
1732        let auth = TestAuth;
1733        let mut smart = SmartProtocol::new(TransportProtocol::Http, repo_access, auth);
1734
1735        let zero = ObjectHash::zero_str(HashKind::Sha1);
1736        let mut pkt = BytesMut::new();
1737        add_pkt_line_string(&mut pkt, format!("{zero} {zero} refs/heads/main\n"));
1738        add_pkt_line_string(&mut pkt, format!("{zero} {zero} refs/tags/v1.0\n"));
1739        pkt.put(&PKT_LINE_END_MARKER[..]);
1740
1741        smart.parse_receive_pack_commands(pkt.freeze()).unwrap();
1742
1743        assert_eq!(smart.command_list.len(), 2);
1744        assert_eq!(smart.command_list[0].ref_name, "refs/heads/main");
1745        assert_eq!(smart.command_list[1].ref_name, "refs/tags/v1.0");
1746    }
1747
1748    /// receive-pack should error if ref commands are not terminated by a flush.
1749    #[tokio::test]
1750    async fn receive_pack_missing_flush_errors() {
1751        let _guard = set_hash_kind_for_test(HashKind::Sha1);
1752        let repo_access = TestRepoAccess::new();
1753        let auth = TestAuth;
1754        let mut smart = SmartProtocol::new(TransportProtocol::Http, repo_access, auth);
1755
1756        let zero = ObjectHash::zero_str(HashKind::Sha1);
1757        let mut pkt = BytesMut::new();
1758        add_pkt_line_string(&mut pkt, format!("{zero} {zero} refs/heads/main\n"));
1759
1760        let request_stream = Box::pin(futures::stream::once(async { Ok(pkt.freeze()) }));
1761        let err = smart
1762            .git_receive_pack_stream(request_stream)
1763            .await
1764            .unwrap_err();
1765        assert!(matches!(err, ProtocolError::InvalidRequest(_)));
1766    }
1767}