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