forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

git_http.rs617 lines, 21.8 KiBHistoryRawDownload
1//! Smart-HTTP routes: info/refs, git-upload-pack and git-receive-pack.
2//! Streams bodies to and from `git <svc> --stateless-rpc`; gzip request bodies are decoded.
3//!
4//! Compression must be off for these responses. Topcoat's compression is configured only on the
5//! router builder (`Router::builder().with(Compression::disable())`), so boot.rs has to set it.
6
7use std::net::IpAddr;
8use std::time::Instant;
9
10use async_compression::tokio::bufread::GzipDecoder;
11use forge_core::User;
12use forge_git::{GitService, pktline};
13use futures_util::TryStreamExt;
14use http::header::{
15 AUTHORIZATION, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_TYPE, HeaderValue, RETRY_AFTER,
16 WWW_AUTHENTICATE,
17};
18use http_body::Frame;
19use http_body_util::StreamBody;
20use tokio::io::AsyncReadExt;
21use tokio::process::{Child, ChildStdin};
22use tokio_util::io::{ReaderStream, StreamReader};
23use topcoat::context::{Cx, context};
24use topcoat::router::request::headers;
25use topcoat::router::response::Response;
26use topcoat::router::{Body, HeaderMap, StatusCode, path_param, query_params, route};
27
28use crate::access::{AccessError, Transport, find_repo, git_process, resolve_repo};
29use crate::client_ip::client_ip;
30use crate::git_auth::{parse_basic_auth, user_from_basic};
31use crate::state::AppState;
32use crate::throttle::{self, GIT_IP_LIMIT};
33
34path_param!(owner);
35path_param!(repo);
36
37#[query_params(error = bad_request)]
38struct InfoRefsQuery {
39 service: Option<String>,
40}
41
42#[route(GET "/{owner}/{repo}/info/refs")]
43async fn info_refs(cx: &Cx) -> topcoat::Result<Response> {
44 let query = query_params::<InfoRefsQuery>(cx)?;
45 let Some(service) = query.service.as_deref().and_then(GitService::from_name) else {
46 return Ok(text(StatusCode::FORBIDDEN, "dumb protocol not supported"));
47 };
48
49 let state = context::<AppState>(cx);
50 let headers = headers(cx);
51 let owner = owner(cx);
52 let repo_name = repo(cx);
53
54 let (actor, repo, path) =
55 match caller_repo(state, client_ip(cx), headers, owner, repo_name, service).await {
56 Ok(found) => found,
57 Err(response) => return Ok(*response),
58 };
59
60 let protocol = git_protocol(headers);
61 let advertisement = git_process(
62 state,
63 &repo,
64 &path,
65 actor.as_ref(),
66 service,
67 Transport::Http,
68 true,
69 protocol,
70 )
71 .output()
72 .await;
73 let mut payload = match advertisement {
74 Ok(refs) => refs,
75 Err(e) => {
76 tracing::error!(error = %e, service = service.name(), "info/refs failed");
77 return Ok(internal_error());
78 }
79 };
80 // Splicing in front reuses the advertisement's buffer instead of copying it into a new one.
81 if needs_service_header(service, wants_v2(protocol)) {
82 payload.splice(..0, pktline::service_advertisement_header(service));
83 }
84
85 Ok(respond(
86 StatusCode::OK,
87 advertisement_content_type(service),
88 Body::from(payload),
89 ))
90}
91
92#[route(POST "/{owner}/{repo}/git-upload-pack")]
93async fn upload_pack(cx: &Cx, body: Body) -> topcoat::Result<Response> {
94 Ok(serve_rpc(cx, GitService::UploadPack, body).await)
95}
96
97#[route(POST "/{owner}/{repo}/git-receive-pack")]
98async fn receive_pack(cx: &Cx, body: Body) -> topcoat::Result<Response> {
99 Ok(serve_rpc(cx, GitService::ReceivePack, body).await)
100}
101
102/// Shared body of the two POST routes: authorize, spawn `git <svc> --stateless-rpc`, pipe the
103/// request body into its stdin and stream its stdout back.
104async fn serve_rpc(cx: &Cx, service: GitService, body: Body) -> Response {
105 let state = context::<AppState>(cx);
106 let headers = headers(cx);
107 let owner = owner(cx);
108 let repo_name = repo(cx);
109
110 let (actor, repo, path) =
111 match caller_repo(state, client_ip(cx), headers, owner, repo_name, service).await {
112 Ok(found) => found,
113 Err(response) => return *response,
114 };
115
116 let gzip = match body_encoding(
117 headers
118 .get(CONTENT_ENCODING)
119 .map(|v| v.to_str().unwrap_or("")),
120 ) {
121 Some(gzip) => gzip,
122 None => {
123 return text(
124 StatusCode::UNSUPPORTED_MEDIA_TYPE,
125 "unsupported content encoding",
126 );
127 }
128 };
129
130 let mut command = git_process(
131 state,
132 &repo,
133 &path,
134 actor.as_ref(),
135 service,
136 Transport::Http,
137 false,
138 git_protocol(headers),
139 )
140 .into_tokio();
141 command
142 .stdin(std::process::Stdio::piped())
143 .stdout(std::process::Stdio::piped())
144 .stderr(std::process::Stdio::piped());
145
146 let mut child = match command.spawn() {
147 Ok(child) => child,
148 Err(e) => {
149 tracing::error!(error = %e, service = service.name(), "failed to spawn git");
150 return internal_error();
151 }
152 };
153 let (Some(stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
154 tracing::error!(service = service.name(), "git child is missing piped stdio");
155 return internal_error();
156 };
157
158 tokio::spawn(pump_request(body, gzip, stdin));
159 tokio::spawn(reap(child, service));
160
161 let chunks = ReaderStream::new(stdout).map_ok(Frame::data);
162 respond(
163 StatusCode::OK,
164 result_content_type(service),
165 Body::new(StreamBody::new(chunks)),
166 )
167}
168
169/// Copies the request body (decoding gzip when `gzip` is set) into git's stdin, then closes it.
170async fn pump_request(body: Body, gzip: bool, mut stdin: ChildStdin) {
171 let reader = StreamReader::new(body.into_data_stream().map_err(std::io::Error::other));
172 let copied = if gzip {
173 tokio::io::copy(&mut GzipDecoder::new(reader), &mut stdin).await
174 } else {
175 let mut reader = reader;
176 tokio::io::copy(&mut reader, &mut stdin).await
177 };
178 if let Err(e) = copied {
179 tracing::debug!(error = %e, "request body ended before git consumed it");
180 }
181 // Closing stdin tells git the request is complete.
182 let _ = tokio::io::AsyncWriteExt::shutdown(&mut stdin).await;
183}
184
185/// Drains stderr into the log and waits for the child, so no zombie is left behind.
186async fn reap(mut child: Child, service: GitService) {
187 let mut stderr_buf = Vec::new();
188 if let Some(mut stderr) = child.stderr.take() {
189 // Only the first 64 KiB is logged. The rest is drained so git never blocks on a full pipe.
190 let _ = (&mut stderr)
191 .take(64 * 1024)
192 .read_to_end(&mut stderr_buf)
193 .await;
194 let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await;
195 }
196 let stderr_text = String::from_utf8_lossy(&stderr_buf);
197 match child.wait().await {
198 Ok(status) if status.success() => {
199 tracing::debug!(service = service.name(), "git finished");
200 }
201 Ok(status) => {
202 tracing::warn!(
203 service = service.name(),
204 %status,
205 stderr = %stderr_text.trim(),
206 "git exited with failure"
207 );
208 }
209 Err(e) => {
210 tracing::warn!(service = service.name(), error = %e, "failed to wait for git");
211 }
212 }
213}
214
215/// Extracts a `Git-Protocol` header value only if it matches `^[a-z0-9=:,._-]{1,64}$`.
216fn git_protocol(headers: &HeaderMap) -> Option<&str> {
217 let value = headers.get("git-protocol")?.to_str().ok()?;
218 valid_git_protocol(value).then_some(value)
219}
220
221fn valid_git_protocol(value: &str) -> bool {
222 (1..=64).contains(&value.len())
223 && value.bytes().all(|b| {
224 b.is_ascii_lowercase()
225 || b.is_ascii_digit()
226 || matches!(b, b'=' | b':' | b',' | b'.' | b'_' | b'-')
227 })
228}
229
230/// True when the protocol string asks for version 2.
231fn wants_v2(protocol: Option<&str>) -> bool {
232 protocol.is_some_and(|p| p.split(':').any(|kv| kv == "version=2"))
233}
234
235/// The `# service=` preamble is required for v0 advertisements. With v2 the upload-pack server
236/// writes its own version line instead. Receive-pack has no v2, so it always gets the preamble.
237fn needs_service_header(service: GitService, v2: bool) -> bool {
238 !(service == GitService::UploadPack && v2)
239}
240
241/// Decodes the request body encoding. `Some(true)` for gzip, `Some(false)` for none or identity,
242/// `None` for anything else.
243fn body_encoding(value: Option<&str>) -> Option<bool> {
244 match value.map(|v| v.trim().to_ascii_lowercase()) {
245 None => Some(false),
246 Some(v) if v == "gzip" => Some(true),
247 Some(v) if v == "identity" => Some(false),
248 Some(_) => None,
249 }
250}
251
252fn advertisement_content_type(service: GitService) -> &'static str {
253 match service {
254 GitService::UploadPack => "application/x-git-upload-pack-advertisement",
255 GitService::ReceivePack => "application/x-git-receive-pack-advertisement",
256 }
257}
258
259fn result_content_type(service: GitService) -> &'static str {
260 match service {
261 GitService::UploadPack => "application/x-git-upload-pack-result",
262 GitService::ReceivePack => "application/x-git-receive-pack-result",
263 }
264}
265
266fn respond(status: StatusCode, content_type: &'static str, body: Body) -> Response {
267 let mut res = Response::new(body);
268 *res.status_mut() = status;
269 res.headers_mut()
270 .insert(CONTENT_TYPE, HeaderValue::from_static(content_type));
271 res.headers_mut()
272 .insert(CACHE_CONTROL, HeaderValue::from_static("no-cache"));
273 res
274}
275
276fn text(status: StatusCode, message: &'static str) -> Response {
277 let mut res = Response::new(Body::from(message));
278 *res.status_mut() = status;
279 res.headers_mut().insert(
280 CONTENT_TYPE,
281 HeaderValue::from_static("text/plain; charset=utf-8"),
282 );
283 res
284}
285
286fn internal_error() -> Response {
287 text(StatusCode::INTERNAL_SERVER_ERROR, "internal server error")
288}
289
290/// Authenticates the request's credentials under the per-IP git failure limit. Only rejected
291/// credentials count, so anonymous requests and successful logins never do. Returns the response
292/// to send when the request must stop: 429 while the IP is throttled, or the access error.
293pub async fn authenticate(
294 state: &AppState,
295 ip: IpAddr,
296 headers: &HeaderMap,
297) -> Result<Option<User>, Box<Response>> {
298 let key = throttle::ip_key("git-ip", ip);
299 let now = Instant::now();
300 if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) {
301 tracing::warn!(
302 ip = %ip,
303 retry_after_secs = retry.as_secs(),
304 "git authentication throttled"
305 );
306 let mut res = text(
307 StatusCode::TOO_MANY_REQUESTS,
308 "too many failed attempts, try again later",
309 );
310 res.headers_mut()
311 .insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1)));
312 return Err(Box::new(res));
313 }
314 match user_from_basic(state, headers).await {
315 Ok(actor) => Ok(actor),
316 Err(AccessError::Unauthorized) if headers.contains_key(AUTHORIZATION) => {
317 state.throttle.record_failure(&key, now);
318 Err(Box::new(access_error(AccessError::Unauthorized)))
319 }
320 Err(error) => Err(Box::new(access_error(error))),
321 }
322}
323
324/// Authorizes a smart-HTTP request. A CI job token (see [`job_token_read`]) is tried first;
325/// otherwise the caller is a user or anonymous, and the normal rules apply. Returns the actor
326/// (`None` for a job), the repo and its path.
327async fn caller_repo(
328 state: &AppState,
329 ip: IpAddr,
330 headers: &HeaderMap,
331 owner: &str,
332 name: &str,
333 service: GitService,
334) -> Result<(Option<User>, forge_core::Repo, std::path::PathBuf), Box<Response>> {
335 if let Some(found) = job_token_read(state, ip, headers, owner, name, service).await {
336 return found.map(|(repo, path)| (None, repo, path));
337 }
338 let actor = authenticate(state, ip, headers).await?;
339 let (repo, path) = resolve_repo(state, actor.as_ref(), owner, name, service)
340 .await
341 .map_err(|e| Box::new(access_error(e)))?;
342 Ok((actor, repo, path))
343}
344
345/// Username of a CI job's git credential. The password is `<job id>:<job token>`.
346pub const JOB_GIT_USERNAME: &str = "ci-job";
347
348/// Read-only git access for a running CI job. Returns `None` unless the request uses the
349/// `ci-job` username, so other callers take the normal path. The token must belong to a job that
350/// is Running (see `job_by_token`), the repo must be that job's repo, and receive-pack is refused.
351/// Failed attempts count against the git failure limit.
352pub async fn job_token_read(
353 state: &AppState,
354 ip: IpAddr,
355 headers: &HeaderMap,
356 owner: &str,
357 name: &str,
358 service: GitService,
359) -> Option<Result<(forge_core::Repo, std::path::PathBuf), Box<Response>>> {
360 let (username, password) = parse_basic_auth(headers)?;
361 if !username.eq_ignore_ascii_case(JOB_GIT_USERNAME) {
362 return None;
363 }
364 let key = throttle::ip_key("git-ip", ip);
365 let now = Instant::now();
366 if let Some(retry) = state.throttle.check(&key, GIT_IP_LIMIT, now) {
367 let mut res = text(
368 StatusCode::TOO_MANY_REQUESTS,
369 "too many failed attempts, try again later",
370 );
371 res.headers_mut()
372 .insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1)));
373 return Some(Err(Box::new(res)));
374 }
375 if service == GitService::ReceivePack {
376 return Some(Err(Box::new(text(
377 StatusCode::FORBIDDEN,
378 "CI job tokens are read-only",
379 ))));
380 }
381 let job_token = match password.split_once(':') {
382 Some((job_id, token)) => state
383 .store
384 .job_by_token(job_id, token)
385 .await
386 .map_err(|e| internal_error_for(&e)),
387 None => Ok(None),
388 };
389 let run_repo = match job_token {
390 Ok(Some(job)) => state
391 .store
392 .run_by_id(&job.run_id)
393 .await
394 .map_err(|e| internal_error_for(&e))
395 .map(|run| run.map(|run| run.repo_id)),
396 Ok(None) => Ok(None),
397 Err(response) => Err(response),
398 };
399 let run_repo = match run_repo {
400 Ok(run_repo) => run_repo,
401 Err(response) => return Some(Err(Box::new(response))),
402 };
403 let Some(job_repo_id) = run_repo else {
404 state.throttle.record_failure(&key, now);
405 return Some(Err(Box::new(access_error(AccessError::Unauthorized))));
406 };
407 // `<repo>.wiki` names the job's repo's wiki. It is hidden while the wiki is off, as for users.
408 let (repo_name, wiki) = match forge_core::names::wiki_base(name) {
409 Some(base) => (base, true),
410 None => (name, false),
411 };
412 let repo = match find_repo(state, owner, repo_name).await {
413 Ok(Some(repo)) if repo.id == job_repo_id => repo,
414 Ok(_) => return Some(Err(Box::new(access_error(AccessError::Unauthorized)))),
415 Err(e) => return Some(Err(Box::new(access_error(e)))),
416 };
417 if wiki {
418 match state.store.wiki_enabled(&repo.id).await {
419 Ok(true) => {}
420 Ok(false) => return Some(Err(Box::new(access_error(AccessError::Unauthorized)))),
421 Err(e) => return Some(Err(Box::new(internal_error_for(&e)))),
422 }
423 return match forge_git::repo::wiki_path(&state.config.data_dir, &repo.id) {
424 Ok(path) => Some(Ok((repo, path))),
425 Err(_) => Some(Err(Box::new(internal_error()))),
426 };
427 }
428 match forge_git::repo::repo_path(&state.config.data_dir, &repo.id) {
429 Ok(path) => Some(Ok((repo, path))),
430 Err(_) => Some(Err(Box::new(internal_error()))),
431 }
432}
433
434fn internal_error_for(error: &forge_core::Error) -> Response {
435 tracing::error!(error = %error, "ci job token check failed");
436 internal_error()
437}
438
439pub fn access_error(error: AccessError) -> Response {
440 match error {
441 AccessError::Unauthorized => {
442 let mut res = text(StatusCode::UNAUTHORIZED, "unauthorized");
443 res.headers_mut().insert(
444 WWW_AUTHENTICATE,
445 HeaderValue::from_static("Basic realm=\"forge\""),
446 );
447 res
448 }
449 AccessError::NotFound => text(StatusCode::NOT_FOUND, "not found"),
450 AccessError::Forbidden => text(StatusCode::FORBIDDEN, "forbidden"),
451 AccessError::Internal(message) => {
452 tracing::error!(error = %message, "smart-http request failed");
453 internal_error()
454 }
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn git_protocol_value_charset_and_length() {
464 // (name, value, expected validity); accepted charset first, then rejects and the length limit.
465 let cases: Vec<(&str, String, bool)> = vec![
466 ("documented version", "version=2".into(), true),
467 (
468 "object format pair",
469 "version=2:object-format=sha1".into(),
470 true,
471 ),
472 ("punctuation charset", "a.b,c_d-e:f".into(), true),
473 ("empty", String::new(), false),
474 ("uppercase key", "Version=2".into(), false),
475 ("space", "version 2".into(), false),
476 ("semicolon", "version=2;x".into(), false),
477 ("newline", "version=2\n".into(), false),
478 ("65 chars", "a".repeat(65), false),
479 ("64 chars", "a".repeat(64), true),
480 ];
481 for (name, value, want) in cases {
482 assert_eq!(valid_git_protocol(&value), want, "case {name}");
483 }
484 }
485
486 #[test]
487 fn git_protocol_header_is_dropped_when_invalid() {
488 let mut headers = HeaderMap::new();
489 headers.insert("git-protocol", HeaderValue::from_static("version=2"));
490 assert_eq!(git_protocol(&headers), Some("version=2"));
491 headers.insert("git-protocol", HeaderValue::from_static("BAD VALUE"));
492 assert_eq!(git_protocol(&headers), None);
493 assert_eq!(git_protocol(&HeaderMap::new()), None);
494 }
495
496 #[test]
497 fn wants_v2_detects_version_pair() {
498 assert!(wants_v2(Some("version=2")));
499 assert!(wants_v2(Some("object-format=sha1:version=2")));
500 assert!(!wants_v2(Some("version=1")));
501 assert!(!wants_v2(None));
502 }
503
504 #[test]
505 fn service_header_rules() {
506 assert!(needs_service_header(GitService::UploadPack, false));
507 assert!(!needs_service_header(GitService::UploadPack, true));
508 assert!(needs_service_header(GitService::ReceivePack, false));
509 assert!(needs_service_header(GitService::ReceivePack, true));
510 }
511
512 #[test]
513 fn body_encoding_rules() {
514 assert_eq!(body_encoding(None), Some(false));
515 assert_eq!(body_encoding(Some("gzip")), Some(true));
516 assert_eq!(body_encoding(Some("GZIP")), Some(true));
517 assert_eq!(body_encoding(Some(" identity ")), Some(false));
518 assert_eq!(body_encoding(Some("br")), None);
519 assert_eq!(body_encoding(Some("gzip, gzip")), None);
520 assert_eq!(body_encoding(Some("")), None);
521 }
522
523 #[tokio::test]
524 async fn gzip_request_body_decodes() {
525 use async_compression::tokio::write::GzipEncoder;
526 use tokio::io::{AsyncWriteExt, BufReader};
527
528 let payload = b"0032want 0123456789abcdef0123456789abcdef01234567\n0000";
529 let mut encoder = GzipEncoder::new(Vec::new());
530 encoder.write_all(payload).await.unwrap();
531 encoder.shutdown().await.unwrap();
532 let compressed = encoder.into_inner();
533
534 let mut decoded = Vec::new();
535 let mut decoder = GzipDecoder::new(BufReader::new(&compressed[..]));
536 tokio::io::copy(&mut decoder, &mut decoded).await.unwrap();
537 assert_eq!(decoded, payload);
538 }
539
540 #[test]
541 fn content_types_match_service() {
542 assert_eq!(
543 advertisement_content_type(GitService::UploadPack),
544 "application/x-git-upload-pack-advertisement"
545 );
546 assert_eq!(
547 result_content_type(GitService::ReceivePack),
548 "application/x-git-receive-pack-result"
549 );
550 }
551
552 #[test]
553 fn access_errors_map_to_status() {
554 assert_eq!(
555 access_error(AccessError::Unauthorized).status(),
556 StatusCode::UNAUTHORIZED
557 );
558 assert_eq!(
559 access_error(AccessError::NotFound).status(),
560 StatusCode::NOT_FOUND
561 );
562 assert_eq!(
563 access_error(AccessError::Forbidden).status(),
564 StatusCode::FORBIDDEN
565 );
566 assert_eq!(
567 access_error(AccessError::Internal("x".into())).status(),
568 StatusCode::INTERNAL_SERVER_ERROR
569 );
570 let res = access_error(AccessError::Unauthorized);
571 assert_eq!(
572 res.headers()
573 .get(WWW_AUTHENTICATE)
574 .and_then(|v| v.to_str().ok()),
575 Some("Basic realm=\"forge\"")
576 );
577 }
578
579 fn basic_headers(plain: &str) -> HeaderMap {
580 let mut headers = HeaderMap::new();
581 use base64::Engine;
582
583 let value = format!("Basic {}", base64::prelude::BASE64_STANDARD.encode(plain));
584 headers.insert(AUTHORIZATION, HeaderValue::from_str(&value).unwrap());
585 headers
586 }
587
588 #[tokio::test]
589 async fn thirty_first_bad_token_is_throttled() {
590 let tmp = tempfile::tempdir().expect("tempdir");
591 let dir = tmp.path();
592 let state = crate::test_support::test_state(dir).await;
593 let ip: IpAddr = "192.0.2.50".parse().unwrap();
594 let bad = basic_headers("tahinli:forge_not_a_real_token");
595
596 for _ in 0..30 {
597 let res = authenticate(&state, ip, &bad).await.unwrap_err();
598 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
599 }
600 let res = authenticate(&state, ip, &bad).await.unwrap_err();
601 assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
602 assert!(res.headers().get(RETRY_AFTER).is_some());
603
604 // Anonymous requests from the same IP are stopped too, and other IPs are unaffected.
605 let other: IpAddr = "192.0.2.51".parse().unwrap();
606 assert!(
607 authenticate(&state, other, &HeaderMap::new())
608 .await
609 .unwrap()
610 .is_none()
611 );
612 let res = authenticate(&state, ip, &HeaderMap::new())
613 .await
614 .unwrap_err();
615 assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
616 }
617}