steid

@jamesgill /

1//! The git smart-HTTP transport — `/{handle}/repos/{name}.git/…`.
2//!
3//! Three routes, one per endpoint of the protocol, each naming the service it serves as
4//! a literal. Nothing here parses an operation out of a path: the route *is* the
5//! operation, and [`serve_git`] rebuilds the path it hands to git from validated values.
6//! That matters because `git http-backend` will happily serve dumb-protocol object files
7//! under any path given to it — the router is the allowlist.
8
9use std::{
10 io,
11 pin::Pin,
12 task::{Context, Poll},
13 time::{Duration, SystemTime},
14};
15
16use base64::{Engine, engine::general_purpose::STANDARD};
17use bytes::Bytes;
18use futures_util::TryStreamExt;
19use http_body::Frame;
20use serde::Deserialize;
21use tokio::io::{AsyncRead, ReadBuf};
22use tokio_util::io::StreamReader;
23use topcoat::{
24 Result,
25 context::Cx,
26 router::{
27 Body, Response, StatusCode,
28 error::{bad_request, forbidden, not_found},
29 header::{AUTHORIZATION, RETRY_AFTER, WWW_AUTHENTICATE},
30 headers, parse_query_params, path_param, route,
31 },
32};
33
34use crate::{
35 application::{
36 DeliveryContext, Error, GitClientHeaders, GitEndpoint, GitService, RETRY_BACKOFF,
37 authenticate_token, deliver_push, describe_identity, port::ByteStream, record_push,
38 serve_git, snapshot_refs,
39 },
40 domain::{Actor, DomainError, ObjectId, OrgName, RefName, RepoName},
41 infrastructure::clock::SystemClock,
42};
43
44use super::{
45 context::{
46 current_actor, deliveries, memberships, orgs, protocol, public_origin, push_events,
47 queries, repos, server_error, tokens, users, webhook_sender, webhooks,
48 },
49 profile::handle_param,
50 rate_limit::git_auth_throttled,
51};
52
53/// How much of the response is read from git in one go.
54///
55/// A clone streams as fast as the client takes it, so this bounds the memory a transfer
56/// holds rather than its speed.
57const CHUNK: usize = 16 * 1024;
58
59/// `{repo}` from the path — the repository name *with* its `.git` suffix.
60#[path_param]
61struct Repo(str);
62
63#[derive(Debug, Deserialize)]
64struct ServiceQuery {
65 service: Option<String>,
66}
67
68/// The repository named by `{repo}`, or 404.
69///
70/// The `.git` suffix is required rather than optional: it is what separates the protocol
71/// from the page at `/{handle}/repos/{name}`, and `RepoName` rejects a name ending in
72/// `.git` so the two can never collide.
73fn repo_param(cx: &Cx) -> Result<RepoName> {
74 let raw = path_param::<Repo>(cx);
75 let name = raw.strip_suffix(".git").ok_or_else(not_found)?;
76
77 Ok(RepoName::new(name).map_err(|_| not_found())?)
78}
79
80/// The four request headers that change what git does.
81fn client_headers(cx: &Cx) -> GitClientHeaders {
82 let headers = headers(cx);
83 let value = |name: &str| {
84 headers
85 .get(name)
86 .and_then(|value| value.to_str().ok())
87 .map(str::to_owned)
88 };
89
90 GitClientHeaders {
91 content_type: value("content-type"),
92 content_encoding: value("content-encoding"),
93 content_length: value("content-length"),
94 git_protocol: value("git-protocol"),
95 }
96}
97
98/// Who is making this git request, or the 429 to answer with instead.
99///
100/// A personal access token over HTTP Basic first, then the session cookie. Both are
101/// supported because both happen: git presents a token, and a signed-in person clicking
102/// a `.git` URL in a browser presents a cookie.
103///
104/// A credential that does not authenticate falls through to anonymous rather than
105/// failing, matching how a bad session cookie is treated. The caller then gets the same
106/// 401 challenge as someone who presented nothing, and can try again.
107///
108/// **Rate limited, but only when a credential is actually presented.** This is an open
109/// endpoint that makes the server hash and look up whatever arrives, and it is reachable
110/// without any repository existing. Anonymous reads of a public repository are not
111/// counted — they do no authentication work, and throttling them would be a cap on
112/// cloning rather than on guessing.
113async fn git_actor(cx: &Cx) -> Result<std::result::Result<Actor, Response<GitBody>>> {
114 if let Some(presented) = basic_credential(cx) {
115 if let Some(retry_after) = git_auth_throttled(cx) {
116 return Ok(Err(too_many_requests(retry_after)?));
117 }
118
119 let actor = authenticate_token(&presented, SystemTime::now(), &tokens(cx))
120 .await
121 .map_err(server_error)?;
122
123 if actor.user_id().is_some() {
124 return Ok(Ok(actor));
125 }
126 }
127
128 current_actor(cx).await.map(Ok)
129}
130
131/// Refuses a request that has spent its authentication budget, in words git will show.
132///
133/// `text/plain`, for the same reason [`archived`] is: git prints the body back to the
134/// terminal behind `remote:`, and "429" on its own sends someone looking for a
135/// credential problem that is not there. It says nothing about which limit was hit.
136pub(super) fn too_many_requests(retry_after: Duration) -> Result<Response<GitBody>> {
137 let seconds = retry_after.as_secs().max(1);
138 let message = format!("Too many authentication attempts. Try again in {seconds} seconds.\n");
139
140 Response::builder()
141 .status(StatusCode::TOO_MANY_REQUESTS)
142 .header(topcoat::router::header::CONTENT_TYPE, "text/plain")
143 .header(RETRY_AFTER, seconds)
144 .body(GitBody::new(Box::pin(std::io::Cursor::new(
145 message.into_bytes(),
146 ))))
147 .map_err(server_error)
148}
149
150/// The secret from an `Authorization: Basic` header.
151///
152/// Git puts the token in the password field, so that is preferred; a token pasted into
153/// the username field with no password is accepted too, because people do that and the
154/// alternative is an authentication failure nothing explains.
155fn basic_credential(cx: &Cx) -> Option<String> {
156 let header = headers(cx).get(AUTHORIZATION)?.to_str().ok()?;
157 let encoded = header.strip_prefix("Basic ")?;
158 let decoded = STANDARD.decode(encoded).ok()?;
159 let decoded = String::from_utf8(decoded).ok()?;
160
161 let (user, password) = decoded.split_once(':')?;
162
163 if password.is_empty() {
164 Some(user.to_owned())
165 } else {
166 Some(password.to_owned())
167 }
168}
169
170/// Asks for credentials.
171///
172/// Sent for anything an anonymous caller may not have — including repositories that do
173/// not exist — so that nothing in the response distinguishes "private" from "absent".
174/// A git client only offers a credential after seeing this, so answering 404 instead
175/// would make an authenticated private clone impossible. See
176/// [0007](../../plans/decisions/0007-tokens-over-http-basic.md).
177fn challenge() -> Result<Response<GitBody>> {
178 Response::builder()
179 .status(StatusCode::UNAUTHORIZED)
180 .header(WWW_AUTHENTICATE, r#"Basic realm="steid""#)
181 .body(GitBody::new(Box::pin(tokio::io::empty())))
182 .map_err(server_error)
183}
184
185/// Refuses a push to an archived repository, in words git will show.
186///
187/// `git push` prints a `text/plain` response body line by line behind `remote:`, so
188/// this arrives at the terminal as the sentence rather than as a status code.
189fn archived() -> Result<Response<GitBody>> {
190 const MESSAGE: &[u8] =
191 b"This repository is archived and is read-only. Unarchive it in Settings to push.\n";
192
193 Response::builder()
194 .status(StatusCode::FORBIDDEN)
195 .header(topcoat::router::header::CONTENT_TYPE, "text/plain")
196 .body(GitBody::new(Box::pin(std::io::Cursor::new(MESSAGE))))
197 .map_err(server_error)
198}
199
200/// Refuses a request the repository's state does not allow right now.
201///
202/// 409 rather than 403: the answer changes on its own, and nothing about the caller is
203/// wrong. The reason is in the body for anyone reading with `curl`.
204fn unavailable(reason: &str) -> Result<Response<GitBody>> {
205 Response::builder()
206 .status(StatusCode::CONFLICT)
207 .header("content-type", "text/plain; charset=utf-8")
208 .body(GitBody::new(Box::pin(std::io::Cursor::new(
209 format!("This repository is unavailable: {reason}\n").into_bytes(),
210 ))))
211 .map_err(server_error)
212}
213
214/// Who is pushing, by handle, for `REMOTE_USER` and for a webhook payload.
215///
216/// `None` for anyone anonymous, and for an actor whose user record has gone — the same
217/// answer [`describe_identity`] gives elsewhere. Two queries, made only on the write
218/// path, and their result is used twice.
219async fn pusher_handle(cx: &Cx, actor: &Actor) -> Option<String> {
220 describe_identity(actor, &users(cx), &orgs(cx))
221 .await
222 .ok()
223 .flatten()
224 .map(|identity| identity.handle.to_string())
225}
226
227/// Runs one protocol request and turns the result into an HTTP response.
228///
229/// Takes the resolved handle, name and actor rather than reading them from `cx`, because
230/// the push route needs the same three values *before* the request runs — to snapshot
231/// the refs — and resolving the actor twice would be a token lookup per push.
232async fn serve(
233 cx: &Cx,
234 handle: &OrgName,
235 name: &RepoName,
236 actor: &Actor,
237 pusher: Option<&str>,
238 endpoint: GitEndpoint,
239 body: ByteStream,
240) -> Result<Response<GitBody>> {
241 let anonymous = actor.user_id().is_none();
242
243 let served = serve_git(
244 handle,
245 name,
246 endpoint,
247 client_headers(cx),
248 body,
249 actor,
250 pusher,
251 SystemTime::now(),
252 &orgs(cx),
253 &memberships(cx),
254 &repos(cx),
255 &protocol(cx),
256 )
257 .await;
258
259 let served = match served {
260 Ok(Some(served)) => served,
261
262 // Absent, or invisible to this caller — the two are the same answer by design.
263 // Anonymous callers are asked for credentials instead, so that a private
264 // repository and a missing one are indistinguishable from outside.
265 Ok(None) if anonymous => return challenge(),
266 Ok(None) => return Err(not_found().into()),
267
268 // Refused a write. Someone signed in is told so; someone anonymous is asked to
269 // identify themselves first, because they may well be allowed once they do.
270 Err(Error::Domain(DomainError::Forbidden)) if anonymous => return challenge(),
271 Err(Error::Domain(DomainError::Forbidden)) => return Err(forbidden().into()),
272
273 // Archived. Answered with a body rather than a bare status because git prints
274 // a `text/plain` error body back to the person who ran the push, prefixed with
275 // `remote:` — and "403" on its own sends them looking for a permissions problem
276 // that is not there. Only a caller who was otherwise allowed to push can reach
277 // this, so the sentence tells them nothing they did not already know.
278 Err(Error::Domain(DomainError::Archived)) => return archived(),
279 // Allowed, but not now — a repository still being imported. A status of its own
280 // rather than 403, because "you may not" and "not yet" send someone to look in
281 // completely different places. See `serve_git`.
282 //
283 // **git prints the body**, as a `remote:` line, before its own "returned error:
284 // 409" — verified against a real `git push`. That is why the reason is written
285 // as a sentence rather than a code: it is the whole of what the person pushing
286 // sees in their terminal.
287 Err(Error::Domain(DomainError::Unavailable { reason, .. })) => {
288 return unavailable(&reason);
289 }
290
291 Err(other) => return Err(server_error(other)),
292 };
293
294 let mut response = Response::builder().status(served.status);
295 for (name, value) in served.headers {
296 response = response.header(name, value);
297 }
298
299 // git sets its own content type and cache headers, and they are forwarded rather
300 // than reinvented: a cached advertisement makes a client fetch a stale ref list and
301 // then fail to find commits that do exist.
302 response
303 .body(GitBody::new(served.body))
304 .map_err(server_error)
305}
306
307/// The ref advertisement that opens every exchange.
308///
309/// The service names the operation, so `service=git-receive-pack` is a write, and is
310/// authorized as one before a client has been told a single ref exists.
311#[route(GET "/{handle}/repos/{repo}/info/refs")]
312async fn info_refs(cx: &Cx) -> Result<Response<GitBody>> {
313 let query =
314 parse_query_params::<ServiceQuery>(cx).map_err(|error| bad_request(error.to_string()))?;
315
316 // No service means the dumb protocol, which Steid does not serve. Refusing beats
317 // guessing: the dumb protocol reads object files straight off disk.
318 let service = query.service.ok_or_else(not_found)?;
319 let service: GitService = service.parse().map_err(|_| not_found())?;
320
321 let actor = match git_actor(cx).await? {
322 Ok(actor) => actor,
323 Err(throttled) => return Ok(throttled),
324 };
325
326 serve(
327 cx,
328 &handle_param(cx)?,
329 &repo_param(cx)?,
330 &actor,
331 None,
332 GitEndpoint::Advertisement(service),
333 Box::pin(tokio::io::empty()),
334 )
335 .await
336}
337
338#[route(POST "/{handle}/repos/{repo}/git-upload-pack")]
339async fn upload_pack(cx: &Cx, body: Body) -> Result<Response<GitBody>> {
340 let actor = match git_actor(cx).await? {
341 Ok(actor) => actor,
342 Err(throttled) => return Ok(throttled),
343 };
344
345 serve(
346 cx,
347 &handle_param(cx)?,
348 &repo_param(cx)?,
349 &actor,
350 None,
351 GitEndpoint::Rpc(GitService::UploadPack),
352 into_reader(body),
353 )
354 .await
355}
356
357/// The push itself — and the one route that records what it did.
358///
359/// The refs are snapshotted here, before the RPC, and again when the response body
360/// reaches its end; the difference is the push. See [`PushWatch`] for why it hangs off
361/// the body rather than off this function.
362#[route(POST "/{handle}/repos/{repo}/git-receive-pack")]
363async fn receive_pack(cx: &Cx, body: Body) -> Result<Response<GitBody>> {
364 let handle = handle_param(cx)?;
365 let name = repo_param(cx)?;
366 let actor = match git_actor(cx).await? {
367 Ok(actor) => actor,
368 Err(throttled) => return Ok(throttled),
369 };
370 let pusher = pusher_handle(cx, &actor).await;
371
372 let watch = PushWatch::open(cx, &handle, &name, &actor, pusher.clone()).await;
373
374 let response = serve(
375 cx,
376 &handle,
377 &name,
378 &actor,
379 pusher.as_deref(),
380 GitEndpoint::Rpc(GitService::ReceivePack),
381 into_reader(body),
382 )
383 .await?;
384
385 let Some(watch) = watch else {
386 return Ok(response);
387 };
388
389 let (parts, body) = response.into_parts();
390
391 Ok(Response::from_parts(
392 parts,
393 body.on_end(move || watch.close()),
394 ))
395}
396
397/// The refs as they were before a push, plus everything needed to act on what changed.
398///
399/// **Why it hangs off the response body.** `serve_git` returns while receive-pack is
400/// still running — the response streams — so the use case has no moment at which the
401/// push is done. The body reaching EOF is that moment: git has written its report-status
402/// by then, which it does after updating the refs.
403///
404/// A client that disappears mid-transfer leaves the body undrained and no event is
405/// recorded. That is the honest answer for a push nobody can confirm landed, and the
406/// next successful push to the same ref records a change from wherever it actually got
407/// to.
408///
409/// Everything here is owned rather than borrowed from `cx`: the work runs in a task that
410/// outlives the request. The adapters are all handles onto a pool or a path, so cloning
411/// them costs nothing.
412struct PushWatch {
413 handle: OrgName,
414 name: RepoName,
415 actor: Actor,
416 before: Vec<(RefName, ObjectId)>,
417 context: DeliveryContext,
418 orgs: crate::infrastructure::repository::SqliteOrgRepo,
419 memberships: crate::infrastructure::repository::SqliteMembershipRepo,
420 repos: crate::infrastructure::repository::SqliteRepoRepo,
421 events: crate::infrastructure::repository::SqlitePushEventRepo,
422 webhooks: crate::infrastructure::repository::SqliteWebhookRepo,
423 deliveries: crate::infrastructure::repository::SqliteWebhookDeliveryRepo,
424 queries: crate::infrastructure::git_query::DiskGitQuery,
425 sender: crate::infrastructure::webhook::UreqWebhookSender,
426}
427
428impl PushWatch {
429 /// Captures the refs as they are now.
430 ///
431 /// `None` for anyone anonymous — a push by one is about to be refused — and for a
432 /// snapshot that could not be taken, because a failed read that was treated as "no
433 /// refs" would record every branch in the repository as newly created.
434 async fn open(
435 cx: &Cx,
436 handle: &OrgName,
437 name: &RepoName,
438 actor: &Actor,
439 pusher: Option<String>,
440 ) -> Option<Self> {
441 actor.user_id()?;
442
443 let queries = queries(cx);
444
445 let before = match snapshot_refs(handle, name, &queries).await {
446 Ok(before) => before,
447 Err(error) => {
448 eprintln!("steid: could not snapshot {handle}/{name} before a push: {error}");
449 return None;
450 }
451 };
452
453 Some(Self {
454 context: DeliveryContext {
455 handle: handle.clone(),
456 name: name.clone(),
457 // Derived from the request, so an instance never has to be told its own
458 // address — the same reasoning as the clone URL on the repository page.
459 repo_url: format!("{}/{handle}/repos/{name}", public_origin(cx)),
460 pusher,
461 },
462 handle: handle.clone(),
463 name: name.clone(),
464 actor: actor.clone(),
465 before,
466 orgs: orgs(cx),
467 memberships: memberships(cx),
468 repos: repos(cx),
469 events: push_events(cx),
470 webhooks: webhooks(cx),
471 deliveries: deliveries(cx),
472 queries,
473 sender: webhook_sender(cx),
474 })
475 }
476
477 /// Snapshots again, records what moved, and delivers it — in a spawned task.
478 ///
479 /// Spawned because this is called from the body's `poll_read`, which must not block,
480 /// and because the retries alone run for two and a half minutes. Nothing waits on it
481 /// and nothing can fail the push: a client that has read its last byte is already
482 /// gone.
483 fn close(self) {
484 tokio::spawn(async move {
485 let after = match snapshot_refs(&self.handle, &self.name, &self.queries).await {
486 Ok(after) => after,
487 Err(error) => {
488 eprintln!(
489 "steid: could not snapshot {}/{} after a push: {error}",
490 self.handle, self.name
491 );
492 return;
493 }
494 };
495
496 let events = match record_push(
497 &self.actor,
498 &self.handle,
499 &self.name,
500 &self.before,
501 &after,
502 std::time::SystemTime::now(),
503 &self.orgs,
504 &self.memberships,
505 &self.repos,
506 &self.events,
507 )
508 .await
509 {
510 Ok(events) => events,
511 Err(error) => {
512 eprintln!(
513 "steid: a push to {}/{} could not be recorded: {error}",
514 self.handle, self.name
515 );
516 return;
517 }
518 };
519
520 if let Err(error) = deliver_push(
521 &events,
522 &self.context,
523 &self.queries,
524 &self.webhooks,
525 &self.deliveries,
526 &self.sender,
527 &SystemClock,
528 &RETRY_BACKOFF,
529 )
530 .await
531 {
532 eprintln!(
533 "steid: the webhooks for {}/{} could not be reached: {error}",
534 self.handle, self.name
535 );
536 }
537 });
538 }
539}
540
541/// Adapts the request body into the byte stream the port takes.
542///
543/// Unbuffered on purpose: a push is arbitrarily large, and `Body` is taken as itself
544/// rather than as `Bytes` precisely so nothing collects it.
545fn into_reader(body: Body) -> ByteStream {
546 Box::pin(StreamReader::new(
547 body.into_data_stream().map_err(io::Error::other),
548 ))
549}
550
551/// The response body, streaming out of git.
552///
553/// Hand-written rather than assembled from stream combinators because the port speaks
554/// `AsyncRead` and `http_body` wants frames; this is the whole of the translation.
555pub struct GitBody {
556 reader: ByteStream,
557}
558
559impl GitBody {
560 /// Also used by the archive route, which streams out of git in exactly the same
561 /// shape — one subprocess's stdout becoming a response body.
562 pub(super) fn new(reader: ByteStream) -> Self {
563 Self { reader }
564 }
565
566 /// Runs `at_end` once, when the body is fully read.
567 ///
568 /// The only signal available that a streamed git operation actually finished — see
569 /// [`PushWatch`]. Never runs if the body is dropped unread, which is what a client
570 /// disconnecting looks like.
571 fn on_end(self, at_end: impl FnOnce() + Send + 'static) -> Self {
572 Self {
573 reader: Box::pin(OnEnd {
574 inner: self.reader,
575 at_end: Some(Box::new(at_end)),
576 }),
577 }
578 }
579}
580
581/// A reader that calls something once it reaches EOF.
582struct OnEnd {
583 inner: ByteStream,
584 /// Taken on the first EOF, so a body polled again after finishing cannot run it
585 /// twice.
586 at_end: Option<Box<dyn FnOnce() + Send>>,
587}
588
589impl AsyncRead for OnEnd {
590 fn poll_read(
591 mut self: Pin<&mut Self>,
592 cx: &mut Context<'_>,
593 buf: &mut ReadBuf<'_>,
594 ) -> Poll<io::Result<()>> {
595 let before = buf.filled().len();
596 let polled = Pin::new(&mut self.inner).poll_read(cx, buf);
597
598 if matches!(polled, Poll::Ready(Ok(())))
599 && buf.filled().len() == before
600 && let Some(at_end) = self.at_end.take()
601 {
602 at_end();
603 }
604
605 polled
606 }
607}
608
609impl http_body::Body for GitBody {
610 type Data = Bytes;
611 type Error = io::Error;
612
613 fn poll_frame(
614 mut self: Pin<&mut Self>,
615 cx: &mut Context<'_>,
616 ) -> Poll<Option<std::result::Result<Frame<Bytes>, io::Error>>> {
617 let mut buffer = [0u8; CHUNK];
618 let mut read = ReadBuf::new(&mut buffer);
619
620 match Pin::new(&mut self.reader).poll_read(cx, &mut read) {
621 Poll::Pending => Poll::Pending,
622 Poll::Ready(Err(error)) => Poll::Ready(Some(Err(error))),
623 Poll::Ready(Ok(())) => {
624 let filled = read.filled();
625
626 // An empty read is EOF: the pack is complete and the body ends.
627 if filled.is_empty() {
628 Poll::Ready(None)
629 } else {
630 Poll::Ready(Some(Ok(Frame::data(Bytes::copy_from_slice(filled)))))
631 }
632 }
633 }
634 }
635}