forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·7.1 MiB·490f099·Tahinli·7 hours ago·322 commits
| 1 | //! Forgejo and Gitea import tests against a tiny local HTTP server that speaks `/api/v1`: the real |
| 2 | //! [`Forgejo`] client, real pagination, nothing on the network. |
| 3 | |
| 4 | use std::sync::{Arc, Mutex}; |
| 5 | |
| 6 | use serde_json::{Value, json}; |
| 7 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 8 | use tokio::net::TcpListener; |
| 9 | |
| 10 | use super::*; |
| 11 | use crate::importer::api::{Auth, Forgejo, Http}; |
| 12 | |
| 13 | type Reply = (Vec<(String, String)>, Vec<u8>); |
| 14 | type Log = Arc<Mutex<Vec<(String, Option<String>)>>>; |
| 15 | |
| 16 | /// Binds a port and returns the base address with the listener. |
| 17 | async fn bind() -> (TcpListener, String) { |
| 18 | let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); |
| 19 | let base = format!("http://{}", listener.local_addr().expect("addr")); |
| 20 | (listener, base) |
| 21 | } |
| 22 | |
| 23 | /// Serves `handler(target)` for every GET; `None` is a 404. Returns the request log |
| 24 | /// (target, `Authorization` header). |
| 25 | fn serve<F>(listener: TcpListener, handler: F) -> Log |
| 26 | where |
| 27 | F: Fn(&str) -> Option<Reply> + Send + Sync + 'static, |
| 28 | { |
| 29 | let log: Log = Arc::default(); |
| 30 | let seen = log.clone(); |
| 31 | let handler = Arc::new(handler); |
| 32 | tokio::spawn(async move { |
| 33 | loop { |
| 34 | let Ok((mut sock, _)) = listener.accept().await else { |
| 35 | return; |
| 36 | }; |
| 37 | let handler = handler.clone(); |
| 38 | let seen = seen.clone(); |
| 39 | tokio::spawn(async move { |
| 40 | let mut buf = Vec::new(); |
| 41 | let mut chunk = [0u8; 2048]; |
| 42 | while !buf.windows(4).any(|w| w == b"\r\n\r\n") { |
| 43 | match sock.read(&mut chunk).await { |
| 44 | Ok(0) | Err(_) => return, |
| 45 | Ok(n) => buf.extend_from_slice(&chunk[..n]), |
| 46 | } |
| 47 | } |
| 48 | let text = String::from_utf8_lossy(&buf).into_owned(); |
| 49 | let target = text |
| 50 | .lines() |
| 51 | .next() |
| 52 | .and_then(|l| l.split_whitespace().nth(1)) |
| 53 | .unwrap_or("/") |
| 54 | .to_owned(); |
| 55 | let auth = text.lines().find_map(|l| { |
| 56 | let (k, v) = l.split_once(':')?; |
| 57 | k.eq_ignore_ascii_case("authorization") |
| 58 | .then(|| v.trim().to_owned()) |
| 59 | }); |
| 60 | seen.lock().unwrap().push((target.clone(), auth)); |
| 61 | let out = match handler(&target) { |
| 62 | Some((headers, body)) => { |
| 63 | let mut head = format!( |
| 64 | "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n", |
| 65 | body.len() |
| 66 | ); |
| 67 | for (k, v) in headers { |
| 68 | head.push_str(&format!("{k}: {v}\r\n")); |
| 69 | } |
| 70 | head.push_str("\r\n"); |
| 71 | let mut out = head.into_bytes(); |
| 72 | out.extend(body); |
| 73 | out |
| 74 | } |
| 75 | None => { |
| 76 | b"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" |
| 77 | .to_vec() |
| 78 | } |
| 79 | }; |
| 80 | let _ = sock.write_all(&out).await; |
| 81 | let _ = sock.shutdown().await; |
| 82 | }); |
| 83 | } |
| 84 | }); |
| 85 | log |
| 86 | } |
| 87 | |
| 88 | fn json_reply(headers: Vec<(&str, String)>, body: &Value) -> Option<Reply> { |
| 89 | let mut all = vec![("content-type".to_owned(), "application/json".to_owned())]; |
| 90 | all.extend(headers.into_iter().map(|(k, v)| (k.to_owned(), v))); |
| 91 | Some((all, body.to_string().into_bytes())) |
| 92 | } |
| 93 | |
| 94 | fn page_of(target: &str) -> usize { |
| 95 | target |
| 96 | .split(['?', '&']) |
| 97 | .find_map(|p| p.strip_prefix("page=")) |
| 98 | .and_then(|v| v.parse().ok()) |
| 99 | .unwrap_or(1) |
| 100 | } |
| 101 | |
| 102 | fn client(base: &str, token: Option<&str>) -> Forgejo { |
| 103 | let notice: crate::importer::api::Notice = Arc::new(|_| {}); |
| 104 | let open = |
| 105 | crate::webhooks::client::WebhookPolicy::from_config(&forge_core::config::WebhookConfig { |
| 106 | allow_http: true, |
| 107 | allowed_hosts: vec!["127.0.0.1".into()], |
| 108 | }) |
| 109 | .expect("policy"); |
| 110 | let http = Http::new( |
| 111 | reqwest::Client::new(), |
| 112 | open, |
| 113 | token.map(str::to_owned), |
| 114 | Auth::Forgejo, |
| 115 | "127.0.0.1".into(), |
| 116 | notice, |
| 117 | ); |
| 118 | Forgejo::new(http, base) |
| 119 | } |
| 120 | |
| 121 | fn issue_json(n: i64, state: &str) -> Value { |
| 122 | json!({ |
| 123 | "number": n, "title": format!("Issue {n}"), "body": "text", "state": state, |
| 124 | "user": {"login": "hubot"}, "labels": [{"name": "bug", "color": "d73a4a"}], |
| 125 | "milestone": null, "created_at": "2020-01-02T03:04:05Z", |
| 126 | "html_url": format!("https://codeberg.example/tahinli/project/issues/{n}"), |
| 127 | }) |
| 128 | } |
| 129 | |
| 130 | #[tokio::test] |
| 131 | async fn pagination_follows_the_link_header_with_a_limit_of_fifty() { |
| 132 | let (listener, base) = bind().await; |
| 133 | let log = serve(listener, |target| { |
| 134 | if !target.starts_with("/api/v1/repos/tahinli/project/issues?type=issues") { |
| 135 | return json_reply(vec![], &json!([])); |
| 136 | } |
| 137 | match page_of(target) { |
| 138 | 1 => json_reply( |
| 139 | vec![ |
| 140 | ("x-total-count", "52".into()), |
| 141 | ( |
| 142 | "link", |
| 143 | "<http://x/api/v1/p?page=2>; rel=\"next\", <http://x/api/v1/p?page=2>; rel=\"last\"" |
| 144 | .into(), |
| 145 | ), |
| 146 | ], |
| 147 | &Value::Array((1..=50).map(|n| issue_json(n, "open")).collect()), |
| 148 | ), |
| 149 | 2 => json_reply( |
| 150 | vec![ |
| 151 | ("x-total-count", "52".into()), |
| 152 | ("link", "<http://x/api/v1/p?page=1>; rel=\"prev\"".into()), |
| 153 | ], |
| 154 | &Value::Array((51..=52).map(|n| issue_json(n, "closed")).collect()), |
| 155 | ), |
| 156 | _ => json_reply(vec![], &json!([])), |
| 157 | } |
| 158 | }); |
| 159 | let api = client(&base, Some("abc123")); |
| 160 | let issues = api.issues("tahinli/project").await.unwrap(); |
| 161 | let plain: Vec<_> = issues.iter().filter(|i| !i.is_pr).collect(); |
| 162 | assert_eq!(plain.len(), 52, "both pages were read"); |
| 163 | assert!(plain[51].closed && !plain[0].closed); |
| 164 | assert_eq!(plain[0].author, "hubot"); |
| 165 | assert_eq!(plain[0].labels, vec!["bug"]); |
| 166 | |
| 167 | let log = log.lock().unwrap(); |
| 168 | let issue_calls: Vec<_> = log |
| 169 | .iter() |
| 170 | .filter(|(t, _)| t.contains("type=issues")) |
| 171 | .collect(); |
| 172 | assert_eq!(issue_calls.len(), 2, "stopped when the link had no next"); |
| 173 | assert!(issue_calls[0].0.contains("limit=50")); |
| 174 | assert!(issue_calls[0].0.contains("page=1") && issue_calls[1].0.contains("page=2")); |
| 175 | assert!( |
| 176 | log.iter() |
| 177 | .all(|(_, auth)| auth.as_deref() == Some("token abc123")), |
| 178 | "every request carries the token header" |
| 179 | ); |
| 180 | } |
| 181 | |
| 182 | #[tokio::test] |
| 183 | async fn the_total_count_stops_a_listing_with_no_link_header() { |
| 184 | let (listener, base) = bind().await; |
| 185 | let log = serve(listener, |target| { |
| 186 | json_reply( |
| 187 | vec![("x-total-count", "50".into())], |
| 188 | &Value::Array( |
| 189 | (0..50) |
| 190 | .map(|i| json!({"name": format!("l{i}"), "color": "00aabb"})) |
| 191 | .collect(), |
| 192 | ), |
| 193 | ) |
| 194 | .filter(|_| target.contains("/labels")) |
| 195 | }); |
| 196 | let api = client(&base, None); |
| 197 | let labels = api.labels("tahinli/project").await.unwrap(); |
| 198 | assert_eq!(labels.len(), 50); |
| 199 | assert_eq!(labels[0].color, "#00aabb"); |
| 200 | assert_eq!( |
| 201 | log.lock().unwrap().len(), |
| 202 | 1, |
| 203 | "a full page of exactly the total is the end" |
| 204 | ); |
| 205 | assert!( |
| 206 | log.lock().unwrap()[0].1.is_none(), |
| 207 | "no token, no Authorization header" |
| 208 | ); |
| 209 | } |
| 210 | |
| 211 | #[tokio::test] |
| 212 | async fn pulls_map_merged_closed_and_open() { |
| 213 | let (listener, base) = bind().await; |
| 214 | serve(listener, |target| { |
| 215 | if target.contains("/pulls?") { |
| 216 | let mut merged = issue_json(2, "closed"); |
| 217 | merged["merged"] = json!(true); |
| 218 | let closed = issue_json(3, "closed"); |
| 219 | let mut open = issue_json(4, "open"); |
| 220 | open["milestone"] = json!({"title": "v1"}); |
| 221 | json_reply(vec![], &json!([merged, closed, open])) |
| 222 | } else if target.contains("/issues?") { |
| 223 | json_reply(vec![], &json!([issue_json(1, "open")])) |
| 224 | } else { |
| 225 | None |
| 226 | } |
| 227 | }); |
| 228 | let api = client(&base, None); |
| 229 | let all = api.issues("tahinli/project").await.unwrap(); |
| 230 | assert_eq!(all.len(), 4); |
| 231 | assert!(!all[0].is_pr); |
| 232 | let pulls: Vec<_> = all.iter().filter(|i| i.is_pr).collect(); |
| 233 | assert!(pulls[0].closed && pulls[0].merged); |
| 234 | assert!(pulls[1].closed && !pulls[1].merged); |
| 235 | assert!(!pulls[2].closed); |
| 236 | assert_eq!(pulls[2].milestone.as_deref(), Some("v1")); |
| 237 | } |
| 238 | |
| 239 | #[tokio::test] |
| 240 | async fn bulk_listing_tries_the_org_then_the_user_and_supports_own_repos() { |
| 241 | let (listener, base) = bind().await; |
| 242 | let repo = |name: &str, private: bool| { |
| 243 | json!({"name": name, "full_name": format!("tahinli/{name}"), "private": private, |
| 244 | "fork": false, "archived": false, "default_branch": "main", "description": null}) |
| 245 | }; |
| 246 | let log = serve(listener, move |target| { |
| 247 | if target.starts_with("/api/v1/users/tahinli/repos") { |
| 248 | json_reply(vec![], &json!([repo("a", false)])) |
| 249 | } else if target.starts_with("/api/v1/user/repos") { |
| 250 | json_reply(vec![], &json!([repo("a", false), repo("b", true)])) |
| 251 | } else { |
| 252 | None |
| 253 | } |
| 254 | }); |
| 255 | let api = client(&base, Some("t")); |
| 256 | let public = api.list_repos("tahinli").await.unwrap(); |
| 257 | assert_eq!(public.len(), 1); |
| 258 | assert_eq!(public[0].full_name, "tahinli/a"); |
| 259 | assert!( |
| 260 | log.lock().unwrap()[0] |
| 261 | .0 |
| 262 | .starts_with("/api/v1/orgs/tahinli/repos"), |
| 263 | "the org is tried first" |
| 264 | ); |
| 265 | let mine = api.list_repos("").await.unwrap(); |
| 266 | assert_eq!(mine.len(), 2); |
| 267 | assert!(mine[1].private); |
| 268 | } |
| 269 | |
| 270 | #[tokio::test] |
| 271 | async fn a_bad_asset_address_is_refused_before_any_request() { |
| 272 | let (listener, base) = bind().await; |
| 273 | let log = serve(listener, |_| None); |
| 274 | let api = client(&base, Some("t")); |
| 275 | let asset = ExtAsset { |
| 276 | url: "https://elsewhere.example/a.bin".into(), |
| 277 | ..ExtAsset::default() |
| 278 | }; |
| 279 | assert!(api.download(&asset, 100).await.is_err()); |
| 280 | assert!(log.lock().unwrap().is_empty()); |
| 281 | } |
| 282 | |
| 283 | #[tokio::test] |
| 284 | async fn full_forgejo_import_maps_issues_pulls_comments_labels_and_releases() { |
| 285 | let fx = fixture().await; |
| 286 | let (listener, base) = bind().await; |
| 287 | let origin = base.clone(); |
| 288 | serve(listener, move |target| { |
| 289 | let path = target.split('?').next().unwrap_or_default(); |
| 290 | match path { |
| 291 | "/api/v1/repos/tahinli/project/labels" => json_reply( |
| 292 | vec![], |
| 293 | &json!([{"name": "bug", "color": "d73a4a", "description": "Broken"}]), |
| 294 | ), |
| 295 | "/api/v1/repos/tahinli/project/milestones" => json_reply( |
| 296 | vec![], |
| 297 | &json!([{"id": 9, "title": "v1", "description": "", "state": "closed", |
| 298 | "due_on": "2020-05-06T00:00:00Z"}]), |
| 299 | ), |
| 300 | "/api/v1/repos/tahinli/project/issues" => { |
| 301 | json_reply(vec![], &json!([issue_json(1, "closed")])) |
| 302 | } |
| 303 | "/api/v1/repos/tahinli/project/pulls" => { |
| 304 | let mut pr = issue_json(2, "closed"); |
| 305 | pr["title"] = json!("Add the thing"); |
| 306 | pr["merged"] = json!(true); |
| 307 | json_reply(vec![], &json!([pr])) |
| 308 | } |
| 309 | "/api/v1/repos/tahinli/project/issues/1/comments" => json_reply( |
| 310 | vec![], |
| 311 | &json!([{"id": 11, "body": "same here", "user": {"login": "hubot"}, |
| 312 | "created_at": "2020-01-03T00:00:00Z", |
| 313 | "html_url": "https://codeberg.example/c/11"}]), |
| 314 | ), |
| 315 | "/api/v1/repos/tahinli/project/issues/2/comments" => json_reply(vec![], &json!([])), |
| 316 | "/api/v1/repos/tahinli/project/releases" => json_reply( |
| 317 | vec![], |
| 318 | &json!([{"id": 5, "tag_name": "v1", "name": "", "body": "notes", "draft": false, |
| 319 | "prerelease": false, "author": {"login": "hubot"}, |
| 320 | "created_at": "2021-01-01T00:00:00Z", |
| 321 | "html_url": "https://codeberg.example/r/5", |
| 322 | "assets": [{"id": 1, "name": "app.tar.gz", "size": 5, |
| 323 | "browser_download_url": format!("{origin}/attachments/uuid-1")}]}]), |
| 324 | ), |
| 325 | "/attachments/uuid-1" => Some((vec![], b"hello".to_vec())), |
| 326 | _ => None, |
| 327 | } |
| 328 | }); |
| 329 | let api = client(&base, Some(TOKEN)); |
| 330 | let job = new_job(&fx, Source::Forgejo).await; |
| 331 | let mut spec = spec(Source::Forgejo, everything()); |
| 332 | spec.instance = base.clone(); |
| 333 | run_job( |
| 334 | &fx.state, |
| 335 | &job, |
| 336 | &spec, |
| 337 | Some(&api), |
| 338 | &Transport::Local(fx.upstream.clone()), |
| 339 | ) |
| 340 | .await; |
| 341 | |
| 342 | let store = &fx.state.store; |
| 343 | let job = store.import_job(&job.id).await.unwrap().unwrap(); |
| 344 | assert_eq!(job.state, ImportState::Done, "{:?}", job.error); |
| 345 | |
| 346 | let all = IssueFilter { |
| 347 | state: None, |
| 348 | per_page: 100, |
| 349 | ..IssueFilter::default() |
| 350 | }; |
| 351 | let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); |
| 352 | assert_eq!(total, 2); |
| 353 | let issue = items.iter().find(|i| i.issue.title == "Issue 1").unwrap(); |
| 354 | assert_eq!(issue.issue.state, IssueState::Closed); |
| 355 | assert!( |
| 356 | issue |
| 357 | .issue |
| 358 | .body |
| 359 | .starts_with("> Originally by \\@hubot on Forgejo, 2020-01-02"), |
| 360 | "{}", |
| 361 | issue.issue.body |
| 362 | ); |
| 363 | assert!(issue.labels.iter().any(|l| l.name == "bug")); |
| 364 | let pull = items |
| 365 | .iter() |
| 366 | .find(|i| i.issue.title == "Add the thing") |
| 367 | .unwrap(); |
| 368 | assert!(pull.issue.body.contains("Imported pull request (merged)")); |
| 369 | let comments = store.list_comments(&issue.issue.id).await.unwrap(); |
| 370 | assert_eq!(comments.len(), 1); |
| 371 | assert!(comments[0].body.ends_with("same here")); |
| 372 | |
| 373 | let release = store |
| 374 | .release_by_tag(&fx.repo.id, "v1") |
| 375 | .await |
| 376 | .unwrap() |
| 377 | .unwrap(); |
| 378 | assert!(release.body.contains("notes")); |
| 379 | let assets = store.list_release_assets(&release.id).await.unwrap(); |
| 380 | assert_eq!(assets.len(), 1); |
| 381 | assert_eq!(assets[0].name, "app.tar.gz"); |
| 382 | assert_eq!(assets[0].size, 5); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn forgejo_remotes_take_a_url_or_a_path_with_an_instance() { |
| 387 | use crate::importer::parse_remote; |
| 388 | assert_eq!( |
| 389 | parse_remote( |
| 390 | Source::Forgejo, |
| 391 | "https://codeberg.org/tahinli/forge.git", |
| 392 | "" |
| 393 | ), |
| 394 | Some(("tahinli/forge".into(), "https://codeberg.org".into())) |
| 395 | ); |
| 396 | assert_eq!( |
| 397 | parse_remote(Source::Forgejo, "tahinli/forge", "https://codeberg.org/"), |
| 398 | Some(("tahinli/forge".into(), "https://codeberg.org".into())) |
| 399 | ); |
| 400 | assert_eq!( |
| 401 | parse_remote(Source::Forgejo, "a/b/c", "https://codeberg.org"), |
| 402 | None |
| 403 | ); |
| 404 | assert_eq!(parse_remote(Source::Forgejo, "tahinli/forge", ""), None); |
| 405 | assert_eq!(Source::parse("gitea"), Some(Source::Forgejo)); |
| 406 | let mut s = spec(Source::Forgejo, ImportOptions::default()); |
| 407 | s.instance = "https://codeberg.org/".into(); |
| 408 | assert_eq!(s.clone_url(), "https://codeberg.org/tahinli/project.git"); |
| 409 | } |