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, Stores,
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 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
253 &protocol(cx),
254 )
255 .await;
256
257 let served = match served {
258 Ok(Some(served)) => served,
259
260 // Absent, or invisible to this caller — the two are the same answer by design.
261 // Anonymous callers are asked for credentials instead, so that a private
262 // repository and a missing one are indistinguishable from outside.
263 Ok(None) if anonymous => return challenge(),
264 Ok(None) => return Err(not_found().into()),
265
266 // Refused a write. Someone signed in is told so; someone anonymous is asked to
267 // identify themselves first, because they may well be allowed once they do.
268 Err(Error::Domain(DomainError::Forbidden)) if anonymous => return challenge(),
269 Err(Error::Domain(DomainError::Forbidden)) => return Err(forbidden().into()),
270
271 // Archived. Answered with a body rather than a bare status because git prints
272 // a `text/plain` error body back to the person who ran the push, prefixed with
273 // `remote:` — and "403" on its own sends them looking for a permissions problem
274 // that is not there. Only a caller who was otherwise allowed to push can reach
275 // this, so the sentence tells them nothing they did not already know.
276 Err(Error::Domain(DomainError::Archived)) => return archived(),
277 // Allowed, but not now — a repository still being imported. A status of its own
278 // rather than 403, because "you may not" and "not yet" send someone to look in
279 // completely different places. See `serve_git`.
280 //
281 // **git prints the body**, as a `remote:` line, before its own "returned error:
282 // 409" — verified against a real `git push`. That is why the reason is written
283 // as a sentence rather than a code: it is the whole of what the person pushing
284 // sees in their terminal.
285 Err(Error::Domain(DomainError::Unavailable { reason, .. })) => {
286 return unavailable(&reason);
287 }
288
289 Err(other) => return Err(server_error(other)),
290 };
291
292 let mut response = Response::builder().status(served.status);
293 for (name, value) in served.headers {
294 response = response.header(name, value);
295 }
296
297 // git sets its own content type and cache headers, and they are forwarded rather
298 // than reinvented: a cached advertisement makes a client fetch a stale ref list and
299 // then fail to find commits that do exist.
300 response
301 .body(GitBody::new(served.body))
302 .map_err(server_error)
303}
304
305/// The ref advertisement that opens every exchange.
306///
307/// The service names the operation, so `service=git-receive-pack` is a write, and is
308/// authorized as one before a client has been told a single ref exists.
309#[route(GET "/{handle}/repos/{repo}/info/refs")]
310async fn info_refs(cx: &Cx) -> Result<Response<GitBody>> {
311 let query =
312 parse_query_params::<ServiceQuery>(cx).map_err(|error| bad_request(error.to_string()))?;
313
314 // No service means the dumb protocol, which Steid does not serve. Refusing beats
315 // guessing: the dumb protocol reads object files straight off disk.
316 let service = query.service.ok_or_else(not_found)?;
317 let service: GitService = service.parse().map_err(|_| not_found())?;
318
319 let actor = match git_actor(cx).await? {
320 Ok(actor) => actor,
321 Err(throttled) => return Ok(throttled),
322 };
323
324 serve(
325 cx,
326 &handle_param(cx)?,
327 &repo_param(cx)?,
328 &actor,
329 None,
330 GitEndpoint::Advertisement(service),
331 Box::pin(tokio::io::empty()),
332 )
333 .await
334}
335
336#[route(POST "/{handle}/repos/{repo}/git-upload-pack")]
337async fn upload_pack(cx: &Cx, body: Body) -> Result<Response<GitBody>> {
338 let actor = match git_actor(cx).await? {
339 Ok(actor) => actor,
340 Err(throttled) => return Ok(throttled),
341 };
342
343 serve(
344 cx,
345 &handle_param(cx)?,
346 &repo_param(cx)?,
347 &actor,
348 None,
349 GitEndpoint::Rpc(GitService::UploadPack),
350 into_reader(body),
351 )
352 .await
353}
354
355/// The push itself — and the one route that records what it did.
356///
357/// The refs are snapshotted here, before the RPC, and again when the response body
358/// reaches its end; the difference is the push. See [`PushWatch`] for why it hangs off
359/// the body rather than off this function.
360#[route(POST "/{handle}/repos/{repo}/git-receive-pack")]
361async fn receive_pack(cx: &Cx, body: Body) -> Result<Response<GitBody>> {
362 let handle = handle_param(cx)?;
363 let name = repo_param(cx)?;
364 let actor = match git_actor(cx).await? {
365 Ok(actor) => actor,
366 Err(throttled) => return Ok(throttled),
367 };
368 let pusher = pusher_handle(cx, &actor).await;
369
370 let watch = PushWatch::open(cx, &handle, &name, &actor, pusher.clone()).await;
371
372 let response = serve(
373 cx,
374 &handle,
375 &name,
376 &actor,
377 pusher.as_deref(),
378 GitEndpoint::Rpc(GitService::ReceivePack),
379 into_reader(body),
380 )
381 .await?;
382
383 let Some(watch) = watch else {
384 return Ok(response);
385 };
386
387 let (parts, body) = response.into_parts();
388
389 Ok(Response::from_parts(
390 parts,
391 body.on_end(move || watch.close()),
392 ))
393}
394
395/// The refs as they were before a push, plus everything needed to act on what changed.
396///
397/// **Why it hangs off the response body.** `serve_git` returns while receive-pack is
398/// still running — the response streams — so the use case has no moment at which the
399/// push is done. The body reaching EOF is that moment: git has written its report-status
400/// by then, which it does after updating the refs.
401///
402/// A client that disappears mid-transfer leaves the body undrained and no event is
403/// recorded. That is the honest answer for a push nobody can confirm landed, and the
404/// next successful push to the same ref records a change from wherever it actually got
405/// to.
406///
407/// Everything here is owned rather than borrowed from `cx`: the work runs in a task that
408/// outlives the request. The adapters are all handles onto a pool or a path, so cloning
409/// them costs nothing.
410struct PushWatch {
411 handle: OrgName,
412 name: RepoName,
413 actor: Actor,
414 before: Vec<(RefName, ObjectId)>,
415 context: DeliveryContext,
416 orgs: crate::infrastructure::repository::SqliteOrgRepo,
417 memberships: crate::infrastructure::repository::SqliteMembershipRepo,
418 repos: crate::infrastructure::repository::SqliteRepoRepo,
419 events: crate::infrastructure::repository::SqlitePushEventRepo,
420 webhooks: crate::infrastructure::repository::SqliteWebhookRepo,
421 deliveries: crate::infrastructure::repository::SqliteWebhookDeliveryRepo,
422 queries: crate::infrastructure::git_query::DiskGitQuery,
423 sender: crate::infrastructure::webhook::UreqWebhookSender,
424}
425
426impl PushWatch {
427 /// Captures the refs as they are now.
428 ///
429 /// `None` for anyone anonymous — a push by one is about to be refused — and for a
430 /// snapshot that could not be taken, because a failed read that was treated as "no
431 /// refs" would record every branch in the repository as newly created.
432 async fn open(
433 cx: &Cx,
434 handle: &OrgName,
435 name: &RepoName,
436 actor: &Actor,
437 pusher: Option<String>,
438 ) -> Option<Self> {
439 actor.user_id()?;
440
441 let queries = queries(cx);
442
443 let before = match snapshot_refs(handle, name, &queries).await {
444 Ok(before) => before,
445 Err(error) => {
446 eprintln!("steid: could not snapshot {handle}/{name} before a push: {error}");
447 return None;
448 }
449 };
450
451 Some(Self {
452 context: DeliveryContext {
453 handle: handle.clone(),
454 name: name.clone(),
455 // Derived from the request, so an instance never has to be told its own
456 // address — the same reasoning as the clone URL on the repository page.
457 repo_url: format!("{}/{handle}/repos/{name}", public_origin(cx)),
458 pusher,
459 },
460 handle: handle.clone(),
461 name: name.clone(),
462 actor: actor.clone(),
463 before,
464 orgs: orgs(cx),
465 memberships: memberships(cx),
466 repos: repos(cx),
467 events: push_events(cx),
468 webhooks: webhooks(cx),
469 deliveries: deliveries(cx),
470 queries,
471 sender: webhook_sender(cx),
472 })
473 }
474
475 /// Snapshots again, records what moved, and delivers it — in a spawned task.
476 ///
477 /// Spawned because this is called from the body's `poll_read`, which must not block,
478 /// and because the retries alone run for two and a half minutes. Nothing waits on it
479 /// and nothing can fail the push: a client that has read its last byte is already
480 /// gone.
481 fn close(self) {
482 tokio::spawn(async move {
483 let after = match snapshot_refs(&self.handle, &self.name, &self.queries).await {
484 Ok(after) => after,
485 Err(error) => {
486 eprintln!(
487 "steid: could not snapshot {}/{} after a push: {error}",
488 self.handle, self.name
489 );
490 return;
491 }
492 };
493
494 let events = match record_push(
495 &self.actor,
496 &self.handle,
497 &self.name,
498 &self.before,
499 &after,
500 std::time::SystemTime::now(),
501 &Stores::new(&self.orgs, &self.memberships, &self.repos),
502 &self.events,
503 )
504 .await
505 {
506 Ok(events) => events,
507 Err(error) => {
508 eprintln!(
509 "steid: a push to {}/{} could not be recorded: {error}",
510 self.handle, self.name
511 );
512 return;
513 }
514 };
515
516 if let Err(error) = deliver_push(
517 &events,
518 &self.context,
519 &self.queries,
520 &self.webhooks,
521 &self.deliveries,
522 &self.sender,
523 &SystemClock,
524 &RETRY_BACKOFF,
525 )
526 .await
527 {
528 eprintln!(
529 "steid: the webhooks for {}/{} could not be reached: {error}",
530 self.handle, self.name
531 );
532 }
533 });
534 }
535}
536
537/// Adapts the request body into the byte stream the port takes.
538///
539/// Unbuffered on purpose: a push is arbitrarily large, and `Body` is taken as itself
540/// rather than as `Bytes` precisely so nothing collects it.
541fn into_reader(body: Body) -> ByteStream {
542 Box::pin(StreamReader::new(
543 body.into_data_stream().map_err(io::Error::other),
544 ))
545}
546
547/// The response body, streaming out of git.
548///
549/// Hand-written rather than assembled from stream combinators because the port speaks
550/// `AsyncRead` and `http_body` wants frames; this is the whole of the translation.
551pub struct GitBody {
552 reader: ByteStream,
553}
554
555impl GitBody {
556 /// Also used by the archive route, which streams out of git in exactly the same
557 /// shape — one subprocess's stdout becoming a response body.
558 pub(super) fn new(reader: ByteStream) -> Self {
559 Self { reader }
560 }
561
562 /// Runs `at_end` once, when the body is fully read.
563 ///
564 /// The only signal available that a streamed git operation actually finished — see
565 /// [`PushWatch`]. Never runs if the body is dropped unread, which is what a client
566 /// disconnecting looks like.
567 fn on_end(self, at_end: impl FnOnce() + Send + 'static) -> Self {
568 Self {
569 reader: Box::pin(OnEnd {
570 inner: self.reader,
571 at_end: Some(Box::new(at_end)),
572 }),
573 }
574 }
575}
576
577/// A reader that calls something once it reaches EOF.
578struct OnEnd {
579 inner: ByteStream,
580 /// Taken on the first EOF, so a body polled again after finishing cannot run it
581 /// twice.
582 at_end: Option<Box<dyn FnOnce() + Send>>,
583}
584
585impl AsyncRead for OnEnd {
586 fn poll_read(
587 mut self: Pin<&mut Self>,
588 cx: &mut Context<'_>,
589 buf: &mut ReadBuf<'_>,
590 ) -> Poll<io::Result<()>> {
591 let before = buf.filled().len();
592 let polled = Pin::new(&mut self.inner).poll_read(cx, buf);
593
594 if matches!(polled, Poll::Ready(Ok(())))
595 && buf.filled().len() == before
596 && let Some(at_end) = self.at_end.take()
597 {
598 at_end();
599 }
600
601 polled
602 }
603}
604
605impl http_body::Body for GitBody {
606 type Data = Bytes;
607 type Error = io::Error;
608
609 fn poll_frame(
610 mut self: Pin<&mut Self>,
611 cx: &mut Context<'_>,
612 ) -> Poll<Option<std::result::Result<Frame<Bytes>, io::Error>>> {
613 let mut buffer = [0u8; CHUNK];
614 let mut read = ReadBuf::new(&mut buffer);
615
616 match Pin::new(&mut self.reader).poll_read(cx, &mut read) {
617 Poll::Pending => Poll::Pending,
618 Poll::Ready(Err(error)) => Poll::Ready(Some(Err(error))),
619 Poll::Ready(Ok(())) => {
620 let filled = read.filled();
621
622 // An empty read is EOF: the pack is complete and the body ends.
623 if filled.is_empty() {
624 Poll::Ready(None)
625 } else {
626 Poll::Ready(Some(Ok(Frame::data(Bytes::copy_from_slice(filled)))))
627 }
628 }
629 }
630 }
631}