From 24f950202335b5d7ca67ee2eee05549b3060ad1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 20 Oct 2026 22:40:47 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20serve=20the=20Gitea=20API?= =?UTF-8?q?=20subset=20Forgejo=20needs=20to=20migrate=20a=20repo=20out=20o?= =?UTF-8?q?f=20forge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/src/api/gitea.rs | 997 ++++++++++++++++++++++++ crates/forge-web/src/api/gitea_tests.rs | 566 ++++++++++++++ crates/forge-web/src/api/mod.rs | 30 +- crates/forge-web/src/api/releases.rs | 107 ++- crates/forge-web/src/pages/releases.rs | 45 +- docs/api.md | 78 +- 6 files changed, 1783 insertions(+), 40 deletions(-) create mode 100644 crates/forge-web/src/api/gitea.rs create mode 100644 crates/forge-web/src/api/gitea_tests.rs diff --git a/crates/forge-web/src/api/gitea.rs b/crates/forge-web/src/api/gitea.rs new file mode 100644 index 0000000..13ef8e7 --- /dev/null +++ b/crates/forge-web/src/api/gitea.rs @@ -0,0 +1,997 @@ +//! A read-only subset of the Gitea REST API, so a Forgejo or Gitea server can migrate a repo out +//! of forge ("New migration", then "Gitea", with this server's URL and a token). The routes and +//! JSON shapes are the ones the Forgejo Gitea downloader (services/migrations/gitea_downloader.go) +//! and the Gitea Go SDK read. See docs/api.md, "Moving to Forgejo or Gitea". +//! +//! Gitea ids are integers while forge ids are ULIDs. Ids shown here come from [`numeric_id`], a +//! stable 48 bit digest, and routes that take such an id find the row by scanning the (already +//! scoped) parent list. Comment ids encode the issue number and the position instead, so the +//! comment reaction route, which has no issue in its path, can find its comment. +//! +//! Reads follow the token: a caller sees what its user may read, drafts only with write access. +//! What forge does not have (topics, reactions beyond the first ten users of an emoji) comes back +//! empty rather than as an error. + +use std::collections::HashMap; + +use forge_core::issues::{ + Comment, IssueFilter, IssueListItem, IssueSort, IssueState, Label, Milestone, +}; +use forge_core::pulls::PullRequest; +use forge_core::reactions::ReactionTarget; +use forge_core::reviews::{Review, ReviewComment, ReviewState, Side}; +use forge_core::token::hash_token; +use forge_core::{Action, Repo as CoreRepo, User, Visibility}; +use http::HeaderMap; +use http::header::{AUTHORIZATION, HeaderName, HeaderValue}; +use serde_json::{Value, json}; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{headers, uri}; +use topcoat::router::response::Response; +use topcoat::router::{StatusCode, path_param, route}; + +use crate::api::{self, Refusal}; +use crate::client_ip::client_ip; +use crate::state::AppState; + +path_param!(owner); +path_param!(repo); +path_param!(index); +path_param!(id); +path_param!(review_id); + +/// The version reported by `GET /api/v1/version`. Forgejo's downloader gates reactions on 1.11, +/// reviews and pagination on 1.12 and PR head shas on 1.14, so this unlocks all of them. +pub const GITEA_VERSION: &str = "1.22.0"; +/// Largest page a caller can ask for, announced by `GET /api/v1/settings/api`. +pub const MAX_PAGE: usize = 50; +/// Page size when the caller names none. +const DEFAULT_PAGE: usize = 30; + +/// A stable positive integer for a forge id, below 2^48 so JSON numbers stay exact. +pub fn numeric_id(id: &str) -> i64 { + let digest = hash_token(id); + i64::from_str_radix(&digest[..12], 16).unwrap_or(0) + 1 +} + +/// True when `raw` is a Gitea style integer id (as opposed to a ULID). +pub fn is_numeric(raw: &str) -> bool { + !raw.is_empty() && raw.len() <= 15 && raw.bytes().all(|b| b.is_ascii_digit()) +} + +/// Comment id: the issue number in the high bits, the 1-based position in the low 20. +fn comment_id(number: i64, position: usize) -> i64 { + (number << 20) | (position as i64 + 1) +} + +fn split_comment_id(id: i64) -> Option<(i64, usize)> { + let position = (id & 0xF_FFFF) as usize; + let number = id >> 20; + (number > 0 && position > 0).then_some((number, position - 1)) +} + +/// The user object. Only what the downloader and the SDK read; emails are never revealed. +pub fn user_json(base: &str, id: &str, name: &str) -> Value { + json!({ + "id": numeric_id(id), + "login": name, + "username": name, + "login_name": "", + "full_name": "", + "email": "", + "avatar_url": "", + "html_url": format!("{}/{}", base.trim_end_matches('/'), name), + "is_admin": false, + }) +} + +/// One value of the query string. +fn query_value(cx: &Cx, key: &str) -> Option { + let query = uri(cx).query()?; + form_urlencoded::parse(query.as_bytes()) + .find(|(k, _)| k == key) + .map(|(_, v)| v.into_owned()) +} + +/// The headers with `?access_token=` or `?token=` folded into an `Authorization` header when the +/// request carries none, so every Gitea auth style reaches the same code. +fn effective_headers(cx: &Cx) -> HeaderMap { + let mut map = headers(cx).clone(); + if !map.contains_key(AUTHORIZATION) + && let Some(token) = query_value(cx, "access_token").or_else(|| query_value(cx, "token")) + && let Ok(value) = HeaderValue::from_str(&format!("token {token}")) + { + map.insert(AUTHORIZATION, value); + } + map +} + +/// Who is asking, and the raw token they used (for the clone URL of a private repo). +async fn caller(cx: &Cx) -> Result<(Option, Option), Refusal> { + let state = app_context::(cx); + let map = effective_headers(cx); + let actor = api::authenticate(state, client_ip(cx), &map).await?; + let token = api::presented_token(&map).flatten(); + Ok((actor, token)) +} + +struct Ctx { + repo: CoreRepo, + token: Option, + base: String, +} + +async fn read_ctx(cx: &Cx) -> Result { + let state = app_context::(cx); + let (actor, token) = caller(cx).await?; + let repo = api::load_repo( + state, + actor.as_ref(), + path_param::(cx), + path_param::(cx), + Action::Read, + ) + .await?; + Ok(Ctx { + repo, + token: actor.and(token), + base: state.config.base_url.trim_end_matches('/').to_owned(), + }) +} + +fn bad(message: &str) -> Refusal { + Box::new(api::error(StatusCode::BAD_REQUEST, message)) +} + +fn not_found(what: &str) -> Refusal { + Box::new(api::error(StatusCode::NOT_FOUND, what)) +} + +/// `page` and `limit` of the request. `default_limit` applies when `limit` is absent; an explicit +/// one is capped at [`MAX_PAGE`]. +pub struct Paging { + pub page: usize, + pub limit: usize, +} + +pub fn paging(cx: &Cx, default_limit: usize) -> Paging { + let number = |key: &str| query_value(cx, key).and_then(|v| v.parse::().ok()); + Paging { + page: number("page").filter(|p| *p > 0).unwrap_or(1), + limit: number("limit") + .filter(|l| *l > 0) + .map_or(default_limit, |l| l.min(MAX_PAGE)), + } +} + +/// The slice of `items` for this page, and the total. +pub fn slice(items: Vec, pg: &Paging) -> (Vec, usize) { + let total = items.len(); + let start = pg.page.saturating_sub(1).saturating_mul(pg.limit); + ( + items.into_iter().skip(start).take(pg.limit).collect(), + total, + ) +} + +/// A 200 JSON array with `X-Total-Count` and a `Link` header (next, prev, first, last). +pub fn page_response(cx: &Cx, items: Vec, total: usize, pg: &Paging) -> Response { + let mut res = api::json(StatusCode::OK, &Value::Array(items)); + let last = total.div_ceil(pg.limit.max(1)).max(1); + let state = app_context::(cx); + let base = state.config.base_url.trim_end_matches('/'); + let mut rest = String::new(); + if let Some(query) = uri(cx).query() { + for (k, v) in form_urlencoded::parse(query.as_bytes()) { + if k != "page" && k != "limit" { + rest.push_str(&format!( + "{}={}&", + form_urlencoded::byte_serialize(k.as_bytes()).collect::(), + form_urlencoded::byte_serialize(v.as_bytes()).collect::() + )); + } + } + } + let link = |page: usize, rel: &str| { + format!( + "<{base}{}?{rest}page={page}&limit={}>; rel=\"{rel}\"", + uri(cx).path(), + pg.limit + ) + }; + let mut links = Vec::new(); + if pg.page < last { + links.push(link(pg.page + 1, "next")); + links.push(link(last, "last")); + } + if pg.page > 1 { + links.push(link(pg.page - 1, "prev")); + links.push(link(1, "first")); + } + let map = res.headers_mut(); + map.insert( + HeaderName::from_static("x-total-count"), + HeaderValue::from(total), + ); + if !links.is_empty() + && let Ok(value) = HeaderValue::from_str(&links.join(", ")) + { + map.insert(HeaderName::from_static("link"), value); + } + map.insert( + HeaderName::from_static("access-control-expose-headers"), + HeaderValue::from_static("Link, X-Total-Count"), + ); + res +} + +fn internal(e: impl std::fmt::Display) -> Refusal { + api::internal(e) +} + +#[route(GET "/api/v1/version")] +async fn version_route(_cx: &Cx) -> topcoat::Result { + Ok(api::json( + StatusCode::OK, + &json!({ "version": GITEA_VERSION }), + )) +} + +#[route(GET "/api/v1/settings/api")] +async fn settings_api(_cx: &Cx) -> topcoat::Result { + Ok(api::json( + StatusCode::OK, + &json!({ + "max_response_items": MAX_PAGE, + "default_paging_num": DEFAULT_PAGE, + "default_git_trees_per_page": 1000, + "default_max_blob_size": 10_485_760, + }), + )) +} + +/// The clone URL; a private repo read with a token carries the token as the password so the +/// server doing the migration can clone with it (git here accepts `oauth2` as the user name). +fn clone_url(base: &str, repo: &CoreRepo, token: Option<&str>) -> String { + let plain = format!("{base}/{}/{}.git", repo.owner_name, repo.name); + match (repo.visibility, token) { + (Visibility::Private, Some(token)) => match plain.split_once("://") { + Some((scheme, rest)) => format!("{scheme}://oauth2:{token}@{rest}"), + None => plain, + }, + _ => plain, + } +} + +/// The Gitea repository object. `token` embeds credentials in `clone_url` for private repos. +pub async fn repo_json( + state: &AppState, + base: &str, + repo: &CoreRepo, + token: Option<&str>, +) -> Result { + let empty = repo.default_branch.is_empty(); + let ssh_host = &state.config.ssh_public_host; + Ok(json!({ + "id": numeric_id(&repo.id), + "owner": user_json(base, &repo.owner_id, &repo.owner_name), + "name": repo.name, + "full_name": format!("{}/{}", repo.owner_name, repo.name), + "description": repo.description, + "empty": empty, + "private": repo.visibility == Visibility::Private, + "fork": repo.fork_of.is_some(), + "template": false, + "mirror": false, + "archived": repo.archived, + "website": "", + "html_url": format!("{base}/{}/{}", repo.owner_name, repo.name), + "clone_url": clone_url(base, repo, token), + "ssh_url": format!("git@{ssh_host}:{}/{}.git", repo.owner_name, repo.name), + "original_url": "", + "default_branch": repo.default_branch, + "avatar_url": "", + "has_issues": true, + "has_pull_requests": true, + "has_wiki": true, + "has_releases": true, + "created_at": repo.created_at, + "updated_at": repo.created_at, + })) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}")] +async fn get_repo(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + match repo_json(state, &ctx.base, &ctx.repo, ctx.token.as_deref()).await { + Ok(value) => Ok(api::json(StatusCode::OK, &value)), + Err(res) => Ok(*res), + } +} + +/// Forge repos have no topics yet; the list is empty. +#[route(GET "/api/v1/repos/{owner}/{repo}/topics")] +async fn topics_route(cx: &Cx) -> topcoat::Result { + match read_ctx(cx).await { + Ok(_) => Ok(api::json(StatusCode::OK, &json!({ "topics": [] }))), + Err(res) => Ok(*res), + } +} + +fn label_json(base: &str, repo: &CoreRepo, label: &Label) -> Value { + json!({ + "id": numeric_id(&label.id), + "name": label.name, + "exclusive": false, + "is_archived": false, + "color": label.color.trim_start_matches('#'), + "description": label.description, + "url": format!("{base}/api/v1/repos/{}/{}/labels/{}", repo.owner_name, repo.name, numeric_id(&label.id)), + }) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/labels")] +async fn list_labels_route(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let all = match state.store.list_labels(&ctx.repo.id).await { + Ok(all) => all, + Err(e) => return Ok(*internal(e)), + }; + let pg = paging(cx, DEFAULT_PAGE); + let (page, total) = slice(all, &pg); + let items = page + .iter() + .map(|l| label_json(&ctx.base, &ctx.repo, l)) + .collect(); + Ok(page_response(cx, items, total, &pg)) +} + +fn date_time(date: &str) -> String { + if date.len() == 10 { + format!("{date}T00:00:00Z") + } else { + date.to_owned() + } +} + +fn milestone_json(m: &Milestone) -> Value { + json!({ + "id": numeric_id(&m.id), + "title": m.title, + "description": m.description, + "state": m.state.as_str(), + "open_issues": m.open_issues, + "closed_issues": m.closed_issues, + "created_at": m.created_at, + "updated_at": m.closed_at.clone().unwrap_or_else(|| m.created_at.clone()), + "closed_at": m.closed_at, + "due_on": m.due_on.as_deref().map(date_time), + }) +} + +/// `state` of a Gitea list: `open` (the default), `closed` or `all`. +fn state_filter(cx: &Cx) -> Result, Refusal> { + match query_value(cx, "state").as_deref() { + None | Some("") | Some("open") => Ok(Some(IssueState::Open)), + Some("closed") => Ok(Some(IssueState::Closed)), + Some("all") => Ok(None), + Some(other) => Err(bad(&format!("unknown state {other:?}"))), + } +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/milestones")] +async fn list_milestones_route(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let wanted = match state_filter(cx) { + Ok(wanted) => wanted, + Err(res) => return Ok(*res), + }; + let all = match state.store.list_milestones(&ctx.repo.id, wanted).await { + Ok(all) => all, + Err(e) => return Ok(*internal(e)), + }; + let pg = paging(cx, DEFAULT_PAGE); + let (page, total) = slice(all, &pg); + let items = page.iter().map(milestone_json).collect(); + Ok(page_response(cx, items, total, &pg)) +} + +/// Usernames by user id, with `ghost` for an id that no longer resolves. +async fn names(state: &AppState, ids: Vec) -> Result, Refusal> { + let found = state.store.usernames_by_ids(&ids).await.map_err(internal)?; + Ok(found + .into_iter() + .map(|(id, (name, _))| (id, name)) + .collect()) +} + +fn user_of(base: &str, names: &HashMap, id: &str) -> Value { + let name = names.get(id).map_or("ghost", String::as_str); + user_json(base, id, name) +} + +/// Shared by issues and pull requests: the fields both lists carry. +async fn issue_core( + state: &AppState, + ctx: &Ctx, + item: &IssueListItem, + milestones: &HashMap, + pull: bool, +) -> Result { + let issue = &item.issue; + let assignees = state + .store + .issue_assignees(&issue.id) + .await + .map_err(internal)?; + let assignees: Vec = assignees + .iter() + .map(|(id, name)| user_json(&ctx.base, id, name)) + .collect(); + let url = format!( + "{}/{}/{}/{}/{}", + ctx.base, + ctx.repo.owner_name, + ctx.repo.name, + if pull { "pulls" } else { "issues" }, + issue.number + ); + Ok(json!({ + "id": numeric_id(&issue.id), + "number": issue.number, + "user": user_json(&ctx.base, &issue.author_id, &item.author), + "title": issue.title, + "body": issue.body, + "labels": item.labels.iter().map(|l| label_json(&ctx.base, &ctx.repo, l)).collect::>(), + "milestone": issue.milestone_id.as_ref().and_then(|m| milestones.get(m)).map(milestone_json), + "assignee": assignees.first(), + "assignees": assignees, + "state": issue.state.as_str(), + "is_locked": issue.locked, + "comments": issue.comment_count, + "created_at": issue.created_at, + "updated_at": issue.updated_at, + "closed_at": issue.closed_at, + "due_date": null, + "html_url": url, + "url": format!("{}/api/v1/repos/{}/{}/issues/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, issue.number), + "pull_request": if pull { json!({"merged": false, "merged_at": null, "html_url": url}) } else { Value::Null }, + })) +} + +async fn milestone_map( + state: &AppState, + repo: &CoreRepo, +) -> Result, Refusal> { + let all = state + .store + .list_milestones(&repo.id, None) + .await + .map_err(internal)?; + Ok(all.into_iter().map(|m| (m.id.clone(), m)).collect()) +} + +fn filter_of(cx: &Cx, pg: &Paging) -> Result { + Ok(IssueFilter { + state: state_filter(cx)?, + sort: IssueSort::Oldest, + page: pg.page as u32, + per_page: pg.limit as u32, + ..IssueFilter::default() + }) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/issues")] +async fn list_issues_route(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + match issues_inner(cx, state, &ctx).await { + Ok(res) => Ok(res), + Err(res) => Ok(*res), + } +} + +async fn issues_inner(cx: &Cx, state: &AppState, ctx: &Ctx) -> Result { + let pg = paging(cx, DEFAULT_PAGE); + let filter = filter_of(cx, &pg)?; + let pulls = query_value(cx, "type").as_deref() == Some("pulls"); + let (rows, total) = if pulls { + state.store.list_pulls(&ctx.repo.id, &filter).await + } else { + state.store.list_issues(&ctx.repo.id, &filter).await + } + .map_err(internal)?; + let milestones = milestone_map(state, &ctx.repo).await?; + let mut out = Vec::with_capacity(rows.len()); + for item in &rows { + out.push(issue_core(state, ctx, item, &milestones, pulls).await?); + } + Ok(page_response(cx, out, total as usize, &pg)) +} + +/// The issue or pull request row with this number. +async fn issue_row( + state: &AppState, + repo: &CoreRepo, + raw: &str, +) -> Result { + let number: i64 = raw.parse().map_err(|_| bad("invalid issue index"))?; + match state.store.issue_by_number(&repo.id, number).await { + Ok(Some(issue)) => Ok(issue), + Ok(None) => Err(not_found("issue not found")), + Err(e) => Err(internal(e)), + } +} + +fn comment_json( + ctx: &Ctx, + issue_number: i64, + position: usize, + comment: &Comment, + names: &HashMap, +) -> Value { + let id = comment_id(issue_number, position); + let issue_url = format!( + "{}/{}/{}/issues/{issue_number}", + ctx.base, ctx.repo.owner_name, ctx.repo.name + ); + json!({ + "id": id, + "html_url": format!("{issue_url}#comment-{id}"), + "issue_url": issue_url, + "pull_request_url": "", + "user": user_of(&ctx.base, names, &comment.author_id), + "original_author": "", + "original_author_id": 0, + "body": comment.body, + "created_at": comment.created_at, + "updated_at": comment.updated_at, + }) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")] +async fn issue_comments(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let result: Result = async { + let issue = issue_row(state, &ctx.repo, path_param::(cx)).await?; + let all = state + .store + .list_comments(&issue.id) + .await + .map_err(internal)?; + let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect(); + let pg = paging(cx, DEFAULT_PAGE); + let (page, total) = slice(numbered, &pg); + let authors = names( + state, + page.iter().map(|(_, c)| c.author_id.clone()).collect(), + ) + .await?; + let items = page + .iter() + .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors)) + .collect(); + Ok(page_response(cx, items, total, &pg)) + } + .await; + Ok(result.unwrap_or_else(|res| *res)) +} + +/// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji. +async fn reactions_json( + state: &AppState, + ctx: &Ctx, + kind: ReactionTarget, + target_id: &str, + created_at: &str, +) -> Result, Refusal> { + let map = state + .store + .reactions_for(kind, &[target_id.to_owned()], None) + .await + .map_err(internal)?; + let mut out = Vec::new(); + for summary in map.get(target_id).into_iter().flatten() { + for username in &summary.users { + let id = match state.store.user_by_username(username).await { + Ok(Some(user)) => user.id, + _ => continue, + }; + out.push(json!({ + "user": user_json(&ctx.base, &id, username), + "reaction": summary.reaction.name(), + "created_at": created_at, + })); + } + } + Ok(out) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")] +async fn issue_reactions(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let result: Result = async { + let issue = issue_row(state, &ctx.repo, path_param::(cx)).await?; + let all = reactions_json( + state, + &ctx, + ReactionTarget::Issue, + &issue.id, + &issue.created_at, + ) + .await?; + let pg = paging(cx, 1000); + let (page, total) = slice(all, &pg); + Ok(page_response(cx, page, total, &pg)) + } + .await; + Ok(result.unwrap_or_else(|res| *res)) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")] +async fn comment_reactions(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let result: Result = async { + let id: i64 = path_param::(cx) + .parse() + .map_err(|_| bad("invalid comment id"))?; + let (number, position) = + split_comment_id(id).ok_or_else(|| not_found("comment not found"))?; + let issue = issue_row(state, &ctx.repo, &number.to_string()).await?; + let all = state + .store + .list_comments(&issue.id) + .await + .map_err(internal)?; + let comment = all + .get(position) + .ok_or_else(|| not_found("comment not found"))?; + let items = reactions_json( + state, + &ctx, + ReactionTarget::Comment, + &comment.id, + &comment.created_at, + ) + .await?; + let pg = paging(cx, 1000); + let (page, total) = slice(items, &pg); + Ok(page_response(cx, page, total, &pg)) + } + .await; + Ok(result.unwrap_or_else(|res| *res)) +} + +fn pr_branch( + ctx: &Ctx, + label_owner: &str, + repo: Option<&CoreRepo>, + branch: &str, + sha: &str, +) -> Value { + json!({ + "label": format!("{label_owner}:{branch}"), + "ref": branch, + "sha": sha, + "repo_id": repo.map(|r| numeric_id(&r.id)), + "repo": repo.map(|r| json!({ + "id": numeric_id(&r.id), + "owner": user_json(&ctx.base, &r.owner_id, &r.owner_name), + "name": r.name, + "full_name": format!("{}/{}", r.owner_name, r.name), + "private": r.visibility == Visibility::Private, + "html_url": format!("{}/{}/{}", ctx.base, r.owner_name, r.name), + "clone_url": format!("{}/{}/{}.git", ctx.base, r.owner_name, r.name), + "default_branch": r.default_branch, + })), + }) +} + +async fn pull_json( + state: &AppState, + ctx: &Ctx, + item: &IssueListItem, + pull: &PullRequest, + milestones: &HashMap, +) -> Result { + let mut value = issue_core(state, ctx, item, milestones, true).await?; + let head_repo = match &pull.head_repo_id { + Some(id) if *id == ctx.repo.id => Some(ctx.repo.clone()), + Some(id) => state.store.repo_by_id(id).await.map_err(internal)?, + None => None, + }; + // A head repo the caller cannot read is shown without its repo object. + let head_repo = match head_repo { + Some(r) if r.id == ctx.repo.id || r.visibility == Visibility::Public => Some(r), + _ => None, + }; + let head_owner = head_repo + .as_ref() + .map_or(ctx.repo.owner_name.as_str(), |r| r.owner_name.as_str()); + let merged_by = match &pull.merged_by { + Some(id) => state + .store + .usernames_by_ids(std::slice::from_ref(id)) + .await + .map_err(internal)? + .get(id) + .map(|(name, _)| user_json(&ctx.base, id, name)), + None => None, + }; + let html = format!( + "{}/{}/{}/pulls/{}", + ctx.base, ctx.repo.owner_name, ctx.repo.name, pull.issue.number + ); + let obj = value.as_object_mut().expect("object"); + obj.insert("merged".into(), json!(pull.merged_at.is_some())); + obj.insert("merged_at".into(), json!(pull.merged_at)); + obj.insert("merged_by".into(), json!(merged_by)); + obj.insert("merge_commit_sha".into(), json!(pull.merge_commit)); + obj.insert("merged_commit_id".into(), json!(pull.merge_commit)); + obj.insert("merge_base".into(), json!(pull.merge_base)); + obj.insert( + "mergeable".into(), + json!(matches!( + pull.mergeable, + forge_core::pulls::Mergeable::Clean + )), + ); + obj.insert("draft".into(), json!(pull.draft)); + obj.insert("allow_maintainer_edit".into(), json!(false)); + obj.insert("diff_url".into(), json!(format!("{html}.diff"))); + obj.insert("patch_url".into(), json!(format!("{html}.patch"))); + obj.insert("flow".into(), json!(0)); + obj.insert( + "base".into(), + pr_branch( + ctx, + &ctx.repo.owner_name, + Some(&ctx.repo), + &pull.base_branch, + &pull.base_oid, + ), + ); + obj.insert( + "head".into(), + pr_branch( + ctx, + head_owner, + head_repo.as_ref(), + &pull.head_branch, + &pull.head_oid, + ), + ); + obj.insert( + "pull_request".into(), + json!({"merged": pull.merged_at.is_some(), "merged_at": pull.merged_at, "html_url": html}), + ); + Ok(value) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/pulls")] +async fn list_pulls_route(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let result: Result = async { + let pg = paging(cx, DEFAULT_PAGE); + let filter = filter_of(cx, &pg)?; + let (rows, total) = state + .store + .list_pulls(&ctx.repo.id, &filter) + .await + .map_err(internal)?; + let milestones = milestone_map(state, &ctx.repo).await?; + let mut out = Vec::with_capacity(rows.len()); + for item in &rows { + let Some(pull) = state + .store + .pull_by_number(&ctx.repo.id, item.issue.number) + .await + .map_err(internal)? + else { + continue; + }; + out.push(pull_json(state, &ctx, item, &pull, &milestones).await?); + } + Ok(page_response(cx, out, total as usize, &pg)) + } + .await; + Ok(result.unwrap_or_else(|res| *res)) +} + +fn review_state(review: &Review) -> &'static str { + let effective = if review.state == ReviewState::Dismissed { + review.dismissed_from.unwrap_or(ReviewState::Commented) + } else { + review.state + }; + match effective { + ReviewState::Approved => "APPROVED", + ReviewState::ChangesRequested => "REQUEST_CHANGES", + ReviewState::Pending => "PENDING", + ReviewState::Commented | ReviewState::Dismissed => "COMMENT", + } +} + +fn review_json(ctx: &Ctx, number: i64, review: &Review, comment_count: usize) -> Value { + let html = format!( + "{}/{}/{}/pulls/{number}", + ctx.base, ctx.repo.owner_name, ctx.repo.name + ); + json!({ + "id": numeric_id(&review.id), + "user": user_json(&ctx.base, &review.author_id, &review.author_name), + "team": null, + "state": review_state(review), + "body": review.body, + "commit_id": review.commit_oid, + "stale": false, + "official": matches!(review_state(review), "APPROVED" | "REQUEST_CHANGES"), + "dismissed": review.state == ReviewState::Dismissed, + "comments_count": comment_count, + "submitted_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()), + "updated_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()), + "html_url": format!("{html}#{}", numeric_id(&review.id)), + "pull_request_url": html, + }) +} + +/// Every non-pending review comment of the pull request, roots and replies, oldest first. +async fn review_comments(state: &AppState, issue_id: &str) -> Result, Refusal> { + let threads = state + .store + .review_threads(issue_id, None) + .await + .map_err(internal)?; + let mut all: Vec = threads + .into_iter() + .flat_map(|t| std::iter::once(t.root).chain(t.replies)) + .filter(|c| !c.pending) + .collect(); + all.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id))); + Ok(all) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")] +async fn pull_reviews(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let result: Result = async { + let issue = pull_issue(state, &ctx.repo, path_param::(cx)).await?; + let reviews = state + .store + .list_reviews(&issue.id) + .await + .map_err(internal)?; + let comments = review_comments(state, &issue.id).await?; + let pg = paging(cx, DEFAULT_PAGE); + let (page, total) = slice(reviews, &pg); + let items = page + .iter() + .map(|r| { + let count = comments.iter().filter(|c| c.review_id == r.id).count(); + review_json(&ctx, issue.number, r, count) + }) + .collect(); + Ok(page_response(cx, items, total, &pg)) + } + .await; + Ok(result.unwrap_or_else(|res| *res)) +} + +/// The issue row of a number that must be a pull request. +async fn pull_issue( + state: &AppState, + repo: &CoreRepo, + raw: &str, +) -> Result { + let number: i64 = raw.parse().map_err(|_| bad("invalid pull request index"))?; + match state.store.pull_by_number(&repo.id, number).await { + Ok(Some(pull)) => Ok(pull.issue), + Ok(None) => Err(not_found("pull request not found")), + Err(e) => Err(internal(e)), + } +} + +fn review_comment_json(ctx: &Ctx, number: i64, c: &ReviewComment) -> Value { + let html = format!( + "{}/{}/{}/pulls/{number}", + ctx.base, ctx.repo.owner_name, ctx.repo.name + ); + let (line, old_line) = match c.side { + Side::New => (c.line, 0), + Side::Old => (0, c.line), + }; + json!({ + "id": numeric_id(&c.id), + "body": c.body, + "user": user_json(&ctx.base, &c.author_id, &c.author_name), + "resolver": null, + "pull_request_review_id": numeric_id(&c.review_id), + "created_at": c.created_at, + "updated_at": c.updated_at, + "path": c.path, + "commit_id": c.commit_oid, + "original_commit_id": c.commit_oid, + "diff_hunk": c.diff_hunk, + "position": line, + "original_position": line, + "line_num": line, + "old_line_num": old_line, + "html_url": format!("{html}#{}", numeric_id(&c.id)), + "pull_request_url": html, + }) +} + +#[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")] +async fn pull_review_comments(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let ctx = match read_ctx(cx).await { + Ok(ctx) => ctx, + Err(res) => return Ok(*res), + }; + let result: Result = async { + let issue = pull_issue(state, &ctx.repo, path_param::(cx)).await?; + let raw = path_param::(cx); + let reviews = state + .store + .list_reviews(&issue.id) + .await + .map_err(internal)?; + let review = reviews + .iter() + .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id)))) + .ok_or_else(|| not_found("review not found"))?; + let own: Vec = review_comments(state, &issue.id) + .await? + .into_iter() + .filter(|c| c.review_id == review.id) + .collect(); + let items = own + .iter() + .map(|c| review_comment_json(&ctx, issue.number, c)) + .collect::>(); + let total = items.len(); + // Review comments are not paged by the downloader; return them whole. + let pg = Paging { + page: 1, + limit: total.max(1), + }; + Ok(page_response(cx, items, total, &pg)) + } + .await; + Ok(result.unwrap_or_else(|res| *res)) +} diff --git a/crates/forge-web/src/api/gitea_tests.rs b/crates/forge-web/src/api/gitea_tests.rs new file mode 100644 index 0000000..f8b3deb --- /dev/null +++ b/crates/forge-web/src/api/gitea_tests.rs @@ -0,0 +1,566 @@ +//! Tests of the Gitea compatible read routes (api/gitea.rs). Each one asserts the JSON fields the +//! Forgejo Gitea downloader reads, plus the pagination headers and the token rules. + +use std::path::{Path, PathBuf}; + +use base64::prelude::{BASE64_STANDARD, Engine}; +use forge_core::reactions::{Reaction, ReactionTarget}; +use forge_core::reviews::{ReviewState, Side}; +use forge_core::token::{generate_token, hash_token}; +use forge_core::{Role, Store, Visibility}; +use forge_git::repo::{init_bare, repo_path}; +use http::HeaderMap; +use http::header::{AUTHORIZATION, CONTENT_TYPE}; +use serde_json::Value; +use topcoat::router::request::Request; +use topcoat::router::{Body, Router, to_bytes}; + +use crate::test_support::{app_router, test_state}; + +const OWNER: &str = "tahinli"; +const REPO: &str = "proj"; + +fn git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .current_dir(dir) + .args(args) + .env("GIT_AUTHOR_NAME", "test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .output() + .expect("git runs"); + assert!(out.status.success(), "git {args:?} failed"); + String::from_utf8_lossy(&out.stdout).trim().to_owned() +} + +struct Fixture { + _tmp: tempfile::TempDir, + router: Router, + owner_token: String, + bob_token: String, + carol_token: String, + oid: String, +} + +async fn token_for(store: &Store, user_id: &str) -> String { + let raw = generate_token(); + store + .create_token( + user_id, + "test", + &hash_token(&raw), + &["repo".to_owned()], + None, + ) + .await + .expect("token"); + raw +} + +async fn seed_git(state: &crate::state::AppState, tmp: &Path, repo_id: &str) -> String { + let bare: PathBuf = repo_path(&state.git.data_dir, repo_id).expect("repo path"); + init_bare(&state.git, &bare, "main").await.expect("init"); + let work = tmp.join(format!("work-{repo_id}")); + git(tmp, &["init", "-b", "main", work.to_str().expect("utf8")]); + std::fs::write(work.join("file.txt"), "one").expect("write"); + git(&work, &["add", "file.txt"]); + git(&work, &["commit", "-m", "one"]); + git(&work, &["push", bare.to_str().expect("utf8"), "main"]); + git(&work, &["rev-parse", "HEAD"]) +} + +/// `tahinli/proj` is public with an issue (label, milestone, assignee, two comments, reactions), +/// a pull request with one review and one line comment, and a release with one asset. +/// `tahinli/secret` is private; bob can read `proj` only, carol nothing. +async fn fixture() -> Fixture { + let tmp = tempfile::tempdir().expect("tempdir"); + let state = test_state(tmp.path()).await; + let store = state.store.clone(); + let owner = store + .create_user(OWNER, None, "x", false) + .await + .expect("owner"); + let bob = store + .create_user("bob", None, "x", false) + .await + .expect("bob"); + let carol = store + .create_user("carol", None, "x", false) + .await + .expect("carol"); + let repo = store + .create_repo(&owner.id, REPO, "A project", Visibility::Public, "main") + .await + .expect("repo"); + store + .set_collaborator(&repo.id, &bob.id, Role::Read) + .await + .expect("collaborator"); + let secret = store + .create_repo(&owner.id, "secret", "", Visibility::Private, "main") + .await + .expect("secret"); + let oid = seed_git(&state, tmp.path(), &repo.id).await; + seed_git(&state, tmp.path(), &secret.id).await; + + let label = store + .create_label(&repo.id, "bug", "#d73a4a", "Something is broken") + .await + .expect("label"); + let milestone = store + .create_milestone(&repo.id, "v1", "First", Some("2026-12-01")) + .await + .expect("milestone"); + let issue = store + .create_issue(&repo.id, &owner.id, "It breaks", "Steps follow") + .await + .expect("issue"); + store + .set_issue_labels(&issue.id, &owner.id, std::slice::from_ref(&label.id)) + .await + .expect("labels"); + store + .set_issue_milestone(&issue.id, &owner.id, Some(&milestone.id)) + .await + .expect("milestone set"); + store + .set_issue_assignees(&issue.id, &owner.id, &[OWNER.to_owned()]) + .await + .expect("assignees"); + let first = store + .add_comment(&issue.id, &bob.id, "I see it too") + .await + .expect("comment"); + store + .add_comment(&issue.id, &owner.id, "Looking") + .await + .expect("comment 2"); + store + .toggle_reaction(ReactionTarget::Issue, &issue.id, &bob.id, Reaction::Heart) + .await + .expect("issue reaction"); + store + .toggle_reaction( + ReactionTarget::Comment, + &first.id, + &owner.id, + Reaction::PlusOne, + ) + .await + .expect("comment reaction"); + + let pull = store + .create_pull( + &repo.id, + &owner.id, + "Add thing", + "Body", + "main", + &repo.id, + "feature", + &oid, + &oid, + ) + .await + .expect("pull"); + store + .add_review_comment( + &pull.issue.id, + &bob.id, + true, + "file.txt", + Side::New, + 1, + &oid, + "@@ -1 +1 @@", + "nit", + ) + .await + .expect("review comment"); + store + .submit_review( + &pull.issue.id, + &bob.id, + ReviewState::ChangesRequested, + "please fix", + &oid, + ) + .await + .expect("review"); + + let owner_token = token_for(&store, &owner.id).await; + let bob_token = token_for(&store, &bob.id).await; + let carol_token = token_for(&store, &carol.id).await; + let router = app_router(state); + let f = Fixture { + _tmp: tmp, + router, + owner_token, + bob_token, + carol_token, + oid, + }; + + let (status, _, body) = f + .get_with( + "POST", + &format!("/api/v1/repos/{OWNER}/{REPO}/releases"), + Some(&format!("token {}", f.owner_token)), + br#"{"tag":"v1.0","target":"main","title":"One","body":"notes"}"#.to_vec(), + "application/json", + ) + .await; + assert_eq!(status, 201, "{body}"); + let uid = body["uid"].as_str().expect("uid").to_owned(); + let (status, _, body) = f + .get_with( + "PUT", + &format!("/api/v1/repos/{OWNER}/{REPO}/releases/{uid}/assets/app.bin"), + Some(&format!("token {}", f.owner_token)), + b"hello".to_vec(), + "application/octet-stream", + ) + .await; + assert_eq!(status, 201, "{body}"); + f +} + +impl Fixture { + async fn get_with( + &self, + method: &str, + uri: &str, + auth: Option<&str>, + body: Vec, + content_type: &str, + ) -> (u16, HeaderMap, Value) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(auth) = auth { + builder = builder.header(AUTHORIZATION, auth); + } + builder = builder.header(CONTENT_TYPE, content_type); + let res = self + .router + .handle(builder.body(Body::from(body)).unwrap()) + .await; + let status = res.status().as_u16(); + let headers = res.headers().clone(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); + let json = serde_json::from_slice(&bytes).unwrap_or(Value::Null); + (status, headers, json) + } + + /// GET as `tahinli` with the `Authorization: token` style the Gitea SDK sends. + async fn get(&self, path: &str) -> (u16, HeaderMap, Value) { + self.get_with( + "GET", + path, + Some(&format!("token {}", self.owner_token)), + Vec::new(), + "application/json", + ) + .await + } + + async fn get_as(&self, path: &str, auth: Option) -> (u16, HeaderMap, Value) { + self.get_with("GET", path, auth.as_deref(), Vec::new(), "application/json") + .await + } +} + +fn repo_path_of(rest: &str) -> String { + format!("/api/v1/repos/{OWNER}/{REPO}{rest}") +} + +#[tokio::test] +async fn version_and_settings_unlock_every_feature() { + let f = fixture().await; + let (status, _, body) = f.get_as("/api/v1/version", None).await; + assert_eq!(status, 200); + assert_eq!(body["version"], "1.22.0"); + let (status, _, body) = f.get_as("/api/v1/settings/api", None).await; + assert_eq!(status, 200); + assert_eq!(body["max_response_items"], 50); +} + +#[tokio::test] +async fn repo_info_topics_labels_and_milestones() { + let f = fixture().await; + let (status, _, repo) = f.get(&repo_path_of("")).await; + assert_eq!(status, 200); + assert_eq!(repo["name"], REPO); + assert_eq!(repo["owner"]["login"], OWNER); + assert_eq!(repo["private"], false); + assert_eq!(repo["description"], "A project"); + assert_eq!(repo["default_branch"], "main"); + assert_eq!( + repo["clone_url"], + format!("https://forge.test/{OWNER}/{REPO}.git") + ); + assert_eq!( + repo["html_url"], + format!("https://forge.test/{OWNER}/{REPO}") + ); + + let (_, _, topics) = f.get(&repo_path_of("/topics")).await; + assert_eq!(topics["topics"], serde_json::json!([])); + + let (_, headers, labels) = f.get(&repo_path_of("/labels?page=1&limit=10")).await; + let label = labels + .as_array() + .unwrap() + .iter() + .find(|l| l["name"] == "bug") + .unwrap(); + assert_eq!(label["color"], "d73a4a"); + assert_eq!(label["description"], "Something is broken"); + assert!(headers.contains_key("x-total-count")); + + let (_, _, milestones) = f + .get(&repo_path_of("/milestones?state=all&page=1&limit=10")) + .await; + let m = &milestones.as_array().unwrap()[0]; + assert_eq!(m["title"], "v1"); + assert_eq!(m["description"], "First"); + assert_eq!(m["state"], "open"); + assert_eq!(m["due_on"], "2026-12-01T00:00:00Z"); + assert!(m["created_at"].is_string()); +} + +#[tokio::test] +async fn issues_carry_labels_milestone_assignees_and_comments() { + let f = fixture().await; + let (status, headers, issues) = f + .get(&repo_path_of( + "/issues?type=issues&state=all&page=1&limit=10", + )) + .await; + assert_eq!(status, 200); + assert_eq!(headers["x-total-count"], "1"); + let list = issues.as_array().unwrap(); + assert_eq!(list.len(), 1, "pulls are not issues"); + let issue = &list[0]; + assert_eq!(issue["number"], 1); + assert_eq!(issue["title"], "It breaks"); + assert_eq!(issue["body"], "Steps follow"); + assert_eq!(issue["state"], "open"); + assert_eq!(issue["is_locked"], false); + assert_eq!(issue["user"]["login"], OWNER); + assert!(issue["user"]["id"].as_i64().unwrap() > 0); + assert_eq!(issue["labels"][0]["name"], "bug"); + assert_eq!(issue["milestone"]["title"], "v1"); + assert_eq!(issue["assignees"][0]["login"], OWNER); + assert!(issue["created_at"].is_string() && issue["updated_at"].is_string()); + assert!(issue["pull_request"].is_null()); + + let (_, headers, comments) = f + .get(&repo_path_of("/issues/1/comments?page=1&limit=10")) + .await; + assert_eq!(headers["x-total-count"], "2"); + let comments = comments.as_array().unwrap(); + assert_eq!(comments[0]["body"], "I see it too"); + assert_eq!(comments[0]["user"]["login"], "bob"); + assert!(comments[0]["id"].as_i64().unwrap() > 0); + assert!(comments[0]["created_at"].is_string() && comments[0]["updated_at"].is_string()); + assert_ne!(comments[0]["id"], comments[1]["id"]); + + let (_, _, reactions) = f.get(&repo_path_of("/issues/1/reactions")).await; + assert_eq!(reactions[0]["reaction"], "heart"); + assert_eq!(reactions[0]["user"]["login"], "bob"); + + let id = comments[0]["id"].as_i64().unwrap(); + let (status, _, reactions) = f + .get(&repo_path_of(&format!("/issues/comments/{id}/reactions"))) + .await; + assert_eq!(status, 200); + assert_eq!(reactions[0]["reaction"], "+1"); + assert_eq!(reactions[0]["user"]["login"], OWNER); +} + +#[tokio::test] +async fn pagination_headers_and_link() { + let f = fixture().await; + let (status, headers, items) = f + .get(&repo_path_of("/issues/1/comments?page=2&limit=1")) + .await; + assert_eq!(status, 200); + assert_eq!(headers["x-total-count"], "2"); + assert_eq!(items.as_array().unwrap().len(), 1); + assert_eq!(items[0]["body"], "Looking"); + let link = headers["link"].to_str().unwrap(); + assert!( + link.contains("rel=\"prev\"") && link.contains("rel=\"first\""), + "{link}" + ); + assert!(!link.contains("rel=\"next\""), "{link}"); + assert!(link.contains("https://forge.test/api/v1/repos/tahinli/proj/issues/1/comments?")); + + let (_, headers, items) = f + .get(&repo_path_of("/issues/1/comments?page=1&limit=1")) + .await; + assert_eq!(items.as_array().unwrap().len(), 1); + let link = headers["link"].to_str().unwrap(); + assert!( + link.contains("rel=\"next\"") && link.contains("rel=\"last\""), + "{link}" + ); + + // Past the last page the list is empty, which ends the downloader's loop. + let (_, _, items) = f + .get(&repo_path_of("/issues/1/comments?page=3&limit=1")) + .await; + assert_eq!(items.as_array().unwrap().len(), 0); +} + +#[tokio::test] +async fn pulls_reviews_and_review_comments() { + let f = fixture().await; + let (status, headers, pulls) = f + .get(&repo_path_of("/pulls?state=all&page=1&limit=10")) + .await; + assert_eq!(status, 200); + assert_eq!(headers["x-total-count"], "1"); + let pr = &pulls[0]; + assert_eq!(pr["number"], 2); + assert_eq!(pr["title"], "Add thing"); + assert_eq!(pr["state"], "open"); + assert_eq!(pr["merged"], false); + assert_eq!(pr["user"]["login"], OWNER); + assert_eq!(pr["head"]["ref"], "feature"); + assert_eq!(pr["head"]["sha"], f.oid); + assert_eq!(pr["head"]["repo"]["owner"]["login"], OWNER); + assert_eq!( + pr["head"]["repo"]["clone_url"], + format!("https://forge.test/{OWNER}/{REPO}.git") + ); + assert_eq!(pr["base"]["ref"], "main"); + assert_eq!(pr["base"]["sha"], f.oid); + assert!(pr["created_at"].is_string() && pr["updated_at"].is_string()); + + let (status, _, reviews) = f + .get(&repo_path_of("/pulls/2/reviews?page=1&limit=10")) + .await; + assert_eq!(status, 200); + let review = &reviews[0]; + assert_eq!(review["state"], "REQUEST_CHANGES"); + assert_eq!(review["body"], "please fix"); + assert_eq!(review["user"]["login"], "bob"); + assert_eq!(review["commit_id"], f.oid); + assert_eq!(review["official"], true); + assert!(review["submitted_at"].is_string()); + let review_id = review["id"].as_i64().unwrap(); + + let (status, _, comments) = f + .get(&repo_path_of(&format!( + "/pulls/2/reviews/{review_id}/comments" + ))) + .await; + assert_eq!(status, 200); + let c = &comments[0]; + assert_eq!(c["body"], "nit"); + assert_eq!(c["path"], "file.txt"); + assert_eq!(c["diff_hunk"], "@@ -1 +1 @@"); + assert_eq!(c["line_num"], 1); + assert_eq!(c["old_line_num"], 0); + assert_eq!(c["commit_id"], f.oid); + assert_eq!(c["user"]["login"], "bob"); + assert_eq!(c["pull_request_review_id"], review_id); + + // An issue number is not a pull request. + let (status, _, _) = f.get(&repo_path_of("/pulls/1/reviews")).await; + assert_eq!(status, 404); +} + +#[tokio::test] +async fn releases_and_assets_in_gitea_shape() { + let f = fixture().await; + let (status, headers, releases) = f.get(&repo_path_of("/releases?page=1&limit=10")).await; + assert_eq!(status, 200); + assert_eq!(headers["x-total-count"], "1"); + let release = &releases[0]; + assert!(release["id"].as_i64().unwrap() > 0); + assert_eq!(release["tag_name"], "v1.0"); + assert_eq!(release["name"], "One"); + assert_eq!(release["body"], "notes"); + assert_eq!(release["draft"], false); + assert_eq!(release["prerelease"], false); + assert_eq!(release["target_commitish"], f.oid); + assert_eq!(release["author"]["login"], OWNER); + assert!(release["created_at"].is_string() && release["published_at"].is_string()); + let asset = &release["assets"][0]; + assert_eq!(asset["name"], "app.bin"); + assert_eq!(asset["size"], 5); + assert_eq!(asset["download_count"], 0); + let url = asset["browser_download_url"].as_str().unwrap(); + assert_eq!( + url, + "https://forge.test/tahinli/proj/releases/download/v1.0/app.bin" + ); + + let rid = release["id"].as_i64().unwrap(); + let aid = asset["id"].as_i64().unwrap(); + let (status, _, one) = f + .get(&repo_path_of(&format!("/releases/{rid}/assets/{aid}"))) + .await; + assert_eq!(status, 200); + assert_eq!(one["name"], "app.bin"); + assert_eq!(one["browser_download_url"], url); +} + +#[tokio::test] +async fn private_repos_follow_the_token() { + let f = fixture().await; + let secret = "/api/v1/repos/tahinli/secret"; + let (status, _, _) = f.get_as(secret, None).await; + assert_eq!(status, 401, "anonymous"); + let (status, _, _) = f + .get_as(secret, Some(format!("token {}", f.carol_token))) + .await; + assert_eq!(status, 404, "a user without access"); + let (status, _, _) = f + .get_as(secret, Some(format!("token {}", f.bob_token))) + .await; + assert_eq!(status, 404, "a reader of another repo"); + + // The owner may use any of the three styles Gitea clients send. + let token = f.owner_token.clone(); + let basic = format!( + "Basic {}", + BASE64_STANDARD.encode(format!("whoever:{token}")) + ); + for auth in [format!("token {token}"), format!("Bearer {token}"), basic] { + let (status, _, repo) = f.get_as(secret, Some(auth.clone())).await; + assert_eq!(status, 200, "{auth}"); + assert_eq!(repo["private"], true); + // The clone URL carries the token so the migrating server can clone. + let clone = repo["clone_url"].as_str().unwrap(); + assert_eq!( + clone, + format!("https://oauth2:{token}@forge.test/tahinli/secret.git") + ); + } + let (status, _, repo) = f + .get_as(&format!("{secret}?access_token={token}"), None) + .await; + assert_eq!(status, 200); + assert_eq!(repo["name"], "secret"); + + // A bad token is refused, not treated as anonymous. + let (status, _, _) = f + .get_as(&repo_path_of(""), Some("token forge_nope".into())) + .await; + assert_eq!(status, 401); +} + +#[tokio::test] +async fn release_asset_downloads_with_a_token() { + let f = fixture().await; + let path = "/tahinli/proj/releases/download/v1.0/app.bin"; + let owner = f.owner_token.clone(); + let basic = format!("Basic {}", BASE64_STANDARD.encode(format!("x:{owner}"))); + let (status, _, _) = f.get_as(path, Some(basic)).await; + assert_eq!(status, 200); + let (status, _, _) = f.get_as(path, Some("token forge_nope".into())).await; + assert_eq!(status, 401); +} diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web/src/api/mod.rs index 0cf901e..a09b4f5 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web/src/api/mod.rs @@ -1,9 +1,13 @@ //! Our own small JSON API under `/api/v1`. Authentication is by personal access token only: -//! `Authorization: Bearer forge_...` or `Authorization: token forge_...`. Session cookies are never +//! `Authorization: Bearer forge_...` or `Authorization: token forge_...`, or, for Gitea clients, Basic auth +//! with the token as the password or `?access_token=` on the Gitea routes. Session cookies are never //! read here, so a browser cannot drive these routes and CSRF protection does not apply. Errors are //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot //! use a repo, the same as git, so missing and hidden repos look identical to them. +pub mod gitea; +#[cfg(test)] +mod gitea_tests; pub mod releases; pub mod statuses; @@ -63,21 +67,25 @@ pub fn internal(message: impl std::fmt::Display) -> Refusal { )) } -/// Pulls the token out of `Bearer ` or `token `. The scheme is matched -/// case-insensitively. Returns `None` for any other shape, including a missing header. -fn presented_token(headers: &HeaderMap) -> Option> { +/// Pulls the token out of `Bearer `, `token ` or `Basic base64(user:)`. The +/// scheme is matched case-insensitively. A Basic user name is ignored, since the token alone +/// names the user. Returns `None` for a missing header and `Some(None)` for any other shape. +pub(crate) fn presented_token(headers: &HeaderMap) -> Option> { let value = headers.get(AUTHORIZATION)?.to_str().ok()?; let Some((scheme, rest)) = value.split_once(' ') else { return Some(None); }; - if !(scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token")) { - return Some(None); - } - let token = rest.trim(); - if token.is_empty() || !token.starts_with("forge_") { - return Some(None); + let token = if scheme.eq_ignore_ascii_case("basic") { + crate::git_auth::parse_basic_auth(headers).map(|(_, password)| password) + } else if scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token") { + Some(rest.trim().to_owned()) + } else { + None + }; + match token { + Some(token) if token.starts_with("forge_") => Some(Some(token)), + _ => Some(None), } - Some(Some(token.to_owned())) } /// Resolves the caller from the `Authorization` header. diff --git a/crates/forge-web/src/api/releases.rs b/crates/forge-web/src/api/releases.rs index 3f1cd81..43064c6 100644 --- a/crates/forge-web/src/api/releases.rs +++ b/crates/forge-web/src/api/releases.rs @@ -18,6 +18,7 @@ use topcoat::router::request::headers; use topcoat::router::response::Response; use topcoat::router::{Body, StatusCode, path_param, route}; +use crate::api::gitea; use crate::api::{self, Refusal}; use crate::client_ip::client_ip; use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError}; @@ -63,14 +64,50 @@ async fn list_releases(cx: &Cx) -> topcoat::Result { Ok(releases) => releases, Err(e) => return Ok(*api::internal(e)), }; + // Without `page` or `limit` the whole list is returned, as before. Gitea clients always send + // both, and every answer carries `X-Total-Count` and `Link`. + let visible: Vec<&Release> = releases.iter().filter(|r| can_write || !r.draft).collect(); + let pg = gitea::paging(cx, usize::MAX / 2); + let (page, total) = gitea::slice(visible, &pg); let mut out = Vec::new(); - for release in releases.iter().filter(|r| can_write || !r.draft) { + for release in page { match release_json(state, &repo, release).await { Ok(value) => out.push(value), Err(res) => return Ok(*res), } } - Ok(api::json(StatusCode::OK, &Value::Array(out))) + Ok(gitea::page_response(cx, out, total, &pg)) +} + +/// Gitea's `GET .../releases/{id}/assets/{attachment_id}`: one asset of one release. +#[route(GET "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")] +async fn get_asset(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + let (repo, can_write) = match read_context(cx).await { + Ok(found) => found, + Err(res) => return Ok(*res), + }; + let release = match release_in_repo(state, &repo, path_param::(cx)).await { + Ok(release) if can_write || !release.draft => release, + Ok(_) => return Ok(not_found()), + Err(res) => return Ok(*res), + }; + let wanted = path_param::(cx); + let assets = match state.store.list_release_assets(&release.id).await { + Ok(assets) => assets, + Err(e) => return Ok(*api::internal(e)), + }; + let found = assets.iter().find(|a| { + a.id == wanted + || (gitea::is_numeric(wanted) && wanted.parse() == Ok(gitea::numeric_id(&a.id))) + }); + match found { + Some(asset) => Ok(api::json( + StatusCode::OK, + &asset_json(&state.config.base_url, &repo, &release, asset), + )), + None => Ok(api::error(StatusCode::NOT_FOUND, "asset not found")), + } } #[route(GET "/api/v1/repos/{owner}/{repo}/releases/tags/{tag}")] @@ -259,7 +296,17 @@ async fn delete_asset(cx: &Cx) -> topcoat::Result { Ok(release) => release, Err(res) => return Ok(*res), }; - match release_ops::delete_asset(state, &repo, &release, path_param::(cx)).await { + // The asset may be named by its forge id or by the integer shown as `id` in the JSON. + let mut asset = path_param::(cx).to_owned(); + if gitea::is_numeric(&asset) + && let Ok(assets) = state.store.list_release_assets(&release.id).await + && let Some(found) = assets + .iter() + .find(|a| asset.parse() == Ok(gitea::numeric_id(&a.id))) + { + asset = found.id.clone(); + } + match release_ops::delete_asset(state, &repo, &release, &asset).await { Ok(()) => Ok(no_content()), Err(e) => Ok(*release_failure(e)), } @@ -312,8 +359,20 @@ async fn write_context(cx: &Cx) -> Result<(CoreRepo, User), Refusal> { } /// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from -/// other repos cannot be probed. Callers of this function already have write access. +/// other repos cannot be probed. `id` is the forge id or the integer shown as `id` in the JSON. +/// Callers of this function already have write access, or check drafts themselves. async fn release_in_repo(state: &AppState, repo: &CoreRepo, id: &str) -> Result { + if gitea::is_numeric(id) { + let all = state + .store + .list_releases(&repo.id) + .await + .map_err(api::internal)?; + return all + .into_iter() + .find(|r| id.parse() == Ok(gitea::numeric_id(&r.id))) + .ok_or_else(|| Box::new(not_found())); + } match state.store.release(id).await { Ok(Some(release)) if release.repo_id == repo.id => Ok(release), Ok(_) => Err(Box::new(not_found())), @@ -337,18 +396,28 @@ async fn release_json( .iter() .map(|asset| asset_json(base, repo, release, asset)) .collect(); + // `id` and `author` follow Gitea (an integer and a user object); `uid` and `author_name` + // keep the forge values, and the forge field names stay next to the Gitea ones. Ok(json!({ - "id": release.id, + "id": gitea::numeric_id(&release.id), + "uid": release.id, "tag": release.tag, + "tag_name": release.tag, "target": release.target_oid, + "target_commitish": release.target_oid, "title": release.title, + "name": release.title, "body": release.body, "draft": release.draft, "prerelease": release.prerelease, - "author": release.author_name, + "author": gitea::user_json(base, &release.author_id, &release.author_name), + "author_name": release.author_name, "created_at": release.created_at, "published_at": release.published_at, "html_url": format!("{base}/{}/{}/releases/tag/{}", repo.owner_name, repo.name, enc(&release.tag)), + "url": format!("{base}/api/v1/repos/{}/{}/releases/{}", repo.owner_name, repo.name, gitea::numeric_id(&release.id)), + "tarball_url": "", + "zipball_url": "", "assets": assets, })) } @@ -356,21 +425,25 @@ async fn release_json( /// The asset JSON. `download_url` is the web download route, which enforces draft visibility. fn asset_json(base: &str, repo: &CoreRepo, release: &Release, asset: &ReleaseAsset) -> Value { let base = base.trim_end_matches('/'); + let download = format!( + "{base}/{}/{}/releases/download/{}/{}", + repo.owner_name, + repo.name, + enc(&release.tag), + enc(&asset.name) + ); json!({ - "id": asset.id, + "id": gitea::numeric_id(&asset.id), + "uid": asset.id, + "uuid": asset.id, "name": asset.name, "size": asset.size, "sha256": asset.sha256, "content_type": asset.content_type, "download_count": asset.download_count, "created_at": asset.created_at, - "download_url": format!( - "{base}/{}/{}/releases/download/{}/{}", - repo.owner_name, - repo.name, - enc(&release.tag), - enc(&asset.name) - ), + "download_url": download, + "browser_download_url": download, }) } @@ -554,7 +627,7 @@ mod tests { async fn create(f: &Fixture, json: &str) -> String { let (status, body) = post_json(f, Some(&bearer(&f.owner_token)), json).await; assert_eq!(status, 201, "{body}"); - body["id"].as_str().expect("id").to_owned() + body["uid"].as_str().expect("uid").to_owned() } async fn upload(f: &Fixture, id: &str, name: &str, bytes: Vec) -> (u16, serde_json::Value) { @@ -621,7 +694,7 @@ mod tests { assert_eq!(body["title"], "v1.0", "the title defaults to the tag"); assert_eq!(body["body"], "notes"); assert_eq!(body["draft"], false); - assert_eq!(body["author"], OWNER); + assert_eq!(body["author_name"], OWNER); assert_eq!(body["assets"], serde_json::json!([])); assert_eq!(body["target"].as_str().map(str::len), Some(40)); assert!( @@ -750,7 +823,7 @@ mod tests { let f = fixture(None).await; let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await; let (_, asset) = upload(&f, &id, "app.bin", b"x".to_vec()).await; - let asset_id = asset["id"].as_str().unwrap().to_owned(); + let asset_id = asset["uid"].as_str().unwrap().to_owned(); let auth = bearer(&f.owner_token); let (status, _) = send( diff --git a/crates/forge-web/src/pages/releases.rs b/crates/forge-web/src/pages/releases.rs index 749e92b..4c5ede8 100644 --- a/crates/forge-web/src/pages/releases.rs +++ b/crates/forge-web/src/pages/releases.rs @@ -1247,15 +1247,52 @@ async fn asset_download(cx: &Cx) -> Result { let repo_name = path_param::(cx); let tag_param = path_param::(cx).to_owned(); let file_name = path_param::(cx).to_owned(); - let ctx = load_repo(cx, owner, repo_name).await?; let state = app_context::(cx); - let Some(release) = state.store.release_by_tag(&ctx.repo.id, &tag_param).await? else { + // A caller that sends credentials (a Gitea or Forgejo server migrating this repo) is judged by + // its token, with the same rules as the API. Everyone else goes through the session. + if headers(cx).contains_key(http::header::AUTHORIZATION) { + let actor = + match crate::api::authenticate(state, crate::client_ip::client_ip(cx), headers(cx)) + .await + { + Ok(actor) => actor, + Err(res) => return Ok(*res), + }; + let repo = match crate::api::load_repo( + state, + actor.as_ref(), + owner, + repo_name, + Action::Read, + ) + .await + { + Ok(repo) => repo, + Err(res) => return Ok(*res), + }; + let writer = crate::api::load_repo(state, actor.as_ref(), owner, repo_name, Action::Write) + .await + .is_ok(); + return stream_asset(state, &repo, writer, &tag_param, &file_name).await; + } + let ctx = load_repo(cx, owner, repo_name).await?; + stream_asset(state, &ctx.repo, can_write(&ctx), &tag_param, &file_name).await +} + +async fn stream_asset( + state: &AppState, + repo: &CoreRepo, + writer: bool, + tag_param: &str, + file_name: &str, +) -> Result { + let Some(release) = state.store.release_by_tag(&repo.id, tag_param).await? else { return Err(not_found().into()); }; - if release.draft && !can_write(&ctx) { + if release.draft && !writer { return Err(not_found().into()); } - let Some(asset) = state.store.release_asset(&release.id, &file_name).await? else { + let Some(asset) = state.store.release_asset(&release.id, file_name).await? else { return Err(not_found().into()); }; let Some(read) = state.blobs.read(&asset_key(&asset.id)).await? else { diff --git a/docs/api.md b/docs/api.md index ed432b4..c18f986 100644 --- a/docs/api.md +++ b/docs/api.md @@ -6,13 +6,17 @@ The examples use the base URL from `config/forge.toml`, `http://127.0.0.1:7660`. ## Authentication Requests authenticate with a personal access token. Create one at **Settings → Tokens** -(`/settings/tokens`). Send it either way: +(`/settings/tokens`). Send it any of these ways: ``` Authorization: Bearer forge_... Authorization: token forge_... +Authorization: Basic base64(any-name:forge_...) ``` +The Basic form takes the token as the password and ignores the user name. The Gitea routes below +also take `?access_token=forge_...`. + - A token needs the `repo` scope. It is the only scope the token form offers. A token without it gets `403`. - Session cookies are never read by this API. A browser that is logged in cannot call these @@ -147,7 +151,10 @@ declarative `[release]` table in `docs/ci.md`. | `DELETE` | `/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` | write | `204` | In the asset routes `{asset}` is the file name for `PUT` and the asset `id` (from the release JSON) -for `DELETE`. +for `DELETE`. `GET /api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` answers one asset +(Gitea's route), with the asset `id` as `{asset}`. A release `{id}` and an asset `id` are the +integers in the JSON; the ULID in `uid` works too. The list takes `page` and `limit` and always +sends `X-Total-Count` and `Link`; without them it returns everything. Drafts are visible only to callers with write access: they are left out of the list, and fetching one by tag gets `404` for anyone else. A release `{id}` must belong to the repo in the path; @@ -168,34 +175,44 @@ A release has these fields: ```json { - "id": "01J...", + "id": 281474976710, + "uid": "01J...", "tag": "v1.2.0", + "tag_name": "v1.2.0", "target": "0123...", + "target_commitish": "0123...", "title": "v1.2.0", + "name": "v1.2.0", "body": "Built by CI", "draft": false, "prerelease": false, - "author": "tahinli", + "author": {"id": 5120043, "login": "tahinli", "username": "tahinli", "...": "..."}, + "author_name": "tahinli", "created_at": "2026-10-19T10:00:00Z", "published_at": "2026-10-19T10:00:00Z", "html_url": "http://127.0.0.1:7660/tahinli/demo/releases/tag/v1.2.0", "assets": [ { - "id": "01J...", + "id": 1099511627, + "uid": "01J...", "name": "forge-linux-x86_64.tar.gz", "size": 1048576, "sha256": "9f86...", "content_type": "application/gzip", "download_count": 3, "created_at": "2026-10-19T10:01:00Z", - "download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz" + "download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz", + "browser_download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz" } ] } ``` -`published_at` is `null` for a draft. `download_url` is the web download route, so it works with -the same visibility rules as the release page. +`published_at` is `null` for a draft. `download_url` (also sent as `browser_download_url`) is the +web download route, so it works with the same visibility rules as the release page, and it +accepts a token (`Authorization: token`, Bearer or Basic) for private repos. `id` and `author` +have Gitea's shapes (an integer and a user object) so Gitea clients can read them; `uid` and +`author_name` keep the forge values. ### Create a release @@ -297,3 +314,48 @@ echo "published $TAG" If the job runs on the tag itself, the tag already exists and `target` is ignored. A simpler alternative needs no script at all: a `[release]` table in `ci.toml` publishes the release from a tag run and attaches the selected artifacts. See `docs/ci.md`, "Releases". + +## Moving to Forgejo or Gitea + +Forgejo and Gitea can pull a repo out of forge with its issues, comments, pull requests, reviews, +labels, milestones and releases (with their files). They do it through their own "Gitea" +migration, which talks to a read-only subset of the Gitea API that forge serves under +`/api/v1`. + +1. In forge, open **Settings → Tokens** and create a token for the account that can read the repo. + A token sees exactly what its user sees, so for a private repo use an account with access. +2. In Forgejo or Gitea, choose **New migration**, then **Gitea**. +3. Set **Migrate / Clone from URL** to the repo's address on forge, for example + `https://forge.example.com/tahinli/demo`. It must start with the `base_url` of + `config/forge.toml`. +4. Paste the token into **Access token**. Leave user name and password empty. +5. Tick what to bring: Issues, Pull requests, Labels, Milestones, Releases. Choose the owner and + name on the new server, then start. + +The target server must be allowed to reach forge. Forgejo and Gitea refuse local and private +addresses by default; when forge runs on one, add `ALLOW_LOCALNETWORKS = true` under +`[migrations]` in the target's `app.ini`. + +What the routes answer (all `GET`, paged with `page` and `limit`, at most 50 per page, with +`X-Total-Count` and `Link` headers): + +| Path | Notes | +| --- | --- | +| `/api/v1/version` | `{"version": "1.22.0"}`, high enough for the downloader to ask for reactions, reviews and pull request head commits. | +| `/api/v1/settings/api` | `max_response_items` 50. | +| `/api/v1/repos/{owner}/{repo}` | Name, description, privacy, default branch, `clone_url`. For a private repo read with a token, `clone_url` carries the token as the password (user `oauth2`) so the target can clone. | +| `.../topics` | Always empty. | +| `.../labels`, `.../milestones` | `state=all` works for milestones. | +| `.../releases`, `.../releases/{id}/assets/{asset}` | Assets download from `browser_download_url`; a token is accepted there. | +| `.../issues` | `type=issues` or `type=pulls`, `state=open`, `closed` or `all`. Labels, milestone and assignees included. | +| `.../issues/{index}/comments` | Pull request comments too. | +| `.../issues/{index}/reactions`, `.../issues/comments/{id}/reactions` | Forge keeps the first ten users per emoji, so a busy emoji is cut short. | +| `.../pulls` | Head and base refs and commits, merge state. | +| `.../pulls/{index}/reviews`, `.../pulls/{index}/reviews/{id}/comments` | Approvals, requested changes, line comments. Pending reviews are never shown. | + +Git over HTTP accepts the same token as the Basic password, with your user name, `oauth2` or +`x-access-token` as the name. + +Not carried over: topics, wiki and LFS objects (the clone brings the code only), user emails and +avatars (people arrive as plain user names, so the target creates placeholders you can re-map), +team reviews, discussions, snippets, CI runs and secrets.