| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::{ |
| 10 | io, |
| 11 | pin::Pin, |
| 12 | task::{Context, Poll}, |
| 13 | time::{Duration, SystemTime}, |
| 14 | }; |
| 15 | |
| 16 | use base64::{Engine, engine::general_purpose::STANDARD}; |
| 17 | use bytes::Bytes; |
| 18 | use futures_util::TryStreamExt; |
| 19 | use http_body::Frame; |
| 20 | use serde::Deserialize; |
| 21 | use tokio::io::{AsyncRead, ReadBuf}; |
| 22 | use tokio_util::io::StreamReader; |
| 23 | use 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 | |
| 34 | use 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 | |
| 44 | use 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 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | const CHUNK: usize = 16 * 1024; |
| 58 | |
| 59 | |
| 60 | #[path_param] |
| 61 | struct Repo(str); |
| 62 | |
| 63 | #[derive(Debug, Deserialize)] |
| 64 | struct ServiceQuery { |
| 65 | service: Option<String>, |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | fn 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 | |
| 81 | fn 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 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | async 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 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | pub(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 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | fn 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 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | fn 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 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | fn 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 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | fn 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 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | async 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 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | async 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 | |
| 261 | |
| 262 | |
| 263 | Ok(None) if anonymous => return challenge(), |
| 264 | Ok(None) => return Err(not_found().into()), |
| 265 | |
| 266 | |
| 267 | |
| 268 | Err(Error::Domain(DomainError::Forbidden)) if anonymous => return challenge(), |
| 269 | Err(Error::Domain(DomainError::Forbidden)) => return Err(forbidden().into()), |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | Err(Error::Domain(DomainError::Archived)) => return archived(), |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 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 | |
| 298 | |
| 299 | |
| 300 | response |
| 301 | .body(GitBody::new(served.body)) |
| 302 | .map_err(server_error) |
| 303 | } |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | #[route(GET "/{handle}/repos/{repo}/info/refs")] |
| 310 | async 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 | |
| 315 | |
| 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")] |
| 337 | async 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 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | #[route(POST "/{handle}/repos/{repo}/git-receive-pack")] |
| 361 | async 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 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | struct 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 | |
| 426 | impl PushWatch { |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | |
| 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 | |
| 456 | |
| 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 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 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 | |
| 538 | |
| 539 | |
| 540 | |
| 541 | fn into_reader(body: Body) -> ByteStream { |
| 542 | Box::pin(StreamReader::new( |
| 543 | body.into_data_stream().map_err(io::Error::other), |
| 544 | )) |
| 545 | } |
| 546 | |
| 547 | |
| 548 | |
| 549 | |
| 550 | |
| 551 | pub struct GitBody { |
| 552 | reader: ByteStream, |
| 553 | } |
| 554 | |
| 555 | impl GitBody { |
| 556 | |
| 557 | |
| 558 | pub(super) fn new(reader: ByteStream) -> Self { |
| 559 | Self { reader } |
| 560 | } |
| 561 | |
| 562 | |
| 563 | |
| 564 | |
| 565 | |
| 566 | |
| 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 | |
| 578 | struct OnEnd { |
| 579 | inner: ByteStream, |
| 580 | |
| 581 | |
| 582 | at_end: Option<Box<dyn FnOnce() + Send>>, |
| 583 | } |
| 584 | |
| 585 | impl 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 | |
| 605 | impl 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 | |
| 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 | } |