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