diff --git a/Cargo.lock b/Cargo.lock index df20c45..33db61e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1962,6 +1962,7 @@ dependencies = [ "bytes", "comrak", "emojis", + "flate2", "forge-ci", "forge-core", "forge-git", @@ -1991,6 +1992,7 @@ dependencies = [ "similar", "subtle", "syntect", + "tar", "tempfile", "time", "tokio", diff --git a/crates/forge-core/migrations/0061_imports.sql b/crates/forge-core/migrations/0061_imports.sql new file mode 100644 index 0000000..f6fadd9 --- /dev/null +++ b/crates/forge-core/migrations/0061_imports.sql @@ -0,0 +1,38 @@ +-- Repository imports from a git URL, GitHub or GitLab. A job is the visible, resumable unit of work. +-- The remote token is never stored: it lives in memory for the length of the job only. + +CREATE TABLE import_jobs ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + repo_id TEXT REFERENCES repos(id) ON DELETE SET NULL, + source TEXT NOT NULL, -- 'git' | 'github' | 'gitlab' + source_ref TEXT NOT NULL, -- what the user typed, without credentials + options TEXT NOT NULL DEFAULT '{}', -- JSON: which parts to import + state TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | failed + stage TEXT NOT NULL DEFAULT '', + done INTEGER NOT NULL DEFAULT 0, + total INTEGER NOT NULL DEFAULT 0, + error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + finished_at TEXT); +CREATE INDEX import_jobs_user ON import_jobs(user_id, created_at); + +CREATE TABLE import_events ( + job_id TEXT NOT NULL REFERENCES import_jobs(id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + level TEXT NOT NULL, -- 'info' | 'warn' | 'error' + message TEXT NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (job_id, seq)); + +-- Maps a remote object to the local one, so a retry skips what was imported already. Also keeps +-- who wrote the original and where it lives, for people with no local account. +CREATE TABLE import_map ( + repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, + kind TEXT NOT NULL, -- label | milestone | issue | comment | release | asset + ext_id TEXT NOT NULL, + local_id TEXT NOT NULL, + orig_author TEXT NOT NULL DEFAULT '', + orig_url TEXT NOT NULL DEFAULT '', + PRIMARY KEY (repo_id, kind, ext_id)); diff --git a/crates/forge-core/migrations/0062_data_exports.sql b/crates/forge-core/migrations/0062_data_exports.sql new file mode 100644 index 0000000..8c329fa --- /dev/null +++ b/crates/forge-core/migrations/0062_data_exports.sql @@ -0,0 +1,12 @@ +-- Per-user data exports: a tar.gz built in the background, downloadable until it expires. + +CREATE TABLE data_exports ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + state TEXT NOT NULL DEFAULT 'building', -- building | ready | failed + size INTEGER NOT NULL DEFAULT 0, + error TEXT, + created_at TEXT NOT NULL, + ready_at TEXT, + expires_at TEXT NOT NULL); +CREATE INDEX data_exports_user ON data_exports(user_id, created_at); diff --git a/crates/forge-core/src/store/exports.rs b/crates/forge-core/src/store/exports.rs new file mode 100644 index 0000000..df10d79 --- /dev/null +++ b/crates/forge-core/src/store/exports.rs @@ -0,0 +1,168 @@ +//! Storage for per-user data exports (migration 0062). The archive bytes live on disk; this layer +//! tracks the state and the expiry. + +use std::time::Duration; + +use turso::{Row, Value}; + +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::error::Result; +use crate::time::{now_stamp, stamp_after}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExportState { + Building, + Ready, + Failed, +} + +impl ExportState { + pub fn as_str(self) -> &'static str { + match self { + ExportState::Building => "building", + ExportState::Ready => "ready", + ExportState::Failed => "failed", + } + } + + fn parse(s: &str) -> Self { + match s { + "ready" => ExportState::Ready, + "failed" => ExportState::Failed, + _ => ExportState::Building, + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DataExport { + pub id: String, + pub user_id: String, + pub state: ExportState, + pub size: i64, + pub error: Option, + pub created_at: String, + pub ready_at: Option, + pub expires_at: String, +} + +const COLS: &str = "id, user_id, state, size, error, created_at, ready_at, expires_at"; + +fn map_export(row: &Row) -> Result { + Ok(DataExport { + id: col_text(row, 0)?, + user_id: col_text(row, 1)?, + state: ExportState::parse(&col_text(row, 2)?), + size: col_int(row, 3)?, + error: col_opt_text(row, 4)?, + created_at: col_text(row, 5)?, + ready_at: col_opt_text(row, 6)?, + expires_at: col_text(row, 7)?, + }) +} + +impl Store { + /// Starts an export. It expires `ttl` from now; becoming ready restarts the clock. + pub async fn create_export(&self, user_id: &str, ttl: Duration) -> Result { + let id = new_id(); + let now = now_stamp(); + let expires = stamp_after(ttl); + { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO data_exports (id, user_id, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4)", + (id.clone(), user_id.to_owned(), now, expires), + ) + .await + .map_err(db_err)?; + } + self.data_export(&id).await?.ok_or_else(super::missing_row) + } + + pub async fn data_export(&self, id: &str) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_opt( + &conn, + &format!("SELECT {COLS} FROM data_exports WHERE id = ?1"), + (id.to_owned(),), + map_export, + ) + .await + } + + /// The user's exports, newest first. + pub async fn list_exports(&self, user_id: &str) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_all( + &conn, + &format!( + "SELECT {COLS} FROM data_exports WHERE user_id = ?1 ORDER BY created_at DESC, id DESC" + ), + (user_id.to_owned(),), + map_export, + ) + .await + } + + /// Marks an export ready and restarts its expiry from now. + pub async fn mark_export_ready(&self, id: &str, size: i64, ttl: Duration) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE data_exports SET state = 'ready', size = ?2, ready_at = ?3, expires_at = ?4 \ + WHERE id = ?1", + vec![ + Value::Text(id.to_owned()), + Value::Integer(size), + Value::Text(now_stamp()), + Value::Text(stamp_after(ttl)), + ], + ) + .await + .map_err(db_err)?; + Ok(()) + } + + pub async fn mark_export_failed(&self, id: &str, error: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE data_exports SET state = 'failed', error = ?2 WHERE id = ?1", + (id.to_owned(), error.to_owned()), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Exports whose expiry has passed at `now`. + pub async fn expired_exports(&self, now: &str) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_all( + &conn, + &format!("SELECT {COLS} FROM data_exports WHERE expires_at <= ?1"), + (now.to_owned(),), + map_export, + ) + .await + } + + pub async fn delete_export(&self, id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute("DELETE FROM data_exports WHERE id = ?1", (id.to_owned(),)) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Fails exports that were still building when the process stopped. Called at boot. + pub async fn fail_interrupted_exports(&self) -> Result { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE data_exports SET state = 'failed', error = 'interrupted by a server restart' \ + WHERE state = 'building'", + (), + ) + .await + .map_err(db_err) + } +} diff --git a/crates/forge-core/src/store/imports.rs b/crates/forge-core/src/store/imports.rs new file mode 100644 index 0000000..98eb635 --- /dev/null +++ b/crates/forge-core/src/store/imports.rs @@ -0,0 +1,351 @@ +//! Storage for repository import jobs, their progress log and the remote-to-local id map +//! (migration 0061). No remote credential is ever stored here. + +use turso::{Row, Value}; + +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::error::{Error, Result}; +use crate::time::now_stamp; + +/// Most progress lines kept per job. Older ones are dropped as new ones arrive. +pub const MAX_EVENTS: i64 = 500; + +/// Where a job is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImportState { + Queued, + Running, + Done, + Failed, +} + +impl ImportState { + pub fn as_str(self) -> &'static str { + match self { + ImportState::Queued => "queued", + ImportState::Running => "running", + ImportState::Done => "done", + ImportState::Failed => "failed", + } + } + + pub fn is_finished(self) -> bool { + matches!(self, ImportState::Done | ImportState::Failed) + } + + fn parse(s: &str) -> Result { + match s { + "queued" => Ok(ImportState::Queued), + "running" => Ok(ImportState::Running), + "done" => Ok(ImportState::Done), + "failed" => Ok(ImportState::Failed), + other => Err(Error::Database(format!("unknown import state `{other}`"))), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ImportJob { + pub id: String, + pub user_id: String, + pub repo_id: Option, + pub source: String, + pub source_ref: String, + pub options: String, + pub state: ImportState, + pub stage: String, + pub done: i64, + pub total: i64, + pub error: Option, + pub created_at: String, + pub updated_at: String, + pub finished_at: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ImportEvent { + pub seq: i64, + pub level: String, + pub message: String, + pub created_at: String, +} + +/// The remote object a local row came from. +#[derive(Debug, Clone, PartialEq)] +pub struct ImportOrigin { + pub local_id: String, + pub author: String, + pub url: String, +} + +const JOB_COLS: &str = "id, user_id, repo_id, source, source_ref, options, state, stage, done, \ + total, error, created_at, updated_at, finished_at"; + +fn map_job(row: &Row) -> Result { + Ok(ImportJob { + id: col_text(row, 0)?, + user_id: col_text(row, 1)?, + repo_id: col_opt_text(row, 2)?, + source: col_text(row, 3)?, + source_ref: col_text(row, 4)?, + options: col_text(row, 5)?, + state: ImportState::parse(&col_text(row, 6)?)?, + stage: col_text(row, 7)?, + done: col_int(row, 8)?, + total: col_int(row, 9)?, + error: col_opt_text(row, 10)?, + created_at: col_text(row, 11)?, + updated_at: col_text(row, 12)?, + finished_at: col_opt_text(row, 13)?, + }) +} + +fn text(s: &str) -> Value { + Value::Text(s.to_owned()) +} + +impl Store { + /// Creates a queued job. `source_ref` must not hold a credential. + pub async fn create_import_job( + &self, + user_id: &str, + repo_id: &str, + source: &str, + source_ref: &str, + options: &str, + ) -> Result { + let id = new_id(); + let now = now_stamp(); + { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO import_jobs (id, user_id, repo_id, source, source_ref, options, \ + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)", + vec![ + text(&id), + text(user_id), + text(repo_id), + text(source), + text(source_ref), + text(options), + text(&now), + ], + ) + .await + .map_err(db_err)?; + } + self.import_job(&id).await?.ok_or_else(super::missing_row) + } + + pub async fn import_job(&self, id: &str) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_opt( + &conn, + &format!("SELECT {JOB_COLS} FROM import_jobs WHERE id = ?1"), + (id.to_owned(),), + map_job, + ) + .await + } + + /// The user's jobs, newest first. + pub async fn list_import_jobs(&self, user_id: &str, limit: u32) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_all( + &conn, + &format!( + "SELECT {JOB_COLS} FROM import_jobs WHERE user_id = ?1 \ + ORDER BY created_at DESC, id DESC LIMIT ?2" + ), + (user_id.to_owned(), i64::from(limit.clamp(1, 200))), + map_job, + ) + .await + } + + /// The unfinished job of a repo, if any. A repo has at most one running import. + pub async fn active_import_for_repo(&self, repo_id: &str) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_opt( + &conn, + &format!( + "SELECT {JOB_COLS} FROM import_jobs WHERE repo_id = ?1 \ + AND state IN ('queued', 'running') LIMIT 1" + ), + (repo_id.to_owned(),), + map_job, + ) + .await + } + + /// Moves a job to `state`. A finished state stamps `finished_at`. A retry clears the error. + pub async fn set_import_state( + &self, + id: &str, + state: ImportState, + error: Option<&str>, + ) -> Result<()> { + let now = now_stamp(); + let finished = state.is_finished().then(|| now.clone()); + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE import_jobs SET state = ?2, error = ?3, updated_at = ?4, finished_at = ?5 \ + WHERE id = ?1", + vec![ + text(id), + text(state.as_str()), + error.map_or(Value::Null, text), + text(&now), + finished.as_deref().map_or(Value::Null, text), + ], + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Records the current stage and how far it is. + pub async fn set_import_progress( + &self, + id: &str, + stage: &str, + done: i64, + total: i64, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE import_jobs SET stage = ?2, done = ?3, total = ?4, updated_at = ?5 WHERE id = ?1", + vec![ + text(id), + text(stage), + Value::Integer(done), + Value::Integer(total), + text(&now_stamp()), + ], + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Appends a progress line and drops the oldest beyond [`MAX_EVENTS`]. + pub async fn add_import_event(&self, job_id: &str, level: &str, message: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + let next = fetch_opt( + &conn, + "SELECT COALESCE(MAX(seq), 0) + 1 FROM import_events WHERE job_id = ?1", + (job_id.to_owned(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(1); + conn.execute( + "INSERT INTO import_events (job_id, seq, level, message, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + vec![ + text(job_id), + Value::Integer(next), + text(level), + text(message), + text(&now_stamp()), + ], + ) + .await + .map_err(db_err)?; + conn.execute( + "DELETE FROM import_events WHERE job_id = ?1 AND seq <= ?2", + (job_id.to_owned(), next - MAX_EVENTS), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The newest `limit` lines of a job, oldest first. + pub async fn list_import_events(&self, job_id: &str, limit: u32) -> Result> { + let conn = self.inner.conn.lock().await; + let mut rows = fetch_all( + &conn, + "SELECT seq, level, message, created_at FROM import_events WHERE job_id = ?1 \ + ORDER BY seq DESC LIMIT ?2", + (job_id.to_owned(), i64::from(limit.clamp(1, 500))), + |row| { + Ok(ImportEvent { + seq: col_int(row, 0)?, + level: col_text(row, 1)?, + message: col_text(row, 2)?, + created_at: col_text(row, 3)?, + }) + }, + ) + .await?; + rows.reverse(); + Ok(rows) + } + + /// The local row a remote object was imported as, if it was. + pub async fn import_origin( + &self, + repo_id: &str, + kind: &str, + ext_id: &str, + ) -> Result> { + let conn = self.inner.conn.lock().await; + fetch_opt( + &conn, + "SELECT local_id, orig_author, orig_url FROM import_map \ + WHERE repo_id = ?1 AND kind = ?2 AND ext_id = ?3", + (repo_id.to_owned(), kind.to_owned(), ext_id.to_owned()), + |row| { + Ok(ImportOrigin { + local_id: col_text(row, 0)?, + author: col_text(row, 1)?, + url: col_text(row, 2)?, + }) + }, + ) + .await + } + + /// Records that a remote object became `origin.local_id`. Idempotent. + pub async fn record_import_origin( + &self, + repo_id: &str, + kind: &str, + ext_id: &str, + origin: &ImportOrigin, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO import_map (repo_id, kind, ext_id, local_id, orig_author, orig_url) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(repo_id, kind, ext_id) DO UPDATE SET \ + local_id = excluded.local_id, orig_author = excluded.orig_author, \ + orig_url = excluded.orig_url", + vec![ + text(repo_id), + text(kind), + text(ext_id), + text(&origin.local_id), + text(&origin.author), + text(&origin.url), + ], + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Fails every job that was queued or running when the process stopped. Called at boot. + pub async fn fail_interrupted_imports(&self) -> Result { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE import_jobs SET state = 'failed', updated_at = ?1, finished_at = ?1, \ + error = 'interrupted by a server restart, retry to continue' \ + WHERE state IN ('queued', 'running')", + (now,), + ) + .await + .map_err(db_err) + } +} diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 4785e69..6d5453e 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -80,6 +80,8 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 53, include_str!("../../migrations/0053_required_checks.sql"), ), + (61, include_str!("../../migrations/0061_imports.sql")), + (62, include_str!("../../migrations/0062_data_exports.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 4b9f378..550de8c 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -9,6 +9,8 @@ pub mod commit_status; pub mod contributions; pub mod discussions; pub mod edit_history_read; +pub mod exports; +pub mod imports; pub mod issues; pub mod labels; pub mod lfs; diff --git a/crates/forge-git/src/mirror.rs b/crates/forge-git/src/mirror.rs index 3caaea4..c78c4df 100644 --- a/crates/forge-git/src/mirror.rs +++ b/crates/forge-git/src/mirror.rs @@ -102,6 +102,19 @@ pub async fn mirror_fetch( with_timeout(timeout, fetch(env, repo, url, auth, allow_http, pin, false)).await } +/// Fetches the mirror refs of a local path over the file transport. This exists so callers' tests +/// can import from a bare repo on disk; the web code never calls it, because every user-supplied +/// URL goes through [`mirror_fetch`], which refuses `file://`. +#[doc(hidden)] +pub async fn mirror_fetch_local( + env: &GitEnv, + repo: &Path, + source: &str, + timeout: Duration, +) -> Result<()> { + with_timeout(timeout, fetch(env, repo, source, None, false, None, true)).await +} + /// Pushes the mirror refs of the bare repo at `repo` to `url`, with prune. With `pin`, git connects /// to the pinned address. Times out after `timeout`, killing git. pub async fn mirror_push( diff --git a/crates/forge-web/Cargo.toml b/crates/forge-web/Cargo.toml index ee00f65..53c3360 100644 --- a/crates/forge-web/Cargo.toml +++ b/crates/forge-web/Cargo.toml @@ -53,6 +53,8 @@ ulid.workspace = true forge-runner = { workspace = true } lettre.workspace = true zip = { workspace = true } +tar.workspace = true +flate2.workspace = true [build-dependencies] grass.workspace = true diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index a025765..0b1318e 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -525,6 +525,18 @@ searchTimer = setTimeout(function () { searchTimer = null; liveSearch(input); }, 250); }); + // A checkbox marked data-select-all="" ticks or clears every checkbox inside the first + // element that matches the selector (the bulk import list). + document.addEventListener('change', function (e) { + var all = e.target && e.target.closest ? e.target.closest('[data-select-all]') : null; + if (!all) { return; } + var scope = document.querySelector(all.getAttribute('data-select-all')); + if (!scope) { return; } + Array.prototype.forEach.call(scope.querySelectorAll('input[type="checkbox"]'), function (box) { + box.checked = all.checked; + }); + }); + // Filter controls submit their form on change. document.addEventListener('change', function (e) { var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 5101178..9646d18 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -141,6 +141,8 @@ pub async fn serve( if let Err(e) = crate::signatures::rebuild_gpg_keyring(&state).await { tracing::error!(error = %e, "rebuilding the GPG keyring failed"); } + crate::importer::on_boot(&state).await; + crate::exporter::on_boot(&state).await; crate::webhooks::worker::spawn(state.clone()); crate::mirrors::worker::spawn(state.clone()); crate::advisories::worker::spawn(state.clone()); diff --git a/crates/forge-web/src/exporter.rs b/crates/forge-web/src/exporter.rs new file mode 100644 index 0000000..aad9751 --- /dev/null +++ b/crates/forge-web/src/exporter.rs @@ -0,0 +1,390 @@ +//! Per-user data export: a tar.gz of the user's repos as bare git bundles, plus their issues with +//! comments, releases and profile as JSON. It is built in a background task, and the user is told +//! when it is ready (the export page updates through its event stream, and a mail goes out when the +//! account has an address). An export expires after [`EXPORT_TTL`]. Expired files are removed the +//! next time anyone starts or lists an export and at boot, so nothing waits on a timer. +//! +//! Archive layout: +//! - `profile.json` +//! - `repos//repo.bundle` (absent for an empty repo) +//! - `repos//repo.json` (description, visibility, default branch, labels, milestones) +//! - `repos//issues.json` (issues and pull requests, each with its comments) +//! - `repos//releases.json` (release metadata and asset names, not the asset bytes) + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{LazyLock, Mutex, PoisonError}; +use std::time::Duration; + +use forge_core::issues::IssueFilter; +use forge_core::store::exports::{DataExport, ExportState}; +use forge_core::time::now_stamp; +use forge_core::{IssueSort, Repo, User}; +use forge_git::backup::bundle_create; +use serde_json::{Value, json}; +use tokio::sync::watch; + +use crate::state::AppState; + +/// How long a finished export stays downloadable. +pub const EXPORT_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60); +/// How many days that is, for the page text. +pub const EXPORT_TTL_DAYS: u64 = 7; +const PAGE: u32 = 100; + +static HUB: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +/// Follows a user's exports. Subscribe before reading their state. +pub fn subscribe(user_id: &str) -> watch::Receiver { + HUB.lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(user_id.to_owned()) + .or_insert_with(|| watch::channel(0).0) + .subscribe() +} + +fn bump(user_id: &str) { + let mut hub = HUB.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(tx) = hub.get(user_id) { + tx.send_modify(|n| *n = n.wrapping_add(1)); + if tx.receiver_count() == 0 { + hub.remove(user_id); + } + } +} + +pub fn export_dir(state: &AppState) -> PathBuf { + state.config.data_dir.join("exports") +} + +pub fn archive_path(state: &AppState, id: &str) -> PathBuf { + export_dir(state).join(format!("{id}.tar.gz")) +} + +/// Starts an export for `user` and returns its row. At most one runs per user: a second request +/// while one is building returns that one. +pub async fn start(state: &AppState, user: &User) -> forge_core::Result { + sweep_expired(state).await; + if let Some(running) = state + .store + .list_exports(&user.id) + .await? + .into_iter() + .find(|e| e.state == ExportState::Building) + { + return Ok(running); + } + let export = state.store.create_export(&user.id, EXPORT_TTL).await?; + let task_state = state.clone(); + let task_user = user.clone(); + let id = export.id.clone(); + tokio::spawn(async move { + run(&task_state, &task_user, &id).await; + }); + Ok(export) +} + +async fn run(state: &AppState, user: &User, id: &str) { + let outcome = build(state, user, id).await; + match outcome { + Ok(size) => { + if let Err(e) = state + .store + .mark_export_ready(id, i64::try_from(size).unwrap_or(i64::MAX), EXPORT_TTL) + .await + { + tracing::error!(error = %e, "export: could not mark the export ready"); + } + notify_ready(state, user, id).await; + } + Err(message) => { + tracing::error!(error = %message, export_id = id, "export failed"); + let _ = tokio::fs::remove_file(archive_path(state, id)).await; + if let Err(e) = state.store.mark_export_failed(id, &message).await { + tracing::error!(error = %e, "export: could not record a failure"); + } + } + } + bump(&user.id); +} + +async fn notify_ready(state: &AppState, user: &User, id: &str) { + let Some(email) = user.email.as_deref().filter(|e| !e.is_empty()) else { + return; + }; + let base = state.config.base_url.trim_end_matches('/'); + let body = format!( + "Your data export is ready.\n\nDownload it at {base}/settings/export (you must be signed in). \ + It is removed after {EXPORT_TTL_DAYS} days.\n" + ); + if let Err(e) = crate::mail::enqueue( + state, + &format!("export:{id}"), + forge_core::mail::MailKind::Other, + Some(&user.id), + email, + "Your data export is ready", + &body, + ) + .await + { + tracing::warn!(error = %e, "export: could not queue the ready mail"); + } +} + +/// Builds the archive and returns its size in bytes. +async fn build(state: &AppState, user: &User, id: &str) -> Result { + let dir = export_dir(state); + tokio::fs::create_dir_all(&dir) + .await + .map_err(|e| e.to_string())?; + let work = dir.join(format!("{id}.work")); + let _ = tokio::fs::remove_dir_all(&work).await; + tokio::fs::create_dir_all(work.join("repos")) + .await + .map_err(|e| e.to_string())?; + let result = stage_and_pack(state, user, id, &work).await; + let _ = tokio::fs::remove_dir_all(&work).await; + result +} + +async fn stage_and_pack( + state: &AppState, + user: &User, + id: &str, + work: &Path, +) -> Result { + write_json(&work.join("profile.json"), &profile_json(user)).await?; + let repos = state + .store + .list_repos_by_owner(&user.id) + .await + .map_err(|e| e.to_string())?; + for repo in &repos { + let repo_dir = work.join("repos").join(&repo.name); + tokio::fs::create_dir_all(&repo_dir) + .await + .map_err(|e| e.to_string())?; + stage_repo(state, repo, &repo_dir).await?; + } + let target = archive_path(state, id); + let partial = target.with_extension("part"); + let (work_buf, partial_buf, name) = ( + work.to_path_buf(), + partial.clone(), + format!("forge-export-{}", user.username), + ); + tokio::task::spawn_blocking(move || pack(&work_buf, &partial_buf, &name)) + .await + .map_err(|e| e.to_string())??; + tokio::fs::rename(&partial, &target) + .await + .map_err(|e| e.to_string())?; + let meta = tokio::fs::metadata(&target) + .await + .map_err(|e| e.to_string())?; + Ok(meta.len()) +} + +fn pack(work: &Path, out: &Path, top: &str) -> Result<(), String> { + use std::os::unix::fs::OpenOptionsExt; + let file = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(out) + .map_err(|e| e.to_string())?; + let gz = flate2::write::GzEncoder::new(file, flate2::Compression::default()); + let mut tar = tar::Builder::new(gz); + tar.append_dir_all(top, work).map_err(|e| e.to_string())?; + let gz = tar.into_inner().map_err(|e| e.to_string())?; + gz.finish().map_err(|e| e.to_string())?; + Ok(()) +} + +async fn write_json(path: &Path, value: &Value) -> Result<(), String> { + let text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?; + tokio::fs::write(path, text) + .await + .map_err(|e| e.to_string()) +} + +/// The account fields worth taking along. Never the password hash. +pub fn profile_json(user: &User) -> Value { + json!({ + "username": user.username, + "display_name": user.display_name, + "email": user.email, + "about": user.about, + "created_at": user.created_at, + "timezone": user.timezone, + "language": user.language, + "theme": user.theme, + "exported_at": now_stamp(), + }) +} + +async fn stage_repo(state: &AppState, repo: &Repo, dir: &Path) -> Result<(), String> { + let git_dir = + forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; + let bundled = bundle_create(&state.git, &git_dir, &dir.join("repo.bundle")) + .await + .map_err(|e| format!("bundling {}: {e}", repo.name))? + .is_some(); + + let labels = state + .store + .list_labels(&repo.id) + .await + .map_err(|e| e.to_string())?; + let milestones = state + .store + .list_milestones(&repo.id, None) + .await + .map_err(|e| e.to_string())?; + let meta = json!({ + "name": repo.name, + "description": repo.description, + "visibility": repo.visibility.as_str(), + "default_branch": repo.default_branch, + "created_at": repo.created_at, + "archived": repo.archived, + "has_bundle": bundled, + "labels": labels.iter().map(|l| json!({"name": l.name, "color": l.color, "description": l.description})).collect::>(), + "milestones": milestones.iter().map(|m| json!({ + "title": m.title, "description": m.description, "due_on": m.due_on, + "state": m.state.as_str(), "created_at": m.created_at, "closed_at": m.closed_at, + })).collect::>(), + }); + write_json(&dir.join("repo.json"), &meta).await?; + + let mut issues = Vec::new(); + let mut page = 1; + loop { + let filter = IssueFilter { + state: None, + sort: IssueSort::Oldest, + page, + per_page: PAGE, + ..IssueFilter::default() + }; + let (items, total) = state + .store + .list_issues(&repo.id, &filter) + .await + .map_err(|e| e.to_string())?; + let got = items.len(); + for item in items { + let comments = state + .store + .list_comments(&item.issue.id) + .await + .map_err(|e| e.to_string())?; + let names = state + .store + .usernames_by_ids( + &comments + .iter() + .map(|c| c.author_id.clone()) + .collect::>(), + ) + .await + .map_err(|e| e.to_string())?; + let names: HashMap = + names.into_iter().map(|(k, (name, _))| (k, name)).collect(); + issues.push(issue_json(&item, &comments, &names)); + } + if got == 0 || (u64::from(page) * u64::from(PAGE)) >= total { + break; + } + page += 1; + } + write_json(&dir.join("issues.json"), &Value::Array(issues)).await?; + + let releases = state + .store + .list_releases(&repo.id) + .await + .map_err(|e| e.to_string())?; + let mut out = Vec::new(); + for r in releases { + let assets = state + .store + .list_release_assets(&r.id) + .await + .map_err(|e| e.to_string())?; + out.push(json!({ + "tag": r.tag, "title": r.title, "body": r.body, "draft": r.draft, + "prerelease": r.prerelease, "author": r.author_name, "target_oid": r.target_oid, + "created_at": r.created_at, "published_at": r.published_at, + "assets": assets.iter().map(|a| json!({ + "name": a.name, "size": a.size, "sha256": a.sha256, + "content_type": a.content_type, "downloads": a.download_count, + })).collect::>(), + })); + } + write_json(&dir.join("releases.json"), &Value::Array(out)).await +} + +fn issue_json( + item: &forge_core::IssueListItem, + comments: &[forge_core::Comment], + names: &HashMap, +) -> Value { + let i = &item.issue; + json!({ + "number": i.number, + "title": i.title, + "body": i.body, + "state": i.state.as_str(), + "author": item.author, + "labels": item.labels.iter().map(|l| l.name.clone()).collect::>(), + "assignees": item.assignees, + "created_at": i.created_at, + "closed_at": i.closed_at, + "comments": comments.iter().map(|c| json!({ + "author": names.get(&c.author_id).cloned().unwrap_or_default(), + "body": c.body, + "created_at": c.created_at, + })).collect::>(), + }) +} + +/// Deletes every export past its expiry, rows and files. Failures are logged. +pub async fn sweep_expired(state: &AppState) { + let expired = match state.store.expired_exports(&now_stamp()).await { + Ok(rows) => rows, + Err(e) => { + tracing::warn!(error = %e, "export: could not list expired exports"); + return; + } + }; + for export in expired { + let path = archive_path(state, &export.id); + match tokio::fs::remove_file(&path).await { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + tracing::warn!(error = %e, "export: could not remove an expired archive"); + continue; + } + } + if let Err(e) = state.store.delete_export(&export.id).await { + tracing::warn!(error = %e, "export: could not delete an expired export row"); + } + bump(&export.user_id); + } +} + +/// Fails exports a restart cut short and removes expired ones. +pub async fn on_boot(state: &AppState) { + if let Err(e) = state.store.fail_interrupted_exports().await { + tracing::error!(error = %e, "export: could not clean up interrupted exports"); + } + sweep_expired(state).await; +} + +#[cfg(test)] +mod tests; diff --git a/crates/forge-web/src/exporter/tests.rs b/crates/forge-web/src/exporter/tests.rs new file mode 100644 index 0000000..f9d71f5 --- /dev/null +++ b/crates/forge-web/src/exporter/tests.rs @@ -0,0 +1,175 @@ +use std::io::Read; + +use forge_core::Visibility; +use forge_core::store::exports::ExportState; + +use super::*; +use crate::test_support::test_state; + +/// Reads a `.tar.gz` into `(path, bytes)` pairs. +fn entries(path: &Path) -> Vec<(String, Vec)> { + let file = std::fs::File::open(path).expect("archive opens"); + let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(file)); + let mut out = Vec::new(); + for entry in archive.entries().expect("entries") { + let mut entry = entry.expect("entry"); + let name = entry.path().expect("path").display().to_string(); + let mut bytes = Vec::new(); + entry.read_to_end(&mut bytes).expect("read"); + out.push((name, bytes)); + } + out +} + +async fn setup() -> (AppState, User, Repo, tempfile::TempDir) { + let dir = tempfile::tempdir().expect("tempdir"); + let state = test_state(dir.path()).await; + let user = state + .store + .create_user("tahinli", Some("tahinli@example.com"), "unused", false) + .await + .expect("user"); + let repo = state + .store + .create_repo(&user.id, "project", "A project", Visibility::Public, "main") + .await + .expect("repo"); + let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path"); + forge_git::repo::init_bare(&state.git, &bare, "main") + .await + .expect("init"); + // One commit so the bundle is not empty. + let run = |args: &[&str]| { + let out = std::process::Command::new("git") + .arg(format!("--git-dir={}", bare.display())) + .args(args) + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@example.com") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@example.com") + .output() + .expect("git"); + assert!(out.status.success(), "{out:?}"); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + let tree = run(&["hash-object", "-t", "tree", "-w", "--stdin"]); + let commit = run(&["commit-tree", &tree, "-m", "first"]); + run(&["update-ref", "refs/heads/main", &commit]); + let issue = state + .store + .create_issue(&repo.id, &user.id, "It breaks", "steps") + .await + .expect("issue"); + state + .store + .add_comment(&issue.id, &user.id, "same here") + .await + .expect("comment"); + (state, user, repo, dir) +} + +#[tokio::test] +async fn the_archive_holds_the_profile_bundles_issues_and_releases() { + let (state, user, _repo, _dir) = setup().await; + let export = start(&state, &user).await.expect("start"); + // Wait for the background build by following its own signal, not by polling. + let mut wake = subscribe(&user.id); + loop { + let row = state.store.data_export(&export.id).await.unwrap().unwrap(); + if row.state != ExportState::Building { + assert_eq!(row.state, ExportState::Ready, "{:?}", row.error); + assert!(row.size > 0); + break; + } + tokio::time::timeout(Duration::from_secs(60), wake.changed()) + .await + .expect("the export finishes") + .expect("signal open"); + } + + let files = entries(&archive_path(&state, &export.id)); + let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); + let has = |suffix: &str| names.iter().any(|n| n.ends_with(suffix)); + assert!(has("profile.json"), "{names:?}"); + assert!(has("repos/project/repo.bundle"), "{names:?}"); + assert!(has("repos/project/repo.json")); + assert!(has("repos/project/issues.json")); + assert!(has("repos/project/releases.json")); + + let read = |suffix: &str| { + let (_, bytes) = files.iter().find(|(n, _)| n.ends_with(suffix)).unwrap(); + String::from_utf8_lossy(bytes).into_owned() + }; + let profile = read("profile.json"); + assert!(profile.contains("tahinli@example.com")); + assert!( + !profile.contains("password"), + "no credential in the profile" + ); + let issues: serde_json::Value = serde_json::from_str(&read("issues.json")).unwrap(); + assert_eq!(issues[0]["title"], "It breaks"); + assert_eq!(issues[0]["comments"][0]["body"], "same here"); + assert_eq!(issues[0]["comments"][0]["author"], "tahinli"); + // The bundle is a real bundle. + let bundle = files + .iter() + .find(|(n, _)| n.ends_with("repo.bundle")) + .unwrap(); + assert!(bundle.1.starts_with(b"# v2 git bundle") || bundle.1.starts_with(b"# v3 git bundle")); +} + +#[tokio::test] +async fn an_expired_export_is_removed_with_its_file() { + let (state, user, _repo, _dir) = setup().await; + let export = state + .store + .create_export(&user.id, Duration::from_secs(0)) + .await + .expect("export"); + let path = archive_path(&state, &export.id); + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&path, b"x").await.unwrap(); + sweep_expired(&state).await; + assert!(state.store.data_export(&export.id).await.unwrap().is_none()); + assert!(!path.exists()); +} + +#[tokio::test] +async fn a_fresh_export_survives_the_sweep() { + let (state, user, _repo, _dir) = setup().await; + let export = state + .store + .create_export(&user.id, EXPORT_TTL) + .await + .unwrap(); + sweep_expired(&state).await; + assert!(state.store.data_export(&export.id).await.unwrap().is_some()); +} + +#[tokio::test] +async fn a_second_request_while_building_returns_the_running_export() { + let (state, user, _repo, _dir) = setup().await; + let running = state + .store + .create_export(&user.id, EXPORT_TTL) + .await + .unwrap(); + let again = start(&state, &user).await.unwrap(); + assert_eq!(again.id, running.id); +} + +#[tokio::test] +async fn ready_mail_is_queued_for_an_account_with_an_address() { + let (state, user, _repo, _dir) = setup().await; + notify_ready(&state, &user, "abc").await; + notify_ready(&state, &user, "abc").await; + let queued = state + .store + .list_mail(None, "9999-12-31T00:00:00Z", 10) + .await + .expect("mail list") + .len(); + assert_eq!(queued, 1, "one mail, however often the ready step runs"); +} diff --git a/crates/forge-web/src/i18n/migrate.rs b/crates/forge-web/src/i18n/migrate.rs new file mode 100644 index 0000000..1104d2c --- /dev/null +++ b/crates/forge-web/src/i18n/migrate.rs @@ -0,0 +1,349 @@ +//! Strings for importing repositories and exporting account data. Same pattern as the other +//! groups: one variant per phrase, an exhaustive `t`, so a missing translation fails to compile. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + // New repository tabs. + TabCreate, + TabImport, + // Import form. + ImportTitle, + ImportIntro, + SrcGit, + SrcGitHub, + SrcGitLab, + GitUrl, + GitUser, + GitPassword, + GitHubRepo, + GitLabInstance, + GitLabProject, + TokenOptional, + TokenHelp, + TargetOwner, + TargetName, + TargetNameHelp, + Description, + WhatToImport, + OptLabels, + OptIssues, + OptPulls, + OptReleases, + OptionsNote, + StartImport, + BulkLink, + JobsLink, + // Bulk import. + BulkTitle, + BulkIntro, + BulkOwnerGitHub, + BulkOwnerGitLab, + BulkListButton, + BulkSelectHeading, + BulkSelectAll, + BulkImportSelected, + BulkNone, + BulkPrivate, + BulkFork, + BulkArchived, + // Jobs. + JobsTitle, + NoJobs, + JobQueued, + JobRunning, + JobDone, + JobFailed, + JobRetry, + JobRetryHelp, + JobOpenRepo, + JobProgress, + JobNoLog, + JobStarted, + StageGit, + StageLabels, + StageMilestones, + StageIssues, + StageReleases, + StageDone, + // Errors. + ErrBadRemote, + ErrBadInstance, + ErrBadOwner, + ErrNothingSelected, + ErrTooMany, + // Data export. + SettingsExport, + ExportTitle, + ExportIntro, + ExportContents, + ExportRequest, + ExportBuilding, + ExportReady, + ExportFailed, + ExportDownload, + ExportNone, + ExportRequested, + ExportSize, + ExportEmailNote, +} + +#[cfg(test)] +const ALL: &[K] = &[ + K::TabCreate, + K::TabImport, + K::ImportTitle, + K::ImportIntro, + K::SrcGit, + K::SrcGitHub, + K::SrcGitLab, + K::GitUrl, + K::GitUser, + K::GitPassword, + K::GitHubRepo, + K::GitLabInstance, + K::GitLabProject, + K::TokenOptional, + K::TokenHelp, + K::TargetOwner, + K::TargetName, + K::TargetNameHelp, + K::Description, + K::WhatToImport, + K::OptLabels, + K::OptIssues, + K::OptPulls, + K::OptReleases, + K::OptionsNote, + K::StartImport, + K::BulkLink, + K::JobsLink, + K::BulkTitle, + K::BulkIntro, + K::BulkOwnerGitHub, + K::BulkOwnerGitLab, + K::BulkListButton, + K::BulkSelectHeading, + K::BulkSelectAll, + K::BulkImportSelected, + K::BulkNone, + K::BulkPrivate, + K::BulkFork, + K::BulkArchived, + K::JobsTitle, + K::NoJobs, + K::JobQueued, + K::JobRunning, + K::JobDone, + K::JobFailed, + K::JobRetry, + K::JobRetryHelp, + K::JobOpenRepo, + K::JobProgress, + K::JobNoLog, + K::JobStarted, + K::StageGit, + K::StageLabels, + K::StageMilestones, + K::StageIssues, + K::StageReleases, + K::StageDone, + K::ErrBadRemote, + K::ErrBadInstance, + K::ErrBadOwner, + K::ErrNothingSelected, + K::ErrTooMany, + K::SettingsExport, + K::ExportTitle, + K::ExportIntro, + K::ExportContents, + K::ExportRequest, + K::ExportBuilding, + K::ExportReady, + K::ExportFailed, + K::ExportDownload, + K::ExportNone, + K::ExportRequested, + K::ExportSize, + K::ExportEmailNote, +]; + +/// `(English, Turkish)` for each phrase. +fn pair(key: K) -> (&'static str, &'static str) { + match key { + K::TabCreate => ("Create", "Oluştur"), + K::TabImport => ("Import", "İçe aktar"), + K::ImportTitle => ("Import a repository", "Depo içe aktar"), + K::ImportIntro => ( + "Copy a repository with all its branches and tags. The result is a normal repository, not a mirror.", + "Bir depoyu tüm dalları ve etiketleriyle kopyalayın. Sonuç yansı değil, normal bir depodur.", + ), + K::SrcGit => ("Git URL", "Git URL'si"), + K::SrcGitHub => ("GitHub", "GitHub"), + K::SrcGitLab => ("GitLab", "GitLab"), + K::GitUrl => ("Repository URL", "Depo URL'si"), + K::GitUser => ("Username (optional)", "Kullanıcı adı (isteğe bağlı)"), + K::GitPassword => ( + "Password or token (optional)", + "Parola veya belirteç (isteğe bağlı)", + ), + K::GitHubRepo => ("Repository (owner/name)", "Depo (sahip/ad)"), + K::GitLabInstance => ("GitLab address", "GitLab adresi"), + K::GitLabProject => ("Project path", "Proje yolu"), + K::TokenOptional => ("Access token (optional)", "Erişim belirteci (isteğe bağlı)"), + K::TokenHelp => ( + "Needed for private repositories and higher rate limits. It is used only while the import runs and is never stored.", + "Özel depolar ve daha yüksek istek sınırı için gerekir. Yalnızca içe aktarma sürerken kullanılır ve asla saklanmaz.", + ), + K::TargetOwner => ("Owner", "Sahip"), + K::TargetName => ("New repository name", "Yeni depo adı"), + K::TargetNameHelp => ( + "Leave blank to keep the original name.", + "Özgün adı korumak için boş bırakın.", + ), + K::Description => ("Description (optional)", "Açıklama (isteğe bağlı)"), + K::WhatToImport => ("Also import", "Şunları da içe aktar"), + K::OptLabels => ("Labels and milestones", "Etiketler ve kilometre taşları"), + K::OptIssues => ("Issues and comments", "Konular ve yorumlar"), + K::OptPulls => ("Pull requests (as issues)", "Çekme istekleri (konu olarak)"), + K::OptReleases => ("Releases and their files", "Sürümler ve dosyaları"), + K::OptionsNote => ( + "Authors with no account here are shown as \"originally by @name on GitHub\". Pull requests become issues marked \"imported PR\", because their branches may be gone.", + "Burada hesabı olmayan yazarlar \"@ad tarafından, GitHub'da\" olarak gösterilir. Çekme istekleri, dalları silinmiş olabileceğinden \"imported PR\" işaretli konulara dönüşür.", + ), + K::StartImport => ("Start import", "İçe aktarmayı başlat"), + K::BulkLink => ("Import several repositories", "Birden çok depoyu içe aktar"), + K::JobsLink => ("Imports", "İçe aktarmalar"), + K::BulkTitle => ("Import several repositories", "Birden çok depoyu içe aktar"), + K::BulkIntro => ( + "List the repositories of a user or organization, tick the ones you want and import them together.", + "Bir kullanıcının veya kuruluşun depolarını listeleyin, istediklerinizi işaretleyin ve birlikte içe aktarın.", + ), + K::BulkOwnerGitHub => ( + "GitHub user or organization", + "GitHub kullanıcısı veya kuruluşu", + ), + K::BulkOwnerGitLab => ("GitLab user or group", "GitLab kullanıcısı veya grubu"), + K::BulkListButton => ("List repositories", "Depoları listele"), + K::BulkSelectHeading => ( + "Select the repositories to import", + "İçe aktarılacak depoları seçin", + ), + K::BulkSelectAll => ("Select all", "Tümünü seç"), + K::BulkImportSelected => ("Import selected", "Seçilenleri içe aktar"), + K::BulkNone => ("No repositories found.", "Depo bulunamadı."), + K::BulkPrivate => ("private", "özel"), + K::BulkFork => ("fork", "çatal"), + K::BulkArchived => ("archived", "arşivlenmiş"), + K::JobsTitle => ("Imports", "İçe aktarmalar"), + K::NoJobs => ("No imports yet.", "Henüz içe aktarma yok."), + K::JobQueued => ("Queued", "Sırada"), + K::JobRunning => ("Running", "Çalışıyor"), + K::JobDone => ("Done", "Bitti"), + K::JobFailed => ("Failed", "Başarısız"), + K::JobRetry => ("Retry", "Yeniden dene"), + K::JobRetryHelp => ( + "Enter the token again to continue. What was already imported is kept and skipped.", + "Devam etmek için belirteci yeniden girin. İçe aktarılanlar korunur ve atlanır.", + ), + K::JobOpenRepo => ("Open repository", "Depoyu aç"), + K::JobProgress => ("Progress", "İlerleme"), + K::JobNoLog => ("Nothing yet.", "Henüz bir şey yok."), + K::JobStarted => ("Started", "Başladı"), + K::StageGit => ("Git data", "Git verisi"), + K::StageLabels => ("Labels", "Etiketler"), + K::StageMilestones => ("Milestones", "Kilometre taşları"), + K::StageIssues => ("Issues and pull requests", "Konular ve çekme istekleri"), + K::StageReleases => ("Releases", "Sürümler"), + K::StageDone => ("Finished", "Tamamlandı"), + K::ErrBadRemote => ( + "That repository address is not valid.", + "Bu depo adresi geçerli değil.", + ), + K::ErrBadInstance => ( + "That GitLab address is not valid.", + "Bu GitLab adresi geçerli değil.", + ), + K::ErrBadOwner => ( + "That user or organization name is not valid.", + "Bu kullanıcı veya kuruluş adı geçerli değil.", + ), + K::ErrNothingSelected => ("Select at least one repository.", "En az bir depo seçin."), + K::ErrTooMany => ( + "Too many repositories selected at once.", + "Bir seferde çok fazla depo seçildi.", + ), + K::SettingsExport => ("Data export", "Veri dışa aktarımı"), + K::ExportTitle => ("Export your data", "Verilerinizi dışa aktarın"), + K::ExportIntro => ( + "Download an archive of your repositories as git bundles, with their issues, comments, releases and your profile as JSON.", + "Depolarınızı git paketleri olarak, konuları, yorumları, sürümleri ve profilinizi JSON olarak içeren bir arşiv indirin.", + ), + K::ExportContents => ( + "The archive holds profile.json and, for each repository, repo.bundle, repo.json, issues.json and releases.json. Release files are listed but not included.", + "Arşiv profile.json dosyasını ve her depo için repo.bundle, repo.json, issues.json ve releases.json dosyalarını içerir. Sürüm dosyaları listelenir ama dahil edilmez.", + ), + K::ExportRequest => ("Request an export", "Dışa aktarım iste"), + K::ExportBuilding => ("Building", "Hazırlanıyor"), + K::ExportReady => ("Ready", "Hazır"), + K::ExportFailed => ("Failed", "Başarısız"), + K::ExportDownload => ("Download", "İndir"), + K::ExportNone => ("No exports yet.", "Henüz dışa aktarım yok."), + K::ExportRequested => ("Requested", "İstendi"), + K::ExportSize => ("Size", "Boyut"), + K::ExportEmailNote => ( + "This page updates when the archive is ready, and we send an email if your account has an address.", + "Arşiv hazır olunca bu sayfa güncellenir; hesabınızda adres varsa e-posta da gönderilir.", + ), + } +} + +pub fn t(lang: Lang, key: K) -> &'static str { + let (en, tr) = pair(key); + match lang { + Lang::En => en, + Lang::Tr => tr, + } +} + +/// "Expires in N days" style line for the export list. +pub fn expires_on(lang: Lang, date: &str) -> String { + match lang { + Lang::En => format!("Expires {date}"), + Lang::Tr => format!("Son geçerlilik {date}"), + } +} + +/// The note about when a finished archive is removed. +pub fn export_ttl_note(lang: Lang, days: u64) -> String { + match lang { + Lang::En => format!("Archives are removed after {days} days."), + Lang::Tr => format!("Arşivler {days} gün sonra silinir."), + } +} + +pub fn progress_of(done: i64, total: i64) -> String { + format!("{done} / {total}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_variant_has_both_languages() { + for key in ALL { + assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English"); + assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish"); + assert!( + !t(Lang::En, *key).contains('\u{2014}'), + "{key:?} has an em dash" + ); + assert!( + !t(Lang::Tr, *key).contains('\u{2014}'), + "{key:?} has an em dash" + ); + } + } +} diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index ccec8a9..3080964 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -24,6 +24,7 @@ pub mod code; pub mod community; pub mod integrations; pub mod issues; +pub mod migrate; pub mod misc; pub mod orgs; pub mod pulls; diff --git a/crates/forge-web/src/importer/api.rs b/crates/forge-web/src/importer/api.rs new file mode 100644 index 0000000..d5a4ff9 --- /dev/null +++ b/crates/forge-web/src/importer/api.rs @@ -0,0 +1,1137 @@ +//! Remote forge APIs for imports. [`RemoteApi`] is the seam: the import job talks only to the +//! trait, so tests use a fake and CI never needs the network. [`GitHub`] and [`GitLab`] are the real +//! clients over REST. They paginate, wait out rate limits (and say so through the notice callback), +//! and send the token only to the API host, never to a redirect target. + +use std::fmt; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; + +use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, LOCATION, RETRY_AFTER}; +use serde::Deserialize; +use serde::de::DeserializeOwned; + +const PER_PAGE: usize = 100; +/// Hard stop on pagination, so a misbehaving server cannot keep a job alive forever. +const MAX_PAGES: usize = 500; +/// Longest rate-limit wait a job sits through. A longer reset fails the job; a retry continues. +const MAX_RATE_WAIT: u64 = 15 * 60; +/// Largest JSON page read. +const MAX_JSON_BYTES: usize = 32 * 1024 * 1024; +const MAX_REDIRECTS: usize = 5; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ApiError { + NotFound(String), + Unauthorized(String), + RateLimited { wait_secs: u64 }, + TooLarge, + Http(String), + Parse(String), +} + +impl fmt::Display for ApiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ApiError::NotFound(what) => write!(f, "not found: {what}"), + ApiError::Unauthorized(what) => write!(f, "access denied: {what}"), + ApiError::RateLimited { wait_secs } => write!( + f, + "the rate limit is used up and resets in {wait_secs} seconds; retry then, nothing imported is lost" + ), + ApiError::TooLarge => write!(f, "the file is larger than the allowed size"), + ApiError::Http(msg) => write!(f, "request failed: {msg}"), + ApiError::Parse(msg) => write!(f, "unexpected response: {msg}"), + } + } +} + +pub type ApiResult = Result; + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtLabel { + pub name: String, + pub color: String, + pub description: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtMilestone { + pub id: String, + pub title: String, + pub description: String, + pub closed: bool, + /// `YYYY-MM-DD`. + pub due_on: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtIssue { + pub number: i64, + pub title: String, + pub body: String, + pub closed: bool, + pub not_planned: bool, + pub merged: bool, + pub author: String, + pub labels: Vec, + pub milestone: Option, + pub created_at: String, + pub url: String, + pub is_pr: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtComment { + pub id: String, + pub author: String, + pub body: String, + pub created_at: String, + pub url: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtAsset { + pub id: String, + pub name: String, + pub size: u64, + pub content_type: String, + pub url: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtRelease { + pub id: String, + pub tag: String, + pub title: String, + pub body: String, + pub draft: bool, + pub prerelease: bool, + pub author: String, + pub created_at: String, + pub url: String, + pub assets: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ExtRepo { + pub name: String, + /// `owner/name`, or the GitLab project path. + pub full_name: String, + pub description: String, + pub private: bool, + pub fork: bool, + pub archived: bool, + pub default_branch: String, + pub web_url: String, +} + +/// What an import needs from a remote forge. `repo` is `owner/name` for GitHub and the full +/// project path for GitLab. +pub trait RemoteApi: Send + Sync { + fn list_repos(&self, owner: &str) -> impl Future>> + Send; + fn labels(&self, repo: &str) -> impl Future>> + Send; + fn milestones(&self, repo: &str) -> impl Future>> + Send; + /// Issues and pull (merge) requests, every state, with `is_pr` set on the latter. + fn issues(&self, repo: &str) -> impl Future>> + Send; + fn comments( + &self, + repo: &str, + issue: &ExtIssue, + ) -> impl Future>> + Send; + fn releases(&self, repo: &str) -> impl Future>> + Send; + /// The bytes of a release asset, at most `max_bytes`. + fn download( + &self, + asset: &ExtAsset, + max_bytes: u64, + ) -> impl Future>> + Send; +} + +/// True for one URL path segment of an owner, repo or group name. +pub fn valid_segment(s: &str) -> bool { + !s.is_empty() + && s.len() <= 100 + && s != "." + && s != ".." + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) +} + +/// `owner/name` made of valid segments, `min..=max` of them. +pub fn valid_path(path: &str, min: usize, max: usize) -> bool { + let parts: Vec<&str> = path.split('/').collect(); + (min..=max).contains(&parts.len()) && parts.iter().all(|p| valid_segment(p)) +} + +/// How long to wait after a 403 or 429. `None` when the response is not a rate limit. +pub fn rate_wait( + retry_after: Option<&str>, + remaining: Option<&str>, + reset_unix: Option<&str>, + now_unix: i64, +) -> Option { + if let Some(secs) = retry_after.and_then(|v| v.trim().parse::().ok()) { + return Some(secs.max(1)); + } + if remaining.map(str::trim) == Some("0") { + let reset = reset_unix.and_then(|v| v.trim().parse::().ok())?; + return Some(u64::try_from(reset - now_unix).unwrap_or(0).max(1)); + } + None +} + +pub type Notice = Arc; + +/// A client under the outbound policy, with the token kept private to the API host. +pub struct Http { + client: reqwest::Client, + token: Option, + /// `Authorization: Bearer` (GitHub) or `PRIVATE-TOKEN` (GitLab). + gitlab: bool, + auth_host: String, + notice: Notice, +} + +impl Http { + pub fn new( + client: reqwest::Client, + token: Option, + gitlab: bool, + auth_host: String, + notice: Notice, + ) -> Self { + let token = token.filter(|t| !t.trim().is_empty()); + Http { + client, + token, + gitlab, + auth_host, + notice, + } + } + + fn host_of(url: &str) -> String { + reqwest::Url::parse(url) + .ok() + .and_then(|u| u.host_str().map(str::to_ascii_lowercase)) + .unwrap_or_default() + } + + fn request(&self, url: &str, accept: &str, authed: bool) -> reqwest::RequestBuilder { + let mut req = self.client.get(url).header(ACCEPT, accept); + if authed + && Self::host_of(url) == self.auth_host + && let Some(token) = &self.token + { + req = if self.gitlab { + req.header("PRIVATE-TOKEN", token) + } else { + req.header(AUTHORIZATION, format!("Bearer {token}")) + .header("X-GitHub-Api-Version", "2022-11-28") + }; + } + req + } + + fn header(headers: &HeaderMap, name: &str) -> Option { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + } + + /// One GET with retries: waits out a rate limit, backs off on a 5xx. Returns a 2xx or 3xx. + async fn send(&self, url: &str, accept: &str, authed: bool) -> ApiResult { + let mut attempt = 0u32; + loop { + attempt += 1; + let resp = self + .request(url, accept, authed) + .send() + .await + .map_err(|e| ApiError::Http(e.without_url().to_string()))?; + let status = resp.status(); + if status.is_success() || status.is_redirection() { + return Ok(resp); + } + let headers = resp.headers(); + match status.as_u16() { + 401 => return Err(ApiError::Unauthorized("the token was refused".into())), + 404 => return Err(ApiError::NotFound(Self::host_of(url))), + 403 | 429 => { + let wait = rate_wait( + Self::header(headers, RETRY_AFTER.as_str()).as_deref(), + Self::header(headers, "x-ratelimit-remaining").as_deref(), + Self::header(headers, "x-ratelimit-reset").as_deref(), + jiff::Timestamp::now().as_second(), + ) + .or_else(|| (status.as_u16() == 429).then_some(60)); + let Some(wait) = wait else { + return Err(ApiError::Unauthorized( + "the server refused the request (is the token valid and allowed to read this?)" + .into(), + )); + }; + if wait > MAX_RATE_WAIT || attempt > 4 { + return Err(ApiError::RateLimited { wait_secs: wait }); + } + (self.notice)(format!("Rate limited, waiting {wait} seconds")); + tokio::time::sleep(Duration::from_secs(wait)).await; + } + 500..=599 if attempt <= 3 => { + tokio::time::sleep(Duration::from_secs(u64::from(attempt) * 2)).await; + } + code => return Err(ApiError::Http(format!("status {code}"))), + } + } + } + + async fn body(resp: reqwest::Response, max: usize) -> ApiResult> { + let mut resp = resp; + let mut out = Vec::new(); + while let Some(chunk) = resp + .chunk() + .await + .map_err(|e| ApiError::Http(e.without_url().to_string()))? + { + if out.len() + chunk.len() > max { + return Err(ApiError::TooLarge); + } + out.extend_from_slice(&chunk); + } + Ok(out) + } + + pub async fn json(&self, url: &str) -> ApiResult { + let resp = self.send(url, "application/json", true).await?; + let bytes = Self::body(resp, MAX_JSON_BYTES).await?; + serde_json::from_slice(&bytes).map_err(|e| ApiError::Parse(e.to_string())) + } + + /// Every page of a list endpoint, 100 per page, stopping at the first short page. + pub async fn pages(&self, base: &str) -> ApiResult> { + let sep = if base.contains('?') { '&' } else { '?' }; + let mut out = Vec::new(); + for page in 1..=MAX_PAGES { + let url = format!("{base}{sep}per_page={PER_PAGE}&page={page}"); + let items: Vec = self.json(&url).await?; + let short = items.len() < PER_PAGE; + out.extend(items); + if short { + break; + } + } + Ok(out) + } + + /// Downloads a file, following redirects by hand: the token goes to the API host only, and + /// each hop is fetched under the same address policy as every other request. + pub async fn download(&self, url: &str, max_bytes: u64) -> ApiResult> { + let max = usize::try_from(max_bytes).unwrap_or(usize::MAX); + let mut current = url.to_owned(); + for _ in 0..=MAX_REDIRECTS { + let resp = self + .send(¤t, "application/octet-stream", true) + .await?; + if resp.status().is_redirection() { + let next = resp + .headers() + .get(LOCATION) + .and_then(|v| v.to_str().ok()) + .ok_or_else(|| ApiError::Http("redirect without a location".into()))?; + let base = + reqwest::Url::parse(¤t).map_err(|e| ApiError::Http(e.to_string()))?; + current = base + .join(next) + .map_err(|e| ApiError::Http(e.to_string()))? + .to_string(); + if !current.starts_with("https://") { + return Err(ApiError::Http("redirect to a non-https address".into())); + } + continue; + } + if let Some(len) = resp.content_length() + && len > max_bytes + { + return Err(ApiError::TooLarge); + } + return Self::body(resp, max).await; + } + Err(ApiError::Http("too many redirects".into())) + } +} + +fn day(stamp: &str) -> Option { + let d = stamp.get(..10)?; + let ok = d.as_bytes().iter().enumerate().all(|(i, b)| match i { + 4 | 7 => *b == b'-', + _ => b.is_ascii_digit(), + }); + ok.then(|| d.to_owned()) +} + +fn s(v: Option) -> String { + v.unwrap_or_default() +} + +// ---- GitHub ---- + +pub struct GitHub { + http: Http, + base: String, +} + +impl GitHub { + pub fn new(http: Http) -> Self { + GitHub { + http, + base: "https://api.github.com".into(), + } + } +} + +#[derive(Deserialize)] +struct GhUser { + login: Option, +} + +#[derive(Deserialize)] +struct GhLabel { + name: String, + color: Option, + description: Option, +} + +#[derive(Deserialize)] +struct GhMilestone { + number: i64, + title: String, + description: Option, + state: String, + due_on: Option, +} + +#[derive(Deserialize)] +struct GhPull { + merged_at: Option, +} + +#[derive(Deserialize)] +struct GhIssue { + number: i64, + title: String, + body: Option, + state: String, + state_reason: Option, + user: Option, + #[serde(default)] + labels: Vec, + milestone: Option, + created_at: Option, + html_url: Option, + pull_request: Option, +} + +#[derive(Deserialize)] +struct GhMilestoneRef { + title: String, +} + +#[derive(Deserialize)] +struct GhComment { + id: i64, + body: Option, + user: Option, + created_at: Option, + html_url: Option, +} + +#[derive(Deserialize)] +struct GhAsset { + id: i64, + name: String, + size: Option, + content_type: Option, + url: String, +} + +#[derive(Deserialize)] +struct GhRelease { + id: i64, + tag_name: String, + name: Option, + body: Option, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + author: Option, + created_at: Option, + html_url: Option, + #[serde(default)] + assets: Vec, +} + +#[derive(Deserialize)] +struct GhRepo { + name: String, + full_name: String, + description: Option, + #[serde(default)] + private: bool, + #[serde(default)] + fork: bool, + #[serde(default)] + archived: bool, + default_branch: Option, + html_url: Option, +} + +fn login(u: Option) -> String { + u.and_then(|u| u.login).unwrap_or_default() +} + +#[cfg(test)] +pub fn parse_github_labels(json: &[u8]) -> ApiResult> { + let raw: Vec = from_json(json)?; + Ok(raw.into_iter().map(label_of).collect()) +} + +fn label_of(l: GhLabel) -> ExtLabel { + ExtLabel { + name: l.name, + color: format!("#{}", s(l.color).trim_start_matches('#')), + description: s(l.description), + } +} + +#[cfg(test)] +fn from_json(json: &[u8]) -> ApiResult { + serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string())) +} + +#[cfg(test)] +pub fn parse_github_issues(json: &[u8]) -> ApiResult> { + let raw: Vec = from_json(json)?; + Ok(raw.into_iter().map(gh_issue).collect()) +} + +fn gh_issue(i: GhIssue) -> ExtIssue { + let merged = i + .pull_request + .as_ref() + .is_some_and(|p| p.merged_at.is_some()); + ExtIssue { + number: i.number, + title: i.title, + body: s(i.body), + closed: i.state == "closed", + not_planned: i.state_reason.as_deref() == Some("not_planned"), + merged, + author: login(i.user), + labels: i.labels.into_iter().map(|l| l.name).collect(), + milestone: i.milestone.map(|m| m.title), + created_at: s(i.created_at), + url: s(i.html_url), + is_pr: i.pull_request.is_some(), + } +} + +#[cfg(test)] +pub fn parse_github_releases(json: &[u8]) -> ApiResult> { + let raw: Vec = from_json(json)?; + Ok(raw + .into_iter() + .map(|r| ExtRelease { + id: r.id.to_string(), + title: r + .name + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| r.tag_name.clone()), + tag: r.tag_name, + body: s(r.body), + draft: r.draft, + prerelease: r.prerelease, + author: login(r.author), + created_at: s(r.created_at), + url: s(r.html_url), + assets: r + .assets + .into_iter() + .map(|a| ExtAsset { + id: a.id.to_string(), + name: a.name, + size: a.size.unwrap_or(0), + content_type: s(a.content_type), + url: a.url, + }) + .collect(), + }) + .collect()) +} + +impl RemoteApi for GitHub { + async fn list_repos(&self, owner: &str) -> ApiResult> { + if !valid_segment(owner) { + return Err(ApiError::NotFound("owner".into())); + } + let org: ApiResult> = self + .http + .pages(&format!("{}/orgs/{owner}/repos?type=all", self.base)) + .await; + let raw = match org { + Ok(raw) => raw, + Err(ApiError::NotFound(_)) => { + self.http + .pages(&format!("{}/users/{owner}/repos?type=owner", self.base)) + .await? + } + Err(e) => return Err(e), + }; + Ok(raw + .into_iter() + .map(|r| ExtRepo { + name: r.name, + full_name: r.full_name, + description: s(r.description), + private: r.private, + fork: r.fork, + archived: r.archived, + default_branch: s(r.default_branch), + web_url: s(r.html_url), + }) + .collect()) + } + + async fn labels(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .pages(&format!("{}/repos/{repo}/labels", self.base)) + .await?; + Ok(raw.into_iter().map(label_of).collect()) + } + + async fn milestones(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .pages(&format!("{}/repos/{repo}/milestones?state=all", self.base)) + .await?; + Ok(raw + .into_iter() + .map(|m| ExtMilestone { + id: m.number.to_string(), + title: m.title, + description: s(m.description), + closed: m.state == "closed", + due_on: m.due_on.as_deref().and_then(day), + }) + .collect()) + } + + async fn issues(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .pages(&format!( + "{}/repos/{repo}/issues?state=all&sort=created&direction=asc", + self.base + )) + .await?; + Ok(raw.into_iter().map(gh_issue).collect()) + } + + async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .pages(&format!( + "{}/repos/{repo}/issues/{}/comments", + self.base, issue.number + )) + .await?; + Ok(raw + .into_iter() + .map(|c| ExtComment { + id: c.id.to_string(), + author: login(c.user), + body: s(c.body), + created_at: s(c.created_at), + url: s(c.html_url), + }) + .collect()) + } + + async fn releases(&self, repo: &str) -> ApiResult> { + check_repo(repo, 2, 2)?; + let raw: Vec = self + .http + .pages(&format!("{}/repos/{repo}/releases", self.base)) + .await?; + // Reuse the one conversion by round-tripping through the parser's mapping. + Ok(raw.into_iter().map(gh_release).collect()) + } + + async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult> { + if !asset.url.starts_with("https://api.github.com/") { + return Err(ApiError::Http("unexpected asset address".into())); + } + self.http.download(&asset.url, max_bytes).await + } +} + +fn gh_release(r: GhRelease) -> ExtRelease { + ExtRelease { + id: r.id.to_string(), + title: r + .name + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| r.tag_name.clone()), + tag: r.tag_name, + body: s(r.body), + draft: r.draft, + prerelease: r.prerelease, + author: login(r.author), + created_at: s(r.created_at), + url: s(r.html_url), + assets: r + .assets + .into_iter() + .map(|a| ExtAsset { + id: a.id.to_string(), + name: a.name, + size: a.size.unwrap_or(0), + content_type: s(a.content_type), + url: a.url, + }) + .collect(), + } +} + +fn check_repo(repo: &str, min: usize, max: usize) -> ApiResult<()> { + if valid_path(repo, min, max) { + Ok(()) + } else { + Err(ApiError::NotFound("repository path".into())) + } +} + +// ---- GitLab ---- + +pub struct GitLab { + http: Http, + /// `https://host/api/v4`. + base: String, +} + +impl GitLab { + /// `instance` is the instance's web address, e.g. `https://gitlab.com`. + pub fn new(http: Http, instance: &str) -> Self { + GitLab { + http, + base: format!("{}/api/v4", instance.trim_end_matches('/')), + } + } + + fn project(&self, repo: &str) -> ApiResult { + check_repo(repo, 2, 20)?; + Ok(format!( + "{}/projects/{}", + self.base, + repo.replace('/', "%2F") + )) + } +} + +#[derive(Deserialize)] +struct GlUser { + username: Option, +} + +#[derive(Deserialize)] +struct GlLabel { + name: String, + color: Option, + description: Option, +} + +#[derive(Deserialize)] +struct GlMilestone { + id: i64, + title: String, + description: Option, + state: String, + due_date: Option, +} + +#[derive(Deserialize)] +struct GlMilestoneRef { + title: String, +} + +#[derive(Deserialize)] +struct GlIssue { + iid: i64, + title: String, + description: Option, + state: String, + author: Option, + #[serde(default)] + labels: Vec, + milestone: Option, + created_at: Option, + web_url: Option, +} + +#[derive(Deserialize)] +struct GlNote { + id: i64, + body: Option, + author: Option, + created_at: Option, + #[serde(default)] + system: bool, +} + +#[derive(Deserialize)] +struct GlLink { + id: i64, + name: String, + url: String, + direct_asset_url: Option, +} + +#[derive(Deserialize, Default)] +struct GlAssets { + #[serde(default)] + links: Vec, +} + +#[derive(Deserialize)] +struct GlRelease { + tag_name: String, + name: Option, + description: Option, + created_at: Option, + #[serde(default)] + upcoming_release: bool, + author: Option, + #[serde(default)] + assets: GlAssets, + #[serde(rename = "_links")] + links: Option, +} + +#[derive(Deserialize)] +struct GlSelf { + #[serde(rename = "self")] + self_url: Option, +} + +#[derive(Deserialize)] +struct GlProject { + path: String, + path_with_namespace: String, + description: Option, + visibility: Option, + default_branch: Option, + web_url: Option, + #[serde(default)] + archived: bool, + forked_from_project: Option, +} + +fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue { + ExtIssue { + number: i.iid, + title: i.title, + body: s(i.description), + closed: i.state != "opened", + not_planned: false, + merged: i.state == "merged", + author: i.author.and_then(|a| a.username).unwrap_or_default(), + labels: i.labels, + milestone: i.milestone.map(|m| m.title), + created_at: s(i.created_at), + url: s(i.web_url), + is_pr, + } +} + +#[cfg(test)] +pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult> { + let raw: Vec = from_json(json)?; + Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect()) +} + +#[cfg(test)] +pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult> { + let raw: Vec = from_json(json)?; + Ok(raw.into_iter().map(gl_release).collect()) +} + +fn gl_release(r: GlRelease) -> ExtRelease { + ExtRelease { + id: r.tag_name.clone(), + title: r + .name + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| r.tag_name.clone()), + tag: r.tag_name, + body: s(r.description), + draft: r.upcoming_release, + prerelease: false, + author: r.author.and_then(|a| a.username).unwrap_or_default(), + created_at: s(r.created_at), + url: r.links.and_then(|l| l.self_url).unwrap_or_default(), + assets: r + .assets + .links + .into_iter() + .map(|l| ExtAsset { + id: l.id.to_string(), + name: l.name, + size: 0, + content_type: String::new(), + url: l + .direct_asset_url + .filter(|u| !u.is_empty()) + .unwrap_or(l.url), + }) + .collect(), + } +} + +impl RemoteApi for GitLab { + async fn list_repos(&self, owner: &str) -> ApiResult> { + check_repo(owner, 1, 20)?; + let enc = owner.replace('/', "%2F"); + let group: ApiResult> = self + .http + .pages(&format!( + "{}/groups/{enc}/projects?include_subgroups=false&simple=false", + self.base + )) + .await; + let raw = match group { + Ok(raw) => raw, + Err(ApiError::NotFound(_)) => { + self.http + .pages(&format!("{}/users/{enc}/projects", self.base)) + .await? + } + Err(e) => return Err(e), + }; + Ok(raw + .into_iter() + .map(|p| ExtRepo { + name: p.path, + full_name: p.path_with_namespace, + description: s(p.description), + private: p.visibility.as_deref() != Some("public"), + fork: p.forked_from_project.is_some(), + archived: p.archived, + default_branch: s(p.default_branch), + web_url: s(p.web_url), + }) + .collect()) + } + + async fn labels(&self, repo: &str) -> ApiResult> { + let raw: Vec = self + .http + .pages(&format!("{}/labels", self.project(repo)?)) + .await?; + Ok(raw + .into_iter() + .map(|l| ExtLabel { + name: l.name, + color: s(l.color), + description: s(l.description), + }) + .collect()) + } + + async fn milestones(&self, repo: &str) -> ApiResult> { + let raw: Vec = self + .http + .pages(&format!("{}/milestones", self.project(repo)?)) + .await?; + Ok(raw + .into_iter() + .map(|m| ExtMilestone { + id: m.id.to_string(), + title: m.title, + description: s(m.description), + closed: m.state == "closed", + due_on: m.due_date.as_deref().and_then(day), + }) + .collect()) + } + + async fn issues(&self, repo: &str) -> ApiResult> { + let project = self.project(repo)?; + let issues: Vec = self + .http + .pages(&format!( + "{project}/issues?state=all&order_by=created_at&sort=asc" + )) + .await?; + let pulls: Vec = self + .http + .pages(&format!( + "{project}/merge_requests?state=all&order_by=created_at&sort=asc" + )) + .await?; + let mut out: Vec = issues.into_iter().map(|i| gl_issue(i, false)).collect(); + out.extend(pulls.into_iter().map(|i| gl_issue(i, true))); + Ok(out) + } + + async fn comments(&self, repo: &str, issue: &ExtIssue) -> ApiResult> { + let kind = if issue.is_pr { + "merge_requests" + } else { + "issues" + }; + let raw: Vec = self + .http + .pages(&format!( + "{}/{kind}/{}/notes?sort=asc&order_by=created_at", + self.project(repo)?, + issue.number + )) + .await?; + Ok(raw + .into_iter() + .filter(|n| !n.system) + .map(|n| ExtComment { + id: n.id.to_string(), + author: n.author.and_then(|a| a.username).unwrap_or_default(), + body: s(n.body), + created_at: s(n.created_at), + url: format!("{}#note_{}", issue.url, n.id), + }) + .collect()) + } + + async fn releases(&self, repo: &str) -> ApiResult> { + let raw: Vec = self + .http + .pages(&format!("{}/releases", self.project(repo)?)) + .await?; + Ok(raw.into_iter().map(gl_release).collect()) + } + + async fn download(&self, asset: &ExtAsset, max_bytes: u64) -> ApiResult> { + if !asset.url.starts_with("https://") { + return Err(ApiError::Http("unexpected asset address".into())); + } + self.http.download(&asset.url, max_bytes).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn segments_reject_traversal_and_separators() { + assert!(valid_segment("tahinli")); + assert!(valid_segment("my-repo_1.rs")); + assert!(!valid_segment("..")); + assert!(!valid_segment("a/b")); + assert!(!valid_segment("a?b")); + assert!(!valid_segment("")); + assert!(valid_path("tahinli/forge", 2, 2)); + assert!(!valid_path("tahinli", 2, 2)); + assert!(!valid_path("a/b/c", 2, 2)); + assert!(valid_path("grp/sub/proj", 2, 20)); + } + + #[test] + fn rate_limit_waits_follow_the_headers() { + assert_eq!(rate_wait(Some("30"), None, None, 100), Some(30)); + assert_eq!(rate_wait(None, Some("0"), Some("160"), 100), Some(60)); + assert_eq!(rate_wait(None, Some("0"), Some("90"), 100), Some(1)); + assert_eq!(rate_wait(None, Some("12"), Some("160"), 100), None); + assert_eq!(rate_wait(None, None, None, 100), None); + assert_eq!(rate_wait(None, Some("0"), None, 100), None); + } + + #[test] + fn github_issues_and_pulls_parse() { + let json = br##"[ + {"number":1,"title":"Bug","body":"it breaks","state":"closed","state_reason":"not_planned", + "user":{"login":"octocat"},"labels":[{"name":"bug","color":"d73a4a"}], + "milestone":{"title":"v1"},"created_at":"2020-01-02T03:04:05Z", + "html_url":"https://github.com/o/r/issues/1"}, + {"number":2,"title":"Add x","body":null,"state":"closed","user":{"login":"hubot"}, + "labels":[],"milestone":null,"created_at":"2020-02-02T00:00:00Z", + "html_url":"https://github.com/o/r/pull/2","pull_request":{"merged_at":"2020-02-03T00:00:00Z"}} + ]"##; + let items = parse_github_issues(json).unwrap(); + assert_eq!(items.len(), 2); + assert!(items[0].closed && items[0].not_planned && !items[0].is_pr); + assert_eq!(items[0].labels, vec!["bug"]); + assert_eq!(items[0].milestone.as_deref(), Some("v1")); + assert!(items[1].is_pr && items[1].merged); + assert_eq!(items[1].body, ""); + assert_eq!(items[1].author, "hubot"); + } + + #[test] + fn github_labels_get_a_hash() { + let labels = + parse_github_labels(br#"[{"name":"bug","color":"d73a4a","description":null}]"#) + .unwrap(); + assert_eq!(labels[0].color, "#d73a4a"); + assert_eq!(labels[0].description, ""); + } + + #[test] + fn github_releases_carry_assets() { + let json = br#"[{"id":7,"tag_name":"v1.0","name":"","body":"notes","draft":false, + "prerelease":true,"author":{"login":"octocat"},"created_at":"2021-01-01T00:00:00Z", + "html_url":"https://github.com/o/r/releases/tag/v1.0", + "assets":[{"id":9,"name":"app.tar.gz","size":12,"content_type":"application/gzip", + "url":"https://api.github.com/repos/o/r/releases/assets/9"}]}]"#; + let rel = parse_github_releases(json).unwrap(); + assert_eq!(rel[0].title, "v1.0", "a blank name falls back to the tag"); + assert!(rel[0].prerelease); + assert_eq!(rel[0].assets[0].name, "app.tar.gz"); + assert_eq!(rel[0].assets[0].size, 12); + } + + #[test] + fn gitlab_states_map() { + let json = br#"[ + {"iid":3,"title":"MR","description":"d","state":"merged","author":{"username":"tahinli"}, + "labels":["x"],"milestone":null,"created_at":"2022-01-01T00:00:00Z","web_url":"https://gl/x/-/merge_requests/3"}, + {"iid":4,"title":"open","description":null,"state":"opened","author":null,"labels":[], + "created_at":null,"web_url":null}]"#; + let items = parse_gitlab_issues(json, true).unwrap(); + assert!(items[0].closed && items[0].merged && items[0].is_pr); + assert!(!items[1].closed); + assert_eq!(items[1].author, ""); + } + + #[test] + fn gitlab_release_links_become_assets() { + let json = br#"[{"tag_name":"v2","name":"Two","description":"n","created_at":"2022-01-01T00:00:00Z", + "assets":{"links":[{"id":1,"name":"bin","url":"https://x/a","direct_asset_url":"https://x/direct"}]}}]"#; + let rel = parse_gitlab_releases(json).unwrap(); + assert_eq!(rel[0].assets[0].url, "https://x/direct"); + assert_eq!(rel[0].tag, "v2"); + } + + #[test] + fn day_keeps_only_a_valid_date_prefix() { + assert_eq!(day("2020-05-06T00:00:00Z").as_deref(), Some("2020-05-06")); + assert_eq!(day("garbage!!!").as_deref(), None); + assert_eq!(day("x").as_deref(), None); + } +} diff --git a/crates/forge-web/src/importer/mod.rs b/crates/forge-web/src/importer/mod.rs new file mode 100644 index 0000000..a843cb1 --- /dev/null +++ b/crates/forge-web/src/importer/mod.rs @@ -0,0 +1,1074 @@ +//! Repository import: a one-shot copy of a repo from a git URL, GitHub or GitLab. +//! +//! The git data comes from the same fetch the pull mirrors use, once, into a normal repo (no mirror +//! row is created). For GitHub and GitLab the job can also copy labels, milestones, issues with +//! comments, pull requests (as issues marked "imported PR") and releases with their assets, through +//! a [`RemoteApi`]. Progress is written to the database and every step wakes the job page's event +//! stream, so the page updates with no polling. +//! +//! The token exists only in the [`JobSpec`] held by the running task. It is never written to the +//! database, a log line or an audit entry. A retry asks for it again. Every imported object is +//! recorded in `import_map`, so a retry (or a second run) skips what is already there. + +pub mod api; +pub mod remote; + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use forge_core::issues::{IssueState, MAX_BODY, MAX_TITLE, StateReason}; +use forge_core::releases::{MAX_ASSET_NAME_LEN, NewRelease}; +use forge_core::store::imports::{ImportJob, ImportOrigin, ImportState}; +use forge_core::{Repo, Store, User}; +use forge_git::mirror::{RemoteAuth, mirror_fetch}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{Semaphore, watch}; + +use self::api::{ApiError, ExtAsset, ExtIssue, ExtRelease, GitHub, Notice, RemoteApi}; +pub use self::remote::{default_name, make_github, make_gitlab, parse_remote, source_ref}; +use crate::mirrors::{check_remote, policy, pull_refs, ref_snapshot}; +use crate::state::AppState; + +/// Hard limit on the git part of one import. +const GIT_TIMEOUT: Duration = Duration::from_secs(60 * 60); +/// Imports that run at once. The rest wait their turn, which also spreads the API rate limit. +static SLOTS: Semaphore = Semaphore::const_new(2); +const IMPORTED_PR_LABEL: &str = "imported PR"; +const IMPORTED_PR_COLOR: &str = "#8b7bd8"; +const FALLBACK_LABEL_COLOR: &str = "#8b949e"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + Git, + GitHub, + GitLab, +} + +impl Source { + pub fn as_str(self) -> &'static str { + match self { + Source::Git => "git", + Source::GitHub => "github", + Source::GitLab => "gitlab", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "git" => Some(Source::Git), + "github" => Some(Source::GitHub), + "gitlab" => Some(Source::GitLab), + _ => None, + } + } + + /// The name shown in "originally by x on ...". + pub fn label(self) -> &'static str { + match self { + Source::Git => "git", + Source::GitHub => "GitHub", + Source::GitLab => "GitLab", + } + } +} + +/// Which parts beyond the git data to copy. Stored on the job (it holds no secret). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct ImportOptions { + #[serde(default)] + pub labels: bool, + #[serde(default)] + pub issues: bool, + #[serde(default)] + pub pulls: bool, + #[serde(default)] + pub releases: bool, +} + +impl ImportOptions { + pub fn any_api(&self) -> bool { + self.labels || self.issues || self.pulls || self.releases + } +} + +/// Everything a running job needs. Held in memory only: it carries the token. +#[derive(Clone)] +pub struct JobSpec { + pub source: Source, + /// The URL for `git`, `owner/repo` for GitHub, the project path for GitLab. + pub remote: String, + /// The GitLab instance, e.g. `https://gitlab.com`. + pub instance: String, + pub token: Option, + /// The user name sent with the token for a plain git URL. + pub git_user: String, + pub options: ImportOptions, +} + +impl std::fmt::Debug for JobSpec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("JobSpec") + .field("source", &self.source) + .field("remote", &self.remote) + .field("token", &self.token.as_ref().map(|_| "[redacted]")) + .finish() + } +} + +impl JobSpec { + pub fn clone_url(&self) -> String { + match self.source { + Source::Git => self.remote.clone(), + Source::GitHub => format!("https://github.com/{}.git", self.remote), + Source::GitLab => format!( + "{}/{}.git", + self.instance.trim_end_matches('/'), + self.remote + ), + } + } + + fn auth(&self) -> Option { + let token = self.token.as_ref().filter(|t| !t.is_empty())?; + let username = match self.source { + Source::GitHub => "x-access-token".to_owned(), + Source::GitLab => "oauth2".to_owned(), + Source::Git if self.git_user.is_empty() => "git".to_owned(), + Source::Git => self.git_user.clone(), + }; + Some(RemoteAuth { + username, + secret: token.clone().into_bytes(), + }) + } +} + +/// How the git data is fetched. Production uses the network under the outbound policy; tests use +/// a local path. +#[derive(Clone)] +pub enum Transport { + Net, + #[cfg(test)] + Local(String), +} + +// ---- live signal ---- + +static HUB: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +fn hub() -> MutexGuard<'static, HashMap>> { + HUB.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Follows a job. Subscribe before reading its state, so a change in between is not lost. +pub fn subscribe(job_id: &str) -> watch::Receiver { + hub() + .entry(job_id.to_owned()) + .or_insert_with(|| watch::channel(0).0) + .subscribe() +} + +fn bump(job_id: &str) { + let mut hub = hub(); + if let Some(tx) = hub.get(job_id) { + tx.send_modify(|n| *n = n.wrapping_add(1)); + if tx.receiver_count() == 0 { + hub.remove(job_id); + } + } +} + +/// Wakes the followers one last time and drops the signal. +fn close(job_id: &str) { + if let Some(tx) = hub().remove(job_id) { + tx.send_modify(|n| *n = n.wrapping_add(1)); + } +} + +// ---- progress ---- + +#[derive(Clone)] +struct Reporter { + store: Store, + job_id: String, +} + +impl Reporter { + async fn log(&self, level: &str, message: impl AsRef) { + if let Err(e) = self + .store + .add_import_event(&self.job_id, level, message.as_ref()) + .await + { + tracing::warn!(error = %e, "import: could not record a progress line"); + } + bump(&self.job_id); + } + + async fn stage(&self, stage: &str, done: usize, total: usize) { + let (done, total) = (done as i64, total as i64); + if let Err(e) = self + .store + .set_import_progress(&self.job_id, stage, done, total) + .await + { + tracing::warn!(error = %e, "import: could not record progress"); + } + bump(&self.job_id); + } +} + +// ---- text helpers ---- + +/// The first lines of an imported body or comment: who wrote the original, where and when. The +/// name is cleaned and its `@` escaped, so it can neither mention nor impersonate a local user. +pub fn origin_note(source: &str, author: &str, created: &str, url: &str) -> String { + let clean: String = author + .chars() + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) + .take(60) + .collect(); + let who = if clean.is_empty() { "unknown" } else { &clean }; + let date: String = created.chars().take(10).collect(); + let mut line = format!("> Originally by \\@{who} on {source}"); + if !date.is_empty() && date.bytes().all(|b| b.is_ascii_digit() || b == b'-') { + line.push_str(", "); + line.push_str(&date); + } + let safe_url = url.starts_with("https://") + && !url + .chars() + .any(|c| c.is_whitespace() || c.is_control() || matches!(c, ')' | '(' | '<' | '>')); + if safe_url { + line.push_str(&format!(", [original]({url})")); + } + line.push_str("\n\n"); + line +} + +/// `note` then `body`, cut to the body limit at a character boundary. +pub fn with_note(note: &str, body: &str) -> String { + let mut text = format!("{note}{body}"); + if text.len() > MAX_BODY { + let mut end = MAX_BODY - 16; + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + text.push_str("\n\n(cut)"); + } + text +} + +fn clip_title(title: &str) -> String { + let t: String = title + .chars() + .filter(|c| !c.is_control()) + .take(MAX_TITLE) + .collect(); + let t = t.trim(); + if t.is_empty() { + "(untitled)".to_owned() + } else { + t.to_owned() + } +} + +/// An asset file name the release store accepts. +pub fn asset_name(name: &str) -> String { + let mut out: String = name + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+') { + c + } else { + '_' + } + }) + .collect(); + while out.starts_with('.') { + out.remove(0); + } + out.truncate(MAX_ASSET_NAME_LEN); + if out.is_empty() { + "asset".to_owned() + } else { + out + } +} + +// ---- running a job ---- + +/// Starts the job in the background. It waits for a free slot, then runs. +pub fn spawn_job(state: AppState, job: ImportJob, spec: JobSpec) { + tokio::spawn(async move { + let Ok(_slot) = SLOTS.acquire().await else { + return; + }; + run_production(&state, &job, &spec).await; + }); +} + +async fn run_production(state: &AppState, job: &ImportJob, spec: &JobSpec) { + let rep = Reporter { + store: state.store.clone(), + job_id: job.id.clone(), + }; + let notice: Notice = { + let rep = rep.clone(); + std::sync::Arc::new(move |msg: String| { + let rep = rep.clone(); + tokio::spawn(async move { rep.log("warn", msg).await }); + }) + }; + let wants_api = spec.options.any_api() && spec.source != Source::Git; + if !wants_api { + run_job::(state, job, spec, None, &Transport::Net).await; + return; + } + match spec.source { + Source::GitHub => match make_github(state, spec.token.clone(), notice) { + Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, + Err(e) => fail(state, &rep, &e).await, + }, + Source::GitLab => match make_gitlab(state, &spec.instance, spec.token.clone(), notice) { + Ok(api) => run_job(state, job, spec, Some(&api), &Transport::Net).await, + Err(e) => fail(state, &rep, &e).await, + }, + Source::Git => {} + } +} + +async fn fail(state: &AppState, rep: &Reporter, message: &str) { + rep.log("error", message).await; + if let Err(e) = state + .store + .set_import_state(&rep.job_id, ImportState::Failed, Some(message)) + .await + { + tracing::error!(error = %e, "import: could not record a failure"); + } + close(&rep.job_id); +} + +/// Runs one job to its end and records the outcome. `api` is `None` for a plain git import. +pub async fn run_job( + state: &AppState, + job: &ImportJob, + spec: &JobSpec, + api: Option<&A>, + transport: &Transport, +) { + let rep = Reporter { + store: state.store.clone(), + job_id: job.id.clone(), + }; + if let Err(e) = state + .store + .set_import_state(&job.id, ImportState::Running, None) + .await + { + tracing::error!(error = %e, "import: could not start the job"); + return; + } + bump(&job.id); + match run_steps(state, job, spec, api, transport, &rep).await { + Ok(summary) => { + rep.log("info", summary).await; + rep.stage("done", 0, 0).await; + if let Err(e) = state + .store + .set_import_state(&job.id, ImportState::Done, None) + .await + { + tracing::error!(error = %e, "import: could not finish the job"); + } + close(&job.id); + } + Err(message) => fail(state, &rep, &message).await, + } +} + +async fn run_steps( + state: &AppState, + job: &ImportJob, + spec: &JobSpec, + api: Option<&A>, + transport: &Transport, + rep: &Reporter, +) -> Result { + let repo_id = job.repo_id.clone().ok_or("the repository is gone")?; + let repo = state + .store + .repo_by_id(&repo_id) + .await + .map_err(|e| e.to_string())? + .ok_or("the repository is gone")?; + let user = state + .store + .user_by_id(&job.user_id) + .await + .map_err(|e| e.to_string())? + .ok_or("the importing user is gone")?; + + rep.stage("git", 0, 0).await; + rep.log("info", "Fetching branches and tags").await; + fetch_git(state, &repo, spec, transport).await?; + let repo = sync_default_branch(state, repo, rep).await; + rep.log("info", "Git data imported").await; + + let (Some(api), true) = (api, spec.options.any_api()) else { + return Ok("Import finished".to_owned()); + }; + let run = Run { + state, + rep, + repo: &repo, + user: &user, + api, + spec, + }; + let mut totals = Totals::default(); + if spec.options.labels { + run.labels(&mut totals).await?; + run.milestones(&mut totals).await?; + } + if spec.options.issues || spec.options.pulls { + run.issues(&mut totals).await?; + } + if spec.options.releases { + run.releases(&mut totals).await?; + } + Ok(format!( + "Import finished: {} labels, {} milestones, {} issues, {} pull requests, {} comments, {} releases, {} assets{}", + totals.labels, + totals.milestones, + totals.issues, + totals.pulls, + totals.comments, + totals.releases, + totals.assets, + if totals.skipped > 0 { + format!(", {} skipped", totals.skipped) + } else { + String::new() + } + )) +} + +async fn fetch_git( + state: &AppState, + repo: &Repo, + spec: &JobSpec, + transport: &Transport, +) -> Result<(), String> { + let repo_dir = + forge_git::repo::repo_path(&state.git.data_dir, &repo.id).map_err(|e| e.to_string())?; + let url = spec.clone_url(); + let fetch = async { + match transport { + Transport::Net => { + let policy = policy(state); + let pin = check_remote(&url, &policy).await?; + let auth = spec.auth(); + mirror_fetch( + &state.git, + &repo_dir, + &url, + auth.as_ref(), + policy.allow_http, + pin.as_ref(), + GIT_TIMEOUT, + ) + .await + .map_err(|e| e.to_string()) + } + #[cfg(test)] + Transport::Local(path) => { + forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT) + .await + .map_err(|e| e.to_string()) + } + } + }; + pull_refs(state, repo, fetch).await.map(|_| ()) +} + +/// Points the stored default branch at the branch HEAD names, when the fetch moved HEAD to the +/// remote's default. +async fn sync_default_branch(state: &AppState, repo: Repo, rep: &Reporter) -> Repo { + let Ok(dir) = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) else { + return repo; + }; + let head = forge_git::command::GitCommand::new(&state.git, "symbolic-ref") + .git_dir(&dir) + .arg("--short") + .arg("HEAD") + .output() + .await + .ok() + .map(|out| String::from_utf8_lossy(&out).trim().to_owned()) + .filter(|b| !b.is_empty()); + let Some(head) = head else { + return repo; + }; + if head == repo.default_branch { + return repo; + } + if let Err(e) = state + .store + .update_repo_general(&repo.id, &repo.description, &head) + .await + { + rep.log("warn", format!("could not set the default branch: {e}")) + .await; + return repo; + } + state + .store + .repo_by_id(&repo.id) + .await + .ok() + .flatten() + .unwrap_or(repo) +} + +#[derive(Default)] +struct Totals { + labels: usize, + milestones: usize, + issues: usize, + pulls: usize, + comments: usize, + releases: usize, + assets: usize, + skipped: usize, +} + +fn api_err(e: ApiError) -> String { + e.to_string() +} + +struct Run<'a, A> { + state: &'a AppState, + rep: &'a Reporter, + repo: &'a Repo, + user: &'a User, + api: &'a A, + spec: &'a JobSpec, +} + +impl Run<'_, A> { + fn store(&self) -> &Store { + &self.state.store + } + + async fn mapped(&self, kind: &str, ext: &str) -> Result, String> { + self.store() + .import_origin(&self.repo.id, kind, ext) + .await + .map_err(|e| e.to_string()) + } + + async fn record(&self, kind: &str, ext: &str, local: &str, author: &str, url: &str) { + let origin = ImportOrigin { + local_id: local.to_owned(), + author: author.to_owned(), + url: url.to_owned(), + }; + if let Err(e) = self + .store() + .record_import_origin(&self.repo.id, kind, ext, &origin) + .await + { + tracing::warn!(error = %e, "import: could not record an id mapping"); + } + } + + async fn labels(&self, totals: &mut Totals) -> Result<(), String> { + self.rep.stage("labels", 0, 0).await; + let labels = self.api.labels(&self.spec.remote).await.map_err(api_err)?; + let total = labels.len(); + for (i, label) in labels.into_iter().enumerate() { + self.rep.stage("labels", i, total).await; + let key = label.name.to_lowercase(); + if self.mapped("label", &key).await?.is_some() { + continue; + } + match self + .store() + .create_label(&self.repo.id, &label.name, &label.color, &label.description) + .await + { + Ok(created) => { + self.record("label", &key, &created.id, "", "").await; + totals.labels += 1; + } + Err(forge_core::Error::Conflict(_)) => {} + Err(e) => { + totals.skipped += 1; + self.rep + .log("warn", format!("label `{}` skipped: {e}", label.name)) + .await; + } + } + } + self.rep.log("info", format!("{total} labels read")).await; + Ok(()) + } + + async fn milestones(&self, totals: &mut Totals) -> Result<(), String> { + self.rep.stage("milestones", 0, 0).await; + let items = self + .api + .milestones(&self.spec.remote) + .await + .map_err(api_err)?; + let total = items.len(); + for (i, m) in items.into_iter().enumerate() { + self.rep.stage("milestones", i, total).await; + if self.mapped("milestone", &m.id).await?.is_some() { + continue; + } + let created = match self + .store() + .create_milestone(&self.repo.id, &m.title, &m.description, m.due_on.as_deref()) + .await + { + Ok(created) => created, + Err(e) => { + totals.skipped += 1; + self.rep + .log("warn", format!("milestone `{}` skipped: {e}", m.title)) + .await; + continue; + } + }; + if m.closed + && let Err(e) = self + .store() + .update_milestone( + &self.repo.id, + &created.id, + &created.title, + &created.description, + created.due_on.as_deref(), + IssueState::Closed, + ) + .await + { + self.rep + .log("warn", format!("milestone `{}` stays open: {e}", m.title)) + .await; + } + self.record("milestone", &m.id, &created.id, "", "").await; + totals.milestones += 1; + } + Ok(()) + } + + /// The id of the repo label `name` (case-insensitive), created when it is missing. + async fn label_id( + &self, + cache: &mut HashMap, + name: &str, + color: &str, + ) -> Option { + let key = name.trim().to_lowercase(); + if let Some(id) = cache.get(&key) { + return Some(id.clone()); + } + match self + .store() + .create_label(&self.repo.id, name, color, "") + .await + { + Ok(label) => { + cache.insert(key, label.id.clone()); + Some(label.id) + } + Err(_) => None, + } + } + + async fn issues(&self, totals: &mut Totals) -> Result<(), String> { + self.rep.stage("issues", 0, 0).await; + let mut items: Vec = self + .api + .issues(&self.spec.remote) + .await + .map_err(api_err)? + .into_iter() + .filter(|i| { + if i.is_pr { + self.spec.options.pulls + } else { + self.spec.options.issues + } + }) + .collect(); + items.sort_by_key(|i| (i.is_pr, i.number)); + // GitHub numbers issues and pull requests together; GitLab keeps two sequences. Sorting + // by number alone keeps GitHub numbers aligned, so do that for it. + if self.spec.source == Source::GitHub { + items.sort_by_key(|i| i.number); + } + let total = items.len(); + let mut labels: HashMap = self + .store() + .list_labels(&self.repo.id) + .await + .map_err(|e| e.to_string())? + .into_iter() + .map(|l| (l.name.to_lowercase(), l.id)) + .collect(); + let milestones: HashMap = self + .store() + .list_milestones(&self.repo.id, None) + .await + .map_err(|e| e.to_string())? + .into_iter() + .map(|m| (m.title.to_lowercase(), m.id)) + .collect(); + self.rep + .log( + "info", + format!("Importing {total} issues and pull requests"), + ) + .await; + for (i, item) in items.iter().enumerate() { + self.rep.stage("issues", i, total).await; + let kind = if item.is_pr { "pull" } else { "issue" }; + let ext = item.number.to_string(); + let local = match self.mapped(kind, &ext).await? { + Some(o) => o.local_id, + None => match self.create_item(item, &mut labels, &milestones).await { + Ok(id) => { + self.record(kind, &ext, &id, &item.author, &item.url).await; + if item.is_pr { + totals.pulls += 1; + } else { + totals.issues += 1; + } + id + } + Err(e) => { + totals.skipped += 1; + self.rep + .log("warn", format!("#{} skipped: {e}", item.number)) + .await; + continue; + } + }, + }; + let comments = self + .api + .comments(&self.spec.remote, item) + .await + .map_err(api_err)?; + for c in comments { + if self + .mapped("comment", &format!("{kind}:{}", c.id)) + .await? + .is_some() + { + continue; + } + let note = origin_note(self.spec.source.label(), &c.author, &c.created_at, &c.url); + let body = with_note(¬e, &c.body); + match self.store().add_comment(&local, &self.user.id, &body).await { + Ok(created) => { + self.record( + "comment", + &format!("{kind}:{}", c.id), + &created.id, + &c.author, + &c.url, + ) + .await; + totals.comments += 1; + } + Err(e) => { + totals.skipped += 1; + self.rep + .log( + "warn", + format!("a comment on #{} skipped: {e}", item.number), + ) + .await; + } + } + } + } + self.rep.stage("issues", total, total).await; + Ok(()) + } + + /// Creates the local issue with its labels, milestone and state. Returns its id. + async fn create_item( + &self, + item: &ExtIssue, + labels: &mut HashMap, + milestones: &HashMap, + ) -> Result { + let source = self.spec.source.label(); + let mut note = origin_note(source, &item.author, &item.created_at, &item.url); + if item.is_pr { + let how = if item.merged { + "merged" + } else if item.closed { + "closed" + } else { + "open" + }; + note.push_str(&format!( + "> Imported pull request ({how}). Its branches may no longer exist, so there is nothing to merge here.\n\n" + )); + } + let body = with_note(¬e, &item.body); + let issue = self + .store() + .create_issue( + &self.repo.id, + &self.user.id, + &clip_title(&item.title), + &body, + ) + .await?; + let mut ids = Vec::new(); + for name in &item.labels { + if let Some(id) = self.label_id(labels, name, FALLBACK_LABEL_COLOR).await { + ids.push(id); + } + } + if item.is_pr + && let Some(id) = self + .label_id(labels, IMPORTED_PR_LABEL, IMPORTED_PR_COLOR) + .await + { + ids.push(id); + } + ids.dedup(); + if !ids.is_empty() { + self.store() + .set_issue_labels(&issue.id, &self.user.id, &ids) + .await?; + } + if let Some(id) = item + .milestone + .as_ref() + .and_then(|t| milestones.get(&t.to_lowercase())) + { + self.store() + .set_issue_milestone(&issue.id, &self.user.id, Some(id)) + .await?; + } + if item.closed { + let reason = if item.not_planned { + StateReason::NotPlanned + } else { + StateReason::Completed + }; + self.store() + .set_issue_state( + &issue.id, + Some(&self.user.id), + IssueState::Closed, + Some(reason), + serde_json::Value::Null, + ) + .await?; + } + Ok(issue.id) + } + + async fn releases(&self, totals: &mut Totals) -> Result<(), String> { + self.rep.stage("releases", 0, 0).await; + let releases = self + .api + .releases(&self.spec.remote) + .await + .map_err(api_err)?; + let repo_dir = forge_git::repo::repo_path(&self.state.git.data_dir, &self.repo.id) + .map_err(|e| e.to_string())?; + let refs = ref_snapshot(self.state, &repo_dir).await?; + let max_bytes = self.state.live().releases.max_asset_mb * 1024 * 1024; + let total = releases.len(); + for (i, rel) in releases.iter().enumerate() { + self.rep.stage("releases", i, total).await; + let Some(release) = self.release_of(rel, &refs, totals).await? else { + continue; + }; + for asset in &rel.assets { + self.asset(&release, rel, asset, max_bytes, totals).await?; + } + } + self.rep.stage("releases", total, total).await; + Ok(()) + } + + /// The local release for `rel`: the one a past run made, a new one, or `None` when it cannot + /// be made (no tag in the imported git data). + async fn release_of( + &self, + rel: &ExtRelease, + refs: &std::collections::BTreeMap, + totals: &mut Totals, + ) -> Result, String> { + if let Some(o) = self.mapped("release", &rel.id).await? { + return self + .store() + .release(&o.local_id) + .await + .map_err(|e| e.to_string()); + } + let Some(oid) = refs.get(&format!("refs/tags/{}", rel.tag)) else { + totals.skipped += 1; + self.rep + .log( + "warn", + format!( + "release `{}` skipped: its tag is not in the git data", + rel.tag + ), + ) + .await; + return Ok(None); + }; + if let Some(existing) = self + .store() + .release_by_tag(&self.repo.id, &rel.tag) + .await + .map_err(|e| e.to_string())? + { + self.record("release", &rel.id, &existing.id, &rel.author, &rel.url) + .await; + return Ok(Some(existing)); + } + let note = origin_note( + self.spec.source.label(), + &rel.author, + &rel.created_at, + &rel.url, + ); + let body = with_note(¬e, &rel.body); + let title = clip_title(&rel.title); + let created = self + .store() + .create_release(&NewRelease { + repo_id: &self.repo.id, + tag: &rel.tag, + target_oid: oid, + title: &title, + body: &body, + draft: rel.draft, + prerelease: rel.prerelease, + author_id: &self.user.id, + }) + .await; + match created { + Ok(release) => { + self.record("release", &rel.id, &release.id, &rel.author, &rel.url) + .await; + totals.releases += 1; + Ok(Some(release)) + } + Err(e) => { + totals.skipped += 1; + self.rep + .log("warn", format!("release `{}` skipped: {e}", rel.tag)) + .await; + Ok(None) + } + } + } + + async fn asset( + &self, + release: &forge_core::releases::Release, + rel: &ExtRelease, + asset: &ExtAsset, + max_bytes: u64, + totals: &mut Totals, + ) -> Result<(), String> { + let ext = format!("{}:{}", rel.id, asset.id); + if self.mapped("asset", &ext).await?.is_some() { + return Ok(()); + } + if asset.size > max_bytes { + totals.skipped += 1; + self.rep + .log( + "warn", + format!( + "asset `{}` skipped: larger than the upload limit", + asset.name + ), + ) + .await; + return Ok(()); + } + self.rep + .log("info", format!("Downloading asset {}", asset.name)) + .await; + let bytes = match self.api.download(asset, max_bytes).await { + Ok(bytes) => bytes, + Err(e @ (ApiError::RateLimited { .. } | ApiError::Unauthorized(_))) => { + return Err(e.to_string()); + } + Err(e) => { + totals.skipped += 1; + self.rep + .log("warn", format!("asset `{}` skipped: {e}", asset.name)) + .await; + return Ok(()); + } + }; + let name = asset_name(&asset.name); + let content_type = (!asset.content_type.is_empty()).then_some(asset.content_type.as_str()); + let stream = + futures_util::stream::iter([Ok::<_, std::io::Error>(bytes::Bytes::from(bytes))]); + match crate::release_ops::put_asset( + self.state, + self.repo, + release, + self.user, + &name, + content_type, + stream, + max_bytes, + ) + .await + { + Ok((stored, _)) => { + self.record("asset", &ext, &stored.id, &rel.author, &asset.url) + .await; + totals.assets += 1; + } + Err(e) => { + totals.skipped += 1; + self.rep + .log( + "warn", + format!("asset `{}` skipped: {}", asset.name, e.message()), + ) + .await; + } + } + Ok(()) + } +} + +/// Marks jobs a restart cut short as failed, so their pages offer a retry. +pub async fn on_boot(state: &AppState) { + match state.store.fail_interrupted_imports().await { + Ok(0) => {} + Ok(n) => tracing::warn!(count = n, "import: marked interrupted jobs as failed"), + Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/forge-web/src/importer/remote.rs b/crates/forge-web/src/importer/remote.rs new file mode 100644 index 0000000..9d14ba1 --- /dev/null +++ b/crates/forge-web/src/importer/remote.rs @@ -0,0 +1,157 @@ +//! Turning what the user typed into a remote reference, and building the API clients. + +use std::time::Duration; + +use super::Source; +use super::api::{self, GitHub, GitLab, Http, Notice}; +use crate::mirrors::policy; +use crate::state::AppState; +use crate::webhooks::client::{policy_client, validate_url}; + +/// A GitHub client under the outbound policy. +pub fn make_github( + state: &AppState, + token: Option, + notice: Notice, +) -> Result { + let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") + .map_err(|e| format!("could not build the HTTP client: {e}"))?; + Ok(GitHub::new(Http::new( + client, + token, + false, + "api.github.com".into(), + notice, + ))) +} + +/// A GitLab client for `instance`, which must pass the outbound policy. +pub fn make_gitlab( + state: &AppState, + instance: &str, + token: Option, + notice: Notice, +) -> Result { + let instance = instance.trim_end_matches('/'); + let host = validate_url(instance, &policy(state)) + .map_err(|e| format!("instance address refused: {e}"))? + .host_str() + .unwrap_or_default() + .to_ascii_lowercase(); + let client = policy_client(policy(state), Duration::from_secs(60), "forge-import/1") + .map_err(|e| format!("could not build the HTTP client: {e}"))?; + Ok(GitLab::new( + Http::new(client, token, true, host, notice), + instance, + )) +} + +/// Splits what the user typed into `(remote, instance)` for a source. `None` when it is not a +/// usable reference. GitHub takes `owner/name` or a github.com URL; GitLab takes a project URL +/// (`https://host/group/project`) or, with `instance` given, a bare path. +pub fn parse_remote(source: Source, text: &str, instance: &str) -> Option<(String, String)> { + let text = text.trim(); + match source { + Source::Git => (text.starts_with("https://") || text.starts_with("http://")) + .then(|| (text.to_owned(), String::new())), + Source::GitHub => { + let path = text + .strip_prefix("https://github.com/") + .unwrap_or(text) + .trim_end_matches('/'); + let path = path.strip_suffix(".git").unwrap_or(path); + api::valid_path(path, 2, 2).then(|| (path.to_owned(), String::new())) + } + Source::GitLab => { + if let Some((scheme, rest)) = text + .strip_prefix("https://") + .map(|r| ("https", r)) + .or_else(|| text.strip_prefix("http://").map(|r| ("http", r))) + { + let (host, path) = rest.split_once('/')?; + let path = path.trim_end_matches('/'); + let path = path.strip_suffix(".git").unwrap_or(path); + if host.is_empty() || host.contains('@') || !api::valid_path(path, 2, 20) { + return None; + } + return Some((path.to_owned(), format!("{scheme}://{host}"))); + } + let instance = instance.trim().trim_end_matches('/'); + let path = text.trim_matches('/'); + let path = path.strip_suffix(".git").unwrap_or(path); + let host = instance + .strip_prefix("https://") + .or_else(|| instance.strip_prefix("http://"))?; + let ok = !host.is_empty() + && !host.contains('@') + && !host.contains('/') + && api::valid_path(path, 2, 20); + ok.then(|| (path.to_owned(), instance.to_owned())) + } + } +} + +/// The reference stored on a job and shown to the user: no credential in it. +pub fn source_ref(source: Source, remote: &str, instance: &str) -> String { + match source { + Source::GitLab => format!("{}/{}", instance.trim_end_matches('/'), remote), + _ => remote.to_owned(), + } +} + +/// The repository name a remote would get by default: its last path segment without `.git`. +pub fn default_name(remote: &str) -> String { + remote + .trim_end_matches('/') + .rsplit('/') + .next() + .unwrap_or_default() + .trim_end_matches(".git") + .to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn github_accepts_owner_name_or_url() { + let ok = |t: &str| parse_remote(Source::GitHub, t, "").map(|r| r.0); + assert_eq!(ok("tahinli/forge").as_deref(), Some("tahinli/forge")); + assert_eq!( + ok("https://github.com/tahinli/forge.git").as_deref(), + Some("tahinli/forge") + ); + assert_eq!(ok("tahinli").as_deref(), None); + assert_eq!(ok("a/b/c").as_deref(), None); + assert_eq!(ok("../etc").as_deref(), None); + } + + #[test] + fn gitlab_takes_a_url_or_a_path_with_an_instance() { + let url = parse_remote(Source::GitLab, "https://gl.example.org/grp/sub/proj", ""); + assert_eq!( + url, + Some(("grp/sub/proj".into(), "https://gl.example.org".into())) + ); + let bare = parse_remote(Source::GitLab, "grp/proj", "https://gitlab.com/"); + assert_eq!(bare, Some(("grp/proj".into(), "https://gitlab.com".into()))); + assert_eq!(parse_remote(Source::GitLab, "grp/proj", ""), None); + assert_eq!( + parse_remote(Source::GitLab, "https://u:p@host/a/b", ""), + None + ); + } + + #[test] + fn git_needs_http_scheme_and_names_default_from_the_path() { + assert!(parse_remote(Source::Git, "file:///etc", "").is_none()); + assert!(parse_remote(Source::Git, "https://example.org/x/y.git", "").is_some()); + assert_eq!(default_name("https://example.org/x/y.git"), "y"); + assert_eq!(default_name("grp/proj"), "proj"); + assert_eq!( + source_ref(Source::GitLab, "g/p", "https://gitlab.com"), + "https://gitlab.com/g/p" + ); + } +} diff --git a/crates/forge-web/src/importer/tests.rs b/crates/forge-web/src/importer/tests.rs new file mode 100644 index 0000000..ae05842 --- /dev/null +++ b/crates/forge-web/src/importer/tests.rs @@ -0,0 +1,544 @@ +//! Import tests. The remote API is a fake behind [`RemoteApi`], and the git side is a bare repo on +//! disk fetched over the local transport, so nothing here touches the network. + +use std::collections::HashMap; +use std::path::Path; +use std::sync::Mutex; + +use forge_core::issues::IssueFilter; +use forge_core::store::imports::{ImportJob, ImportState}; +use forge_core::{IssueState, Visibility}; + +use super::api::{ + ApiError, ApiResult, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone, ExtRelease, + ExtRepo, RemoteApi, +}; +use super::{ + ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note, +}; +use crate::state::AppState; +use crate::test_support::test_state; + +const TOKEN: &str = "ghp_supersecret_token_value"; + +#[derive(Default)] +struct Fake { + labels: Vec, + milestones: Vec, + issues: Vec, + comments: HashMap>, + releases: Vec, + files: HashMap>, + /// Errors handed out by `comments`, one per call, before it starts answering. + comment_failures: Mutex>, + comment_calls: Mutex, +} + +impl RemoteApi for Fake { + async fn list_repos(&self, _owner: &str) -> ApiResult> { + Ok(vec![ExtRepo { + name: "project".into(), + full_name: "tahinli/project".into(), + ..ExtRepo::default() + }]) + } + + async fn labels(&self, _repo: &str) -> ApiResult> { + Ok(self.labels.clone()) + } + + async fn milestones(&self, _repo: &str) -> ApiResult> { + Ok(self.milestones.clone()) + } + + async fn issues(&self, _repo: &str) -> ApiResult> { + Ok(self.issues.clone()) + } + + async fn comments(&self, _repo: &str, issue: &ExtIssue) -> ApiResult> { + *self.comment_calls.lock().unwrap() += 1; + if let Some(e) = self.comment_failures.lock().unwrap().pop() { + return Err(e); + } + Ok(self + .comments + .get(&issue.number) + .cloned() + .unwrap_or_default()) + } + + async fn releases(&self, _repo: &str) -> ApiResult> { + Ok(self.releases.clone()) + } + + async fn download(&self, asset: &ExtAsset, _max: u64) -> ApiResult> { + self.files + .get(&asset.url) + .cloned() + .ok_or_else(|| ApiError::NotFound("asset".into())) + } +} + +fn plumbing(git_dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .arg(format!("--git-dir={}", git_dir.display())) + .args(args) + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@example.com") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@example.com") + .output() + .expect("git runs"); + assert!(out.status.success(), "git {args:?}: {out:?}"); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +fn commit_to(git_dir: &Path, refname: &str, message: &str) { + let tree = plumbing(git_dir, &["hash-object", "-t", "tree", "-w", "--stdin"]); + let commit = plumbing(git_dir, &["commit-tree", &tree, "-m", message]); + plumbing(git_dir, &["update-ref", refname, &commit]); +} + +/// A bare "remote" with `master`, a `dev` branch and a `v1` tag, HEAD on `master`. +fn upstream(dir: &Path) -> String { + let path = dir.join("upstream.git"); + let out = std::process::Command::new("git") + .args(["init", "--bare", "-q"]) + .arg(&path) + .output() + .expect("git init"); + assert!(out.status.success()); + plumbing(&path, &["symbolic-ref", "HEAD", "refs/heads/master"]); + commit_to(&path, "refs/heads/master", "one"); + commit_to(&path, "refs/heads/dev", "dev work"); + commit_to(&path, "refs/tags/v1", "tagged"); + path.display().to_string() +} + +struct Fixture { + state: AppState, + repo: forge_core::Repo, + user: forge_core::User, + _dir: tempfile::TempDir, + upstream: String, +} + +async fn fixture() -> Fixture { + let dir = tempfile::tempdir().expect("tempdir"); + let state = test_state(dir.path()).await; + let user = state + .store + .create_user("tahinli", None, "unused", false) + .await + .expect("user"); + let repo = state + .store + .create_repo(&user.id, "project", "", Visibility::Public, "main") + .await + .expect("repo"); + let bare = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).expect("path"); + forge_git::repo::init_bare(&state.git, &bare, "main") + .await + .expect("init bare"); + let upstream = upstream(dir.path()); + Fixture { + state, + repo, + user, + _dir: dir, + upstream, + } +} + +fn spec(source: Source, options: ImportOptions) -> JobSpec { + JobSpec { + source, + remote: "tahinli/project".into(), + instance: String::new(), + token: Some(TOKEN.into()), + git_user: String::new(), + options, + } +} + +async fn new_job(fx: &Fixture, source: Source) -> ImportJob { + fx.state + .store + .create_import_job( + &fx.user.id, + &fx.repo.id, + source.as_str(), + "tahinli/project", + "{}", + ) + .await + .expect("job") +} + +fn everything() -> ImportOptions { + ImportOptions { + labels: true, + issues: true, + pulls: true, + releases: true, + } +} + +fn fake() -> Fake { + let mut fake = Fake { + labels: vec![ExtLabel { + name: "bug".into(), + color: "#d73a4a".into(), + description: "Broken".into(), + }], + milestones: vec![ExtMilestone { + id: "1".into(), + title: "v1".into(), + closed: true, + due_on: Some("2020-05-06".into()), + ..ExtMilestone::default() + }], + issues: vec![ + ExtIssue { + number: 1, + title: "It breaks".into(), + body: "steps".into(), + closed: true, + author: "octocat".into(), + labels: vec!["bug".into()], + milestone: Some("v1".into()), + created_at: "2020-01-02T03:04:05Z".into(), + url: "https://github.com/tahinli/project/issues/1".into(), + ..ExtIssue::default() + }, + ExtIssue { + number: 2, + title: "Add the thing".into(), + body: "patch".into(), + closed: true, + merged: true, + is_pr: true, + author: "hubot".into(), + created_at: "2020-02-02T00:00:00Z".into(), + url: "https://github.com/tahinli/project/pull/2".into(), + ..ExtIssue::default() + }, + ], + releases: vec![ExtRelease { + id: "7".into(), + tag: "v1".into(), + title: "First".into(), + body: "notes".into(), + author: "octocat".into(), + assets: vec![ExtAsset { + id: "9".into(), + name: "app 1.tar.gz".into(), + size: 5, + content_type: "application/gzip".into(), + url: "https://api.github.com/assets/9".into(), + }], + ..ExtRelease::default() + }], + ..Fake::default() + }; + fake.comments.insert( + 1, + vec![ExtComment { + id: "100".into(), + author: "hubot".into(), + body: "same here".into(), + created_at: "2020-01-03T00:00:00Z".into(), + url: "https://github.com/tahinli/project/issues/1#c100".into(), + }], + ); + fake.files + .insert("https://api.github.com/assets/9".into(), b"hello".to_vec()); + fake +} + +#[tokio::test] +async fn git_url_import_copies_all_branches_and_tags_into_a_normal_repo() { + let fx = fixture().await; + let job = new_job(&fx, Source::Git).await; + let spec = spec(Source::Git, ImportOptions::default()); + run_job::( + &fx.state, + &job, + &spec, + None, + &Transport::Local(fx.upstream.clone()), + ) + .await; + + let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(job.state, ImportState::Done, "{:?}", job.error); + let dir = forge_git::repo::repo_path(&fx.state.git.data_dir, &fx.repo.id).unwrap(); + let refs = crate::mirrors::ref_snapshot(&fx.state, &dir).await.unwrap(); + assert!(refs.contains_key("refs/heads/master")); + assert!(refs.contains_key("refs/heads/dev")); + assert!(refs.contains_key("refs/tags/v1")); + // The remote's default branch becomes the repo's, and no mirror row exists: it is a normal repo. + let repo = fx + .state + .store + .repo_by_id(&fx.repo.id) + .await + .unwrap() + .unwrap(); + assert_eq!(repo.default_branch, "master"); + assert!( + fx.state + .store + .pull_mirror(&fx.repo.id) + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn full_api_import_brings_issues_pulls_comments_labels_and_releases() { + let fx = fixture().await; + let api = fake(); + let job = new_job(&fx, Source::GitHub).await; + let spec = spec(Source::GitHub, everything()); + run_job( + &fx.state, + &job, + &spec, + Some(&api), + &Transport::Local(fx.upstream.clone()), + ) + .await; + + let store = &fx.state.store; + let job = store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(job.state, ImportState::Done, "{:?}", job.error); + + let all = IssueFilter { + state: None, + per_page: 100, + ..IssueFilter::default() + }; + let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); + assert_eq!(total, 2); + let issue = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); + assert_eq!(issue.issue.state, IssueState::Closed); + assert_eq!( + issue.issue.author_id, fx.user.id, + "the importer owns the row" + ); + assert!( + issue + .issue + .body + .starts_with("> Originally by \\@octocat on GitHub, 2020-01-02"), + "{}", + issue.issue.body + ); + assert!(issue.labels.iter().any(|l| l.name == "bug")); + assert!(issue.issue.milestone_id.is_some()); + + let pull = items + .iter() + .find(|i| i.issue.title == "Add the thing") + .unwrap(); + assert!(pull.labels.iter().any(|l| l.name == "imported PR")); + assert!(pull.issue.body.contains("Imported pull request (merged)")); + assert!(pull.issue.body.contains("Originally by \\@hubot")); + + let comments = store.list_comments(&issue.issue.id).await.unwrap(); + assert_eq!(comments.len(), 1); + assert!( + comments[0] + .body + .contains("Originally by \\@hubot on GitHub") + ); + assert!(comments[0].body.ends_with("same here")); + + let release = store + .release_by_tag(&fx.repo.id, "v1") + .await + .unwrap() + .unwrap(); + assert!(release.body.contains("notes")); + let assets = store.list_release_assets(&release.id).await.unwrap(); + assert_eq!(assets.len(), 1); + assert_eq!(assets[0].name, "app_1.tar.gz"); + assert_eq!(assets[0].size, 5); +} + +#[tokio::test] +async fn running_an_import_twice_creates_nothing_twice() { + let fx = fixture().await; + let api = fake(); + let spec = spec(Source::GitHub, everything()); + for _ in 0..2 { + let job = new_job(&fx, Source::GitHub).await; + run_job( + &fx.state, + &job, + &spec, + Some(&api), + &Transport::Local(fx.upstream.clone()), + ) + .await; + let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(job.state, ImportState::Done, "{:?}", job.error); + } + let store = &fx.state.store; + let all = IssueFilter { + state: None, + per_page: 100, + ..IssueFilter::default() + }; + let (items, total) = store.list_issues(&fx.repo.id, &all).await.unwrap(); + assert_eq!(total, 2); + let first = items.iter().find(|i| i.issue.title == "It breaks").unwrap(); + assert_eq!(store.list_comments(&first.issue.id).await.unwrap().len(), 1); + assert_eq!(store.list_releases(&fx.repo.id).await.unwrap().len(), 1); + let release = store + .release_by_tag(&fx.repo.id, "v1") + .await + .unwrap() + .unwrap(); + assert_eq!( + store.list_release_assets(&release.id).await.unwrap().len(), + 1 + ); + // The labels: the imported one, plus "imported PR", each once. + let labels = store.list_labels(&fx.repo.id).await.unwrap(); + assert_eq!(labels.iter().filter(|l| l.name == "bug").count(), 1); +} + +#[tokio::test] +async fn a_rate_limit_fails_the_job_clearly_and_a_retry_finishes_it() { + let fx = fixture().await; + let api = fake(); + api.comment_failures + .lock() + .unwrap() + .push(ApiError::RateLimited { wait_secs: 3600 }); + let job = new_job(&fx, Source::GitHub).await; + let spec = spec(Source::GitHub, everything()); + let transport = Transport::Local(fx.upstream.clone()); + run_job(&fx.state, &job, &spec, Some(&api), &transport).await; + + let failed = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(failed.state, ImportState::Failed); + let message = failed.error.clone().unwrap(); + assert!(message.contains("rate limit"), "{message}"); + let events = fx + .state + .store + .list_import_events(&job.id, 50) + .await + .unwrap(); + assert!(events.iter().any(|e| e.level == "error")); + + // Retry on the same job: the first issue exists already and is not created again. + run_job(&fx.state, &job, &spec, Some(&api), &transport).await; + let done = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(done.state, ImportState::Done, "{:?}", done.error); + assert!(done.error.is_none()); + let all = IssueFilter { + state: None, + per_page: 100, + ..IssueFilter::default() + }; + let (_, total) = fx.state.store.list_issues(&fx.repo.id, &all).await.unwrap(); + assert_eq!(total, 2); +} + +#[tokio::test] +async fn the_token_is_never_written_to_the_database() { + let fx = fixture().await; + let api = fake(); + api.comment_failures + .lock() + .unwrap() + .push(ApiError::Http(format!("boom {}", "x"))); + let job = new_job(&fx, Source::GitHub).await; + let spec = spec(Source::GitHub, everything()); + run_job( + &fx.state, + &job, + &spec, + Some(&api), + &Transport::Local(fx.upstream.clone()), + ) + .await; + let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + let events = fx + .state + .store + .list_import_events(&job.id, 500) + .await + .unwrap(); + let mut text = format!("{job:?}"); + for e in events { + text.push_str(&e.message); + } + assert!( + !text.contains(TOKEN), + "the token leaked into stored job data" + ); + assert!( + !format!("{spec:?}").contains(TOKEN), + "Debug prints the token" + ); +} + +#[tokio::test] +async fn a_failed_git_fetch_marks_the_job_failed() { + let fx = fixture().await; + let job = new_job(&fx, Source::Git).await; + let spec = spec(Source::Git, ImportOptions::default()); + run_job::( + &fx.state, + &job, + &spec, + None, + &Transport::Local("/nonexistent/path.git".into()), + ) + .await; + let job = fx.state.store.import_job(&job.id).await.unwrap().unwrap(); + assert_eq!(job.state, ImportState::Failed); + assert!(job.error.is_some()); +} + +#[test] +fn the_origin_note_escapes_the_mention_and_cleans_the_name() { + let note = origin_note( + "GitHub", + "evil @tahinli\n", + "2021-03-04T00:00:00Z", + "https://github.com/o/r/issues/1", + ); + assert!(note.starts_with("> Originally by \\@eviltahinli on GitHub, 2021-03-04")); + assert!(note.contains("[original](https://github.com/o/r/issues/1)")); + assert!(note.ends_with("\n\n")); + let none = origin_note("GitHub", "", "", "javascript:alert(1)"); + assert!(none.contains("\\@unknown")); + assert!(!none.contains("javascript")); +} + +#[test] +fn bodies_are_cut_at_the_limit_on_a_char_boundary() { + let long = "\u{e9}".repeat(forge_core::issues::MAX_BODY); + let text = with_note("> note\n\n", &long); + assert!(text.len() <= forge_core::issues::MAX_BODY); + assert!(text.ends_with("(cut)")); +} + +#[test] +fn asset_names_are_made_safe() { + assert_eq!(asset_name("app 1.tar.gz"), "app_1.tar.gz"); + assert_eq!(asset_name("../../etc/passwd"), "_.._etc_passwd"); + assert_eq!(asset_name(".hidden"), "hidden"); + assert_eq!(asset_name("###"), "___"); + assert_eq!(asset_name(""), "asset"); + assert!(forge_core::releases::valid_asset_name(&asset_name( + "a b/c?d" + ))); +} diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index b2f407b..9deff48 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -23,10 +23,12 @@ mod boot; mod ci; mod client_ip; mod compression; +mod exporter; mod git_auth; mod git_http; mod hook_cmd; mod i18n; +mod importer; mod internal; mod lfs; mod lfs_pointer; diff --git a/crates/forge-web/src/pages/import.rs b/crates/forge-web/src/pages/import.rs new file mode 100644 index 0000000..f0ddd63 --- /dev/null +++ b/crates/forge-web/src/pages/import.rs @@ -0,0 +1,1172 @@ +//! Pages: import a repository (`/new/import`), import several (`/new/import/bulk`), and watch an +//! import (`/import`, `/import/{id}`). The job page follows its event stream (`data-live`), so it +//! updates as the import runs with no polling and no reload. + +use std::collections::HashMap; + +use forge_core::store::imports::{ImportJob, ImportState}; +use forge_core::time::stamp_to_unix; +use forge_core::{AuditAction, Repo, User, Visibility}; +use forge_git::repo::{init_bare, repo_path}; +use futures_util::stream; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::error::{SeeOther, not_found, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param, query_params, route}; +use topcoat::view::{View, component, view}; + +use crate::audit::{self, Actor, Target}; +use crate::auth::{require_csrf, require_user}; +use crate::i18n::migrate::{self as g, K}; +use crate::i18n::{self, Key, Lang}; +use crate::importer::api::{ApiError, RemoteApi}; +use crate::importer::{ + self, ImportOptions, JobSpec, Source, default_name, make_github, make_gitlab, parse_remote, + source_ref, +}; +use crate::pages::ci_runs::{changed_event, events_response}; +use crate::pages::new_repo::{owner_choices, repo_owner}; +use crate::state::AppState; +use crate::views::{alert, csrf_field, now_unix, relative_time, shell, user_facing_message}; + +path_param!(job_id); + +/// Most repositories one bulk submit starts. +const MAX_BULK: usize = 50; +const DEFAULT_BRANCH: &str = "main"; + +#[derive(Deserialize, Default)] +struct ImportForm { + #[serde(default)] + csrf: String, + #[serde(default)] + source: String, + #[serde(default)] + remote: String, + #[serde(default)] + instance: String, + #[serde(default)] + token: String, + #[serde(default)] + git_user: String, + #[serde(default)] + owner: String, + #[serde(default)] + name: String, + #[serde(default)] + description: String, + #[serde(default)] + visibility: String, + #[serde(default)] + opt_labels: String, + #[serde(default)] + opt_issues: String, + #[serde(default)] + opt_pulls: String, + #[serde(default)] + opt_releases: String, +} + +#[derive(Deserialize, Default)] +struct BulkForm { + #[serde(default)] + csrf: String, + #[serde(default)] + stage: String, + #[serde(default)] + source: String, + #[serde(default)] + instance: String, + #[serde(default)] + token: String, + #[serde(default)] + from: String, + #[serde(default)] + owner: String, + #[serde(default)] + visibility: String, + #[serde(default)] + opt_labels: String, + #[serde(default)] + opt_issues: String, + #[serde(default)] + opt_pulls: String, + #[serde(default)] + opt_releases: String, + /// The ticked repositories arrive as `sel_0`, `sel_1`, ... with the repository as the value. + #[serde(flatten)] + extra: HashMap, +} + +#[query_params(error = bad_request)] +struct SourceQuery { + source: Option, + error: Option, +} + +#[query_params(error = bad_request)] +struct SeenQuery { + v: Option, +} + +fn options_of(labels: &str, issues: &str, pulls: &str, releases: &str) -> ImportOptions { + ImportOptions { + labels: !labels.is_empty(), + issues: !issues.is_empty(), + pulls: !pulls.is_empty(), + releases: !releases.is_empty(), + } +} + +fn source_of(raw: Option<&str>) -> Source { + raw.and_then(Source::parse).unwrap_or(Source::GitHub) +} + +fn token_of(raw: &str) -> Option { + let t = raw.trim(); + (!t.is_empty()).then(|| t.to_owned()) +} + +// ---- shared pieces ---- + +#[component] +pub(crate) async fn newrepo_tabs(lang: Lang, active: &str) -> Result { + let create = active == "create"; + let import = active == "import"; + Ok(view! { + + }) +} + +#[component] +async fn source_tabs(lang: Lang, base: &str, active: Source) -> Result { + let git = format!("{base}?source=git"); + let github = format!("{base}?source=github"); + let gitlab = format!("{base}?source=gitlab"); + Ok(view! { + + }) +} + +#[component] +async fn visibility_pick(lang: Lang, private: bool) -> Result { + Ok(view! { +
+ (i18n::t(lang, Key::NewRepository)) +
+ + +
+
+ }) +} + +#[component] +async fn option_boxes(lang: Lang, opts: ImportOptions) -> Result { + Ok(view! { +
+ (g::t(lang, K::WhatToImport)) + + + + +

(g::t(lang, K::OptionsNote))

+
+ }) +} + +// ---- single import ---- + +struct Draft { + source: Source, + remote: String, + instance: String, + git_user: String, + owner: String, + name: String, + description: String, + private: bool, + opts: ImportOptions, +} + +impl Draft { + fn fresh(source: Source) -> Self { + Draft { + source, + remote: String::new(), + instance: "https://gitlab.com".into(), + git_user: String::new(), + owner: String::new(), + name: String::new(), + description: String::new(), + private: true, + opts: ImportOptions { + labels: true, + issues: true, + pulls: true, + releases: true, + }, + } + } + + /// The submitted values, never the token. + fn from_form(form: &ImportForm, source: Source) -> Self { + Draft { + source, + remote: form.remote.trim().to_owned(), + instance: form.instance.trim().to_owned(), + git_user: form.git_user.trim().to_owned(), + owner: form.owner.trim().to_owned(), + name: form.name.trim().to_owned(), + description: form.description.clone(), + private: form.visibility != "public", + opts: options_of( + &form.opt_labels, + &form.opt_issues, + &form.opt_pulls, + &form.opt_releases, + ), + } + } +} + +#[component] +async fn import_form( + lang: Lang, + csrf: &str, + draft: Draft, + error: Option, + owners: Vec, +) -> Result { + let source = draft.source; + let selected_owner = if draft.owner.is_empty() { + owners.first().cloned().unwrap_or_default() + } else { + draft.owner.clone() + }; + let source_value = source.as_str(); + let is_git = source == Source::Git; + let is_gitlab = source == Source::GitLab; + let bulk_href = if is_git { + String::new() + } else { + format!("/new/import/bulk?source={source_value}") + }; + let remote_label = match source { + Source::Git => g::t(lang, K::GitUrl), + Source::GitHub => g::t(lang, K::GitHubRepo), + Source::GitLab => g::t(lang, K::GitLabProject), + }; + let remote_placeholder = match source { + Source::Git => "https://example.org/tahinli/project.git", + Source::GitHub => "tahinli/project", + Source::GitLab => "tahinli/project", + }; + let token_label = if is_git { + g::t(lang, K::GitPassword) + } else { + g::t(lang, K::TokenOptional) + }; + let private = draft.private; + let opts = draft.opts; + Ok(view! { + newrepo_tabs(lang: lang, active: "import") + if let Some(message) = error { + alert(message: message.as_str()) + } +
+ csrf_field(token: csrf) + +
+

(g::t(lang, K::ImportTitle))

+
+ visibility_pick(lang: lang, private: private) + +
+
+ source_tabs(lang: lang, base: "/new/import", active: source) +

(g::t(lang, K::ImportIntro))

+
+ if is_gitlab { + + } + +
+ if is_git { + + } + +
+

(g::t(lang, K::TokenHelp))

+ if !is_git { + option_boxes(lang: lang, opts: opts) + } +
+
+
+ + + +
+

(g::t(lang, K::TargetNameHelp))

+ +
+ if !is_git { +

(g::t(lang, K::BulkLink))

+ } +
+ }) +} + +#[page("/new/import")] +async fn import_page(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let query = query_params::(cx)?; + let source = source_of(query.source.as_deref()); + let owners = owner_choices(app_context::(cx), &viewer.0).await?; + let csrf = viewer.1.csrf_token.clone(); + Ok(view! { cx => + shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), + import_form(lang: lang, csrf: csrf.as_str(), draft: Draft::fresh(source), error: None, owners: owners)) + }) +} + +#[page(POST "/new/import")] +async fn import_submit(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let source = source_of(Some(&form.source)); + match start_single(cx, &viewer.0, lang, source, &form).await? { + Ok(job_id) => Err(see_other(format!("/import/{job_id}")).into()), + Err(message) => { + let owners = owner_choices(app_context::(cx), &viewer.0).await?; + let csrf = viewer.1.csrf_token.clone(); + let draft = Draft::from_form(&form, source); + Ok(view! { cx => + shell(title: g::t(lang, K::ImportTitle), viewer: Some(&viewer), + import_form(lang: lang, csrf: csrf.as_str(), draft: draft, error: Some(message), owners: owners)) + }) + } + } +} + +/// Validates the form, creates the repo and the job, and starts it. `Ok(Err(message))` is a +/// rejection to show; the token is never part of what is returned. +async fn start_single( + cx: &Cx, + viewer: &User, + lang: Lang, + source: Source, + form: &ImportForm, +) -> Result> { + let state = app_context::(cx); + let Some((remote, instance)) = parse_remote(source, &form.remote, &form.instance) else { + let message = if source == Source::GitLab && form.remote.trim().starts_with("http") { + g::t(lang, K::ErrBadInstance) + } else { + g::t(lang, K::ErrBadRemote) + }; + return Ok(Err(message.to_owned())); + }; + if source == Source::Git + && crate::webhooks::client::validate_url(&remote, &crate::mirrors::policy(state)).is_err() + { + return Ok(Err(g::t(lang, K::ErrBadRemote).to_owned())); + } + let target = match repo_owner(state, viewer, lang, &form.owner).await? { + Ok(target) => target, + Err(message) => return Ok(Err(message)), + }; + let name = match form.name.trim() { + "" => default_name(&remote), + given => given.to_owned(), + }; + let spec = JobSpec { + source, + remote: remote.clone(), + instance: instance.clone(), + token: token_of(&form.token), + git_user: form.git_user.trim().to_owned(), + options: if source == Source::Git { + ImportOptions::default() + } else { + options_of( + &form.opt_labels, + &form.opt_issues, + &form.opt_pulls, + &form.opt_releases, + ) + }, + }; + let visibility = if form.visibility == "public" { + Visibility::Public + } else { + Visibility::Private + }; + begin( + cx, + viewer, + &target, + &name, + form.description.trim(), + visibility, + spec, + ) + .await +} + +/// Creates the repo and the import job for `spec` and starts it. `Ok(Err(message))` is a rejection. +async fn begin( + cx: &Cx, + actor: &User, + target: &User, + name: &str, + description: &str, + visibility: Visibility, + spec: JobSpec, +) -> Result> { + let state = app_context::(cx); + let lang = i18n::lang(cx, Some(actor)); + let name = match forge_core::names::validate_name(name) { + Ok(name) => name, + Err(e) => { + return Ok(Err(user_facing_message(&e).unwrap_or_else(|| { + crate::i18n::misc::t(lang, crate::i18n::misc::K::InvalidRepoName).to_owned() + }))); + } + }; + if description.chars().count() > 350 { + return Ok(Err(crate::i18n::misc::description_too_long(lang, 350))); + } + let repo = match state + .store + .create_repo(&target.id, &name, description, visibility, DEFAULT_BRANCH) + .await + { + Ok(repo) => repo, + Err(e) => match user_facing_message(&e) { + Some(message) => return Ok(Err(message)), + None => return Err(e.into()), + }, + }; + let path = repo_path(&state.config.data_dir, &repo.id)?; + if let Err(e) = init_bare(&state.git, &path, DEFAULT_BRANCH).await { + return Ok(Err(crate::i18n::misc::git_init_failed(lang, e))); + } + let job = state + .store + .create_import_job( + &actor.id, + &repo.id, + spec.source.as_str(), + &source_ref(spec.source, &spec.remote, &spec.instance), + &serde_json::to_string(&spec.options).unwrap_or_else(|_| "{}".into()), + ) + .await?; + let full_name = format!("{}/{}", repo.owner_name, repo.name); + audit::record( + &state.store, + Some(cx), + Actor::User(actor), + AuditAction::RepoCreated, + Target { + kind: "repo", + id: &repo.id, + name: &full_name, + }, + serde_json::json!({ "import": spec.source.as_str() }), + ) + .await; + importer::spawn_job(state.clone(), job.clone(), spec); + Ok(Ok(job.id)) +} + +// ---- bulk import ---- + +#[component] +async fn bulk_form( + lang: Lang, + csrf: &str, + source: Source, + instance: &str, + owners: Vec, + error: Option, +) -> Result { + let is_gitlab = source == Source::GitLab; + let source_value = source.as_str(); + let owner_label = if is_gitlab { + g::t(lang, K::BulkOwnerGitLab) + } else { + g::t(lang, K::BulkOwnerGitHub) + }; + Ok(view! { + newrepo_tabs(lang: lang, active: "import") + if let Some(message) = error { + alert(message: message.as_str()) + } +
+ csrf_field(token: csrf) + + +
+

(g::t(lang, K::BulkTitle))

+
+ +
+
+ source_tabs(lang: lang, base: "/new/import/bulk", active: source) +

(g::t(lang, K::BulkIntro))

+
+ if is_gitlab { + + } + + +

(g::t(lang, K::TokenHelp))

+
+ +
+ }) +} + +struct Listed { + name: String, + full_name: String, + description: String, + private: bool, + fork: bool, + archived: bool, +} + +#[component] +async fn bulk_select( + lang: Lang, + csrf: &str, + form: BulkFormEcho, + repos: Vec, + owners: Vec, +) -> Result { + let count = repos.len(); + let empty = repos.is_empty(); + let private = form.private; + let opts = form.opts; + let selected_owner = if form.owner.is_empty() { + owners.first().cloned().unwrap_or_default() + } else { + form.owner.clone() + }; + Ok(view! { + newrepo_tabs(lang: lang, active: "import") +
+ csrf_field(token: csrf) + + + + + +
+

(g::t(lang, K::BulkSelectHeading))

+
+ visibility_pick(lang: lang, private: private) + if !empty { + + } +
+
+ if empty { +

(g::t(lang, K::BulkNone))

+ } else { +
+ +
    + for (i, repo) in repos.iter().enumerate() { +
  • + + if !repo.description.is_empty() { + (repo.description.as_str()) + } +
  • + } +
+
+
+ + if form.source != "git" { + option_boxes(lang: lang, opts: opts) + } +
+ } +
+ }) +} + +/// The bulk form's values carried to the selection step (the token is in a hidden field, sent back +/// once; the server never stores it). +struct BulkFormEcho { + source: String, + instance: String, + token: String, + from: String, + owner: String, + private: bool, + opts: ImportOptions, +} + +#[page("/new/import/bulk")] +async fn bulk_page(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let query = query_params::(cx)?; + let source = match source_of(query.source.as_deref()) { + Source::Git => Source::GitHub, + other => other, + }; + let owners = owner_choices(app_context::(cx), &viewer.0).await?; + let csrf = viewer.1.csrf_token.clone(); + Ok(view! { cx => + shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), + bulk_form(lang: lang, csrf: csrf.as_str(), source: source, instance: "https://gitlab.com", owners: owners, error: query.error.clone().filter(|e| e.len() < 300))) + }) +} + +fn notice_for(state: &AppState) -> importer::api::Notice { + let _ = state; + std::sync::Arc::new(|_msg: String| {}) +} + +/// Lists the repos of `from` through the API. The error text is safe to show. +async fn list_remote( + state: &AppState, + source: Source, + instance: &str, + from: &str, + token: Option, +) -> std::result::Result, String> { + let notice = notice_for(state); + let listed = match source { + Source::GitLab => { + make_gitlab(state, instance, token, notice)? + .list_repos(from) + .await + } + _ => make_github(state, token, notice)?.list_repos(from).await, + }; + listed.map_err(|e: ApiError| e.to_string()) +} + +#[page(POST "/new/import/bulk")] +async fn bulk_submit(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let source = match source_of(Some(&form.source)) { + Source::Git => Source::GitHub, + other => other, + }; + let owners = owner_choices(state, &viewer.0).await?; + let csrf = viewer.1.csrf_token.clone(); + let instance = if source == Source::GitLab && !form.instance.trim().is_empty() { + form.instance.trim().to_owned() + } else { + "https://gitlab.com".to_owned() + }; + + if form.stage == "run" { + let Err(redirect) = run_bulk(cx, &viewer.0, lang, source, &instance, &form).await; + return Err(redirect); + } + + let from = form.from.trim(); + let bad_owner = + !crate::importer::api::valid_path(from, 1, if source == Source::GitLab { 20 } else { 1 }); + let result = if bad_owner { + Err(g::t(lang, K::ErrBadOwner).to_owned()) + } else { + list_remote(state, source, &instance, from, token_of(&form.token)).await + }; + let (error, picker) = match result { + Err(message) => (Some(message), None), + Ok(found) => { + let repos: Vec = found + .into_iter() + .map(|r| Listed { + name: r.name, + full_name: r.full_name, + description: r.description, + private: r.private, + fork: r.fork, + archived: r.archived, + }) + .collect(); + let echo = BulkFormEcho { + source: source.as_str().to_owned(), + instance: instance.clone(), + token: form.token.trim().to_owned(), + from: from.to_owned(), + owner: form.owner.trim().to_owned(), + private: true, + opts: ImportOptions { + labels: true, + issues: true, + pulls: true, + releases: true, + }, + }; + (None, Some((echo, repos))) + } + }; + Ok(view! { cx => + shell(title: g::t(lang, K::BulkTitle), viewer: Some(&viewer), + bulk_stage(lang: lang, csrf: csrf.as_str(), source: source, instance: instance.as_str(), owners: owners, error: error, picker: picker)) + }) +} + +/// The bulk page body: the picker once a listing exists, the lookup form otherwise. +#[component] +async fn bulk_stage( + lang: Lang, + csrf: &str, + source: Source, + instance: &str, + owners: Vec, + error: Option, + picker: Option<(BulkFormEcho, Vec)>, +) -> Result { + Ok(view! { + if let Some((echo, repos)) = picker { + bulk_select(lang: lang, csrf: csrf, form: echo, repos: repos, owners: owners) + } else { + bulk_form(lang: lang, csrf: csrf, source: source, instance: instance, owners: owners, error: error) + } + }) +} + +/// Starts one job per ticked repository, then shows the imports list. +async fn run_bulk( + cx: &Cx, + viewer: &User, + lang: Lang, + source: Source, + instance: &str, + form: &BulkForm, +) -> Result { + let state = app_context::(cx); + let mut picked: Vec<(usize, &String)> = form + .extra + .iter() + .filter_map(|(k, v)| Some((k.strip_prefix("sel_")?.parse::().ok()?, v))) + .collect(); + picked.sort_by_key(|(i, _)| *i); + let fail = |message: &str| -> Result { + Err(see_other(format!( + "/new/import/bulk?source={}&error={}", + source.as_str(), + crate::views::enc(message) + )) + .into()) + }; + if picked.is_empty() { + return fail(g::t(lang, K::ErrNothingSelected)); + } + if picked.len() > MAX_BULK { + return fail(g::t(lang, K::ErrTooMany)); + } + let target = match repo_owner(state, viewer, lang, &form.owner).await? { + Ok(target) => target, + Err(message) => return fail(&message), + }; + let options = options_of( + &form.opt_labels, + &form.opt_issues, + &form.opt_pulls, + &form.opt_releases, + ); + let visibility = if form.visibility == "public" { + Visibility::Public + } else { + Visibility::Private + }; + for (_, full_name) in picked { + let Some((remote, inst)) = parse_remote(source, full_name, instance) else { + continue; + }; + let spec = JobSpec { + source, + remote: remote.clone(), + instance: inst, + token: token_of(&form.token), + git_user: String::new(), + options, + }; + let name = default_name(&remote); + // A name already taken, or any refusal, is skipped here; the list page shows the rest. + if let Err(message) = begin(cx, viewer, &target, &name, "", visibility, spec).await? { + tracing::info!(repo = %remote, %message, "bulk import: skipped a repository"); + } + } + Err(see_other("/import").into()) +} + +// ---- jobs ---- + +fn state_badge(lang: Lang, state: ImportState) -> (&'static str, &'static str) { + match state { + ImportState::Queued => ("badge", g::t(lang, K::JobQueued)), + ImportState::Running => ("badge import-running", g::t(lang, K::JobRunning)), + ImportState::Done => ("badge public", g::t(lang, K::JobDone)), + ImportState::Failed => ("badge import-failed", g::t(lang, K::JobFailed)), + } +} + +fn stage_name(lang: Lang, stage: &str) -> &'static str { + match stage { + "git" => g::t(lang, K::StageGit), + "labels" => g::t(lang, K::StageLabels), + "milestones" => g::t(lang, K::StageMilestones), + "issues" => g::t(lang, K::StageIssues), + "releases" => g::t(lang, K::StageReleases), + "done" => g::t(lang, K::StageDone), + _ => "", + } +} + +fn ago(lang: Lang, stamp: &str) -> String { + stamp_to_unix(stamp).map_or_else(String::new, |t| relative_time(lang, t, now_unix())) +} + +#[component] +async fn jobs_list(lang: Lang, jobs: Vec<(ImportJob, Option)>) -> Result { + let empty = jobs.is_empty(); + Ok(view! { + newrepo_tabs(lang: lang, active: "jobs") +
+

(g::t(lang, K::JobsTitle))

+
+ if empty { +

(g::t(lang, K::NoJobs))

+ } else { +
+ +
+ } + }) +} + +#[page("/import")] +async fn jobs_page(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let jobs = state.store.list_import_jobs(&viewer.0.id, 50).await?; + let mut rows = Vec::with_capacity(jobs.len()); + for job in jobs { + let repo = match &job.repo_id { + Some(id) => state.store.repo_by_id(id).await?, + None => None, + }; + rows.push((job, repo)); + } + Ok(view! { cx => + shell(title: g::t(lang, K::JobsTitle), viewer: Some(&viewer), jobs_list(lang: lang, jobs: rows)) + }) +} + +#[component] +async fn job_view( + lang: Lang, + csrf: &str, + job: ImportJob, + repo: Option, + log: Vec, +) -> Result { + let (badge_class, badge_text) = state_badge(lang, job.state); + let live = (!job.state.is_finished()).then(|| { + format!( + "/import/{}/events?v={}", + job.id, + crate::views::enc(&job.updated_at) + ) + }); + let stage = stage_name(lang, &job.stage); + let has_progress = job.total > 0 && !job.state.is_finished(); + let progress_text = g::progress_of(job.done, job.total); + let failed = job.state == ImportState::Failed; + let done = job.state == ImportState::Done; + let repo_href = repo + .as_ref() + .map(|r| format!("/{}/{}", r.owner_name, r.name)); + let retry_action = format!("/import/{}/retry", job.id); + let error = job.error.clone(); + let state_word = job.state.as_str(); + let empty_log = log.is_empty(); + Ok(view! { + newrepo_tabs(lang: lang, active: "jobs") +
+
+

(job.source_ref.as_str())

+ (badge_text) +
+ if let Some(href) = repo_href.as_ref() { + if done { + (g::t(lang, K::JobOpenRepo)) + } + } +
+
+
+ if !stage.is_empty() { +
+ (stage) + if has_progress { + (progress_text.as_str()) + } +
+ } + if has_progress { + + } else if !job.state.is_finished() { + + } + if let Some(message) = error { + alert(message: message.as_str()) + } + if failed { +
+ csrf_field(token: csrf) + +

(g::t(lang, K::JobRetryHelp))

+ +
+ } +
+
+

(g::t(lang, K::JobProgress))

+ if empty_log { +

(g::t(lang, K::JobNoLog))

+ } else { +
    + for line in log.iter() { +
  1. (line.message.as_str())
  2. + } +
+ } +
+
+ }) +} + +/// The job when the viewer owns it. Anyone else gets 404. +async fn owned_job(cx: &Cx, viewer: &User) -> Result { + let id = path_param::(cx).to_owned(); + let state = app_context::(cx); + match state.store.import_job(&id).await? { + Some(job) if job.user_id == viewer.id => Ok(job), + _ => Err(not_found().into()), + } +} + +#[page("/import/{job_id}")] +async fn job_page(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + let job = owned_job(cx, &viewer.0).await?; + let repo = match &job.repo_id { + Some(id) => state.store.repo_by_id(id).await?, + None => None, + }; + let log = state.store.list_import_events(&job.id, 200).await?; + let csrf = viewer.1.csrf_token.clone(); + let title = job.source_ref.clone(); + Ok(view! { cx => + shell(title: title.as_str(), viewer: Some(&viewer), + job_view(lang: lang, csrf: csrf.as_str(), job: job, repo: repo, log: log)) + }) +} + +/// The job's `changed` stream. It sends when the job differs from the version the page was +/// rendered with, then on every change, and ends once the job is finished. +#[route(GET "/import/{job_id}/events")] +async fn job_events(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let job = owned_job(cx, &viewer.0).await?; + let query = query_params::(cx)?; + let state = app_context::(cx); + let seen = query.v.clone().unwrap_or_default(); + // Subscribed before the job is read again below, so a change in between is not lost. + let wake = (!job.state.is_finished()).then(|| importer::subscribe(&job.id)); + let store = state.store.clone(); + let id = job.id.clone(); + let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| { + let store = store.clone(); + let id = id.clone(); + async move { + if ended { + return None; + } + loop { + let job = store.import_job(&id).await.ok().flatten()?; + if job.updated_at != seen { + seen = job.updated_at.clone(); + let finished = job.state.is_finished(); + return Some(( + changed_event(job.state.as_str().to_owned()), + (wake, seen, finished), + )); + } + if job.state.is_finished() { + return None; + } + let rx = wake.as_mut()?; + rx.changed().await.ok()?; + } + } + }); + events_response(cx, events) +} + +#[derive(Deserialize)] +struct RetryForm { + #[serde(default)] + csrf: String, + #[serde(default)] + token: String, +} + +#[route(POST "/import/{job_id}/retry")] +async fn job_retry(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + let job = owned_job(cx, &viewer.0).await?; + let href = format!("/import/{}", job.id); + if job.state != ImportState::Failed { + return Err(see_other(href).into()); + } + let Some(source) = Source::parse(&job.source) else { + return Err(see_other(href).into()); + }; + let Some((remote, instance)) = parse_remote(source, &job.source_ref, "") else { + return Err(see_other(href).into()); + }; + if let Some(repo_id) = &job.repo_id + && state.store.active_import_for_repo(repo_id).await?.is_some() + { + return Err(see_other(href).into()); + } + let options: ImportOptions = serde_json::from_str(&job.options).unwrap_or_default(); + state + .store + .set_import_state(&job.id, ImportState::Queued, None) + .await?; + state + .store + .add_import_event( + &job.id, + "info", + "Retrying; what was imported before is skipped", + ) + .await?; + let spec = JobSpec { + source, + remote, + instance, + token: token_of(&form.token), + git_user: String::new(), + options, + }; + importer::spawn_job(state.clone(), job, spec); + Err(see_other(href).into()) +} diff --git a/crates/forge-web/src/pages/import_tests.rs b/crates/forge-web/src/pages/import_tests.rs new file mode 100644 index 0000000..bb4d59f --- /dev/null +++ b/crates/forge-web/src/pages/import_tests.rs @@ -0,0 +1,171 @@ +//! Route-level tests for the import pages and the data export page: they render, they need a +//! session, and one user cannot see another user's job or archive. + +use forge_core::Store; +use topcoat::router::request::Request; +use topcoat::router::{Body, Router, to_bytes}; + +use crate::auth::SESSION_COOKIE; +use crate::test_support::{app_router, create_session, test_state}; + +const TOKEN: &str = "import-session"; +const CSRF: &str = "import-csrf"; +const OTHER: &str = "other-session"; + +struct Fixture { + _dir: tempfile::TempDir, + router: Router, + store: Store, + user_id: String, +} + +async fn fixture() -> Fixture { + let dir = tempfile::tempdir().expect("tempdir"); + let data_dir = dir.path().join("data"); + std::fs::create_dir_all(&data_dir).expect("data dir"); + let state = test_state(&data_dir).await; + let owner = state + .store + .create_user("tahinli", None, "h", false) + .await + .expect("user"); + let other = state + .store + .create_user("nina", None, "h", false) + .await + .expect("user"); + create_session(&state.store, &owner.id, TOKEN, CSRF).await; + create_session(&state.store, &other.id, OTHER, "other-csrf").await; + Fixture { + _dir: dir, + router: app_router(state.clone()), + store: state.store.clone(), + user_id: owner.id, + } +} + +async fn send( + router: &Router, + method: &str, + uri: &str, + token: Option<&str>, + form: Option, +) -> (u16, String) { + let mut builder = Request::builder().method(method).uri(uri); + if let Some(token) = token { + builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); + } + let body = match form { + Some(form) => { + builder = builder.header("content-type", "application/x-www-form-urlencoded"); + Body::from(form) + } + None => Body::empty(), + }; + let res = router.handle(builder.body(body).expect("request")).await; + let status = res.status().as_u16(); + let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); + (status, String::from_utf8_lossy(&bytes).into_owned()) +} + +#[tokio::test] +async fn the_import_pages_render_for_a_signed_in_user() { + let fx = fixture().await; + for (uri, needle) in [ + ("/new/import?source=git", "Import a repository"), + ("/new/import?source=github", "Import a repository"), + ("/new/import?source=gitlab", "Import a repository"), + ( + "/new/import/bulk?source=github", + "Import several repositories", + ), + ("/import", "Imports"), + ("/settings/export", "Export your data"), + ] { + let (status, body) = send(&fx.router, "GET", uri, Some(TOKEN), None).await; + assert_eq!(status, 200, "{uri}: {body}"); + assert!(body.contains(needle), "{uri} lacks {needle}"); + } +} + +#[tokio::test] +async fn the_import_and_export_pages_need_a_session() { + let fx = fixture().await; + for uri in [ + "/new/import", + "/new/import/bulk", + "/import", + "/settings/export", + ] { + let (status, body) = send(&fx.router, "GET", uri, None, None).await; + assert_ne!(status, 200, "{uri}: {body}"); + } +} + +#[tokio::test] +async fn a_post_without_the_csrf_token_starts_nothing() { + let fx = fixture().await; + let form = "source=git&remote=https%3A%2F%2Fexample.org%2Fa.git&csrf=wrong".to_owned(); + let (status, _) = send(&fx.router, "POST", "/new/import", Some(TOKEN), Some(form)).await; + assert_ne!(status, 303, "a bad token must not redirect to a job"); + assert!( + fx.store + .list_import_jobs(&fx.user_id, 10) + .await + .expect("jobs") + .is_empty() + ); + let (status, _) = send( + &fx.router, + "POST", + "/settings/export", + Some(TOKEN), + Some("csrf=wrong".into()), + ) + .await; + assert_ne!(status, 303); + assert!( + fx.store + .list_exports(&fx.user_id) + .await + .expect("exports") + .is_empty() + ); +} + +#[tokio::test] +async fn a_private_address_is_refused_before_any_job_exists() { + let fx = fixture().await; + let form = format!( + "csrf={CSRF}&source=git&remote=https%3A%2F%2F127.0.0.1%2Fa.git&owner=tahinli&visibility=private" + ); + let (status, body) = send(&fx.router, "POST", "/new/import", Some(TOKEN), Some(form)).await; + assert_ne!(status, 500, "{body}"); + assert!( + fx.store + .list_import_jobs(&fx.user_id, 10) + .await + .expect("jobs") + .is_empty(), + "no job for a refused address" + ); +} + +#[tokio::test] +async fn another_users_archive_cannot_be_downloaded() { + let fx = fixture().await; + let export = fx + .store + .create_export(&fx.user_id, std::time::Duration::from_secs(3600)) + .await + .expect("export"); + fx.store + .mark_export_ready(&export.id, 10, std::time::Duration::from_secs(3600)) + .await + .expect("ready"); + let uri = format!("/settings/export/{}/download", export.id); + let (status, _) = send(&fx.router, "GET", &uri, Some(OTHER), None).await; + assert_eq!(status, 404, "a stranger gets not found"); + let (status, _) = send(&fx.router, "GET", &uri, None, None).await; + assert_ne!(status, 200); +} diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 186e9b6..809c146 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -34,6 +34,9 @@ pub mod explore; pub mod finder; pub mod forgot; pub mod fork; +pub mod import; +#[cfg(test)] +mod import_tests; pub mod invites; pub mod issue_meta; #[cfg(test)] @@ -87,6 +90,7 @@ pub mod repo_webhooks; #[cfg(test)] mod security_tab_tests; pub mod settings_appearance; +pub mod settings_export; pub mod settings_gpg; #[cfg(test)] mod settings_gpg_tests; diff --git a/crates/forge-web/src/pages/new_repo.rs b/crates/forge-web/src/pages/new_repo.rs index dde51a7..9c4b70d 100644 --- a/crates/forge-web/src/pages/new_repo.rs +++ b/crates/forge-web/src/pages/new_repo.rs @@ -126,6 +126,7 @@ async fn new_repo_form( let draft_mirror_username = draft.mirror_username; let draft_mirror_interval = draft.mirror_interval; Ok(view! { + crate::pages::import::newrepo_tabs(lang: lang, active: "create") if let Some(message) = error { alert(message: message.as_str()) } @@ -216,7 +217,7 @@ async fn new_repo_form( /// The accounts the viewer may create a repo under: themselves, then the orgs where /// `may_create_repo_in` allows it. -async fn owner_choices(state: &AppState, viewer: &User) -> Result> { +pub(crate) async fn owner_choices(state: &AppState, viewer: &User) -> Result> { let mut names = vec![viewer.username.clone()]; for (org, _) in state.store.orgs_for_user(&viewer.id).await? { if may_create_repo_in(state, &org.id, &viewer.id).await? { @@ -257,7 +258,7 @@ async fn new_repo_submit(cx: &Cx, Form(form): Form) -> Result, +} + +/// One word per export and its state, so the stream can tell the page is out of date. +fn signature(exports: &[DataExport]) -> String { + exports + .iter() + .map(|e| format!("{}:{}", e.id, e.state.as_str())) + .collect::>() + .join(",") +} + +fn ago(lang: Lang, stamp: &str) -> String { + stamp_to_unix(stamp).map_or_else(String::new, |t| relative_time(lang, t, now_unix())) +} + +fn day(stamp: &str) -> String { + stamp.chars().take(10).collect() +} + +#[component] +async fn export_view(lang: Lang, csrf: &str, exports: Vec) -> Result { + let building = exports.iter().any(|e| e.state == ExportState::Building); + let live = building.then(|| { + format!( + "/settings/export/events?v={}", + crate::views::enc(&signature(&exports)) + ) + }); + let empty = exports.is_empty(); + let ttl_note = g::export_ttl_note(lang, exporter::EXPORT_TTL_DAYS); + Ok(view! { +
+

(g::t(lang, K::ExportTitle))

+
+
+
+

(g::t(lang, K::ExportIntro))

+

(g::t(lang, K::ExportContents))

+

(g::t(lang, K::ExportEmailNote)) " " (ttl_note.as_str())

+
+ csrf_field(token: csrf) + +
+
+
+ if empty { +

(g::t(lang, K::ExportNone))

+ } else { +
    + for export in exports.iter() { +
  • +
    + (g::t(lang, K::ExportRequested)) " " (ago(lang, &export.created_at)) + if export.state == ExportState::Ready { + + (g::t(lang, K::ExportSize)) ": " (human_size(lang, u64::try_from(export.size).unwrap_or(0))) + " · " (g::expires_on(lang, &day(&export.expires_at))) + + } +
    + if export.state == ExportState::Ready { + (g::t(lang, K::ExportReady)) + (g::t(lang, K::ExportDownload)) + } + if export.state == ExportState::Building { + (g::t(lang, K::ExportBuilding)) + + } + if export.state == ExportState::Failed { + (g::t(lang, K::ExportFailed)) + } +
  • + if let Some(message) = export.error.as_ref() { +
  • alert(message: message.as_str())
  • + } + } +
+ } +
+
+ }) +} + +#[page("/settings/export")] +async fn export_page(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let lang = i18n::lang(cx, Some(&viewer.0)); + let state = app_context::(cx); + exporter::sweep_expired(state).await; + let exports = state.store.list_exports(&viewer.0.id).await?; + let csrf = viewer.1.csrf_token.clone(); + Ok(view! { cx => + shell(title: g::t(lang, K::SettingsExport), viewer: Some(&viewer), + export_view(lang: lang, csrf: csrf.as_str(), exports: exports)) + }) +} + +#[route(POST "/settings/export")] +async fn export_request(cx: &Cx, Form(form): Form) -> Result { + let viewer = require_csrf(cx, &form.csrf).await?; + let state = app_context::(cx); + exporter::start(state, &viewer.0).await?; + Err(see_other("/settings/export").into()) +} + +/// The `changed` stream of the export page. It sends when the exports differ from what the page +/// shows, then on each change, and ends once nothing is building. +#[route(GET "/settings/export/events")] +async fn export_events(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let query = query_params::(cx)?; + let state = app_context::(cx); + let user_id = viewer.0.id.clone(); + let wake = exporter::subscribe(&user_id); + let store = state.store.clone(); + let seen = query.v.clone().unwrap_or_default(); + let events = stream::unfold((wake, seen, false), move |(mut wake, mut seen, ended)| { + let store = store.clone(); + let user_id = user_id.clone(); + async move { + if ended { + return None; + } + loop { + let exports = store.list_exports(&user_id).await.ok()?; + let sig = signature(&exports); + let building = exports.iter().any(|e| e.state == ExportState::Building); + if sig != seen { + seen = sig; + return Some((changed_event("export".to_owned()), (wake, seen, !building))); + } + if !building { + return None; + } + wake.changed().await.ok()?; + } + } + }); + events_response(cx, events) +} + +/// Sends the archive. Only its owner, only while it is ready and unexpired. +#[route(GET "/settings/export/{export_id}/download")] +async fn export_download(cx: &Cx) -> Result { + let viewer = require_user(cx).await?; + let id = path_param::(cx).to_owned(); + let state = app_context::(cx); + exporter::sweep_expired(state).await; + let export = match state.store.data_export(&id).await? { + Some(e) if e.user_id == viewer.0.id && e.state == ExportState::Ready => e, + _ => return Err(not_found().into()), + }; + let file = match tokio::fs::File::open(exporter::archive_path(state, &export.id)).await { + Ok(file) => file, + Err(_) => return Err(not_found().into()), + }; + let len = file.metadata().await?.len(); + let chunks = ReaderStream::new(file).map_ok(Frame::data); + let mut res = Response::new(Body::new(StreamBody::new(chunks))); + let headers = res.headers_mut(); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/gzip")); + headers.insert( + CONTENT_DISPOSITION, + HeaderValue::from_str(&format!( + "attachment; filename=\"forge-export-{}.tar.gz\"", + viewer.0.username + ))?, + ); + headers.insert(CONTENT_LENGTH, HeaderValue::from(len)); + headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); + headers.insert(CACHE_CONTROL, HeaderValue::from_static("private, no-store")); + Ok(res) +} diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web/src/views/mod.rs index bce3a03..73da7ea 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web/src/views/mod.rs @@ -26,6 +26,7 @@ use topcoat::view::{Child, View, component, view}; use crate::i18n::admin::{self as ad, K as AK}; use crate::i18n::code::{self as g, K}; use crate::i18n::community::{self as cm, K as CK}; +use crate::i18n::migrate::{self as mg, K as MGK}; use crate::i18n::misc::{self as mi, K as MK}; use crate::i18n::orgs::{self as o, K as OK}; use crate::i18n::{self, Key, Lang, t}; @@ -563,6 +564,12 @@ fn settings_items(lang: Lang) -> Vec { o::t(lang, OK::CustomizePins), "pins", ), + item( + "export", + "/settings/export", + mg::t(lang, MGK::SettingsExport), + "export", + ), ] } @@ -701,6 +708,9 @@ async fn nav_icon(name: &str) -> Result { if name == "appearance" { } + if name == "export" { + + } if name == "pins" { } diff --git a/crates/forge-web/src/webhooks/client.rs b/crates/forge-web/src/webhooks/client.rs index 5fd7744..f3f54b5 100644 --- a/crates/forge-web/src/webhooks/client.rs +++ b/crates/forge-web/src/webhooks/client.rs @@ -252,6 +252,25 @@ async fn resolve_allowed(policy: Arc, host: String) -> Result reqwest::Result { + reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(10)) + .timeout(timeout) + .dns_resolver(Arc::new(PolicyResolver { + policy: Arc::new(policy), + })) + .user_agent(user_agent) + .no_proxy() + .build() +} + /// What happened when a delivery was sent. A failure leaves `status` as `None` and sets `error`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SendOutcome { diff --git a/style/_import.scss b/style/_import.scss new file mode 100644 index 0000000..b7ec330 --- /dev/null +++ b/style/_import.scss @@ -0,0 +1,286 @@ +// Import and export (pages/import.rs, pages/settings_export.rs). Tokens only, so both themes follow +// main.scss. The forms reuse the .newrepo-* cards. + +.import-tabs { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + max-width: 960px; + margin: 0 0 16px; + border-bottom: 1px solid var(--border); +} + +.import-tab { + margin-bottom: -1px; + padding: 8px 14px; + border-bottom: 2px solid transparent; + font-size: 0.875rem; + font-weight: 500; + color: var(--muted); + text-decoration: none; + + &:hover { + color: var(--text); + } + + &[aria-current="page"] { + color: var(--accent-ink); + border-bottom-color: var(--accent); + } + + &.import-tab-end { + margin-left: auto; + } +} + +.import-sources { + display: inline-flex; + align-items: center; + align-self: flex-start; + gap: 2px; + max-width: 100%; + padding: 2px; + border: 1px solid var(--border); + border-radius: var(--radius-full); + background: var(--surface-2); +} + +.import-source { + display: inline-flex; + align-items: center; + height: 26px; + padding: 0 14px; + border-radius: var(--radius-full); + font-size: 0.8125rem; + font-weight: 500; + color: var(--muted); + text-decoration: none; + white-space: nowrap; + + &:hover { + color: var(--text); + } + + &[aria-current="page"] { + background: var(--surface); + color: var(--accent-ink); + box-shadow: 0 1px 2px rgba(30, 36, 32, .12); + } +} + +.import-opts { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; + margin: 0; + padding: 0; + border: 0; + + legend { + padding: 0; + margin-bottom: 6px; + font-size: 0.875rem; + font-weight: 500; + color: var(--text-2); + } + + p { + margin: 4px 0 0; + } +} + +.import-pick { + gap: 0; + padding: 0; +} + +.import-pick-all { + margin: 0; + padding: 12px 22px; + border-bottom: 1px solid var(--border); +} + +.import-pick-list { + max-height: 52vh; + overflow-y: auto; +} + +.import-pick-row { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 2px 12px; + padding: 9px 22px; + border-bottom: 1px solid var(--border); + + &:last-child { + border-bottom: 0; + } + + .inline { + margin: 0; + } +} + +.import-pick-name { + font-family: var(--mono); + font-size: 0.875rem; +} + +.import-pick-desc { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 100%; +} + +.import-job { + display: flex; + flex-direction: column; + gap: 16px; + max-width: 960px; + min-width: 0; +} + +.import-job-title { + margin: 0; + min-width: 0; + font-size: 1.25rem; + font-family: var(--mono); + overflow-wrap: anywhere; +} + +.import-job-name { + font-family: var(--mono); + font-size: 0.875rem; + overflow-wrap: anywhere; +} + +.import-job-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; + + .item-main { + flex: 1 1 260px; + min-width: 0; + } +} + +.import-stage { + display: flex; + align-items: baseline; + gap: 10px; +} + +.import-progress { + width: 100%; + height: 8px; + border-radius: var(--radius-full); + overflow: hidden; +} + +.badge.import-running { + background: var(--accent-soft, var(--surface-2)); + color: var(--accent-ink); +} + +.badge.import-failed { + background: var(--danger-bg); + color: var(--alert-text); +} + +.import-retry { + display: flex; + flex-direction: column; + gap: 10px; + max-width: 420px; + + p { + margin: 0; + } +} + +.import-log-title { + margin: 0; + font-size: 0.9375rem; +} + +.import-log { + display: flex; + flex-direction: column; + gap: 2px; + max-height: 46vh; + margin: 0; + padding: 0; + overflow-y: auto; + list-style: none; + font-family: var(--mono); + font-size: 0.8125rem; +} + +.import-log-line { + overflow-wrap: anywhere; + color: var(--text-2); + + &.import-log-warn { + color: var(--warn); + } + + &.import-log-error { + color: var(--danger); + } +} + +.export-page { + display: flex; + flex-direction: column; + gap: 16px; + max-width: 960px; +} + +.export-intro { + display: flex; + flex-direction: column; + gap: 8px; + + p { + margin: 0; + } +} + +.export-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; + + .item-main { + flex: 1 1 240px; + min-width: 0; + } +} + +.export-progress { + width: 120px; +} + +.export-error { + list-style: none; + + .alert { + margin: 0; + } +} + +@media (max-width: 560px) { + .import-pick-row, + .import-pick-all { + padding-left: 14px; + padding-right: 14px; + } +} diff --git a/style/main.scss b/style/main.scss index 5a1578e..f2cd847 100644 --- a/style/main.scss +++ b/style/main.scss @@ -5573,6 +5573,7 @@ button.ci-job-last { @import "dashboard"; @import "wiki"; @import "browse"; +@import "import"; // Code inside cards, notices and settings panels must stay inside the card. Long tokens and // commands wrap instead of running past the right edge. The rendered README card (.readme) and