| 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 | Error, GitClientHeaders, GitEndpoint, GitService, authenticate_token, port::ByteStream, |
| 36 | serve_git, |
| 37 | }, |
| 38 | domain::{Actor, DomainError, RepoName}, |
| 39 | }; |
| 40 | |
| 41 | use super::{ |
| 42 | context::{current_actor, memberships, orgs, protocol, repos, server_error, tokens}, |
| 43 | profile::handle_param, |
| 44 | }; |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | const CHUNK: usize = 16 * 1024; |
| 51 | |
| 52 | |
| 53 | #[path_param] |
| 54 | struct Repo(str); |
| 55 | |
| 56 | #[derive(Debug, Deserialize)] |
| 57 | struct ServiceQuery { |
| 58 | service: Option<String>, |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | fn repo_param(cx: &Cx) -> Result<RepoName> { |
| 67 | let raw = path_param::<Repo>(cx); |
| 68 | let name = raw.strip_suffix(".git").ok_or_else(not_found)?; |
| 69 | |
| 70 | Ok(RepoName::new(name).map_err(|_| not_found())?) |
| 71 | } |
| 72 | |
| 73 | |
| 74 | fn client_headers(cx: &Cx) -> GitClientHeaders { |
| 75 | let headers = headers(cx); |
| 76 | let value = |name: &str| { |
| 77 | headers |
| 78 | .get(name) |
| 79 | .and_then(|value| value.to_str().ok()) |
| 80 | .map(str::to_owned) |
| 81 | }; |
| 82 | |
| 83 | GitClientHeaders { |
| 84 | content_type: value("content-type"), |
| 85 | content_encoding: value("content-encoding"), |
| 86 | content_length: value("content-length"), |
| 87 | git_protocol: value("git-protocol"), |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | async fn git_actor(cx: &Cx) -> Result<Actor> { |
| 101 | if let Some(presented) = basic_credential(cx) { |
| 102 | let actor = authenticate_token(&presented, &tokens(cx)) |
| 103 | .await |
| 104 | .map_err(server_error)?; |
| 105 | |
| 106 | if actor.user_id().is_some() { |
| 107 | return Ok(actor); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | current_actor(cx).await |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | fn basic_credential(cx: &Cx) -> Option<String> { |
| 120 | let header = headers(cx).get(AUTHORIZATION)?.to_str().ok()?; |
| 121 | let encoded = header.strip_prefix("Basic ")?; |
| 122 | let decoded = STANDARD.decode(encoded).ok()?; |
| 123 | let decoded = String::from_utf8(decoded).ok()?; |
| 124 | |
| 125 | let (user, password) = decoded.split_once(':')?; |
| 126 | |
| 127 | if password.is_empty() { |
| 128 | Some(user.to_owned()) |
| 129 | } else { |
| 130 | Some(password.to_owned()) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | fn challenge() -> Result<Response<GitBody>> { |
| 142 | Response::builder() |
| 143 | .status(StatusCode::UNAUTHORIZED) |
| 144 | .header(WWW_AUTHENTICATE, r#"Basic realm="steid""#) |
| 145 | .body(GitBody::new(Box::pin(tokio::io::empty()))) |
| 146 | .map_err(server_error) |
| 147 | } |
| 148 | |
| 149 | |
| 150 | async fn serve(cx: &Cx, endpoint: GitEndpoint, body: ByteStream) -> Result<Response<GitBody>> { |
| 151 | let handle = handle_param(cx)?; |
| 152 | let name = repo_param(cx)?; |
| 153 | let actor = git_actor(cx).await?; |
| 154 | let anonymous = actor.user_id().is_none(); |
| 155 | |
| 156 | let served = serve_git( |
| 157 | &handle, |
| 158 | &name, |
| 159 | endpoint, |
| 160 | client_headers(cx), |
| 161 | body, |
| 162 | &actor, |
| 163 | &orgs(cx), |
| 164 | &memberships(cx), |
| 165 | &repos(cx), |
| 166 | &protocol(cx), |
| 167 | ) |
| 168 | .await; |
| 169 | |
| 170 | let served = match served { |
| 171 | Ok(Some(served)) => served, |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | Ok(None) if anonymous => return challenge(), |
| 177 | Ok(None) => return Err(not_found().into()), |
| 178 | |
| 179 | |
| 180 | |
| 181 | Err(Error::Domain(DomainError::Forbidden)) if anonymous => return challenge(), |
| 182 | Err(Error::Domain(DomainError::Forbidden)) => return Err(forbidden().into()), |
| 183 | |
| 184 | Err(other) => return Err(server_error(other)), |
| 185 | }; |
| 186 | |
| 187 | let mut response = Response::builder().status(served.status); |
| 188 | for (name, value) in served.headers { |
| 189 | response = response.header(name, value); |
| 190 | } |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | response |
| 196 | .body(GitBody::new(served.body)) |
| 197 | .map_err(server_error) |
| 198 | } |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | #[route(GET "/{handle}/repos/{repo}/info/refs")] |
| 205 | async fn info_refs(cx: &Cx) -> Result<Response<GitBody>> { |
| 206 | let query = |
| 207 | parse_query_params::<ServiceQuery>(cx).map_err(|error| bad_request(error.to_string()))?; |
| 208 | |
| 209 | |
| 210 | |
| 211 | let service = query.service.ok_or_else(not_found)?; |
| 212 | let service: GitService = service.parse().map_err(|_| not_found())?; |
| 213 | |
| 214 | serve( |
| 215 | cx, |
| 216 | GitEndpoint::Advertisement(service), |
| 217 | Box::pin(tokio::io::empty()), |
| 218 | ) |
| 219 | .await |
| 220 | } |
| 221 | |
| 222 | #[route(POST "/{handle}/repos/{repo}/git-upload-pack")] |
| 223 | async fn upload_pack(cx: &Cx, body: Body) -> Result<Response<GitBody>> { |
| 224 | serve( |
| 225 | cx, |
| 226 | GitEndpoint::Rpc(GitService::UploadPack), |
| 227 | into_reader(body), |
| 228 | ) |
| 229 | .await |
| 230 | } |
| 231 | |
| 232 | #[route(POST "/{handle}/repos/{repo}/git-receive-pack")] |
| 233 | async fn receive_pack(cx: &Cx, body: Body) -> Result<Response<GitBody>> { |
| 234 | serve( |
| 235 | cx, |
| 236 | GitEndpoint::Rpc(GitService::ReceivePack), |
| 237 | into_reader(body), |
| 238 | ) |
| 239 | .await |
| 240 | } |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | fn into_reader(body: Body) -> ByteStream { |
| 247 | Box::pin(StreamReader::new( |
| 248 | body.into_data_stream().map_err(io::Error::other), |
| 249 | )) |
| 250 | } |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | pub struct GitBody { |
| 257 | reader: ByteStream, |
| 258 | } |
| 259 | |
| 260 | impl GitBody { |
| 261 | |
| 262 | |
| 263 | pub(super) fn new(reader: ByteStream) -> Self { |
| 264 | Self { reader } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | impl http_body::Body for GitBody { |
| 269 | type Data = Bytes; |
| 270 | type Error = io::Error; |
| 271 | |
| 272 | fn poll_frame( |
| 273 | mut self: Pin<&mut Self>, |
| 274 | cx: &mut Context<'_>, |
| 275 | ) -> Poll<Option<std::result::Result<Frame<Bytes>, io::Error>>> { |
| 276 | let mut buffer = [0u8; CHUNK]; |
| 277 | let mut read = ReadBuf::new(&mut buffer); |
| 278 | |
| 279 | match Pin::new(&mut self.reader).poll_read(cx, &mut read) { |
| 280 | Poll::Pending => Poll::Pending, |
| 281 | Poll::Ready(Err(error)) => Poll::Ready(Some(Err(error))), |
| 282 | Poll::Ready(Ok(())) => { |
| 283 | let filled = read.filled(); |
| 284 | |
| 285 | |
| 286 | if filled.is_empty() { |
| 287 | Poll::Ready(None) |
| 288 | } else { |
| 289 | Poll::Ready(Some(Ok(Frame::data(Bytes::copy_from_slice(filled))))) |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | } |