| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use std::{ |
| 10 | io, |
| 11 | pin::Pin, |
| 12 | task::{Context, Poll}, |
| 13 | }; |
| 14 | |
| 15 | use base64::{Engine, engine::general_purpose::STANDARD}; |
| 16 | use bytes::Bytes; |
| 17 | use futures_util::TryStreamExt; |
| 18 | use http_body::Frame; |
| 19 | use serde::Deserialize; |
| 20 | use tokio::io::{AsyncRead, ReadBuf}; |
| 21 | use tokio_util::io::StreamReader; |
| 22 | use 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 | |
| 33 | use 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 | |
| 42 | use 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 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | const CHUNK: usize = 16 * 1024; |
| 55 | |
| 56 | |
| 57 | #[path_param] |
| 58 | struct Repo(str); |
| 59 | |
| 60 | #[derive(Debug, Deserialize)] |
| 61 | struct ServiceQuery { |
| 62 | service: Option<String>, |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | fn 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 | |
| 78 | fn 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 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | async 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 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | fn 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 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | fn 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 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | fn 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 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | fn 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 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | async 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 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | async 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 | |
| 230 | |
| 231 | |
| 232 | Ok(None) if anonymous => return challenge(), |
| 233 | Ok(None) => return Err(not_found().into()), |
| 234 | |
| 235 | |
| 236 | |
| 237 | Err(Error::Domain(DomainError::Forbidden)) if anonymous => return challenge(), |
| 238 | Err(Error::Domain(DomainError::Forbidden)) => return Err(forbidden().into()), |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | Err(Error::Domain(DomainError::Archived)) => return archived(), |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 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 | |
| 267 | |
| 268 | |
| 269 | response |
| 270 | .body(GitBody::new(served.body)) |
| 271 | .map_err(server_error) |
| 272 | } |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | #[route(GET "/{handle}/repos/{repo}/info/refs")] |
| 279 | async 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 | |
| 284 | |
| 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")] |
| 303 | async 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 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | #[route(POST "/{handle}/repos/{repo}/git-receive-pack")] |
| 324 | async 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 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | struct 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 | |
| 386 | impl PushWatch { |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 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 | |
| 416 | |
| 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 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 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 | |
| 499 | |
| 500 | |
| 501 | |
| 502 | fn into_reader(body: Body) -> ByteStream { |
| 503 | Box::pin(StreamReader::new( |
| 504 | body.into_data_stream().map_err(io::Error::other), |
| 505 | )) |
| 506 | } |
| 507 | |
| 508 | |
| 509 | |
| 510 | |
| 511 | |
| 512 | pub struct GitBody { |
| 513 | reader: ByteStream, |
| 514 | } |
| 515 | |
| 516 | impl GitBody { |
| 517 | |
| 518 | |
| 519 | pub(super) fn new(reader: ByteStream) -> Self { |
| 520 | Self { reader } |
| 521 | } |
| 522 | |
| 523 | |
| 524 | |
| 525 | |
| 526 | |
| 527 | |
| 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 | |
| 539 | struct OnEnd { |
| 540 | inner: ByteStream, |
| 541 | |
| 542 | |
| 543 | at_end: Option<Box<dyn FnOnce() + Send>>, |
| 544 | } |
| 545 | |
| 546 | impl 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 | |
| 566 | impl 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 | |
| 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 | } |