forge
Explore
Log in

Don't you dare go Hollow

Serve the Gitea API subset Forgejo needs to migrate a repo out of forge

Browse files at this commit

24f950202335b5d7ca67ee2eee05549b3060ad1aAhmet Kaan GümüşParent: 08d9c2e
  • feat
    • serve the Gitea API subset Forgejo needs to migrate a repo out of forge
Show full message
✨ feat: serve the Gitea API subset Forgejo needs to migrate a repo out of forge
crates/forge-web/src/api/gitea.rsadded+997 -0
@@ -0,0 +1,997 @@
1+//! A read-only subset of the Gitea REST API, so a Forgejo or Gitea server can migrate a repo out
2+//! of forge ("New migration", then "Gitea", with this server's URL and a token). The routes and
3+//! JSON shapes are the ones the Forgejo Gitea downloader (services/migrations/gitea_downloader.go)
4+//! and the Gitea Go SDK read. See docs/api.md, "Moving to Forgejo or Gitea".
5+//!
6+//! Gitea ids are integers while forge ids are ULIDs. Ids shown here come from [`numeric_id`], a
7+//! stable 48 bit digest, and routes that take such an id find the row by scanning the (already
8+//! scoped) parent list. Comment ids encode the issue number and the position instead, so the
9+//! comment reaction route, which has no issue in its path, can find its comment.
10+//!
11+//! Reads follow the token: a caller sees what its user may read, drafts only with write access.
12+//! What forge does not have (topics, reactions beyond the first ten users of an emoji) comes back
13+//! empty rather than as an error.
14+
15+use std::collections::HashMap;
16+
17+use forge_core::issues::{
18+ Comment, IssueFilter, IssueListItem, IssueSort, IssueState, Label, Milestone,
19+};
20+use forge_core::pulls::PullRequest;
21+use forge_core::reactions::ReactionTarget;
22+use forge_core::reviews::{Review, ReviewComment, ReviewState, Side};
23+use forge_core::token::hash_token;
24+use forge_core::{Action, Repo as CoreRepo, User, Visibility};
25+use http::HeaderMap;
26+use http::header::{AUTHORIZATION, HeaderName, HeaderValue};
27+use serde_json::{Value, json};
28+use topcoat::context::{Cx, app_context};
29+use topcoat::router::request::{headers, uri};
30+use topcoat::router::response::Response;
31+use topcoat::router::{StatusCode, path_param, route};
32+
33+use crate::api::{self, Refusal};
34+use crate::client_ip::client_ip;
35+use crate::state::AppState;
36+
37+path_param!(owner);
38+path_param!(repo);
39+path_param!(index);
40+path_param!(id);
41+path_param!(review_id);
42+
43+/// The version reported by `GET /api/v1/version`. Forgejo's downloader gates reactions on 1.11,
44+/// reviews and pagination on 1.12 and PR head shas on 1.14, so this unlocks all of them.
45+pub const GITEA_VERSION: &str = "1.22.0";
46+/// Largest page a caller can ask for, announced by `GET /api/v1/settings/api`.
47+pub const MAX_PAGE: usize = 50;
48+/// Page size when the caller names none.
49+const DEFAULT_PAGE: usize = 30;
50+
51+/// A stable positive integer for a forge id, below 2^48 so JSON numbers stay exact.
52+pub fn numeric_id(id: &str) -> i64 {
53+ let digest = hash_token(id);
54+ i64::from_str_radix(&digest[..12], 16).unwrap_or(0) + 1
55+}
56+
57+/// True when `raw` is a Gitea style integer id (as opposed to a ULID).
58+pub fn is_numeric(raw: &str) -> bool {
59+ !raw.is_empty() && raw.len() <= 15 && raw.bytes().all(|b| b.is_ascii_digit())
60+}
61+
62+/// Comment id: the issue number in the high bits, the 1-based position in the low 20.
63+fn comment_id(number: i64, position: usize) -> i64 {
64+ (number << 20) | (position as i64 + 1)
65+}
66+
67+fn split_comment_id(id: i64) -> Option<(i64, usize)> {
68+ let position = (id & 0xF_FFFF) as usize;
69+ let number = id >> 20;
70+ (number > 0 && position > 0).then_some((number, position - 1))
71+}
72+
73+/// The user object. Only what the downloader and the SDK read; emails are never revealed.
74+pub fn user_json(base: &str, id: &str, name: &str) -> Value {
75+ json!({
76+ "id": numeric_id(id),
77+ "login": name,
78+ "username": name,
79+ "login_name": "",
80+ "full_name": "",
81+ "email": "",
82+ "avatar_url": "",
83+ "html_url": format!("{}/{}", base.trim_end_matches('/'), name),
84+ "is_admin": false,
85+ })
86+}
87+
88+/// One value of the query string.
89+fn query_value(cx: &Cx, key: &str) -> Option<String> {
90+ let query = uri(cx).query()?;
91+ form_urlencoded::parse(query.as_bytes())
92+ .find(|(k, _)| k == key)
93+ .map(|(_, v)| v.into_owned())
94+}
95+
96+/// The headers with `?access_token=` or `?token=` folded into an `Authorization` header when the
97+/// request carries none, so every Gitea auth style reaches the same code.
98+fn effective_headers(cx: &Cx) -> HeaderMap {
99+ let mut map = headers(cx).clone();
100+ if !map.contains_key(AUTHORIZATION)
101+ && let Some(token) = query_value(cx, "access_token").or_else(|| query_value(cx, "token"))
102+ && let Ok(value) = HeaderValue::from_str(&format!("token {token}"))
103+ {
104+ map.insert(AUTHORIZATION, value);
105+ }
106+ map
107+}
108+
109+/// Who is asking, and the raw token they used (for the clone URL of a private repo).
110+async fn caller(cx: &Cx) -> Result<(Option<User>, Option<String>), Refusal> {
111+ let state = app_context::<AppState>(cx);
112+ let map = effective_headers(cx);
113+ let actor = api::authenticate(state, client_ip(cx), &map).await?;
114+ let token = api::presented_token(&map).flatten();
115+ Ok((actor, token))
116+}
117+
118+struct Ctx {
119+ repo: CoreRepo,
120+ token: Option<String>,
121+ base: String,
122+}
123+
124+async fn read_ctx(cx: &Cx) -> Result<Ctx, Refusal> {
125+ let state = app_context::<AppState>(cx);
126+ let (actor, token) = caller(cx).await?;
127+ let repo = api::load_repo(
128+ state,
129+ actor.as_ref(),
130+ path_param::<Owner>(cx),
131+ path_param::<Repo>(cx),
132+ Action::Read,
133+ )
134+ .await?;
135+ Ok(Ctx {
136+ repo,
137+ token: actor.and(token),
138+ base: state.config.base_url.trim_end_matches('/').to_owned(),
139+ })
140+}
141+
142+fn bad(message: &str) -> Refusal {
143+ Box::new(api::error(StatusCode::BAD_REQUEST, message))
144+}
145+
146+fn not_found(what: &str) -> Refusal {
147+ Box::new(api::error(StatusCode::NOT_FOUND, what))
148+}
149+
150+/// `page` and `limit` of the request. `default_limit` applies when `limit` is absent; an explicit
151+/// one is capped at [`MAX_PAGE`].
152+pub struct Paging {
153+ pub page: usize,
154+ pub limit: usize,
155+}
156+
157+pub fn paging(cx: &Cx, default_limit: usize) -> Paging {
158+ let number = |key: &str| query_value(cx, key).and_then(|v| v.parse::<usize>().ok());
159+ Paging {
160+ page: number("page").filter(|p| *p > 0).unwrap_or(1),
161+ limit: number("limit")
162+ .filter(|l| *l > 0)
163+ .map_or(default_limit, |l| l.min(MAX_PAGE)),
164+ }
165+}
166+
167+/// The slice of `items` for this page, and the total.
168+pub fn slice<T>(items: Vec<T>, pg: &Paging) -> (Vec<T>, usize) {
169+ let total = items.len();
170+ let start = pg.page.saturating_sub(1).saturating_mul(pg.limit);
171+ (
172+ items.into_iter().skip(start).take(pg.limit).collect(),
173+ total,
174+ )
175+}
176+
177+/// A 200 JSON array with `X-Total-Count` and a `Link` header (next, prev, first, last).
178+pub fn page_response(cx: &Cx, items: Vec<Value>, total: usize, pg: &Paging) -> Response {
179+ let mut res = api::json(StatusCode::OK, &Value::Array(items));
180+ let last = total.div_ceil(pg.limit.max(1)).max(1);
181+ let state = app_context::<AppState>(cx);
182+ let base = state.config.base_url.trim_end_matches('/');
183+ let mut rest = String::new();
184+ if let Some(query) = uri(cx).query() {
185+ for (k, v) in form_urlencoded::parse(query.as_bytes()) {
186+ if k != "page" && k != "limit" {
187+ rest.push_str(&format!(
188+ "{}={}&",
189+ form_urlencoded::byte_serialize(k.as_bytes()).collect::<String>(),
190+ form_urlencoded::byte_serialize(v.as_bytes()).collect::<String>()
191+ ));
192+ }
193+ }
194+ }
195+ let link = |page: usize, rel: &str| {
196+ format!(
197+ "<{base}{}?{rest}page={page}&limit={}>; rel=\"{rel}\"",
198+ uri(cx).path(),
199+ pg.limit
200+ )
201+ };
202+ let mut links = Vec::new();
203+ if pg.page < last {
204+ links.push(link(pg.page + 1, "next"));
205+ links.push(link(last, "last"));
206+ }
207+ if pg.page > 1 {
208+ links.push(link(pg.page - 1, "prev"));
209+ links.push(link(1, "first"));
210+ }
211+ let map = res.headers_mut();
212+ map.insert(
213+ HeaderName::from_static("x-total-count"),
214+ HeaderValue::from(total),
215+ );
216+ if !links.is_empty()
217+ && let Ok(value) = HeaderValue::from_str(&links.join(", "))
218+ {
219+ map.insert(HeaderName::from_static("link"), value);
220+ }
221+ map.insert(
222+ HeaderName::from_static("access-control-expose-headers"),
223+ HeaderValue::from_static("Link, X-Total-Count"),
224+ );
225+ res
226+}
227+
228+fn internal(e: impl std::fmt::Display) -> Refusal {
229+ api::internal(e)
230+}
231+
232+#[route(GET "/api/v1/version")]
233+async fn version_route(_cx: &Cx) -> topcoat::Result<Response> {
234+ Ok(api::json(
235+ StatusCode::OK,
236+ &json!({ "version": GITEA_VERSION }),
237+ ))
238+}
239+
240+#[route(GET "/api/v1/settings/api")]
241+async fn settings_api(_cx: &Cx) -> topcoat::Result<Response> {
242+ Ok(api::json(
243+ StatusCode::OK,
244+ &json!({
245+ "max_response_items": MAX_PAGE,
246+ "default_paging_num": DEFAULT_PAGE,
247+ "default_git_trees_per_page": 1000,
248+ "default_max_blob_size": 10_485_760,
249+ }),
250+ ))
251+}
252+
253+/// The clone URL; a private repo read with a token carries the token as the password so the
254+/// server doing the migration can clone with it (git here accepts `oauth2` as the user name).
255+fn clone_url(base: &str, repo: &CoreRepo, token: Option<&str>) -> String {
256+ let plain = format!("{base}/{}/{}.git", repo.owner_name, repo.name);
257+ match (repo.visibility, token) {
258+ (Visibility::Private, Some(token)) => match plain.split_once("://") {
259+ Some((scheme, rest)) => format!("{scheme}://oauth2:{token}@{rest}"),
260+ None => plain,
261+ },
262+ _ => plain,
263+ }
264+}
265+
266+/// The Gitea repository object. `token` embeds credentials in `clone_url` for private repos.
267+pub async fn repo_json(
268+ state: &AppState,
269+ base: &str,
270+ repo: &CoreRepo,
271+ token: Option<&str>,
272+) -> Result<Value, Refusal> {
273+ let empty = repo.default_branch.is_empty();
274+ let ssh_host = &state.config.ssh_public_host;
275+ Ok(json!({
276+ "id": numeric_id(&repo.id),
277+ "owner": user_json(base, &repo.owner_id, &repo.owner_name),
278+ "name": repo.name,
279+ "full_name": format!("{}/{}", repo.owner_name, repo.name),
280+ "description": repo.description,
281+ "empty": empty,
282+ "private": repo.visibility == Visibility::Private,
283+ "fork": repo.fork_of.is_some(),
284+ "template": false,
285+ "mirror": false,
286+ "archived": repo.archived,
287+ "website": "",
288+ "html_url": format!("{base}/{}/{}", repo.owner_name, repo.name),
289+ "clone_url": clone_url(base, repo, token),
290+ "ssh_url": format!("git@{ssh_host}:{}/{}.git", repo.owner_name, repo.name),
291+ "original_url": "",
292+ "default_branch": repo.default_branch,
293+ "avatar_url": "",
294+ "has_issues": true,
295+ "has_pull_requests": true,
296+ "has_wiki": true,
297+ "has_releases": true,
298+ "created_at": repo.created_at,
299+ "updated_at": repo.created_at,
300+ }))
301+}
302+
303+#[route(GET "/api/v1/repos/{owner}/{repo}")]
304+async fn get_repo(cx: &Cx) -> topcoat::Result<Response> {
305+ let state = app_context::<AppState>(cx);
306+ let ctx = match read_ctx(cx).await {
307+ Ok(ctx) => ctx,
308+ Err(res) => return Ok(*res),
309+ };
310+ match repo_json(state, &ctx.base, &ctx.repo, ctx.token.as_deref()).await {
311+ Ok(value) => Ok(api::json(StatusCode::OK, &value)),
312+ Err(res) => Ok(*res),
313+ }
314+}
315+
316+/// Forge repos have no topics yet; the list is empty.
317+#[route(GET "/api/v1/repos/{owner}/{repo}/topics")]
318+async fn topics_route(cx: &Cx) -> topcoat::Result<Response> {
319+ match read_ctx(cx).await {
320+ Ok(_) => Ok(api::json(StatusCode::OK, &json!({ "topics": [] }))),
321+ Err(res) => Ok(*res),
322+ }
323+}
324+
325+fn label_json(base: &str, repo: &CoreRepo, label: &Label) -> Value {
326+ json!({
327+ "id": numeric_id(&label.id),
328+ "name": label.name,
329+ "exclusive": false,
330+ "is_archived": false,
331+ "color": label.color.trim_start_matches('#'),
332+ "description": label.description,
333+ "url": format!("{base}/api/v1/repos/{}/{}/labels/{}", repo.owner_name, repo.name, numeric_id(&label.id)),
334+ })
335+}
336+
337+#[route(GET "/api/v1/repos/{owner}/{repo}/labels")]
338+async fn list_labels_route(cx: &Cx) -> topcoat::Result<Response> {
339+ let state = app_context::<AppState>(cx);
340+ let ctx = match read_ctx(cx).await {
341+ Ok(ctx) => ctx,
342+ Err(res) => return Ok(*res),
343+ };
344+ let all = match state.store.list_labels(&ctx.repo.id).await {
345+ Ok(all) => all,
346+ Err(e) => return Ok(*internal(e)),
347+ };
348+ let pg = paging(cx, DEFAULT_PAGE);
349+ let (page, total) = slice(all, &pg);
350+ let items = page
351+ .iter()
352+ .map(|l| label_json(&ctx.base, &ctx.repo, l))
353+ .collect();
354+ Ok(page_response(cx, items, total, &pg))
355+}
356+
357+fn date_time(date: &str) -> String {
358+ if date.len() == 10 {
359+ format!("{date}T00:00:00Z")
360+ } else {
361+ date.to_owned()
362+ }
363+}
364+
365+fn milestone_json(m: &Milestone) -> Value {
366+ json!({
367+ "id": numeric_id(&m.id),
368+ "title": m.title,
369+ "description": m.description,
370+ "state": m.state.as_str(),
371+ "open_issues": m.open_issues,
372+ "closed_issues": m.closed_issues,
373+ "created_at": m.created_at,
374+ "updated_at": m.closed_at.clone().unwrap_or_else(|| m.created_at.clone()),
375+ "closed_at": m.closed_at,
376+ "due_on": m.due_on.as_deref().map(date_time),
377+ })
378+}
379+
380+/// `state` of a Gitea list: `open` (the default), `closed` or `all`.
381+fn state_filter(cx: &Cx) -> Result<Option<IssueState>, Refusal> {
382+ match query_value(cx, "state").as_deref() {
383+ None | Some("") | Some("open") => Ok(Some(IssueState::Open)),
384+ Some("closed") => Ok(Some(IssueState::Closed)),
385+ Some("all") => Ok(None),
386+ Some(other) => Err(bad(&format!("unknown state {other:?}"))),
387+ }
388+}
389+
390+#[route(GET "/api/v1/repos/{owner}/{repo}/milestones")]
391+async fn list_milestones_route(cx: &Cx) -> topcoat::Result<Response> {
392+ let state = app_context::<AppState>(cx);
393+ let ctx = match read_ctx(cx).await {
394+ Ok(ctx) => ctx,
395+ Err(res) => return Ok(*res),
396+ };
397+ let wanted = match state_filter(cx) {
398+ Ok(wanted) => wanted,
399+ Err(res) => return Ok(*res),
400+ };
401+ let all = match state.store.list_milestones(&ctx.repo.id, wanted).await {
402+ Ok(all) => all,
403+ Err(e) => return Ok(*internal(e)),
404+ };
405+ let pg = paging(cx, DEFAULT_PAGE);
406+ let (page, total) = slice(all, &pg);
407+ let items = page.iter().map(milestone_json).collect();
408+ Ok(page_response(cx, items, total, &pg))
409+}
410+
411+/// Usernames by user id, with `ghost` for an id that no longer resolves.
412+async fn names(state: &AppState, ids: Vec<String>) -> Result<HashMap<String, String>, Refusal> {
413+ let found = state.store.usernames_by_ids(&ids).await.map_err(internal)?;
414+ Ok(found
415+ .into_iter()
416+ .map(|(id, (name, _))| (id, name))
417+ .collect())
418+}
419+
420+fn user_of(base: &str, names: &HashMap<String, String>, id: &str) -> Value {
421+ let name = names.get(id).map_or("ghost", String::as_str);
422+ user_json(base, id, name)
423+}
424+
425+/// Shared by issues and pull requests: the fields both lists carry.
426+async fn issue_core(
427+ state: &AppState,
428+ ctx: &Ctx,
429+ item: &IssueListItem,
430+ milestones: &HashMap<String, Milestone>,
431+ pull: bool,
432+) -> Result<Value, Refusal> {
433+ let issue = &item.issue;
434+ let assignees = state
435+ .store
436+ .issue_assignees(&issue.id)
437+ .await
438+ .map_err(internal)?;
439+ let assignees: Vec<Value> = assignees
440+ .iter()
441+ .map(|(id, name)| user_json(&ctx.base, id, name))
442+ .collect();
443+ let url = format!(
444+ "{}/{}/{}/{}/{}",
445+ ctx.base,
446+ ctx.repo.owner_name,
447+ ctx.repo.name,
448+ if pull { "pulls" } else { "issues" },
449+ issue.number
450+ );
451+ Ok(json!({
452+ "id": numeric_id(&issue.id),
453+ "number": issue.number,
454+ "user": user_json(&ctx.base, &issue.author_id, &item.author),
455+ "title": issue.title,
456+ "body": issue.body,
457+ "labels": item.labels.iter().map(|l| label_json(&ctx.base, &ctx.repo, l)).collect::<Vec<_>>(),
458+ "milestone": issue.milestone_id.as_ref().and_then(|m| milestones.get(m)).map(milestone_json),
459+ "assignee": assignees.first(),
460+ "assignees": assignees,
461+ "state": issue.state.as_str(),
462+ "is_locked": issue.locked,
463+ "comments": issue.comment_count,
464+ "created_at": issue.created_at,
465+ "updated_at": issue.updated_at,
466+ "closed_at": issue.closed_at,
467+ "due_date": null,
468+ "html_url": url,
469+ "url": format!("{}/api/v1/repos/{}/{}/issues/{}", ctx.base, ctx.repo.owner_name, ctx.repo.name, issue.number),
470+ "pull_request": if pull { json!({"merged": false, "merged_at": null, "html_url": url}) } else { Value::Null },
471+ }))
472+}
473+
474+async fn milestone_map(
475+ state: &AppState,
476+ repo: &CoreRepo,
477+) -> Result<HashMap<String, Milestone>, Refusal> {
478+ let all = state
479+ .store
480+ .list_milestones(&repo.id, None)
481+ .await
482+ .map_err(internal)?;
483+ Ok(all.into_iter().map(|m| (m.id.clone(), m)).collect())
484+}
485+
486+fn filter_of(cx: &Cx, pg: &Paging) -> Result<IssueFilter, Refusal> {
487+ Ok(IssueFilter {
488+ state: state_filter(cx)?,
489+ sort: IssueSort::Oldest,
490+ page: pg.page as u32,
491+ per_page: pg.limit as u32,
492+ ..IssueFilter::default()
493+ })
494+}
495+
496+#[route(GET "/api/v1/repos/{owner}/{repo}/issues")]
497+async fn list_issues_route(cx: &Cx) -> topcoat::Result<Response> {
498+ let state = app_context::<AppState>(cx);
499+ let ctx = match read_ctx(cx).await {
500+ Ok(ctx) => ctx,
501+ Err(res) => return Ok(*res),
502+ };
503+ match issues_inner(cx, state, &ctx).await {
504+ Ok(res) => Ok(res),
505+ Err(res) => Ok(*res),
506+ }
507+}
508+
509+async fn issues_inner(cx: &Cx, state: &AppState, ctx: &Ctx) -> Result<Response, Refusal> {
510+ let pg = paging(cx, DEFAULT_PAGE);
511+ let filter = filter_of(cx, &pg)?;
512+ let pulls = query_value(cx, "type").as_deref() == Some("pulls");
513+ let (rows, total) = if pulls {
514+ state.store.list_pulls(&ctx.repo.id, &filter).await
515+ } else {
516+ state.store.list_issues(&ctx.repo.id, &filter).await
517+ }
518+ .map_err(internal)?;
519+ let milestones = milestone_map(state, &ctx.repo).await?;
520+ let mut out = Vec::with_capacity(rows.len());
521+ for item in &rows {
522+ out.push(issue_core(state, ctx, item, &milestones, pulls).await?);
523+ }
524+ Ok(page_response(cx, out, total as usize, &pg))
525+}
526+
527+/// The issue or pull request row with this number.
528+async fn issue_row(
529+ state: &AppState,
530+ repo: &CoreRepo,
531+ raw: &str,
532+) -> Result<forge_core::issues::Issue, Refusal> {
533+ let number: i64 = raw.parse().map_err(|_| bad("invalid issue index"))?;
534+ match state.store.issue_by_number(&repo.id, number).await {
535+ Ok(Some(issue)) => Ok(issue),
536+ Ok(None) => Err(not_found("issue not found")),
537+ Err(e) => Err(internal(e)),
538+ }
539+}
540+
541+fn comment_json(
542+ ctx: &Ctx,
543+ issue_number: i64,
544+ position: usize,
545+ comment: &Comment,
546+ names: &HashMap<String, String>,
547+) -> Value {
548+ let id = comment_id(issue_number, position);
549+ let issue_url = format!(
550+ "{}/{}/{}/issues/{issue_number}",
551+ ctx.base, ctx.repo.owner_name, ctx.repo.name
552+ );
553+ json!({
554+ "id": id,
555+ "html_url": format!("{issue_url}#comment-{id}"),
556+ "issue_url": issue_url,
557+ "pull_request_url": "",
558+ "user": user_of(&ctx.base, names, &comment.author_id),
559+ "original_author": "",
560+ "original_author_id": 0,
561+ "body": comment.body,
562+ "created_at": comment.created_at,
563+ "updated_at": comment.updated_at,
564+ })
565+}
566+
567+#[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/comments")]
568+async fn issue_comments(cx: &Cx) -> topcoat::Result<Response> {
569+ let state = app_context::<AppState>(cx);
570+ let ctx = match read_ctx(cx).await {
571+ Ok(ctx) => ctx,
572+ Err(res) => return Ok(*res),
573+ };
574+ let result: Result<Response, Refusal> = async {
575+ let issue = issue_row(state, &ctx.repo, path_param::<Index>(cx)).await?;
576+ let all = state
577+ .store
578+ .list_comments(&issue.id)
579+ .await
580+ .map_err(internal)?;
581+ let numbered: Vec<(usize, Comment)> = all.into_iter().enumerate().collect();
582+ let pg = paging(cx, DEFAULT_PAGE);
583+ let (page, total) = slice(numbered, &pg);
584+ let authors = names(
585+ state,
586+ page.iter().map(|(_, c)| c.author_id.clone()).collect(),
587+ )
588+ .await?;
589+ let items = page
590+ .iter()
591+ .map(|(pos, c)| comment_json(&ctx, issue.number, *pos, c, &authors))
592+ .collect();
593+ Ok(page_response(cx, items, total, &pg))
594+ }
595+ .await;
596+ Ok(result.unwrap_or_else(|res| *res))
597+}
598+
599+/// Reactions of one target as the Gitea list. Forge keeps the first ten users per emoji.
600+async fn reactions_json(
601+ state: &AppState,
602+ ctx: &Ctx,
603+ kind: ReactionTarget,
604+ target_id: &str,
605+ created_at: &str,
606+) -> Result<Vec<Value>, Refusal> {
607+ let map = state
608+ .store
609+ .reactions_for(kind, &[target_id.to_owned()], None)
610+ .await
611+ .map_err(internal)?;
612+ let mut out = Vec::new();
613+ for summary in map.get(target_id).into_iter().flatten() {
614+ for username in &summary.users {
615+ let id = match state.store.user_by_username(username).await {
616+ Ok(Some(user)) => user.id,
617+ _ => continue,
618+ };
619+ out.push(json!({
620+ "user": user_json(&ctx.base, &id, username),
621+ "reaction": summary.reaction.name(),
622+ "created_at": created_at,
623+ }));
624+ }
625+ }
626+ Ok(out)
627+}
628+
629+#[route(GET "/api/v1/repos/{owner}/{repo}/issues/{index}/reactions")]
630+async fn issue_reactions(cx: &Cx) -> topcoat::Result<Response> {
631+ let state = app_context::<AppState>(cx);
632+ let ctx = match read_ctx(cx).await {
633+ Ok(ctx) => ctx,
634+ Err(res) => return Ok(*res),
635+ };
636+ let result: Result<Response, Refusal> = async {
637+ let issue = issue_row(state, &ctx.repo, path_param::<Index>(cx)).await?;
638+ let all = reactions_json(
639+ state,
640+ &ctx,
641+ ReactionTarget::Issue,
642+ &issue.id,
643+ &issue.created_at,
644+ )
645+ .await?;
646+ let pg = paging(cx, 1000);
647+ let (page, total) = slice(all, &pg);
648+ Ok(page_response(cx, page, total, &pg))
649+ }
650+ .await;
651+ Ok(result.unwrap_or_else(|res| *res))
652+}
653+
654+#[route(GET "/api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions")]
655+async fn comment_reactions(cx: &Cx) -> topcoat::Result<Response> {
656+ let state = app_context::<AppState>(cx);
657+ let ctx = match read_ctx(cx).await {
658+ Ok(ctx) => ctx,
659+ Err(res) => return Ok(*res),
660+ };
661+ let result: Result<Response, Refusal> = async {
662+ let id: i64 = path_param::<Id>(cx)
663+ .parse()
664+ .map_err(|_| bad("invalid comment id"))?;
665+ let (number, position) =
666+ split_comment_id(id).ok_or_else(|| not_found("comment not found"))?;
667+ let issue = issue_row(state, &ctx.repo, &number.to_string()).await?;
668+ let all = state
669+ .store
670+ .list_comments(&issue.id)
671+ .await
672+ .map_err(internal)?;
673+ let comment = all
674+ .get(position)
675+ .ok_or_else(|| not_found("comment not found"))?;
676+ let items = reactions_json(
677+ state,
678+ &ctx,
679+ ReactionTarget::Comment,
680+ &comment.id,
681+ &comment.created_at,
682+ )
683+ .await?;
684+ let pg = paging(cx, 1000);
685+ let (page, total) = slice(items, &pg);
686+ Ok(page_response(cx, page, total, &pg))
687+ }
688+ .await;
689+ Ok(result.unwrap_or_else(|res| *res))
690+}
691+
692+fn pr_branch(
693+ ctx: &Ctx,
694+ label_owner: &str,
695+ repo: Option<&CoreRepo>,
696+ branch: &str,
697+ sha: &str,
698+) -> Value {
699+ json!({
700+ "label": format!("{label_owner}:{branch}"),
701+ "ref": branch,
702+ "sha": sha,
703+ "repo_id": repo.map(|r| numeric_id(&r.id)),
704+ "repo": repo.map(|r| json!({
705+ "id": numeric_id(&r.id),
706+ "owner": user_json(&ctx.base, &r.owner_id, &r.owner_name),
707+ "name": r.name,
708+ "full_name": format!("{}/{}", r.owner_name, r.name),
709+ "private": r.visibility == Visibility::Private,
710+ "html_url": format!("{}/{}/{}", ctx.base, r.owner_name, r.name),
711+ "clone_url": format!("{}/{}/{}.git", ctx.base, r.owner_name, r.name),
712+ "default_branch": r.default_branch,
713+ })),
714+ })
715+}
716+
717+async fn pull_json(
718+ state: &AppState,
719+ ctx: &Ctx,
720+ item: &IssueListItem,
721+ pull: &PullRequest,
722+ milestones: &HashMap<String, Milestone>,
723+) -> Result<Value, Refusal> {
724+ let mut value = issue_core(state, ctx, item, milestones, true).await?;
725+ let head_repo = match &pull.head_repo_id {
726+ Some(id) if *id == ctx.repo.id => Some(ctx.repo.clone()),
727+ Some(id) => state.store.repo_by_id(id).await.map_err(internal)?,
728+ None => None,
729+ };
730+ // A head repo the caller cannot read is shown without its repo object.
731+ let head_repo = match head_repo {
732+ Some(r) if r.id == ctx.repo.id || r.visibility == Visibility::Public => Some(r),
733+ _ => None,
734+ };
735+ let head_owner = head_repo
736+ .as_ref()
737+ .map_or(ctx.repo.owner_name.as_str(), |r| r.owner_name.as_str());
738+ let merged_by = match &pull.merged_by {
739+ Some(id) => state
740+ .store
741+ .usernames_by_ids(std::slice::from_ref(id))
742+ .await
743+ .map_err(internal)?
744+ .get(id)
745+ .map(|(name, _)| user_json(&ctx.base, id, name)),
746+ None => None,
747+ };
748+ let html = format!(
749+ "{}/{}/{}/pulls/{}",
750+ ctx.base, ctx.repo.owner_name, ctx.repo.name, pull.issue.number
751+ );
752+ let obj = value.as_object_mut().expect("object");
753+ obj.insert("merged".into(), json!(pull.merged_at.is_some()));
754+ obj.insert("merged_at".into(), json!(pull.merged_at));
755+ obj.insert("merged_by".into(), json!(merged_by));
756+ obj.insert("merge_commit_sha".into(), json!(pull.merge_commit));
757+ obj.insert("merged_commit_id".into(), json!(pull.merge_commit));
758+ obj.insert("merge_base".into(), json!(pull.merge_base));
759+ obj.insert(
760+ "mergeable".into(),
761+ json!(matches!(
762+ pull.mergeable,
763+ forge_core::pulls::Mergeable::Clean
764+ )),
765+ );
766+ obj.insert("draft".into(), json!(pull.draft));
767+ obj.insert("allow_maintainer_edit".into(), json!(false));
768+ obj.insert("diff_url".into(), json!(format!("{html}.diff")));
769+ obj.insert("patch_url".into(), json!(format!("{html}.patch")));
770+ obj.insert("flow".into(), json!(0));
771+ obj.insert(
772+ "base".into(),
773+ pr_branch(
774+ ctx,
775+ &ctx.repo.owner_name,
776+ Some(&ctx.repo),
777+ &pull.base_branch,
778+ &pull.base_oid,
779+ ),
780+ );
781+ obj.insert(
782+ "head".into(),
783+ pr_branch(
784+ ctx,
785+ head_owner,
786+ head_repo.as_ref(),
787+ &pull.head_branch,
788+ &pull.head_oid,
789+ ),
790+ );
791+ obj.insert(
792+ "pull_request".into(),
793+ json!({"merged": pull.merged_at.is_some(), "merged_at": pull.merged_at, "html_url": html}),
794+ );
795+ Ok(value)
796+}
797+
798+#[route(GET "/api/v1/repos/{owner}/{repo}/pulls")]
799+async fn list_pulls_route(cx: &Cx) -> topcoat::Result<Response> {
800+ let state = app_context::<AppState>(cx);
801+ let ctx = match read_ctx(cx).await {
802+ Ok(ctx) => ctx,
803+ Err(res) => return Ok(*res),
804+ };
805+ let result: Result<Response, Refusal> = async {
806+ let pg = paging(cx, DEFAULT_PAGE);
807+ let filter = filter_of(cx, &pg)?;
808+ let (rows, total) = state
809+ .store
810+ .list_pulls(&ctx.repo.id, &filter)
811+ .await
812+ .map_err(internal)?;
813+ let milestones = milestone_map(state, &ctx.repo).await?;
814+ let mut out = Vec::with_capacity(rows.len());
815+ for item in &rows {
816+ let Some(pull) = state
817+ .store
818+ .pull_by_number(&ctx.repo.id, item.issue.number)
819+ .await
820+ .map_err(internal)?
821+ else {
822+ continue;
823+ };
824+ out.push(pull_json(state, &ctx, item, &pull, &milestones).await?);
825+ }
826+ Ok(page_response(cx, out, total as usize, &pg))
827+ }
828+ .await;
829+ Ok(result.unwrap_or_else(|res| *res))
830+}
831+
832+fn review_state(review: &Review) -> &'static str {
833+ let effective = if review.state == ReviewState::Dismissed {
834+ review.dismissed_from.unwrap_or(ReviewState::Commented)
835+ } else {
836+ review.state
837+ };
838+ match effective {
839+ ReviewState::Approved => "APPROVED",
840+ ReviewState::ChangesRequested => "REQUEST_CHANGES",
841+ ReviewState::Pending => "PENDING",
842+ ReviewState::Commented | ReviewState::Dismissed => "COMMENT",
843+ }
844+}
845+
846+fn review_json(ctx: &Ctx, number: i64, review: &Review, comment_count: usize) -> Value {
847+ let html = format!(
848+ "{}/{}/{}/pulls/{number}",
849+ ctx.base, ctx.repo.owner_name, ctx.repo.name
850+ );
851+ json!({
852+ "id": numeric_id(&review.id),
853+ "user": user_json(&ctx.base, &review.author_id, &review.author_name),
854+ "team": null,
855+ "state": review_state(review),
856+ "body": review.body,
857+ "commit_id": review.commit_oid,
858+ "stale": false,
859+ "official": matches!(review_state(review), "APPROVED" | "REQUEST_CHANGES"),
860+ "dismissed": review.state == ReviewState::Dismissed,
861+ "comments_count": comment_count,
862+ "submitted_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()),
863+ "updated_at": review.submitted_at.clone().unwrap_or_else(|| review.created_at.clone()),
864+ "html_url": format!("{html}#{}", numeric_id(&review.id)),
865+ "pull_request_url": html,
866+ })
867+}
868+
869+/// Every non-pending review comment of the pull request, roots and replies, oldest first.
870+async fn review_comments(state: &AppState, issue_id: &str) -> Result<Vec<ReviewComment>, Refusal> {
871+ let threads = state
872+ .store
873+ .review_threads(issue_id, None)
874+ .await
875+ .map_err(internal)?;
876+ let mut all: Vec<ReviewComment> = threads
877+ .into_iter()
878+ .flat_map(|t| std::iter::once(t.root).chain(t.replies))
879+ .filter(|c| !c.pending)
880+ .collect();
881+ all.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
882+ Ok(all)
883+}
884+
885+#[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews")]
886+async fn pull_reviews(cx: &Cx) -> topcoat::Result<Response> {
887+ let state = app_context::<AppState>(cx);
888+ let ctx = match read_ctx(cx).await {
889+ Ok(ctx) => ctx,
890+ Err(res) => return Ok(*res),
891+ };
892+ let result: Result<Response, Refusal> = async {
893+ let issue = pull_issue(state, &ctx.repo, path_param::<Index>(cx)).await?;
894+ let reviews = state
895+ .store
896+ .list_reviews(&issue.id)
897+ .await
898+ .map_err(internal)?;
899+ let comments = review_comments(state, &issue.id).await?;
900+ let pg = paging(cx, DEFAULT_PAGE);
901+ let (page, total) = slice(reviews, &pg);
902+ let items = page
903+ .iter()
904+ .map(|r| {
905+ let count = comments.iter().filter(|c| c.review_id == r.id).count();
906+ review_json(&ctx, issue.number, r, count)
907+ })
908+ .collect();
909+ Ok(page_response(cx, items, total, &pg))
910+ }
911+ .await;
912+ Ok(result.unwrap_or_else(|res| *res))
913+}
914+
915+/// The issue row of a number that must be a pull request.
916+async fn pull_issue(
917+ state: &AppState,
918+ repo: &CoreRepo,
919+ raw: &str,
920+) -> Result<forge_core::issues::Issue, Refusal> {
921+ let number: i64 = raw.parse().map_err(|_| bad("invalid pull request index"))?;
922+ match state.store.pull_by_number(&repo.id, number).await {
923+ Ok(Some(pull)) => Ok(pull.issue),
924+ Ok(None) => Err(not_found("pull request not found")),
925+ Err(e) => Err(internal(e)),
926+ }
927+}
928+
929+fn review_comment_json(ctx: &Ctx, number: i64, c: &ReviewComment) -> Value {
930+ let html = format!(
931+ "{}/{}/{}/pulls/{number}",
932+ ctx.base, ctx.repo.owner_name, ctx.repo.name
933+ );
934+ let (line, old_line) = match c.side {
935+ Side::New => (c.line, 0),
936+ Side::Old => (0, c.line),
937+ };
938+ json!({
939+ "id": numeric_id(&c.id),
940+ "body": c.body,
941+ "user": user_json(&ctx.base, &c.author_id, &c.author_name),
942+ "resolver": null,
943+ "pull_request_review_id": numeric_id(&c.review_id),
944+ "created_at": c.created_at,
945+ "updated_at": c.updated_at,
946+ "path": c.path,
947+ "commit_id": c.commit_oid,
948+ "original_commit_id": c.commit_oid,
949+ "diff_hunk": c.diff_hunk,
950+ "position": line,
951+ "original_position": line,
952+ "line_num": line,
953+ "old_line_num": old_line,
954+ "html_url": format!("{html}#{}", numeric_id(&c.id)),
955+ "pull_request_url": html,
956+ })
957+}
958+
959+#[route(GET "/api/v1/repos/{owner}/{repo}/pulls/{index}/reviews/{review_id}/comments")]
960+async fn pull_review_comments(cx: &Cx) -> topcoat::Result<Response> {
961+ let state = app_context::<AppState>(cx);
962+ let ctx = match read_ctx(cx).await {
963+ Ok(ctx) => ctx,
964+ Err(res) => return Ok(*res),
965+ };
966+ let result: Result<Response, Refusal> = async {
967+ let issue = pull_issue(state, &ctx.repo, path_param::<Index>(cx)).await?;
968+ let raw = path_param::<ReviewId>(cx);
969+ let reviews = state
970+ .store
971+ .list_reviews(&issue.id)
972+ .await
973+ .map_err(internal)?;
974+ let review = reviews
975+ .iter()
976+ .find(|r| r.id == raw || (is_numeric(raw) && raw.parse() == Ok(numeric_id(&r.id))))
977+ .ok_or_else(|| not_found("review not found"))?;
978+ let own: Vec<ReviewComment> = review_comments(state, &issue.id)
979+ .await?
980+ .into_iter()
981+ .filter(|c| c.review_id == review.id)
982+ .collect();
983+ let items = own
984+ .iter()
985+ .map(|c| review_comment_json(&ctx, issue.number, c))
986+ .collect::<Vec<_>>();
987+ let total = items.len();
988+ // Review comments are not paged by the downloader; return them whole.
989+ let pg = Paging {
990+ page: 1,
991+ limit: total.max(1),
992+ };
993+ Ok(page_response(cx, items, total, &pg))
994+ }
995+ .await;
996+ Ok(result.unwrap_or_else(|res| *res))
997+}
crates/forge-web/src/api/gitea_tests.rsadded+566 -0
@@ -0,0 +1,566 @@
1+//! Tests of the Gitea compatible read routes (api/gitea.rs). Each one asserts the JSON fields the
2+//! Forgejo Gitea downloader reads, plus the pagination headers and the token rules.
3+
4+use std::path::{Path, PathBuf};
5+
6+use base64::prelude::{BASE64_STANDARD, Engine};
7+use forge_core::reactions::{Reaction, ReactionTarget};
8+use forge_core::reviews::{ReviewState, Side};
9+use forge_core::token::{generate_token, hash_token};
10+use forge_core::{Role, Store, Visibility};
11+use forge_git::repo::{init_bare, repo_path};
12+use http::HeaderMap;
13+use http::header::{AUTHORIZATION, CONTENT_TYPE};
14+use serde_json::Value;
15+use topcoat::router::request::Request;
16+use topcoat::router::{Body, Router, to_bytes};
17+
18+use crate::test_support::{app_router, test_state};
19+
20+const OWNER: &str = "tahinli";
21+const REPO: &str = "proj";
22+
23+fn git(dir: &Path, args: &[&str]) -> String {
24+ let out = std::process::Command::new("git")
25+ .current_dir(dir)
26+ .args(args)
27+ .env("GIT_AUTHOR_NAME", "test")
28+ .env("GIT_AUTHOR_EMAIL", "test@example.com")
29+ .env("GIT_COMMITTER_NAME", "test")
30+ .env("GIT_COMMITTER_EMAIL", "test@example.com")
31+ .output()
32+ .expect("git runs");
33+ assert!(out.status.success(), "git {args:?} failed");
34+ String::from_utf8_lossy(&out.stdout).trim().to_owned()
35+}
36+
37+struct Fixture {
38+ _tmp: tempfile::TempDir,
39+ router: Router,
40+ owner_token: String,
41+ bob_token: String,
42+ carol_token: String,
43+ oid: String,
44+}
45+
46+async fn token_for(store: &Store, user_id: &str) -> String {
47+ let raw = generate_token();
48+ store
49+ .create_token(
50+ user_id,
51+ "test",
52+ &hash_token(&raw),
53+ &["repo".to_owned()],
54+ None,
55+ )
56+ .await
57+ .expect("token");
58+ raw
59+}
60+
61+async fn seed_git(state: &crate::state::AppState, tmp: &Path, repo_id: &str) -> String {
62+ let bare: PathBuf = repo_path(&state.git.data_dir, repo_id).expect("repo path");
63+ init_bare(&state.git, &bare, "main").await.expect("init");
64+ let work = tmp.join(format!("work-{repo_id}"));
65+ git(tmp, &["init", "-b", "main", work.to_str().expect("utf8")]);
66+ std::fs::write(work.join("file.txt"), "one").expect("write");
67+ git(&work, &["add", "file.txt"]);
68+ git(&work, &["commit", "-m", "one"]);
69+ git(&work, &["push", bare.to_str().expect("utf8"), "main"]);
70+ git(&work, &["rev-parse", "HEAD"])
71+}
72+
73+/// `tahinli/proj` is public with an issue (label, milestone, assignee, two comments, reactions),
74+/// a pull request with one review and one line comment, and a release with one asset.
75+/// `tahinli/secret` is private; bob can read `proj` only, carol nothing.
76+async fn fixture() -> Fixture {
77+ let tmp = tempfile::tempdir().expect("tempdir");
78+ let state = test_state(tmp.path()).await;
79+ let store = state.store.clone();
80+ let owner = store
81+ .create_user(OWNER, None, "x", false)
82+ .await
83+ .expect("owner");
84+ let bob = store
85+ .create_user("bob", None, "x", false)
86+ .await
87+ .expect("bob");
88+ let carol = store
89+ .create_user("carol", None, "x", false)
90+ .await
91+ .expect("carol");
92+ let repo = store
93+ .create_repo(&owner.id, REPO, "A project", Visibility::Public, "main")
94+ .await
95+ .expect("repo");
96+ store
97+ .set_collaborator(&repo.id, &bob.id, Role::Read)
98+ .await
99+ .expect("collaborator");
100+ let secret = store
101+ .create_repo(&owner.id, "secret", "", Visibility::Private, "main")
102+ .await
103+ .expect("secret");
104+ let oid = seed_git(&state, tmp.path(), &repo.id).await;
105+ seed_git(&state, tmp.path(), &secret.id).await;
106+
107+ let label = store
108+ .create_label(&repo.id, "bug", "#d73a4a", "Something is broken")
109+ .await
110+ .expect("label");
111+ let milestone = store
112+ .create_milestone(&repo.id, "v1", "First", Some("2026-12-01"))
113+ .await
114+ .expect("milestone");
115+ let issue = store
116+ .create_issue(&repo.id, &owner.id, "It breaks", "Steps follow")
117+ .await
118+ .expect("issue");
119+ store
120+ .set_issue_labels(&issue.id, &owner.id, std::slice::from_ref(&label.id))
121+ .await
122+ .expect("labels");
123+ store
124+ .set_issue_milestone(&issue.id, &owner.id, Some(&milestone.id))
125+ .await
126+ .expect("milestone set");
127+ store
128+ .set_issue_assignees(&issue.id, &owner.id, &[OWNER.to_owned()])
129+ .await
130+ .expect("assignees");
131+ let first = store
132+ .add_comment(&issue.id, &bob.id, "I see it too")
133+ .await
134+ .expect("comment");
135+ store
136+ .add_comment(&issue.id, &owner.id, "Looking")
137+ .await
138+ .expect("comment 2");
139+ store
140+ .toggle_reaction(ReactionTarget::Issue, &issue.id, &bob.id, Reaction::Heart)
141+ .await
142+ .expect("issue reaction");
143+ store
144+ .toggle_reaction(
145+ ReactionTarget::Comment,
146+ &first.id,
147+ &owner.id,
148+ Reaction::PlusOne,
149+ )
150+ .await
151+ .expect("comment reaction");
152+
153+ let pull = store
154+ .create_pull(
155+ &repo.id,
156+ &owner.id,
157+ "Add thing",
158+ "Body",
159+ "main",
160+ &repo.id,
161+ "feature",
162+ &oid,
163+ &oid,
164+ )
165+ .await
166+ .expect("pull");
167+ store
168+ .add_review_comment(
169+ &pull.issue.id,
170+ &bob.id,
171+ true,
172+ "file.txt",
173+ Side::New,
174+ 1,
175+ &oid,
176+ "@@ -1 +1 @@",
177+ "nit",
178+ )
179+ .await
180+ .expect("review comment");
181+ store
182+ .submit_review(
183+ &pull.issue.id,
184+ &bob.id,
185+ ReviewState::ChangesRequested,
186+ "please fix",
187+ &oid,
188+ )
189+ .await
190+ .expect("review");
191+
192+ let owner_token = token_for(&store, &owner.id).await;
193+ let bob_token = token_for(&store, &bob.id).await;
194+ let carol_token = token_for(&store, &carol.id).await;
195+ let router = app_router(state);
196+ let f = Fixture {
197+ _tmp: tmp,
198+ router,
199+ owner_token,
200+ bob_token,
201+ carol_token,
202+ oid,
203+ };
204+
205+ let (status, _, body) = f
206+ .get_with(
207+ "POST",
208+ &format!("/api/v1/repos/{OWNER}/{REPO}/releases"),
209+ Some(&format!("token {}", f.owner_token)),
210+ br#"{"tag":"v1.0","target":"main","title":"One","body":"notes"}"#.to_vec(),
211+ "application/json",
212+ )
213+ .await;
214+ assert_eq!(status, 201, "{body}");
215+ let uid = body["uid"].as_str().expect("uid").to_owned();
216+ let (status, _, body) = f
217+ .get_with(
218+ "PUT",
219+ &format!("/api/v1/repos/{OWNER}/{REPO}/releases/{uid}/assets/app.bin"),
220+ Some(&format!("token {}", f.owner_token)),
221+ b"hello".to_vec(),
222+ "application/octet-stream",
223+ )
224+ .await;
225+ assert_eq!(status, 201, "{body}");
226+ f
227+}
228+
229+impl Fixture {
230+ async fn get_with(
231+ &self,
232+ method: &str,
233+ uri: &str,
234+ auth: Option<&str>,
235+ body: Vec<u8>,
236+ content_type: &str,
237+ ) -> (u16, HeaderMap, Value) {
238+ let mut builder = Request::builder().method(method).uri(uri);
239+ if let Some(auth) = auth {
240+ builder = builder.header(AUTHORIZATION, auth);
241+ }
242+ builder = builder.header(CONTENT_TYPE, content_type);
243+ let res = self
244+ .router
245+ .handle(builder.body(Body::from(body)).unwrap())
246+ .await;
247+ let status = res.status().as_u16();
248+ let headers = res.headers().clone();
249+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
250+ let json = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
251+ (status, headers, json)
252+ }
253+
254+ /// GET as `tahinli` with the `Authorization: token` style the Gitea SDK sends.
255+ async fn get(&self, path: &str) -> (u16, HeaderMap, Value) {
256+ self.get_with(
257+ "GET",
258+ path,
259+ Some(&format!("token {}", self.owner_token)),
260+ Vec::new(),
261+ "application/json",
262+ )
263+ .await
264+ }
265+
266+ async fn get_as(&self, path: &str, auth: Option<String>) -> (u16, HeaderMap, Value) {
267+ self.get_with("GET", path, auth.as_deref(), Vec::new(), "application/json")
268+ .await
269+ }
270+}
271+
272+fn repo_path_of(rest: &str) -> String {
273+ format!("/api/v1/repos/{OWNER}/{REPO}{rest}")
274+}
275+
276+#[tokio::test]
277+async fn version_and_settings_unlock_every_feature() {
278+ let f = fixture().await;
279+ let (status, _, body) = f.get_as("/api/v1/version", None).await;
280+ assert_eq!(status, 200);
281+ assert_eq!(body["version"], "1.22.0");
282+ let (status, _, body) = f.get_as("/api/v1/settings/api", None).await;
283+ assert_eq!(status, 200);
284+ assert_eq!(body["max_response_items"], 50);
285+}
286+
287+#[tokio::test]
288+async fn repo_info_topics_labels_and_milestones() {
289+ let f = fixture().await;
290+ let (status, _, repo) = f.get(&repo_path_of("")).await;
291+ assert_eq!(status, 200);
292+ assert_eq!(repo["name"], REPO);
293+ assert_eq!(repo["owner"]["login"], OWNER);
294+ assert_eq!(repo["private"], false);
295+ assert_eq!(repo["description"], "A project");
296+ assert_eq!(repo["default_branch"], "main");
297+ assert_eq!(
298+ repo["clone_url"],
299+ format!("https://forge.test/{OWNER}/{REPO}.git")
300+ );
301+ assert_eq!(
302+ repo["html_url"],
303+ format!("https://forge.test/{OWNER}/{REPO}")
304+ );
305+
306+ let (_, _, topics) = f.get(&repo_path_of("/topics")).await;
307+ assert_eq!(topics["topics"], serde_json::json!([]));
308+
309+ let (_, headers, labels) = f.get(&repo_path_of("/labels?page=1&limit=10")).await;
310+ let label = labels
311+ .as_array()
312+ .unwrap()
313+ .iter()
314+ .find(|l| l["name"] == "bug")
315+ .unwrap();
316+ assert_eq!(label["color"], "d73a4a");
317+ assert_eq!(label["description"], "Something is broken");
318+ assert!(headers.contains_key("x-total-count"));
319+
320+ let (_, _, milestones) = f
321+ .get(&repo_path_of("/milestones?state=all&page=1&limit=10"))
322+ .await;
323+ let m = &milestones.as_array().unwrap()[0];
324+ assert_eq!(m["title"], "v1");
325+ assert_eq!(m["description"], "First");
326+ assert_eq!(m["state"], "open");
327+ assert_eq!(m["due_on"], "2026-12-01T00:00:00Z");
328+ assert!(m["created_at"].is_string());
329+}
330+
331+#[tokio::test]
332+async fn issues_carry_labels_milestone_assignees_and_comments() {
333+ let f = fixture().await;
334+ let (status, headers, issues) = f
335+ .get(&repo_path_of(
336+ "/issues?type=issues&state=all&page=1&limit=10",
337+ ))
338+ .await;
339+ assert_eq!(status, 200);
340+ assert_eq!(headers["x-total-count"], "1");
341+ let list = issues.as_array().unwrap();
342+ assert_eq!(list.len(), 1, "pulls are not issues");
343+ let issue = &list[0];
344+ assert_eq!(issue["number"], 1);
345+ assert_eq!(issue["title"], "It breaks");
346+ assert_eq!(issue["body"], "Steps follow");
347+ assert_eq!(issue["state"], "open");
348+ assert_eq!(issue["is_locked"], false);
349+ assert_eq!(issue["user"]["login"], OWNER);
350+ assert!(issue["user"]["id"].as_i64().unwrap() > 0);
351+ assert_eq!(issue["labels"][0]["name"], "bug");
352+ assert_eq!(issue["milestone"]["title"], "v1");
353+ assert_eq!(issue["assignees"][0]["login"], OWNER);
354+ assert!(issue["created_at"].is_string() && issue["updated_at"].is_string());
355+ assert!(issue["pull_request"].is_null());
356+
357+ let (_, headers, comments) = f
358+ .get(&repo_path_of("/issues/1/comments?page=1&limit=10"))
359+ .await;
360+ assert_eq!(headers["x-total-count"], "2");
361+ let comments = comments.as_array().unwrap();
362+ assert_eq!(comments[0]["body"], "I see it too");
363+ assert_eq!(comments[0]["user"]["login"], "bob");
364+ assert!(comments[0]["id"].as_i64().unwrap() > 0);
365+ assert!(comments[0]["created_at"].is_string() && comments[0]["updated_at"].is_string());
366+ assert_ne!(comments[0]["id"], comments[1]["id"]);
367+
368+ let (_, _, reactions) = f.get(&repo_path_of("/issues/1/reactions")).await;
369+ assert_eq!(reactions[0]["reaction"], "heart");
370+ assert_eq!(reactions[0]["user"]["login"], "bob");
371+
372+ let id = comments[0]["id"].as_i64().unwrap();
373+ let (status, _, reactions) = f
374+ .get(&repo_path_of(&format!("/issues/comments/{id}/reactions")))
375+ .await;
376+ assert_eq!(status, 200);
377+ assert_eq!(reactions[0]["reaction"], "+1");
378+ assert_eq!(reactions[0]["user"]["login"], OWNER);
379+}
380+
381+#[tokio::test]
382+async fn pagination_headers_and_link() {
383+ let f = fixture().await;
384+ let (status, headers, items) = f
385+ .get(&repo_path_of("/issues/1/comments?page=2&limit=1"))
386+ .await;
387+ assert_eq!(status, 200);
388+ assert_eq!(headers["x-total-count"], "2");
389+ assert_eq!(items.as_array().unwrap().len(), 1);
390+ assert_eq!(items[0]["body"], "Looking");
391+ let link = headers["link"].to_str().unwrap();
392+ assert!(
393+ link.contains("rel=\"prev\"") && link.contains("rel=\"first\""),
394+ "{link}"
395+ );
396+ assert!(!link.contains("rel=\"next\""), "{link}");
397+ assert!(link.contains("https://forge.test/api/v1/repos/tahinli/proj/issues/1/comments?"));
398+
399+ let (_, headers, items) = f
400+ .get(&repo_path_of("/issues/1/comments?page=1&limit=1"))
401+ .await;
402+ assert_eq!(items.as_array().unwrap().len(), 1);
403+ let link = headers["link"].to_str().unwrap();
404+ assert!(
405+ link.contains("rel=\"next\"") && link.contains("rel=\"last\""),
406+ "{link}"
407+ );
408+
409+ // Past the last page the list is empty, which ends the downloader's loop.
410+ let (_, _, items) = f
411+ .get(&repo_path_of("/issues/1/comments?page=3&limit=1"))
412+ .await;
413+ assert_eq!(items.as_array().unwrap().len(), 0);
414+}
415+
416+#[tokio::test]
417+async fn pulls_reviews_and_review_comments() {
418+ let f = fixture().await;
419+ let (status, headers, pulls) = f
420+ .get(&repo_path_of("/pulls?state=all&page=1&limit=10"))
421+ .await;
422+ assert_eq!(status, 200);
423+ assert_eq!(headers["x-total-count"], "1");
424+ let pr = &pulls[0];
425+ assert_eq!(pr["number"], 2);
426+ assert_eq!(pr["title"], "Add thing");
427+ assert_eq!(pr["state"], "open");
428+ assert_eq!(pr["merged"], false);
429+ assert_eq!(pr["user"]["login"], OWNER);
430+ assert_eq!(pr["head"]["ref"], "feature");
431+ assert_eq!(pr["head"]["sha"], f.oid);
432+ assert_eq!(pr["head"]["repo"]["owner"]["login"], OWNER);
433+ assert_eq!(
434+ pr["head"]["repo"]["clone_url"],
435+ format!("https://forge.test/{OWNER}/{REPO}.git")
436+ );
437+ assert_eq!(pr["base"]["ref"], "main");
438+ assert_eq!(pr["base"]["sha"], f.oid);
439+ assert!(pr["created_at"].is_string() && pr["updated_at"].is_string());
440+
441+ let (status, _, reviews) = f
442+ .get(&repo_path_of("/pulls/2/reviews?page=1&limit=10"))
443+ .await;
444+ assert_eq!(status, 200);
445+ let review = &reviews[0];
446+ assert_eq!(review["state"], "REQUEST_CHANGES");
447+ assert_eq!(review["body"], "please fix");
448+ assert_eq!(review["user"]["login"], "bob");
449+ assert_eq!(review["commit_id"], f.oid);
450+ assert_eq!(review["official"], true);
451+ assert!(review["submitted_at"].is_string());
452+ let review_id = review["id"].as_i64().unwrap();
453+
454+ let (status, _, comments) = f
455+ .get(&repo_path_of(&format!(
456+ "/pulls/2/reviews/{review_id}/comments"
457+ )))
458+ .await;
459+ assert_eq!(status, 200);
460+ let c = &comments[0];
461+ assert_eq!(c["body"], "nit");
462+ assert_eq!(c["path"], "file.txt");
463+ assert_eq!(c["diff_hunk"], "@@ -1 +1 @@");
464+ assert_eq!(c["line_num"], 1);
465+ assert_eq!(c["old_line_num"], 0);
466+ assert_eq!(c["commit_id"], f.oid);
467+ assert_eq!(c["user"]["login"], "bob");
468+ assert_eq!(c["pull_request_review_id"], review_id);
469+
470+ // An issue number is not a pull request.
471+ let (status, _, _) = f.get(&repo_path_of("/pulls/1/reviews")).await;
472+ assert_eq!(status, 404);
473+}
474+
475+#[tokio::test]
476+async fn releases_and_assets_in_gitea_shape() {
477+ let f = fixture().await;
478+ let (status, headers, releases) = f.get(&repo_path_of("/releases?page=1&limit=10")).await;
479+ assert_eq!(status, 200);
480+ assert_eq!(headers["x-total-count"], "1");
481+ let release = &releases[0];
482+ assert!(release["id"].as_i64().unwrap() > 0);
483+ assert_eq!(release["tag_name"], "v1.0");
484+ assert_eq!(release["name"], "One");
485+ assert_eq!(release["body"], "notes");
486+ assert_eq!(release["draft"], false);
487+ assert_eq!(release["prerelease"], false);
488+ assert_eq!(release["target_commitish"], f.oid);
489+ assert_eq!(release["author"]["login"], OWNER);
490+ assert!(release["created_at"].is_string() && release["published_at"].is_string());
491+ let asset = &release["assets"][0];
492+ assert_eq!(asset["name"], "app.bin");
493+ assert_eq!(asset["size"], 5);
494+ assert_eq!(asset["download_count"], 0);
495+ let url = asset["browser_download_url"].as_str().unwrap();
496+ assert_eq!(
497+ url,
498+ "https://forge.test/tahinli/proj/releases/download/v1.0/app.bin"
499+ );
500+
501+ let rid = release["id"].as_i64().unwrap();
502+ let aid = asset["id"].as_i64().unwrap();
503+ let (status, _, one) = f
504+ .get(&repo_path_of(&format!("/releases/{rid}/assets/{aid}")))
505+ .await;
506+ assert_eq!(status, 200);
507+ assert_eq!(one["name"], "app.bin");
508+ assert_eq!(one["browser_download_url"], url);
509+}
510+
511+#[tokio::test]
512+async fn private_repos_follow_the_token() {
513+ let f = fixture().await;
514+ let secret = "/api/v1/repos/tahinli/secret";
515+ let (status, _, _) = f.get_as(secret, None).await;
516+ assert_eq!(status, 401, "anonymous");
517+ let (status, _, _) = f
518+ .get_as(secret, Some(format!("token {}", f.carol_token)))
519+ .await;
520+ assert_eq!(status, 404, "a user without access");
521+ let (status, _, _) = f
522+ .get_as(secret, Some(format!("token {}", f.bob_token)))
523+ .await;
524+ assert_eq!(status, 404, "a reader of another repo");
525+
526+ // The owner may use any of the three styles Gitea clients send.
527+ let token = f.owner_token.clone();
528+ let basic = format!(
529+ "Basic {}",
530+ BASE64_STANDARD.encode(format!("whoever:{token}"))
531+ );
532+ for auth in [format!("token {token}"), format!("Bearer {token}"), basic] {
533+ let (status, _, repo) = f.get_as(secret, Some(auth.clone())).await;
534+ assert_eq!(status, 200, "{auth}");
535+ assert_eq!(repo["private"], true);
536+ // The clone URL carries the token so the migrating server can clone.
537+ let clone = repo["clone_url"].as_str().unwrap();
538+ assert_eq!(
539+ clone,
540+ format!("https://oauth2:{token}@forge.test/tahinli/secret.git")
541+ );
542+ }
543+ let (status, _, repo) = f
544+ .get_as(&format!("{secret}?access_token={token}"), None)
545+ .await;
546+ assert_eq!(status, 200);
547+ assert_eq!(repo["name"], "secret");
548+
549+ // A bad token is refused, not treated as anonymous.
550+ let (status, _, _) = f
551+ .get_as(&repo_path_of(""), Some("token forge_nope".into()))
552+ .await;
553+ assert_eq!(status, 401);
554+}
555+
556+#[tokio::test]
557+async fn release_asset_downloads_with_a_token() {
558+ let f = fixture().await;
559+ let path = "/tahinli/proj/releases/download/v1.0/app.bin";
560+ let owner = f.owner_token.clone();
561+ let basic = format!("Basic {}", BASE64_STANDARD.encode(format!("x:{owner}")));
562+ let (status, _, _) = f.get_as(path, Some(basic)).await;
563+ assert_eq!(status, 200);
564+ let (status, _, _) = f.get_as(path, Some("token forge_nope".into())).await;
565+ assert_eq!(status, 401);
566+}
crates/forge-web/src/api/mod.rsmodified+19 -11
@@ -1,9 +1,13 @@
1 //! Our own small JSON API under `/api/v1`. Authentication is by personal access token only:1 //! Our own small JSON API under `/api/v1`. Authentication is by personal access token only:
2-//! `Authorization: Bearer forge_...` or `Authorization: token forge_...`. Session cookies are never2+//! `Authorization: Bearer forge_...` or `Authorization: token forge_...`, or, for Gitea clients, Basic auth
3+//! with the token as the password or `?access_token=` on the Gitea routes. Session cookies are never
3 //! read here, so a browser cannot drive these routes and CSRF protection does not apply. Errors are4 //! read here, so a browser cannot drive these routes and CSRF protection does not apply. Errors are
4 //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot5 //! `{"error": "..."}` with a matching status code. Anonymous callers get 401 whenever they cannot
5 //! use a repo, the same as git, so missing and hidden repos look identical to them.6 //! use a repo, the same as git, so missing and hidden repos look identical to them.
6 7
8+pub mod gitea;
9+#[cfg(test)]
10+mod gitea_tests;
7 pub mod releases;11 pub mod releases;
8 pub mod statuses;12 pub mod statuses;
9 13
@@ -63,21 +67,25 @@ pub fn internal(message: impl std::fmt::Display) -> Refusal {
63 ))67 ))
64 }68 }
65 69
66-/// Pulls the token out of `Bearer <token>` or `token <token>`. The scheme is matched70+/// Pulls the token out of `Bearer <token>`, `token <token>` or `Basic base64(user:<token>)`. The
67-/// case-insensitively. Returns `None` for any other shape, including a missing header.71+/// scheme is matched case-insensitively. A Basic user name is ignored, since the token alone
68-fn presented_token(headers: &HeaderMap) -> Option<Option<String>> {72+/// names the user. Returns `None` for a missing header and `Some(None)` for any other shape.
73+pub(crate) fn presented_token(headers: &HeaderMap) -> Option<Option<String>> {
69 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;74 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
70 let Some((scheme, rest)) = value.split_once(' ') else {75 let Some((scheme, rest)) = value.split_once(' ') else {
71 return Some(None);76 return Some(None);
72 };77 };
73- if !(scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token")) {78+ let token = if scheme.eq_ignore_ascii_case("basic") {
74- return Some(None);79+ crate::git_auth::parse_basic_auth(headers).map(|(_, password)| password)
75- }80+ } else if scheme.eq_ignore_ascii_case("bearer") || scheme.eq_ignore_ascii_case("token") {
76- let token = rest.trim();81+ Some(rest.trim().to_owned())
77- if token.is_empty() || !token.starts_with("forge_") {82+ } else {
78- return Some(None);83+ None
84+ };
85+ match token {
86+ Some(token) if token.starts_with("forge_") => Some(Some(token)),
87+ _ => Some(None),
79 }88 }
80- Some(Some(token.to_owned()))
81 }89 }
82 90
83 /// Resolves the caller from the `Authorization` header.91 /// Resolves the caller from the `Authorization` header.
crates/forge-web/src/api/releases.rsmodified+90 -17
@@ -18,6 +18,7 @@ use topcoat::router::request::headers;
18 use topcoat::router::response::Response;18 use topcoat::router::response::Response;
19 use topcoat::router::{Body, StatusCode, path_param, route};19 use topcoat::router::{Body, StatusCode, path_param, route};
20 20
21+use crate::api::gitea;
21 use crate::api::{self, Refusal};22 use crate::api::{self, Refusal};
22 use crate::client_ip::client_ip;23 use crate::client_ip::client_ip;
23 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};24 use crate::release_ops::{self, CreateRelease, EditRelease, ReleaseError};
@@ -63,14 +64,50 @@ async fn list_releases(cx: &Cx) -> topcoat::Result<Response> {
63 Ok(releases) => releases,64 Ok(releases) => releases,
64 Err(e) => return Ok(*api::internal(e)),65 Err(e) => return Ok(*api::internal(e)),
65 };66 };
67+ // Without `page` or `limit` the whole list is returned, as before. Gitea clients always send
68+ // both, and every answer carries `X-Total-Count` and `Link`.
69+ let visible: Vec<&Release> = releases.iter().filter(|r| can_write || !r.draft).collect();
70+ let pg = gitea::paging(cx, usize::MAX / 2);
71+ let (page, total) = gitea::slice(visible, &pg);
66 let mut out = Vec::new();72 let mut out = Vec::new();
67- for release in releases.iter().filter(|r| can_write || !r.draft) {73+ for release in page {
68 match release_json(state, &repo, release).await {74 match release_json(state, &repo, release).await {
69 Ok(value) => out.push(value),75 Ok(value) => out.push(value),
70 Err(res) => return Ok(*res),76 Err(res) => return Ok(*res),
71 }77 }
72 }78 }
73- Ok(api::json(StatusCode::OK, &Value::Array(out)))79+ Ok(gitea::page_response(cx, out, total, &pg))
80+}
81+
82+/// Gitea's `GET .../releases/{id}/assets/{attachment_id}`: one asset of one release.
83+#[route(GET "/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}")]
84+async fn get_asset(cx: &Cx) -> topcoat::Result<Response> {
85+ let state = app_context::<AppState>(cx);
86+ let (repo, can_write) = match read_context(cx).await {
87+ Ok(found) => found,
88+ Err(res) => return Ok(*res),
89+ };
90+ let release = match release_in_repo(state, &repo, path_param::<Id>(cx)).await {
91+ Ok(release) if can_write || !release.draft => release,
92+ Ok(_) => return Ok(not_found()),
93+ Err(res) => return Ok(*res),
94+ };
95+ let wanted = path_param::<Asset>(cx);
96+ let assets = match state.store.list_release_assets(&release.id).await {
97+ Ok(assets) => assets,
98+ Err(e) => return Ok(*api::internal(e)),
99+ };
100+ let found = assets.iter().find(|a| {
101+ a.id == wanted
102+ || (gitea::is_numeric(wanted) && wanted.parse() == Ok(gitea::numeric_id(&a.id)))
103+ });
104+ match found {
105+ Some(asset) => Ok(api::json(
106+ StatusCode::OK,
107+ &asset_json(&state.config.base_url, &repo, &release, asset),
108+ )),
109+ None => Ok(api::error(StatusCode::NOT_FOUND, "asset not found")),
110+ }
74 }111 }
75 112
76 #[route(GET "/api/v1/repos/{owner}/{repo}/releases/tags/{tag}")]113 #[route(GET "/api/v1/repos/{owner}/{repo}/releases/tags/{tag}")]
@@ -259,7 +296,17 @@ async fn delete_asset(cx: &Cx) -> topcoat::Result<Response> {
259 Ok(release) => release,296 Ok(release) => release,
260 Err(res) => return Ok(*res),297 Err(res) => return Ok(*res),
261 };298 };
262- match release_ops::delete_asset(state, &repo, &release, path_param::<Asset>(cx)).await {299+ // The asset may be named by its forge id or by the integer shown as `id` in the JSON.
300+ let mut asset = path_param::<Asset>(cx).to_owned();
301+ if gitea::is_numeric(&asset)
302+ && let Ok(assets) = state.store.list_release_assets(&release.id).await
303+ && let Some(found) = assets
304+ .iter()
305+ .find(|a| asset.parse() == Ok(gitea::numeric_id(&a.id)))
306+ {
307+ asset = found.id.clone();
308+ }
309+ match release_ops::delete_asset(state, &repo, &release, &asset).await {
263 Ok(()) => Ok(no_content()),310 Ok(()) => Ok(no_content()),
264 Err(e) => Ok(*release_failure(e)),311 Err(e) => Ok(*release_failure(e)),
265 }312 }
@@ -312,8 +359,20 @@ async fn write_context(cx: &Cx) -> Result<(CoreRepo, User), Refusal> {
312 }359 }
313 360
314 /// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from361 /// The release with this id, which must belong to `repo`. Anything else is a 404, so ids from
315-/// other repos cannot be probed. Callers of this function already have write access.362+/// other repos cannot be probed. `id` is the forge id or the integer shown as `id` in the JSON.
363+/// Callers of this function already have write access, or check drafts themselves.
316 async fn release_in_repo(state: &AppState, repo: &CoreRepo, id: &str) -> Result<Release, Refusal> {364 async fn release_in_repo(state: &AppState, repo: &CoreRepo, id: &str) -> Result<Release, Refusal> {
365+ if gitea::is_numeric(id) {
366+ let all = state
367+ .store
368+ .list_releases(&repo.id)
369+ .await
370+ .map_err(api::internal)?;
371+ return all
372+ .into_iter()
373+ .find(|r| id.parse() == Ok(gitea::numeric_id(&r.id)))
374+ .ok_or_else(|| Box::new(not_found()));
375+ }
317 match state.store.release(id).await {376 match state.store.release(id).await {
318 Ok(Some(release)) if release.repo_id == repo.id => Ok(release),377 Ok(Some(release)) if release.repo_id == repo.id => Ok(release),
319 Ok(_) => Err(Box::new(not_found())),378 Ok(_) => Err(Box::new(not_found())),
@@ -337,18 +396,28 @@ async fn release_json(
337 .iter()396 .iter()
338 .map(|asset| asset_json(base, repo, release, asset))397 .map(|asset| asset_json(base, repo, release, asset))
339 .collect();398 .collect();
399+ // `id` and `author` follow Gitea (an integer and a user object); `uid` and `author_name`
400+ // keep the forge values, and the forge field names stay next to the Gitea ones.
340 Ok(json!({401 Ok(json!({
341- "id": release.id,402+ "id": gitea::numeric_id(&release.id),
403+ "uid": release.id,
342 "tag": release.tag,404 "tag": release.tag,
405+ "tag_name": release.tag,
343 "target": release.target_oid,406 "target": release.target_oid,
407+ "target_commitish": release.target_oid,
344 "title": release.title,408 "title": release.title,
409+ "name": release.title,
345 "body": release.body,410 "body": release.body,
346 "draft": release.draft,411 "draft": release.draft,
347 "prerelease": release.prerelease,412 "prerelease": release.prerelease,
348- "author": release.author_name,413+ "author": gitea::user_json(base, &release.author_id, &release.author_name),
414+ "author_name": release.author_name,
349 "created_at": release.created_at,415 "created_at": release.created_at,
350 "published_at": release.published_at,416 "published_at": release.published_at,
351 "html_url": format!("{base}/{}/{}/releases/tag/{}", repo.owner_name, repo.name, enc(&release.tag)),417 "html_url": format!("{base}/{}/{}/releases/tag/{}", repo.owner_name, repo.name, enc(&release.tag)),
418+ "url": format!("{base}/api/v1/repos/{}/{}/releases/{}", repo.owner_name, repo.name, gitea::numeric_id(&release.id)),
419+ "tarball_url": "",
420+ "zipball_url": "",
352 "assets": assets,421 "assets": assets,
353 }))422 }))
354 }423 }
@@ -356,21 +425,25 @@ async fn release_json(
356 /// The asset JSON. `download_url` is the web download route, which enforces draft visibility.425 /// The asset JSON. `download_url` is the web download route, which enforces draft visibility.
357 fn asset_json(base: &str, repo: &CoreRepo, release: &Release, asset: &ReleaseAsset) -> Value {426 fn asset_json(base: &str, repo: &CoreRepo, release: &Release, asset: &ReleaseAsset) -> Value {
358 let base = base.trim_end_matches('/');427 let base = base.trim_end_matches('/');
428+ let download = format!(
429+ "{base}/{}/{}/releases/download/{}/{}",
430+ repo.owner_name,
431+ repo.name,
432+ enc(&release.tag),
433+ enc(&asset.name)
434+ );
359 json!({435 json!({
360- "id": asset.id,436+ "id": gitea::numeric_id(&asset.id),
437+ "uid": asset.id,
438+ "uuid": asset.id,
361 "name": asset.name,439 "name": asset.name,
362 "size": asset.size,440 "size": asset.size,
363 "sha256": asset.sha256,441 "sha256": asset.sha256,
364 "content_type": asset.content_type,442 "content_type": asset.content_type,
365 "download_count": asset.download_count,443 "download_count": asset.download_count,
366 "created_at": asset.created_at,444 "created_at": asset.created_at,
367- "download_url": format!(445+ "download_url": download,
368- "{base}/{}/{}/releases/download/{}/{}",446+ "browser_download_url": download,
369- repo.owner_name,
370- repo.name,
371- enc(&release.tag),
372- enc(&asset.name)
373- ),
374 })447 })
375 }448 }
376 449
@@ -554,7 +627,7 @@ mod tests {
554 async fn create(f: &Fixture, json: &str) -> String {627 async fn create(f: &Fixture, json: &str) -> String {
555 let (status, body) = post_json(f, Some(&bearer(&f.owner_token)), json).await;628 let (status, body) = post_json(f, Some(&bearer(&f.owner_token)), json).await;
556 assert_eq!(status, 201, "{body}");629 assert_eq!(status, 201, "{body}");
557- body["id"].as_str().expect("id").to_owned()630+ body["uid"].as_str().expect("uid").to_owned()
558 }631 }
559 632
560 async fn upload(f: &Fixture, id: &str, name: &str, bytes: Vec<u8>) -> (u16, serde_json::Value) {633 async fn upload(f: &Fixture, id: &str, name: &str, bytes: Vec<u8>) -> (u16, serde_json::Value) {
@@ -621,7 +694,7 @@ mod tests {
621 assert_eq!(body["title"], "v1.0", "the title defaults to the tag");694 assert_eq!(body["title"], "v1.0", "the title defaults to the tag");
622 assert_eq!(body["body"], "notes");695 assert_eq!(body["body"], "notes");
623 assert_eq!(body["draft"], false);696 assert_eq!(body["draft"], false);
624- assert_eq!(body["author"], OWNER);697+ assert_eq!(body["author_name"], OWNER);
625 assert_eq!(body["assets"], serde_json::json!([]));698 assert_eq!(body["assets"], serde_json::json!([]));
626 assert_eq!(body["target"].as_str().map(str::len), Some(40));699 assert_eq!(body["target"].as_str().map(str::len), Some(40));
627 assert!(700 assert!(
@@ -750,7 +823,7 @@ mod tests {
750 let f = fixture(None).await;823 let f = fixture(None).await;
751 let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await;824 let id = create(&f, r#"{"tag":"v1","target":"main"}"#).await;
752 let (_, asset) = upload(&f, &id, "app.bin", b"x".to_vec()).await;825 let (_, asset) = upload(&f, &id, "app.bin", b"x".to_vec()).await;
753- let asset_id = asset["id"].as_str().unwrap().to_owned();826+ let asset_id = asset["uid"].as_str().unwrap().to_owned();
754 let auth = bearer(&f.owner_token);827 let auth = bearer(&f.owner_token);
755 828
756 let (status, _) = send(829 let (status, _) = send(
crates/forge-web/src/pages/releases.rsmodified+41 -4
@@ -1247,15 +1247,52 @@ async fn asset_download(cx: &Cx) -> Result<Response> {
1247 let repo_name = path_param::<Repo>(cx);1247 let repo_name = path_param::<Repo>(cx);
1248 let tag_param = path_param::<Tag>(cx).to_owned();1248 let tag_param = path_param::<Tag>(cx).to_owned();
1249 let file_name = path_param::<Name>(cx).to_owned();1249 let file_name = path_param::<Name>(cx).to_owned();
1250- let ctx = load_repo(cx, owner, repo_name).await?;
1251 let state = app_context::<AppState>(cx);1250 let state = app_context::<AppState>(cx);
1252- let Some(release) = state.store.release_by_tag(&ctx.repo.id, &tag_param).await? else {1251+ // A caller that sends credentials (a Gitea or Forgejo server migrating this repo) is judged by
1252+ // its token, with the same rules as the API. Everyone else goes through the session.
1253+ if headers(cx).contains_key(http::header::AUTHORIZATION) {
1254+ let actor =
1255+ match crate::api::authenticate(state, crate::client_ip::client_ip(cx), headers(cx))
1256+ .await
1257+ {
1258+ Ok(actor) => actor,
1259+ Err(res) => return Ok(*res),
1260+ };
1261+ let repo = match crate::api::load_repo(
1262+ state,
1263+ actor.as_ref(),
1264+ owner,
1265+ repo_name,
1266+ Action::Read,
1267+ )
1268+ .await
1269+ {
1270+ Ok(repo) => repo,
1271+ Err(res) => return Ok(*res),
1272+ };
1273+ let writer = crate::api::load_repo(state, actor.as_ref(), owner, repo_name, Action::Write)
1274+ .await
1275+ .is_ok();
1276+ return stream_asset(state, &repo, writer, &tag_param, &file_name).await;
1277+ }
1278+ let ctx = load_repo(cx, owner, repo_name).await?;
1279+ stream_asset(state, &ctx.repo, can_write(&ctx), &tag_param, &file_name).await
1280+}
1281+
1282+async fn stream_asset(
1283+ state: &AppState,
1284+ repo: &CoreRepo,
1285+ writer: bool,
1286+ tag_param: &str,
1287+ file_name: &str,
1288+) -> Result<Response> {
1289+ let Some(release) = state.store.release_by_tag(&repo.id, tag_param).await? else {
1253 return Err(not_found().into());1290 return Err(not_found().into());
1254 };1291 };
1255- if release.draft && !can_write(&ctx) {1292+ if release.draft && !writer {
1256 return Err(not_found().into());1293 return Err(not_found().into());
1257 }1294 }
1258- let Some(asset) = state.store.release_asset(&release.id, &file_name).await? else {1295+ let Some(asset) = state.store.release_asset(&release.id, file_name).await? else {
1259 return Err(not_found().into());1296 return Err(not_found().into());
1260 };1297 };
1261 let Some(read) = state.blobs.read(&asset_key(&asset.id)).await? else {1298 let Some(read) = state.blobs.read(&asset_key(&asset.id)).await? else {
docs/api.mdmodified+70 -8
@@ -6,13 +6,17 @@ The examples use the base URL from `config/forge.toml`, `http://127.0.0.1:7660`.
6 ## Authentication6 ## Authentication
7 7
8 Requests authenticate with a personal access token. Create one at **Settings → Tokens**8 Requests authenticate with a personal access token. Create one at **Settings → Tokens**
9-(`/settings/tokens`). Send it either way:9+(`/settings/tokens`). Send it any of these ways:
10 10
11 ```11 ```
12 Authorization: Bearer forge_...12 Authorization: Bearer forge_...
13 Authorization: token forge_...13 Authorization: token forge_...
14+Authorization: Basic base64(any-name:forge_...)
14 ```15 ```
15 16
17+The Basic form takes the token as the password and ignores the user name. The Gitea routes below
18+also take `?access_token=forge_...`.
19+
16 - A token needs the `repo` scope. It is the only scope the token form offers. A token without it20 - A token needs the `repo` scope. It is the only scope the token form offers. A token without it
17 gets `403`.21 gets `403`.
18 - Session cookies are never read by this API. A browser that is logged in cannot call these22 - 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`.
147 | `DELETE` | `/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` | write | `204` |151 | `DELETE` | `/api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` | write | `204` |
148 152
149 In the asset routes `{asset}` is the file name for `PUT` and the asset `id` (from the release JSON)153 In the asset routes `{asset}` is the file name for `PUT` and the asset `id` (from the release JSON)
150-for `DELETE`.154+for `DELETE`. `GET /api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset}` answers one asset
155+(Gitea's route), with the asset `id` as `{asset}`. A release `{id}` and an asset `id` are the
156+integers in the JSON; the ULID in `uid` works too. The list takes `page` and `limit` and always
157+sends `X-Total-Count` and `Link`; without them it returns everything.
151 158
152 Drafts are visible only to callers with write access: they are left out of the list, and fetching159 Drafts are visible only to callers with write access: they are left out of the list, and fetching
153 one by tag gets `404` for anyone else. A release `{id}` must belong to the repo in the path;160 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:
168 175
169 ```json176 ```json
170 {177 {
171- "id": "01J...",178+ "id": 281474976710,
179+ "uid": "01J...",
172 "tag": "v1.2.0",180 "tag": "v1.2.0",
181+ "tag_name": "v1.2.0",
173 "target": "0123...",182 "target": "0123...",
183+ "target_commitish": "0123...",
174 "title": "v1.2.0",184 "title": "v1.2.0",
185+ "name": "v1.2.0",
175 "body": "Built by CI",186 "body": "Built by CI",
176 "draft": false,187 "draft": false,
177 "prerelease": false,188 "prerelease": false,
178- "author": "tahinli",189+ "author": {"id": 5120043, "login": "tahinli", "username": "tahinli", "...": "..."},
190+ "author_name": "tahinli",
179 "created_at": "2026-10-19T10:00:00Z",191 "created_at": "2026-10-19T10:00:00Z",
180 "published_at": "2026-10-19T10:00:00Z",192 "published_at": "2026-10-19T10:00:00Z",
181 "html_url": "http://127.0.0.1:7660/tahinli/demo/releases/tag/v1.2.0",193 "html_url": "http://127.0.0.1:7660/tahinli/demo/releases/tag/v1.2.0",
182 "assets": [194 "assets": [
183 {195 {
184- "id": "01J...",196+ "id": 1099511627,
197+ "uid": "01J...",
185 "name": "forge-linux-x86_64.tar.gz",198 "name": "forge-linux-x86_64.tar.gz",
186 "size": 1048576,199 "size": 1048576,
187 "sha256": "9f86...",200 "sha256": "9f86...",
188 "content_type": "application/gzip",201 "content_type": "application/gzip",
189 "download_count": 3,202 "download_count": 3,
190 "created_at": "2026-10-19T10:01:00Z",203 "created_at": "2026-10-19T10:01:00Z",
191- "download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz"204+ "download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz",
205+ "browser_download_url": "http://127.0.0.1:7660/tahinli/demo/releases/download/v1.2.0/forge-linux-x86_64.tar.gz"
192 }206 }
193 ]207 ]
194 }208 }
195 ```209 ```
196 210
197-`published_at` is `null` for a draft. `download_url` is the web download route, so it works with211+`published_at` is `null` for a draft. `download_url` (also sent as `browser_download_url`) is the
198-the same visibility rules as the release page.212+web download route, so it works with the same visibility rules as the release page, and it
213+accepts a token (`Authorization: token`, Bearer or Basic) for private repos. `id` and `author`
214+have Gitea's shapes (an integer and a user object) so Gitea clients can read them; `uid` and
215+`author_name` keep the forge values.
199 216
200 ### Create a release217 ### Create a release
201 218
@@ -297,3 +314,48 @@ echo "published $TAG"
297 If the job runs on the tag itself, the tag already exists and `target` is ignored. A simpler314 If the job runs on the tag itself, the tag already exists and `target` is ignored. A simpler
298 alternative needs no script at all: a `[release]` table in `ci.toml` publishes the release from315 alternative needs no script at all: a `[release]` table in `ci.toml` publishes the release from
299 a tag run and attaches the selected artifacts. See `docs/ci.md`, "Releases".316 a tag run and attaches the selected artifacts. See `docs/ci.md`, "Releases".
317+
318+## Moving to Forgejo or Gitea
319+
320+Forgejo and Gitea can pull a repo out of forge with its issues, comments, pull requests, reviews,
321+labels, milestones and releases (with their files). They do it through their own "Gitea"
322+migration, which talks to a read-only subset of the Gitea API that forge serves under
323+`/api/v1`.
324+
325+1. In forge, open **Settings → Tokens** and create a token for the account that can read the repo.
326+ A token sees exactly what its user sees, so for a private repo use an account with access.
327+2. In Forgejo or Gitea, choose **New migration**, then **Gitea**.
328+3. Set **Migrate / Clone from URL** to the repo's address on forge, for example
329+ `https://forge.example.com/tahinli/demo`. It must start with the `base_url` of
330+ `config/forge.toml`.
331+4. Paste the token into **Access token**. Leave user name and password empty.
332+5. Tick what to bring: Issues, Pull requests, Labels, Milestones, Releases. Choose the owner and
333+ name on the new server, then start.
334+
335+The target server must be allowed to reach forge. Forgejo and Gitea refuse local and private
336+addresses by default; when forge runs on one, add `ALLOW_LOCALNETWORKS = true` under
337+`[migrations]` in the target's `app.ini`.
338+
339+What the routes answer (all `GET`, paged with `page` and `limit`, at most 50 per page, with
340+`X-Total-Count` and `Link` headers):
341+
342+| Path | Notes |
343+| --- | --- |
344+| `/api/v1/version` | `{"version": "1.22.0"}`, high enough for the downloader to ask for reactions, reviews and pull request head commits. |
345+| `/api/v1/settings/api` | `max_response_items` 50. |
346+| `/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. |
347+| `.../topics` | Always empty. |
348+| `.../labels`, `.../milestones` | `state=all` works for milestones. |
349+| `.../releases`, `.../releases/{id}/assets/{asset}` | Assets download from `browser_download_url`; a token is accepted there. |
350+| `.../issues` | `type=issues` or `type=pulls`, `state=open`, `closed` or `all`. Labels, milestone and assignees included. |
351+| `.../issues/{index}/comments` | Pull request comments too. |
352+| `.../issues/{index}/reactions`, `.../issues/comments/{id}/reactions` | Forge keeps the first ten users per emoji, so a busy emoji is cut short. |
353+| `.../pulls` | Head and base refs and commits, merge state. |
354+| `.../pulls/{index}/reviews`, `.../pulls/{index}/reviews/{id}/comments` | Approvals, requested changes, line comments. Pending reviews are never shown. |
355+
356+Git over HTTP accepts the same token as the Basic password, with your user name, `oauth2` or
357+`x-access-token` as the name.
358+
359+Not carried over: topics, wiki and LFS objects (the clone brings the code only), user emails and
360+avatars (people arrive as plain user names, so the target creates placeholders you can re-map),
361+team reviews, discussions, snippets, CI runs and secrets.