flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/services/repos/src/git_http.rs

843 lines31,960 bytesCodeBlame
1//! Git over HTTPS: the smart HTTP remote at `/<namespace>/<repo>.git`,
2//! proxied to the git store with a short-lived token.
3
4use g1t_contracts::identity::GitCredentialsArgs;
5use g1t_contracts::repos::{GitAccess, GitService, RepoPath};
6use g1t_contracts::{FailureCode, Outcome, Viewer};
7use worker::js_sys::Uint8Array;
8use worker::{Fetch, Fetcher, Headers, Method, Request, RequestInit, Response, Result, Url};
9
10const ENDPOINTS: [&str; 3] = ["info/refs", "git-upload-pack", "git-receive-pack"];
11const FORWARDED_HEADERS: [&str; 5] = [
12 "accept",
13 "content-encoding",
14 "content-type",
15 "git-protocol",
16 "user-agent",
17];
18
19/// A git request, parsed from its URL.
20pub struct GitRequest {
21 pub path: RepoPath,
22 pub endpoint: &'static str,
23 pub service: GitService,
24}
25
26/// Parses `/<namespace>/<name>[.git]/<endpoint>`, or returns `None` if the
27/// request is not git's.
28pub fn parse(url: &Url) -> Option<GitRequest> {
29 let path = url.path().strip_prefix('/')?;
30 let endpoint = ENDPOINTS
31 .into_iter()
32 .find(|endpoint| path.ends_with(&format!("/{endpoint}")))?;
33 let repo = &path[..path.len() - endpoint.len() - 1];
34 let (namespace, name) = repo.split_once('/')?;
35 let name = name.strip_suffix(".git").unwrap_or(name);
36 if namespace.is_empty() || name.is_empty() || name.contains('/') {
37 return None;
38 }
39 let service = if endpoint == "info/refs" {
40 url.query_pairs()
41 .find(|(key, _)| key == "service")
42 .map(|(_, value)| value.into_owned())?
43 } else {
44 endpoint.to_owned()
45 };
46 let service = match service.as_str() {
47 "git-upload-pack" => GitService::UploadPack,
48 "git-receive-pack" => GitService::ReceivePack,
49 _ => return None,
50 };
51 Some(GitRequest {
52 path: RepoPath {
53 namespace: namespace.to_owned(),
54 name: name.to_owned(),
55 },
56 endpoint,
57 service,
58 })
59}
60
61/// How long each step of a git request took, sent back to git as a
62/// `Server-Timing` header so that a slow clone shows where its time went.
63/// Step names and whole milliseconds only. The Workers clock moves only
64/// while a request waits on something, so each step is the time spent
65/// waiting on the database, another service or the git store. A note
66/// says how a step went without a duration: `refs;desc=hit-colo`.
67pub struct Timing {
68 started: u64,
69 last: u64,
70 steps: Vec<(&'static str, u64)>,
71 notes: Vec<(&'static str, &'static str)>,
72}
73
74impl Timing {
75 pub fn start() -> Self {
76 let now = g1t_kit::now_ms();
77 Self {
78 started: now,
79 last: now,
80 steps: Vec::new(),
81 notes: Vec::new(),
82 }
83 }
84
85 /// Says how `name` went: where an answer or a credential came from.
86 pub fn note(&mut self, name: &'static str, description: &'static str) {
87 self.notes.push((name, description));
88 }
89
90 /// Ends a step, named `step`, that began when the last one ended.
91 pub fn mark(&mut self, step: &'static str) {
92 let now = g1t_kit::now_ms();
93 self.steps.push((step, now.saturating_sub(self.last)));
94 self.last = now;
95 }
96
97 /// `response`, with how long each step took.
98 pub fn apply(&self, response: Response) -> Result<Response> {
99 let total = g1t_kit::now_ms().saturating_sub(self.started);
100 let headers = response.headers().clone();
101 headers.set("server-timing", &server_timing(&self.steps, &self.notes, total))?;
102 Ok(response.with_headers(headers))
103 }
104}
105
106/// A `Server-Timing` value: each step with its duration, the notes, then
107/// the total.
108fn server_timing(steps: &[(&str, u64)], notes: &[(&str, &str)], total: u64) -> String {
109 steps
110 .iter()
111 .map(|(step, ms)| format!("{step};dur={ms}"))
112 .chain(notes.iter().map(|(name, description)| format!("{name};desc={description}")))
113 .chain(std::iter::once(format!("total;dur={total}")))
114 .collect::<Vec<_>>()
115 .join(", ")
116}
117
118/// The user named by an HTTP Basic `Authorization` header, as git sends it.
119pub async fn viewer(request: &Request, identity: &Fetcher) -> Result<Viewer> {
120 let Some(header) = request.headers().get("authorization")? else {
121 return Ok(None);
122 };
123 let Some((scheme, encoded)) = header.split_once(' ') else {
124 return Ok(None);
125 };
126 if !scheme.eq_ignore_ascii_case("basic") {
127 return Ok(None);
128 }
129 let Some(decoded) = decode_base64(encoded.trim()) else {
130 return Ok(None);
131 };
132 let Some((username, secret)) = decoded.split_once(':') else {
133 return Ok(None);
134 };
135 g1t_kit::call(
136 identity,
137 "user_for_git_credentials",
138 &GitCredentialsArgs {
139 username: username.to_owned(),
140 secret: secret.to_owned(),
141 },
142 )
143 .await
144}
145
146/// Standard base64 to a UTF-8 string, or `None` if either step fails.
147fn decode_base64(input: &str) -> Option<String> {
148 let mut bytes = Vec::with_capacity(input.len() * 3 / 4);
149 let mut buffer = 0u32;
150 let mut bits = 0;
151 for byte in input.bytes().filter(|byte| *byte != b'=') {
152 let value = match byte {
153 b'A'..=b'Z' => byte - b'A',
154 b'a'..=b'z' => byte - b'a' + 26,
155 b'0'..=b'9' => byte - b'0' + 52,
156 b'+' => 62,
157 b'/' => 63,
158 _ => return None,
159 };
160 buffer = (buffer << 6) | u32::from(value);
161 bits += 6;
162 if bits >= 8 {
163 bits -= 8;
164 bytes.push((buffer >> bits) as u8);
165 }
166 }
167 String::from_utf8(bytes).ok()
168}
169
170/// The response for a refused git request. Anonymous callers are asked to
171/// authenticate, which is what makes git prompt for credentials.
172pub fn refuse<T>(outcome: Outcome<T>) -> Result<Response> {
173 let Outcome::Fail(failure) = outcome else {
174 return Response::error("Not found", 404);
175 };
176 let mut response = Response::error(failure.message, failure.code.http_status())?;
177 if failure.code == FailureCode::Unauthenticated {
178 response
179 .headers_mut()
180 .set("www-authenticate", "Basic realm=\"g1t\"")?;
181 }
182 Ok(response)
183}
184
185/// `url` with its first path segment, the workspace, replaced by `slug`.
186pub fn with_namespace(url: &Url, slug: &str) -> Option<String> {
187 let rest = url.path().strip_prefix('/')?.split_once('/')?.1;
188 let mut moved = url.clone();
189 moved.set_path(&format!("/{slug}/{rest}"));
190 Some(moved.to_string())
191}
192
193/// Where a git request for a renamed workspace's old address should go
194/// now, if its first segment is an old slug that still redirects.
195pub async fn renamed(url: &Url, identity: &Fetcher) -> Result<Option<String>> {
196 let Some(old) = url.path().strip_prefix('/').and_then(|path| path.split('/').next()) else {
197 return Ok(None);
198 };
199 let current: Option<String> = g1t_kit::call(
200 identity,
201 "resolve_slug",
202 &g1t_contracts::identity::SlugArgs {
203 slug: old.to_owned(),
204 },
205 )
206 .await?;
207 Ok(current.and_then(|slug| with_namespace(url, &slug)))
208}
209
210/// `url` with its repository, the first two path segments, replaced by
211/// `to`: where a request for a transferred repository's old path goes.
212/// Keeps whether the old address ended in `.git`.
213pub fn transferred(url: &Url, to: &RepoPath) -> Option<String> {
214 let path = url.path().strip_prefix('/')?;
215 let mut segments = path.splitn(3, '/');
216 let (_, name, rest) = (segments.next()?, segments.next()?, segments.next()?);
217 let suffix = if name.ends_with(".git") { ".git" } else { "" };
218 let mut moved = url.clone();
219 moved.set_path(&format!("/{}/{}{suffix}/{rest}", to.namespace, to.name));
220 Some(moved.to_string())
221}
222
223/// A permanent redirect: 301 for git's first request for refs, which it
224/// follows and then uses the new address for the rest; 308 for the
225/// others, so a POST stays a POST.
226pub fn moved(location: &str, get: bool) -> Result<Response> {
227 let mut response = Response::empty()?.with_status(if get { 301 } else { 308 });
228 response.headers_mut().set("location", location)?;
229 Ok(response)
230}
231
232const ZERO_ID: &str = "0000000000000000000000000000000000000000";
233const HEADS: &str = "refs/heads/";
234const TAGS: &str = "refs/tags/";
235
236/// One ref a push asks to change.
237struct Command {
238 old: String,
239 new: String,
240 name: String,
241}
242
243/// The commands at the start of a receive-pack request, and the
244/// capabilities the client sent with the first of them.
245fn commands(body: &[u8]) -> (Vec<Command>, String) {
246 let mut commands = Vec::new();
247 let mut capabilities = String::new();
248 let mut position = 0;
249 // Commands are pkt-lines; a flush packet ends them and the pack follows.
250 while let Some(length) = body
251 .get(position..position + 4)
252 .and_then(|hex| std::str::from_utf8(hex).ok())
253 .and_then(|hex| usize::from_str_radix(hex, 16).ok())
254 {
255 if length < 4 || position + length > body.len() {
256 break;
257 }
258 let line = &body[position + 4..position + length];
259 position += length;
260 // `<old> <new> <ref>`, and on the first command a NUL then capabilities.
261 let mut halves = line.splitn(2, |byte| *byte == 0);
262 let command = halves.next().unwrap_or_default();
263 if let Some(rest) = halves.next() {
264 capabilities = String::from_utf8_lossy(rest).trim().to_owned();
265 }
266 let Ok(command) = std::str::from_utf8(command) else {
267 continue;
268 };
269 let mut parts = command.trim_end().splitn(3, ' ');
270 if let (Some(old), Some(new), Some(name)) = (parts.next(), parts.next(), parts.next()) {
271 commands.push(Command {
272 old: old.to_owned(),
273 new: new.to_owned(),
274 name: name.to_owned(),
275 });
276 }
277 }
278 (commands, capabilities)
279}
280
281/// The bytes of the pack a receive-pack request carries: everything after
282/// the flush packet that ends its commands. Zero for a push that only
283/// deletes refs.
284pub(crate) fn pack_bytes(body: &[u8]) -> u64 {
285 let mut position = 0;
286 while let Some(length) = body
287 .get(position..position + 4)
288 .and_then(|hex| std::str::from_utf8(hex).ok())
289 .and_then(|hex| usize::from_str_radix(hex, 16).ok())
290 {
291 if length == 0 {
292 return (body.len() - position - 4) as u64;
293 }
294 if length < 4 || position + length > body.len() {
295 break;
296 }
297 position += length;
298 }
299 0
300}
301
302fn pkt_line(payload: &[u8]) -> Vec<u8> {
303 let mut line = format!("{:04x}", payload.len() + 4).into_bytes();
304 line.extend_from_slice(payload);
305 line
306}
307
308/// What git is told when a push would change a protected branch: every ref
309/// in it is declined, with the reason against the protected one, so that
310/// git prints it beside the branch. `None` if the push leaves the branch
311/// alone, or creates it in a repository that does not have it yet.
312fn refusal(body: &[u8], protected: &str) -> Option<Vec<u8>> {
313 let (commands, capabilities) = commands(body);
314 let reference = format!("{HEADS}{protected}");
315 if !commands
316 .iter()
317 .any(|command| command.name == reference && command.old != ZERO_ID)
318 {
319 return None;
320 }
321 let mut report = pkt_line(b"unpack ok\n");
322 for command in &commands {
323 let reason = if command.name == reference {
324 format!("{protected} is protected: push a branch and open a pull request")
325 } else {
326 format!("not pushed, because the same push would change {protected}")
327 };
328 report.extend(pkt_line(
329 format!("ng {} {reason}\n", command.name).as_bytes(),
330 ));
331 }
332 report.extend_from_slice(b"0000");
333 Some(framed(report, &capabilities, &[]))
334}
335
336/// A report-status as git expects it: inside channel 1 when the client
337/// asked for side-band, after `messages` on channel 2, which git prints as
338/// `remote:` lines. Without side-band the messages cannot be shown.
339fn framed(report: Vec<u8>, capabilities: &str, messages: &[String]) -> Vec<u8> {
340 let sideband = capabilities
341 .split(' ')
342 .any(|capability| capability.starts_with("side-band"));
343 if !sideband {
344 return report;
345 }
346 let mut body = Vec::new();
347 for message in messages {
348 let mut packet = vec![2u8];
349 packet.extend_from_slice(message.as_bytes());
350 packet.push(b'\n');
351 body.extend(pkt_line(&packet));
352 }
353 // side-band (not -64k) packets carry at most 1000 bytes.
354 for chunk in report.chunks(990) {
355 let mut packet = vec![1u8];
356 packet.extend_from_slice(chunk);
357 body.extend(pkt_line(&packet));
358 }
359 body.extend_from_slice(b"0000");
360 body
361}
362
363/// Declines every ref in a push with `reason`, explaining why in
364/// `messages`: what push protection answers when a push adds a secret.
365pub fn declined(body: &[u8], reason: &str, messages: &[String]) -> Result<Response> {
366 let (commands, capabilities) = commands(body);
367 let mut report = pkt_line(b"unpack ok\n");
368 for command in &commands {
369 report.extend(pkt_line(format!("ng {} {reason}\n", command.name).as_bytes()));
370 }
371 report.extend_from_slice(b"0000");
372 let headers = Headers::new();
373 headers.set("content-type", "application/x-git-receive-pack-result")?;
374 headers.set("cache-control", "no-cache")?;
375 Ok(Response::from_bytes(framed(report, &capabilities, messages))?.with_headers(headers))
376}
377
378/// A branch or tag a push asks to move.
379#[derive(Debug, PartialEq, Eq)]
380pub struct Pushed {
381 /// The full ref: `refs/heads/main`, `refs/tags/v1`.
382 pub git_ref: String,
383 /// Where it pointed before; `None` for a new ref.
384 pub before: Option<String>,
385 pub after: String,
386}
387
388impl Pushed {
389 pub fn branch(&self) -> Option<&str> {
390 self.git_ref.strip_prefix(HEADS)
391 }
392}
393
394/// The branches and tags a push asks to move, read from the commands at the
395/// start of a receive-pack request. Deletions and other refs are left out.
396fn pushed_branches(body: &[u8]) -> Vec<Pushed> {
397 commands(body)
398 .0
399 .into_iter()
400 .filter(|command| command.new != ZERO_ID)
401 .filter(|command| command.name.starts_with(HEADS) || command.name.starts_with(TAGS))
402 .map(|Command { old, new, name }| Pushed {
403 git_ref: name,
404 before: (old != ZERO_ID).then_some(old),
405 after: new,
406 })
407 .collect()
408}
409
410/// The git store's answer, and what the request asked it to change.
411pub struct Forwarded {
412 pub response: Response,
413 /// For a push: the branches and tags it asks to move, and the commits
414 /// to move them to. Whether each moved is for the caller to confirm.
415 pub pushed: Vec<Pushed>,
416 /// For a push: the size of the pack it sent, for the storage meter.
417 pub pack_bytes: u64,
418}
419
420/// What became of a git request.
421pub enum Push {
422 Forwarded(Forwarded),
423 /// A push to a protected branch, answered here without reaching the store.
424 Refused(Response),
425 /// A push that adds a secret nobody allowed, answered the same way.
426 Blocked(Response),
427}
428
429/// One packet of a pkt-line stream: data, or a flush (`0000`), delimiter
430/// (`0001`) or response-end (`0002`) packet, kept as its four bytes.
431#[derive(Debug, PartialEq, Eq)]
432enum Packet {
433 Data(Vec<u8>),
434 Special([u8; 4]),
435}
436
437/// The packets in `bytes`, or `None` if it is not a whole pkt-line stream.
438fn packets(bytes: &[u8]) -> Option<Vec<Packet>> {
439 let mut out = Vec::new();
440 let mut position = 0;
441 while position < bytes.len() {
442 let header = bytes.get(position..position + 4)?;
443 let length = usize::from_str_radix(std::str::from_utf8(header).ok()?, 16).ok()?;
444 if length < 4 {
445 out.push(Packet::Special(header.try_into().ok()?));
446 position += 4;
447 continue;
448 }
449 out.push(Packet::Data(bytes.get(position + 4..position + length)?.to_vec()));
450 position += length;
451 }
452 Some(out)
453}
454
455fn encode(packets: &[Packet]) -> Vec<u8> {
456 let mut out = Vec::new();
457 for packet in packets {
458 match packet {
459 Packet::Data(data) => out.extend(pkt_line(data)),
460 Packet::Special(bytes) => out.extend_from_slice(bytes),
461 }
462 }
463 out
464}
465
466/// A ref advertisement (`info/refs` for upload-pack) or a protocol v2
467/// `ls-refs` answer with `HEAD` pointing at `branch`, the repository's
468/// default branch as g1t keeps it, so a clone checks it out. The git store
469/// holds the HEAD it was created with; g1t can change the default branch
470/// since. `None` when there is nothing to change: no `HEAD` line, `HEAD`
471/// already names `branch`, or `branch` is not advertised.
472pub fn with_head(body: &[u8], branch: &str) -> Option<Vec<u8>> {
473 let mut packets = packets(body)?;
474 let target = format!("{HEADS}{branch}");
475 let oid = packets.iter().find_map(|packet| {
476 let Packet::Data(data) = packet else { return None };
477 let line = data.split(|byte| *byte == 0).next()?;
478 let line = std::str::from_utf8(line).ok()?.trim_end();
479 let (oid, name) = line.split_once(' ')?;
480 // v2 lines may carry attributes after the name.
481 let name = name.split(' ').next()?;
482 (name == target).then(|| oid.to_owned())
483 })?;
484 let mut changed = false;
485 for packet in &mut packets {
486 let Packet::Data(data) = packet else { continue };
487 let text = String::from_utf8_lossy(data).into_owned();
488 let Some((_, rest)) = text.split_once(' ') else { continue };
489 if !(rest.starts_with("HEAD\0") || rest.starts_with("HEAD\n") || rest.starts_with("HEAD ") || rest == "HEAD") {
490 continue;
491 }
492 let mut line = format!("{oid} {rest}");
493 // v0: `symref=HEAD:refs/heads/<old>` among the capabilities.
494 // v2: `symref-target:refs/heads/<old>` after the name.
495 for marker in ["symref=HEAD:", "symref-target:"] {
496 if let Some(at) = line.find(marker) {
497 let start = at + marker.len();
498 let end = line[start..]
499 .find([' ', '\n', '\0'])
500 .map_or(line.len(), |offset| start + offset);
501 line.replace_range(start..end, &target);
502 }
503 }
504 changed = line != text;
505 if changed {
506 *data = line.into_bytes();
507 }
508 break;
509 }
510 changed.then(|| encode(&packets))
511}
512
513/// Whether a request to the git store is one whose answer names `HEAD`:
514/// the ref advertisement for a fetch, or a protocol v2 `ls-refs`.
515fn names_head(git: &GitRequest, body: Option<&[u8]>) -> bool {
516 if git.service != GitService::UploadPack {
517 return false;
518 }
519 match body {
520 None => git.endpoint == "info/refs",
521 Some(body) => {
522 git.endpoint == "git-upload-pack"
523 && body.windows(b"command=ls-refs".len()).any(|window| window == b"command=ls-refs")
524 }
525 }
526}
527
528/// Sends the request on to the git store and returns its response as is,
529/// unless it is a push that would change the `protected` branch, or one
530/// that `scan` (push protection) answers itself. A fetch's ref listing has
531/// its `HEAD` pointed at `default_branch` (see [`with_head`]). A POST's
532/// body is `read` when the caller has read it already.
533pub async fn forward(
534 mut request: Request,
535 read: Option<Vec<u8>>,
536 git: &GitRequest,
537 access: &GitAccess,
538 protected: Option<&str>,
539 default_branch: Option<&str>,
540 scan: impl AsyncFnOnce(&[u8]) -> Result<Option<Response>>,
541) -> Result<Push> {
542 let headers = Headers::new();
543 headers.set("authorization", &format!("Bearer {}", access.token))?;
544 for name in FORWARDED_HEADERS {
545 if let Some(value) = request.headers().get(name)? {
546 headers.set(name, &value)?;
547 }
548 }
549 let query = request
550 .url()?
551 .query()
552 .map(|query| format!("?{query}"))
553 .unwrap_or_default();
554 let mut init = RequestInit::new();
555 init.with_method(request.method()).with_headers(headers);
556 let mut pushed = Vec::new();
557 let mut pack = 0;
558 let mut lists_head = request.method() == Method::Get && names_head(git, None);
559 if request.method() == Method::Post {
560 // Pushes are capped at 100 MB by the platform, so buffering is safe.
561 let body = match read {
562 Some(body) => body,
563 None => request.bytes().await?,
564 };
565 if git.endpoint == "git-receive-pack" {
566 if let Some(report) = protected.and_then(|branch| refusal(&body, branch)) {
567 let headers = Headers::new();
568 headers.set("content-type", "application/x-git-receive-pack-result")?;
569 headers.set("cache-control", "no-cache")?;
570 return Ok(Push::Refused(
571 Response::from_bytes(report)?.with_headers(headers),
572 ));
573 }
574 if let Some(response) = scan(&body).await? {
575 return Ok(Push::Blocked(response));
576 }
577 pushed = pushed_branches(&body);
578 pack = pack_bytes(&body);
579 }
580 lists_head = names_head(git, Some(&body));
581 init.with_body(Some(Uint8Array::from(body.as_slice()).into()));
582 }
583 let upstream =
584 Request::new_with_init(&format!("{}/{}{query}", access.remote, git.endpoint), &init)?;
585 let mut response = Fetch::Request(upstream).send().await?;
586 if let (true, Some(branch)) = (lists_head, default_branch)
587 && response.status_code() == 200
588 {
589 let headers = response.headers().clone();
590 headers.delete("content-length")?;
591 let body = response.bytes().await?;
592 let body = with_head(&body, branch).unwrap_or(body);
593 response = Response::from_bytes(body)?.with_headers(headers);
594 }
595 Ok(Push::Forwarded(Forwarded {
596 response,
597 pushed,
598 pack_bytes: pack,
599 }))
600}
601
602#[cfg(test)]
603mod tests {
604 use super::{Pushed, RepoPath, Url, ZERO_ID, framed, pack_bytes, pushed_branches, refusal, server_timing, transferred, with_head, with_namespace};
605
606 #[test]
607 fn server_timing_names_each_step_and_the_total() {
608 assert_eq!(
609 server_timing(&[("repo", 12), ("token", 0), ("store", 140)], &[], 153),
610 "repo;dur=12, token;dur=0, store;dur=140, total;dur=153"
611 );
612 assert_eq!(server_timing(&[], &[], 3), "total;dur=3");
613 assert_eq!(
614 server_timing(&[("repo", 1), ("cache", 2)], &[("refs", "hit-colo")], 4),
615 "repo;dur=1, cache;dur=2, refs;desc=hit-colo, total;dur=4"
616 );
617 }
618
619 #[test]
620 fn a_renamed_repository_redirects_to_its_new_name() {
621 // A rename keeps the old path in the same table as a transfer, so
622 // the old remote is sent to the new name the same way.
623 let to = RepoPath {
624 namespace: "acme".into(),
625 name: "booster".into(),
626 };
627 let url = Url::parse("https://g1t.sh/acme/rocket.git/info/refs?service=git-upload-pack").unwrap();
628 assert_eq!(
629 transferred(&url, &to).as_deref(),
630 Some("https://g1t.sh/acme/booster.git/info/refs?service=git-upload-pack")
631 );
632 }
633
634 #[test]
635 fn head_follows_the_default_branch_in_a_v0_advertisement() {
636 let main = "1111111111111111111111111111111111111111";
637 let trunk = "2222222222222222222222222222222222222222";
638 let body = [
639 pkt("# service=git-upload-pack\n"),
640 b"0000".to_vec(),
641 pkt(&format!("{main} HEAD\0multi_ack symref=HEAD:refs/heads/main agent=git/2\n")),
642 pkt(&format!("{main} refs/heads/main\n")),
643 pkt(&format!("{trunk} refs/heads/trunk\n")),
644 b"0000".to_vec(),
645 ]
646 .concat();
647 let changed = String::from_utf8(with_head(&body, "trunk").unwrap()).unwrap();
648 assert!(changed.contains(&format!("{trunk} HEAD\0multi_ack symref=HEAD:refs/heads/trunk agent=git/2\n")));
649 assert!(changed.contains(&format!("{main} refs/heads/main\n")));
650 assert!(changed.starts_with("001e# service=git-upload-pack\n0000"));
651 // Already right, or a branch it does not have: left alone.
652 assert!(with_head(&body, "main").is_none());
653 assert!(with_head(&body, "gone").is_none());
654 }
655
656 #[test]
657 fn head_follows_the_default_branch_in_a_v2_listing() {
658 let main = "1111111111111111111111111111111111111111";
659 let trunk = "2222222222222222222222222222222222222222";
660 let body = [
661 pkt(&format!("{main} HEAD symref-target:refs/heads/main\n")),
662 pkt(&format!("{main} refs/heads/main\n")),
663 pkt(&format!("{trunk} refs/heads/trunk\n")),
664 b"0000".to_vec(),
665 ]
666 .concat();
667 let changed = String::from_utf8(with_head(&body, "trunk").unwrap()).unwrap();
668 assert!(changed.starts_with(&String::from_utf8(pkt(&format!("{trunk} HEAD symref-target:refs/heads/trunk\n"))).unwrap()));
669 assert!(changed.ends_with("0000"));
670 // Without symrefs asked for, only the commit changes.
671 let plain = [pkt(&format!("{main} HEAD\n")), pkt(&format!("{trunk} refs/heads/trunk\n")), b"0000".to_vec()].concat();
672 let changed = String::from_utf8(with_head(&plain, "trunk").unwrap()).unwrap();
673 assert!(changed.starts_with(&format!("0032{trunk} HEAD\n")));
674 }
675
676 #[test]
677 fn a_push_is_measured_by_the_pack_after_its_commands() {
678 let old = "c71546fcd893ef8b0f57388b65e620d759705dda";
679 let new = "4807077b296e6edbf410d55e72749d3e1170c291";
680 let pack = b"PACK\0\0\0\x02\0\0\0\0rest-of-pack";
681 let body = [
682 pkt(&format!("{old} {new} refs/heads/main\0 report-status\n")),
683 b"0000".to_vec(),
684 pack.to_vec(),
685 ]
686 .concat();
687 assert_eq!(pack_bytes(&body), pack.len() as u64);
688 // Only deletions: no pack.
689 let body = [pkt(&format!("{old} {ZERO_ID} refs/heads/gone\n")), b"0000".to_vec()].concat();
690 assert_eq!(pack_bytes(&body), 0);
691 assert_eq!(pack_bytes(b"garbage"), 0);
692 }
693
694 #[test]
695 fn a_transferred_repository_keeps_the_rest_of_the_address() {
696 let to = RepoPath {
697 namespace: "flagon-io".into(),
698 name: "g1t".into(),
699 };
700 let url = Url::parse("https://g1t.sh/syntaqx/g1t.git/info/refs?service=git-receive-pack").unwrap();
701 assert_eq!(
702 transferred(&url, &to).as_deref(),
703 Some("https://g1t.sh/flagon-io/g1t.git/info/refs?service=git-receive-pack")
704 );
705 let url = Url::parse("https://g1t.sh/syntaqx/g1t/git-upload-pack").unwrap();
706 assert_eq!(
707 transferred(&url, &to).as_deref(),
708 Some("https://g1t.sh/flagon-io/g1t/git-upload-pack")
709 );
710 }
711
712 #[test]
713 fn a_renamed_workspace_keeps_the_rest_of_the_address() {
714 let url = worker::Url::parse(
715 "https://g1t.sh/acme/rocket.git/info/refs?service=git-upload-pack",
716 )
717 .unwrap();
718 assert_eq!(
719 with_namespace(&url, "acme-inc").as_deref(),
720 Some("https://g1t.sh/acme-inc/rocket.git/info/refs?service=git-upload-pack")
721 );
722 let bare = worker::Url::parse("https://g1t.sh/acme").unwrap();
723 assert_eq!(with_namespace(&bare, "acme-inc"), None);
724 }
725
726 fn pkt(payload: &str) -> Vec<u8> {
727 format!("{:04x}{payload}", payload.len() + 4).into_bytes()
728 }
729
730 #[test]
731 fn pushed_branches_are_read_from_the_commands() {
732 let old = "c71546fcd893ef8b0f57388b65e620d759705dda";
733 let new = "4807077b296e6edbf410d55e72749d3e1170c291";
734 let body = [
735 pkt(&format!(
736 "{old} {new} refs/heads/main\0 report-status side-band-64k\n"
737 )),
738 pkt(&format!("{ZERO_ID} {new} refs/heads/feature/x\n")),
739 pkt(&format!("{old} {ZERO_ID} refs/heads/gone\n")),
740 pkt(&format!("{ZERO_ID} {new} refs/tags/v1\n")),
741 b"0000".to_vec(),
742 b"PACK\0\0\0\x02\0\0\0\0".to_vec(),
743 ]
744 .concat();
745 assert_eq!(
746 pushed_branches(&body),
747 [
748 Pushed {
749 git_ref: "refs/heads/main".to_owned(),
750 before: Some(old.to_owned()),
751 after: new.to_owned()
752 },
753 Pushed {
754 git_ref: "refs/heads/feature/x".to_owned(),
755 before: None,
756 after: new.to_owned()
757 },
758 Pushed {
759 git_ref: "refs/tags/v1".to_owned(),
760 before: None,
761 after: new.to_owned()
762 },
763 ]
764 );
765 }
766
767 #[test]
768 fn a_push_to_a_protected_branch_is_declined_with_the_reason() {
769 let old = "c71546fcd893ef8b0f57388b65e620d759705dda";
770 let new = "4807077b296e6edbf410d55e72749d3e1170c291";
771 let body = [
772 pkt(&format!("{old} {new} refs/heads/main\0 report-status\n")),
773 pkt(&format!("{ZERO_ID} {new} refs/heads/feature\n")),
774 b"0000".to_vec(),
775 ]
776 .concat();
777 let report = String::from_utf8(refusal(&body, "main").unwrap()).unwrap();
778 assert!(report.starts_with("000eunpack ok\n"));
779 assert!(report.contains("ng refs/heads/main main is protected"));
780 assert!(report.contains("ng refs/heads/feature not pushed"));
781 assert!(report.ends_with("0000"));
782 }
783
784 #[test]
785 fn the_report_is_framed_for_a_client_that_asked_for_side_band() {
786 let old = "c71546fcd893ef8b0f57388b65e620d759705dda";
787 let body = [
788 pkt(&format!(
789 "{old} {ZERO_ID} refs/heads/main\0 report-status side-band-64k\n"
790 )),
791 b"0000".to_vec(),
792 ]
793 .concat();
794 let report = refusal(&body, "main").unwrap();
795 // A length, then channel 1, then the report itself.
796 assert_eq!(report[4], 1);
797 assert_eq!(&report[5..18], b"000eunpack ok");
798 assert!(report.ends_with(b"00000000"));
799 }
800
801 #[test]
802 fn other_branches_and_a_first_push_are_let_through() {
803 let old = "c71546fcd893ef8b0f57388b65e620d759705dda";
804 let new = "4807077b296e6edbf410d55e72749d3e1170c291";
805 let feature = [
806 pkt(&format!("{old} {new} refs/heads/feature\0 report-status\n")),
807 b"0000".to_vec(),
808 ]
809 .concat();
810 assert!(refusal(&feature, "main").is_none());
811 // An empty repository has to be able to receive its first commits.
812 let first = [
813 pkt(&format!(
814 "{ZERO_ID} {new} refs/heads/main\0 report-status\n"
815 )),
816 b"0000".to_vec(),
817 ]
818 .concat();
819 assert!(refusal(&first, "main").is_none());
820 }
821
822 #[test]
823 fn a_blocked_push_explains_itself_on_the_progress_channel() {
824 let report = b"000eunpack ok\n0000".to_vec();
825 let messages = vec!["g1t found a secret in this push, so nothing was pushed.".to_owned()];
826 let body = framed(report.clone(), "report-status side-band-64k", &messages);
827 // Channel 2 first, which git prints as `remote:` lines.
828 assert_eq!(body[4], 2);
829 assert!(String::from_utf8_lossy(&body).contains("so nothing was pushed.\n"));
830 let at = body.windows(5).position(|w| w == b"000eu").unwrap();
831 assert_eq!(body[at - 1], 1);
832 assert!(body.ends_with(b"0000"));
833 // A client without side-band gets the bare report.
834 assert_eq!(framed(report.clone(), "report-status", &messages), report);
835 }
836
837 #[test]
838 fn a_fetch_request_names_no_branches() {
839 assert!(
840 pushed_branches(b"0032want c71546fcd893ef8b0f57388b65e620d759705dda\n0000").is_empty()
841 );
842 }
843}