diff --git a/Cargo.lock b/Cargo.lock index 547c701..cfaa738 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2115,10 +2115,10 @@ dependencies = [ "forge-git", "forge-runner", "forge-ssh", + "forge-web-app", "forge-web-base", "form_urlencoded", "futures-util", - "grass", "hex", "hkdf 0.13.0", "hmac 0.13.0", @@ -2156,6 +2156,57 @@ dependencies = [ "zip", ] +[[package]] +name = "forge-web-app" +version = "0.1.0" +dependencies = [ + "aes-gcm 0.11.1", + "async-compression", + "base64 0.23.1", + "bytes", + "flate2", + "forge-ci", + "forge-core", + "forge-git", + "forge-ssh", + "forge-web-base", + "form_urlencoded", + "futures-util", + "grass", + "hex", + "hkdf 0.13.0", + "hmac 0.13.0", + "http", + "http-body", + "http-body-util", + "image", + "ipnet", + "jiff 1.0.3", + "lettre", + "multer", + "nix 0.31.4", + "p256", + "rand 0.10.4", + "reqwest", + "scraper", + "serde", + "serde_json", + "sha2 0.11.1", + "similar", + "subtle", + "tar", + "tempfile", + "time", + "tokio", + "tokio-util", + "topcoat", + "tracing", + "tracing-subscriber", + "ulid", + "webauthn-authenticator-rs", + "zip", +] + [[package]] name = "forge-web-base" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 9a1f1ff..89efadd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "crates/forge-ssh", "crates/forge-web", "crates/forge-web-base", + "crates/forge-web-app", "crates/forge-ci", "crates/forge-runner", "crates/forge-e2e", @@ -34,6 +35,7 @@ forge-git = { path = "crates/forge-git" } forge-ssh = { path = "crates/forge-ssh" } forge-runner = { path = "crates/forge-runner" } forge-web-base = { path = "crates/forge-web-base" } +forge-web-app = { path = "crates/forge-web-app" } # async runtime and HTTP plumbing tokio = { version = "1.54.1", features = ["full"] } diff --git a/crates/forge-web-app/Cargo.toml b/crates/forge-web-app/Cargo.toml new file mode 100644 index 0000000..5be67e6 --- /dev/null +++ b/crates/forge-web-app/Cargo.toml @@ -0,0 +1,68 @@ +[package] +name = "forge-web-app" +description = "forge web foundation below the pages: app state, auth, live updates, views, CI, mail, backup and the HTTP APIs" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[features] +test-support = ["dep:tempfile"] + +[dependencies] +forge-core.workspace = true +ipnet.workspace = true +forge-git.workspace = true +forge-ssh.workspace = true +forge-ci.workspace = true +forge-web-base.workspace = true +topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] } +tokio.workspace = true +futures-util.workspace = true +bytes.workspace = true +http.workspace = true +http-body-util.workspace = true +async-compression.workspace = true +serde.workspace = true +serde_json.workspace = true +form_urlencoded.workspace = true +jiff.workspace = true +base64.workspace = true +subtle.workspace = true +tracing.workspace = true +tracing-subscriber = { workspace = true, features = ["env-filter"] } +tokio-util = { workspace = true, features = ["io"] } +http-body.workspace = true +rand.workspace = true +hex.workspace = true +nix = { workspace = true } +sha2.workspace = true +time.workspace = true +reqwest = { workspace = true } +hmac.workspace = true +similar = { workspace = true } +multer.workspace = true +ulid.workspace = true +lettre.workspace = true +zip = { workspace = true } +tar.workspace = true +flate2.workspace = true +p256.workspace = true +hkdf.workspace = true +aes-gcm.workspace = true + +tempfile = { workspace = true, optional = true } + +[build-dependencies] +grass.workspace = true +hex.workspace = true +sha2.workspace = true + +[dev-dependencies] +tempfile.workspace = true +image = { workspace = true } +scraper = { workspace = true } +webauthn-authenticator-rs = { version = "0.6.2", features = ["softpasskey"] } + +[lints] +workspace = true diff --git a/crates/forge-web/build.rs b/crates/forge-web-app/build.rs similarity index 97% rename from crates/forge-web/build.rs rename to crates/forge-web-app/build.rs index 98aeb21..9364b81 100644 --- a/crates/forge-web/build.rs +++ b/crates/forge-web-app/build.rs @@ -198,7 +198,7 @@ fn main() { println!("cargo:rerun-if-changed=../forge-ci/build_identity.rs"); emit_identity(); println!("cargo:rerun-if-changed=../../style"); - println!("cargo:rerun-if-changed=assets/nav.js"); + println!("cargo:rerun-if-changed=../forge-web/assets/nav.js"); println!("cargo:rerun-if-changed=../forge-web-base/src/accent_palette.rs"); let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string()); @@ -220,6 +220,7 @@ fn main() { ); fs::write(out.join("main.css"), css).expect("writing compiled stylesheet to OUT_DIR"); - let nav = fs::read(manifest.join("assets/nav.js")).expect("reading assets/nav.js"); + let nav = fs::read(manifest.join("../forge-web/assets/nav.js")) + .expect("reading forge-web/assets/nav.js"); println!("cargo:rustc-env=FORGE_NAV_JS_V={}", content_version(&nav)); } diff --git a/crates/forge-web/src/access.rs b/crates/forge-web-app/src/access.rs similarity index 100% rename from crates/forge-web/src/access.rs rename to crates/forge-web-app/src/access.rs diff --git a/crates/forge-web/src/admin_client.rs b/crates/forge-web-app/src/admin_client.rs similarity index 100% rename from crates/forge-web/src/admin_client.rs rename to crates/forge-web-app/src/admin_client.rs diff --git a/crates/forge-web/src/advisories/mod.rs b/crates/forge-web-app/src/advisories/mod.rs similarity index 100% rename from crates/forge-web/src/advisories/mod.rs rename to crates/forge-web-app/src/advisories/mod.rs diff --git a/crates/forge-web/src/advisories/scan.rs b/crates/forge-web-app/src/advisories/scan.rs similarity index 100% rename from crates/forge-web/src/advisories/scan.rs rename to crates/forge-web-app/src/advisories/scan.rs diff --git a/crates/forge-web/src/advisories/worker.rs b/crates/forge-web-app/src/advisories/worker.rs similarity index 100% rename from crates/forge-web/src/advisories/worker.rs rename to crates/forge-web-app/src/advisories/worker.rs diff --git a/crates/forge-web/src/alerts.rs b/crates/forge-web-app/src/alerts.rs similarity index 100% rename from crates/forge-web/src/alerts.rs rename to crates/forge-web-app/src/alerts.rs diff --git a/crates/forge-web/src/api/gitea.rs b/crates/forge-web-app/src/api/gitea.rs similarity index 100% rename from crates/forge-web/src/api/gitea.rs rename to crates/forge-web-app/src/api/gitea.rs diff --git a/crates/forge-web/src/api/mod.rs b/crates/forge-web-app/src/api/mod.rs similarity index 98% rename from crates/forge-web/src/api/mod.rs rename to crates/forge-web-app/src/api/mod.rs index 192591d..abde51a 100644 --- a/crates/forge-web/src/api/mod.rs +++ b/crates/forge-web-app/src/api/mod.rs @@ -6,8 +6,6 @@ //! use a repo, the same as git, so missing and hidden repos look identical to them. pub mod gitea; -#[cfg(test)] -mod gitea_tests; pub mod packages; pub mod releases; pub mod statuses; @@ -71,7 +69,7 @@ pub fn internal(message: impl std::fmt::Display) -> Refusal { /// Pulls the token out of `Bearer `, `token ` or `Basic base64(user:)`. The /// scheme is matched case-insensitively. A Basic user name is ignored, since the token alone /// names the user. Returns `None` for a missing header and `Some(None)` for any other shape. -pub(crate) fn presented_token(headers: &HeaderMap) -> Option> { +pub fn presented_token(headers: &HeaderMap) -> Option> { let value = headers.get(AUTHORIZATION)?.to_str().ok()?; let Some((scheme, rest)) = value.split_once(' ') else { return Some(None); @@ -120,7 +118,7 @@ pub async fn authenticate( /// The user a token names, with the token's id and scopes. `None` when the request carries no /// Authorization header. The scope is not checked and the token is not touched: the caller does both. -pub(crate) async fn authenticate_token( +pub async fn authenticate_token( state: &AppState, ip: IpAddr, headers: &HeaderMap, diff --git a/crates/forge-web/src/api/packages.rs b/crates/forge-web-app/src/api/packages.rs similarity index 100% rename from crates/forge-web/src/api/packages.rs rename to crates/forge-web-app/src/api/packages.rs diff --git a/crates/forge-web/src/api/releases.rs b/crates/forge-web-app/src/api/releases.rs similarity index 100% rename from crates/forge-web/src/api/releases.rs rename to crates/forge-web-app/src/api/releases.rs diff --git a/crates/forge-web/src/api/statuses.rs b/crates/forge-web-app/src/api/statuses.rs similarity index 99% rename from crates/forge-web/src/api/statuses.rs rename to crates/forge-web-app/src/api/statuses.rs index ede86c7..b82e411 100644 --- a/crates/forge-web/src/api/statuses.rs +++ b/crates/forge-web-app/src/api/statuses.rs @@ -178,7 +178,7 @@ mod tests { use topcoat::router::{Body, Router, to_bytes}; use crate::auth::SESSION_COOKIE; - use crate::pages::commits::test_support::{Fixture, OWNER, REPO}; + use crate::test_support::fixture::{Fixture, OWNER, REPO}; /// Sends one request through the router: `(status, json body)`. async fn send( diff --git a/crates/forge-web/src/audit.rs b/crates/forge-web-app/src/audit.rs similarity index 100% rename from crates/forge-web/src/audit.rs rename to crates/forge-web-app/src/audit.rs diff --git a/crates/forge-web/src/auth.rs b/crates/forge-web-app/src/auth.rs similarity index 100% rename from crates/forge-web/src/auth.rs rename to crates/forge-web-app/src/auth.rs diff --git a/crates/forge-web/src/automerge.rs b/crates/forge-web-app/src/automerge.rs similarity index 100% rename from crates/forge-web/src/automerge.rs rename to crates/forge-web-app/src/automerge.rs diff --git a/crates/forge-web/src/backup/create.rs b/crates/forge-web-app/src/backup/create.rs similarity index 100% rename from crates/forge-web/src/backup/create.rs rename to crates/forge-web-app/src/backup/create.rs diff --git a/crates/forge-web/src/backup/fsck.rs b/crates/forge-web-app/src/backup/fsck.rs similarity index 100% rename from crates/forge-web/src/backup/fsck.rs rename to crates/forge-web-app/src/backup/fsck.rs diff --git a/crates/forge-web/src/backup/healthcheck.rs b/crates/forge-web-app/src/backup/healthcheck.rs similarity index 100% rename from crates/forge-web/src/backup/healthcheck.rs rename to crates/forge-web-app/src/backup/healthcheck.rs diff --git a/crates/forge-web/src/backup/mod.rs b/crates/forge-web-app/src/backup/mod.rs similarity index 99% rename from crates/forge-web/src/backup/mod.rs rename to crates/forge-web-app/src/backup/mod.rs index 6cce490..fdef9e5 100644 --- a/crates/forge-web/src/backup/mod.rs +++ b/crates/forge-web-app/src/backup/mod.rs @@ -7,7 +7,7 @@ mod create; mod fsck; -pub(crate) mod healthcheck; +pub mod healthcheck; mod restore; mod retention; pub mod scheduler; diff --git a/crates/forge-web/src/backup/restore.rs b/crates/forge-web-app/src/backup/restore.rs similarity index 100% rename from crates/forge-web/src/backup/restore.rs rename to crates/forge-web-app/src/backup/restore.rs diff --git a/crates/forge-web/src/backup/retention.rs b/crates/forge-web-app/src/backup/retention.rs similarity index 100% rename from crates/forge-web/src/backup/retention.rs rename to crates/forge-web-app/src/backup/retention.rs diff --git a/crates/forge-web/src/backup/scheduler.rs b/crates/forge-web-app/src/backup/scheduler.rs similarity index 100% rename from crates/forge-web/src/backup/scheduler.rs rename to crates/forge-web-app/src/backup/scheduler.rs diff --git a/crates/forge-web/src/backup/tests.rs b/crates/forge-web-app/src/backup/tests.rs similarity index 100% rename from crates/forge-web/src/backup/tests.rs rename to crates/forge-web-app/src/backup/tests.rs diff --git a/crates/forge-web/src/backup/verify.rs b/crates/forge-web-app/src/backup/verify.rs similarity index 100% rename from crates/forge-web/src/backup/verify.rs rename to crates/forge-web-app/src/backup/verify.rs diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web-app/src/ci/api.rs similarity index 100% rename from crates/forge-web/src/ci/api.rs rename to crates/forge-web-app/src/ci/api.rs diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web-app/src/ci/api_tests.rs similarity index 99% rename from crates/forge-web/src/ci/api_tests.rs rename to crates/forge-web-app/src/ci/api_tests.rs index 69e83f3..97f401f 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web-app/src/ci/api_tests.rs @@ -11,7 +11,7 @@ use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use super::{artifact_key, cache_scope, fit_to_cap, log_path, valid_artifact_name}; -use crate::pages::commits::test_support::{Fixture, OWNER, REPO}; +use crate::test_support::fixture::{Fixture, OWNER, REPO}; use crate::test_support::{app_router, test_state}; /// A response: status, headers and raw body. diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web-app/src/ci/live.rs similarity index 98% rename from crates/forge-web/src/ci/live.rs rename to crates/forge-web-app/src/ci/live.rs index 2f918db..d714e50 100644 --- a/crates/forge-web/src/ci/live.rs +++ b/crates/forge-web-app/src/ci/live.rs @@ -138,7 +138,7 @@ impl CiLive { /// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due. #[derive(Default)] -pub(crate) struct Signals { +pub struct Signals { counters: Mutex>>, } @@ -147,7 +147,7 @@ impl Signals { self.counters.lock().unwrap_or_else(PoisonError::into_inner) } - pub(crate) fn subscribe(&self, key: &str) -> watch::Receiver { + pub fn subscribe(&self, key: &str) -> watch::Receiver { self.counters() .entry(key.to_owned()) .or_insert_with(|| watch::channel(0).0) @@ -156,7 +156,7 @@ impl Signals { /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry /// whose last receiver is gone is removed here. - pub(crate) fn bump(&self, key: &str) { + pub fn bump(&self, key: &str) { let mut counters = self.counters(); let Some(tx) = counters.get(key) else { return; diff --git a/crates/forge-web/src/ci/metrics_chart.rs b/crates/forge-web-app/src/ci/metrics_chart.rs similarity index 100% rename from crates/forge-web/src/ci/metrics_chart.rs rename to crates/forge-web-app/src/ci/metrics_chart.rs diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web-app/src/ci/mod.rs similarity index 99% rename from crates/forge-web/src/ci/mod.rs rename to crates/forge-web-app/src/ci/mod.rs index 56246bc..2903036 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web-app/src/ci/mod.rs @@ -84,7 +84,7 @@ pub async fn sync_run_statuses(state: &AppState, run: &CiRun) -> forge_core::Res /// Writes one commit status for `run`. The creator is the run's actor, or the repo owner for a /// system run (the status table references users). -pub(crate) async fn publish( +pub async fn publish( state: &AppState, repo: &Repo, run: &CiRun, diff --git a/crates/forge-web/src/ci/reaper.rs b/crates/forge-web-app/src/ci/reaper.rs similarity index 100% rename from crates/forge-web/src/ci/reaper.rs rename to crates/forge-web-app/src/ci/reaper.rs diff --git a/crates/forge-web/src/ci/release.rs b/crates/forge-web-app/src/ci/release.rs similarity index 100% rename from crates/forge-web/src/ci/release.rs rename to crates/forge-web-app/src/ci/release.rs diff --git a/crates/forge-web/src/ci/runner_log.rs b/crates/forge-web-app/src/ci/runner_log.rs similarity index 100% rename from crates/forge-web/src/ci/runner_log.rs rename to crates/forge-web-app/src/ci/runner_log.rs diff --git a/crates/forge-web/src/ci/runner_metrics.rs b/crates/forge-web-app/src/ci/runner_metrics.rs similarity index 100% rename from crates/forge-web/src/ci/runner_metrics.rs rename to crates/forge-web-app/src/ci/runner_metrics.rs diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web-app/src/ci/schedule.rs similarity index 100% rename from crates/forge-web/src/ci/schedule.rs rename to crates/forge-web-app/src/ci/schedule.rs diff --git a/crates/forge-web/src/ci/scheduled.rs b/crates/forge-web-app/src/ci/scheduled.rs similarity index 100% rename from crates/forge-web/src/ci/scheduled.rs rename to crates/forge-web-app/src/ci/scheduled.rs diff --git a/crates/forge-web/src/client_ip.rs b/crates/forge-web-app/src/client_ip.rs similarity index 99% rename from crates/forge-web/src/client_ip.rs rename to crates/forge-web-app/src/client_ip.rs index ee3ab4f..2a71997 100644 --- a/crates/forge-web/src/client_ip.rs +++ b/crates/forge-web-app/src/client_ip.rs @@ -38,7 +38,7 @@ pub fn client_addr(cx: &Cx) -> IpAddr { /// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty. /// Only the tests use the bucketed form; the server takes [`client_ip`], which buckets itself. -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] pub fn resolve(peer: Option, forwarded: &str, trusted: &[IpNet]) -> IpAddr { bucket(resolve_addr(peer, forwarded, trusted)) } diff --git a/crates/forge-web/src/exporter.rs b/crates/forge-web-app/src/exporter.rs similarity index 100% rename from crates/forge-web/src/exporter.rs rename to crates/forge-web-app/src/exporter.rs diff --git a/crates/forge-web/src/exporter/tests.rs b/crates/forge-web-app/src/exporter/tests.rs similarity index 100% rename from crates/forge-web/src/exporter/tests.rs rename to crates/forge-web-app/src/exporter/tests.rs diff --git a/crates/forge-web/src/git_auth.rs b/crates/forge-web-app/src/git_auth.rs similarity index 100% rename from crates/forge-web/src/git_auth.rs rename to crates/forge-web-app/src/git_auth.rs diff --git a/crates/forge-web/src/git_http.rs b/crates/forge-web-app/src/git_http.rs similarity index 99% rename from crates/forge-web/src/git_http.rs rename to crates/forge-web-app/src/git_http.rs index 7e86461..65a970e 100644 --- a/crates/forge-web/src/git_http.rs +++ b/crates/forge-web-app/src/git_http.rs @@ -290,7 +290,7 @@ fn internal_error() -> Response { /// Authenticates the request's credentials under the per-IP git failure limit. Only rejected /// credentials count, so anonymous requests and successful logins never do. Returns the response /// to send when the request must stop: 429 while the IP is throttled, or the access error. -pub(crate) async fn authenticate( +pub async fn authenticate( state: &AppState, ip: IpAddr, headers: &HeaderMap, @@ -343,13 +343,13 @@ async fn caller_repo( } /// Username of a CI job's git credential. The password is `:`. -pub(crate) const JOB_GIT_USERNAME: &str = "ci-job"; +pub const JOB_GIT_USERNAME: &str = "ci-job"; /// Read-only git access for a running CI job. Returns `None` unless the request uses the /// `ci-job` username, so other callers take the normal path. The token must belong to a job that /// is Running (see `job_by_token`), the repo must be that job's repo, and receive-pack is refused. /// Failed attempts count against the git failure limit. -pub(crate) async fn job_token_read( +pub async fn job_token_read( state: &AppState, ip: IpAddr, headers: &HeaderMap, @@ -436,7 +436,7 @@ fn internal_error_for(error: &forge_core::Error) -> Response { internal_error() } -pub(crate) fn access_error(error: AccessError) -> Response { +pub fn access_error(error: AccessError) -> Response { match error { AccessError::Unauthorized => { let mut res = text(StatusCode::UNAUTHORIZED, "unauthorized"); diff --git a/crates/forge-web/src/hook_cmd.rs b/crates/forge-web-app/src/hook_cmd.rs similarity index 99% rename from crates/forge-web/src/hook_cmd.rs rename to crates/forge-web-app/src/hook_cmd.rs index da8dd05..6ca9fd6 100644 --- a/crates/forge-web/src/hook_cmd.rs +++ b/crates/forge-web-app/src/hook_cmd.rs @@ -147,7 +147,7 @@ fn find(haystack: &[u8], needle: &[u8]) -> Option { } /// Parses an HTTP/1.1 response with `Content-Length` or chunked framing. -pub(crate) fn parse_response(raw: &[u8]) -> io::Result<(u16, Vec)> { +pub fn parse_response(raw: &[u8]) -> io::Result<(u16, Vec)> { let split = find(raw, b"\r\n\r\n").ok_or_else(|| invalid("missing end of HTTP headers"))?; let head = std::str::from_utf8(&raw[..split]).map_err(|_| invalid("HTTP headers are not UTF-8"))?; diff --git a/crates/forge-web/src/importer/api.rs b/crates/forge-web-app/src/importer/api.rs similarity index 99% rename from crates/forge-web/src/importer/api.rs rename to crates/forge-web-app/src/importer/api.rs index c9f4093..c780a5c 100644 --- a/crates/forge-web/src/importer/api.rs +++ b/crates/forge-web-app/src/importer/api.rs @@ -584,7 +584,7 @@ fn login(u: Option) -> String { u.and_then(|u| u.login).unwrap_or_default() } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] pub fn parse_github_labels(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(label_of).collect()) @@ -598,12 +598,12 @@ fn label_of(l: GhLabel) -> ExtLabel { } } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] fn from_json(json: &[u8]) -> ApiResult { serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string())) } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] pub fn parse_github_issues(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(gh_issue).collect()) @@ -630,7 +630,7 @@ fn gh_issue(i: GhIssue) -> ExtIssue { } } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] pub fn parse_github_releases(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw @@ -952,13 +952,13 @@ fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue { } } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] 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)] +#[cfg(any(test, feature = "test-support"))] pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult> { let raw: Vec = from_json(json)?; Ok(raw.into_iter().map(gl_release).collect()) diff --git a/crates/forge-web/src/importer/mod.rs b/crates/forge-web-app/src/importer/mod.rs similarity index 99% rename from crates/forge-web/src/importer/mod.rs rename to crates/forge-web-app/src/importer/mod.rs index 9c7adac..a2577f1 100644 --- a/crates/forge-web/src/importer/mod.rs +++ b/crates/forge-web-app/src/importer/mod.rs @@ -159,7 +159,7 @@ impl JobSpec { #[derive(Clone)] pub enum Transport { Net, - #[cfg(test)] + #[cfg(any(test, feature = "test-support"))] Local(String), } @@ -504,7 +504,7 @@ async fn fetch_git( .await .map_err(|e| e.to_string()) } - #[cfg(test)] + #[cfg(any(test, feature = "test-support"))] Transport::Local(path) => { forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT) .await @@ -1106,6 +1106,3 @@ pub async fn on_boot(state: &AppState) { 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-app/src/importer/remote.rs similarity index 100% rename from crates/forge-web/src/importer/remote.rs rename to crates/forge-web-app/src/importer/remote.rs diff --git a/crates/forge-web/src/internal.rs b/crates/forge-web-app/src/internal.rs similarity index 99% rename from crates/forge-web/src/internal.rs rename to crates/forge-web-app/src/internal.rs index dffa2bc..a0843b9 100644 --- a/crates/forge-web/src/internal.rs +++ b/crates/forge-web-app/src/internal.rs @@ -698,7 +698,7 @@ pub async fn evaluate_pre_receive( /// Whether `actor_id` may push straight to a `restrict_push` branch: an instance admin, the owner /// of a person-owned repo, or someone whose effective role is Admin (a collaborator Admin, or an /// org owner or admin team on an org-owned repo). Pull request merges do not go through here. -pub(crate) async fn may_push_directly( +pub async fn may_push_directly( store: &Store, repo: &Repo, actor_id: &str, diff --git a/crates/forge-web/src/layers.rs b/crates/forge-web-app/src/layers.rs similarity index 100% rename from crates/forge-web/src/layers.rs rename to crates/forge-web-app/src/layers.rs diff --git a/crates/forge-web/src/lfs/gc.rs b/crates/forge-web-app/src/lfs/gc.rs similarity index 100% rename from crates/forge-web/src/lfs/gc.rs rename to crates/forge-web-app/src/lfs/gc.rs diff --git a/crates/forge-web/src/lfs/mod.rs b/crates/forge-web-app/src/lfs/mod.rs similarity index 100% rename from crates/forge-web/src/lfs/mod.rs rename to crates/forge-web-app/src/lfs/mod.rs diff --git a/crates/forge-web/src/lfs/route_tests.rs b/crates/forge-web-app/src/lfs/route_tests.rs similarity index 100% rename from crates/forge-web/src/lfs/route_tests.rs rename to crates/forge-web-app/src/lfs/route_tests.rs diff --git a/crates/forge-web/src/lfs/routes.rs b/crates/forge-web-app/src/lfs/routes.rs similarity index 100% rename from crates/forge-web/src/lfs/routes.rs rename to crates/forge-web-app/src/lfs/routes.rs diff --git a/crates/forge-web/src/lfs_pointer.rs b/crates/forge-web-app/src/lfs_pointer.rs similarity index 100% rename from crates/forge-web/src/lfs_pointer.rs rename to crates/forge-web-app/src/lfs_pointer.rs diff --git a/crates/forge-web-app/src/lib.rs b/crates/forge-web-app/src/lib.rs new file mode 100644 index 0000000..f2058bf --- /dev/null +++ b/crates/forge-web-app/src/lib.rs @@ -0,0 +1,62 @@ +//! forge web foundation: everything below the pages. + +#![recursion_limit = "256"] + +pub use forge_web_base::{ + accent, accent_palette, blobs, compression, custom_colour, i18n, render, repo_stats, templates, + theme, throttle, +}; + +pub mod access; +pub mod admin_client; +pub mod advisories; +pub mod alerts; +pub mod api; +pub mod audit; +pub mod auth; +pub mod automerge; +pub mod backup; +pub mod ci; +pub mod client_ip; +pub mod exporter; +pub mod git_auth; +pub mod git_http; +pub mod hook_cmd; +pub mod importer; +pub mod internal; +pub mod layers; +pub mod lfs; +pub mod lfs_pointer; +pub mod live; +pub mod mail; +pub mod merge; +pub mod merge_queue; +pub mod mirrors; +pub mod notify; +pub mod notify_hub; +pub mod oci; +pub mod package_ops; +pub mod packages_live; +pub mod post_update; +pub mod prune; +pub mod pulls_sync; +pub mod raw; +pub mod release_ops; +pub mod replication; +pub mod self_update; +pub mod signatures; +pub mod ssh_backend; +pub mod state; +#[cfg(any(test, feature = "test-support"))] +pub mod test_support; +pub mod views; +pub mod web_push; +pub mod webhooks; + +pub mod build_info { + pub const BUILD_SHA: &str = env!("FORGE_BUILD_SHA"); + pub const GIT_SHA: &str = env!("FORGE_GIT_SHA"); + pub const GIT_DATE: &str = env!("FORGE_GIT_DATE"); + pub const GIT_DIRTY: bool = matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"); + pub const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); +} diff --git a/crates/forge-web/src/live.rs b/crates/forge-web-app/src/live.rs similarity index 99% rename from crates/forge-web/src/live.rs rename to crates/forge-web-app/src/live.rs index 9e39f0d..0fcde9a 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web-app/src/live.rs @@ -382,7 +382,7 @@ pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) { const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30); /// A run's or job's status word and whether it is terminal. `None` when the row is gone. -pub(crate) type Status = Option<(String, bool)>; +pub type Status = Option<(String, bool)>; /// One `changed` event carrying the status word. pub fn changed_event(status: String) -> Result { @@ -513,7 +513,7 @@ impl Drop for StreamSlot { /// How long the browser waits before it reconnects a dropped event stream. The browser's default is /// a few seconds; one second makes a page come back as soon as a server restart is done. -pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1); +pub const STREAM_RETRY: Duration = Duration::from_secs(1); /// The response of an event stream: keep-alive comments while idle, no buffering by a reverse /// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`. diff --git a/crates/forge-web/src/mail/account.rs b/crates/forge-web-app/src/mail/account.rs similarity index 100% rename from crates/forge-web/src/mail/account.rs rename to crates/forge-web-app/src/mail/account.rs diff --git a/crates/forge-web/src/mail/live.rs b/crates/forge-web-app/src/mail/live.rs similarity index 100% rename from crates/forge-web/src/mail/live.rs rename to crates/forge-web-app/src/mail/live.rs diff --git a/crates/forge-web/src/mail/log.rs b/crates/forge-web-app/src/mail/log.rs similarity index 100% rename from crates/forge-web/src/mail/log.rs rename to crates/forge-web-app/src/mail/log.rs diff --git a/crates/forge-web/src/mail/mod.rs b/crates/forge-web-app/src/mail/mod.rs similarity index 96% rename from crates/forge-web/src/mail/mod.rs rename to crates/forge-web-app/src/mail/mod.rs index ceca17e..00c400b 100644 --- a/crates/forge-web/src/mail/mod.rs +++ b/crates/forge-web-app/src/mail/mod.rs @@ -68,14 +68,14 @@ pub async fn enqueue_message( /// A mailer for tests. It records every message it accepts. [`FakeMailer::fail_next`] makes the /// next sends fail, to exercise the retry path. -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] #[derive(Default)] pub struct FakeMailer { sent: std::sync::Mutex>, failures: std::sync::Mutex>, } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] impl FakeMailer { /// Messages accepted so far, oldest first. pub fn sent(&self) -> Vec { @@ -94,7 +94,7 @@ impl FakeMailer { } } -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] impl Mailer for FakeMailer { fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a> { Box::pin(async move { diff --git a/crates/forge-web/src/mail/smtp.rs b/crates/forge-web-app/src/mail/smtp.rs similarity index 100% rename from crates/forge-web/src/mail/smtp.rs rename to crates/forge-web-app/src/mail/smtp.rs diff --git a/crates/forge-web/src/mail/templates.rs b/crates/forge-web-app/src/mail/templates.rs similarity index 100% rename from crates/forge-web/src/mail/templates.rs rename to crates/forge-web-app/src/mail/templates.rs diff --git a/crates/forge-web/src/mail/worker.rs b/crates/forge-web-app/src/mail/worker.rs similarity index 100% rename from crates/forge-web/src/mail/worker.rs rename to crates/forge-web-app/src/mail/worker.rs diff --git a/crates/forge-web/src/merge.rs b/crates/forge-web-app/src/merge.rs similarity index 100% rename from crates/forge-web/src/merge.rs rename to crates/forge-web-app/src/merge.rs diff --git a/crates/forge-web/src/merge_queue.rs b/crates/forge-web-app/src/merge_queue.rs similarity index 100% rename from crates/forge-web/src/merge_queue.rs rename to crates/forge-web-app/src/merge_queue.rs diff --git a/crates/forge-web/src/mirrors/mod.rs b/crates/forge-web-app/src/mirrors/mod.rs similarity index 100% rename from crates/forge-web/src/mirrors/mod.rs rename to crates/forge-web-app/src/mirrors/mod.rs diff --git a/crates/forge-web/src/mirrors/worker.rs b/crates/forge-web-app/src/mirrors/worker.rs similarity index 100% rename from crates/forge-web/src/mirrors/worker.rs rename to crates/forge-web-app/src/mirrors/worker.rs diff --git a/crates/forge-web/src/notify.rs b/crates/forge-web-app/src/notify.rs similarity index 100% rename from crates/forge-web/src/notify.rs rename to crates/forge-web-app/src/notify.rs diff --git a/crates/forge-web/src/notify_hub.rs b/crates/forge-web-app/src/notify_hub.rs similarity index 100% rename from crates/forge-web/src/notify_hub.rs rename to crates/forge-web-app/src/notify_hub.rs diff --git a/crates/forge-web/src/oci/auth.rs b/crates/forge-web-app/src/oci/auth.rs similarity index 100% rename from crates/forge-web/src/oci/auth.rs rename to crates/forge-web-app/src/oci/auth.rs diff --git a/crates/forge-web/src/oci/blobs.rs b/crates/forge-web-app/src/oci/blobs.rs similarity index 100% rename from crates/forge-web/src/oci/blobs.rs rename to crates/forge-web-app/src/oci/blobs.rs diff --git a/crates/forge-web/src/oci/gc.rs b/crates/forge-web-app/src/oci/gc.rs similarity index 100% rename from crates/forge-web/src/oci/gc.rs rename to crates/forge-web-app/src/oci/gc.rs diff --git a/crates/forge-web/src/oci/manifests.rs b/crates/forge-web-app/src/oci/manifests.rs similarity index 100% rename from crates/forge-web/src/oci/manifests.rs rename to crates/forge-web-app/src/oci/manifests.rs diff --git a/crates/forge-web/src/oci/mod.rs b/crates/forge-web-app/src/oci/mod.rs similarity index 100% rename from crates/forge-web/src/oci/mod.rs rename to crates/forge-web-app/src/oci/mod.rs diff --git a/crates/forge-web/src/package_ops.rs b/crates/forge-web-app/src/package_ops.rs similarity index 100% rename from crates/forge-web/src/package_ops.rs rename to crates/forge-web-app/src/package_ops.rs diff --git a/crates/forge-web/src/packages_live.rs b/crates/forge-web-app/src/packages_live.rs similarity index 100% rename from crates/forge-web/src/packages_live.rs rename to crates/forge-web-app/src/packages_live.rs diff --git a/crates/forge-web/src/post_update.rs b/crates/forge-web-app/src/post_update.rs similarity index 100% rename from crates/forge-web/src/post_update.rs rename to crates/forge-web-app/src/post_update.rs diff --git a/crates/forge-web/src/prune.rs b/crates/forge-web-app/src/prune.rs similarity index 100% rename from crates/forge-web/src/prune.rs rename to crates/forge-web-app/src/prune.rs diff --git a/crates/forge-web/src/pulls_sync.rs b/crates/forge-web-app/src/pulls_sync.rs similarity index 100% rename from crates/forge-web/src/pulls_sync.rs rename to crates/forge-web-app/src/pulls_sync.rs diff --git a/crates/forge-web/src/raw/media.rs b/crates/forge-web-app/src/raw/media.rs similarity index 99% rename from crates/forge-web/src/raw/media.rs rename to crates/forge-web-app/src/raw/media.rs index fd8e916..68add2d 100644 --- a/crates/forge-web/src/raw/media.rs +++ b/crates/forge-web-app/src/raw/media.rs @@ -52,7 +52,7 @@ pub fn media_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String url } -pub(crate) fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { +pub fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { Box::pin(async move { Ok(serve(cx).await) }) } diff --git a/crates/forge-web/src/raw/mod.rs b/crates/forge-web-app/src/raw/mod.rs similarity index 97% rename from crates/forge-web/src/raw/mod.rs rename to crates/forge-web-app/src/raw/mod.rs index 6d54d02..be4fa3f 100644 --- a/crates/forge-web/src/raw/mod.rs +++ b/crates/forge-web-app/src/raw/mod.rs @@ -36,17 +36,17 @@ const MAX_INLINE_BYTES: u64 = 8 * 1024 * 1024; /// Bytes inspected to decide text versus binary. const SNIFF_BYTES: usize = 8000; /// Lifetime of a signed private raw URL. -pub(crate) const LINK_TTL_SECS: i64 = 600; +pub const LINK_TTL_SECS: i64 = 600; const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox"; const CORP: &str = "cross-origin"; /// Raw responses revalidate on every use (an unchanged blob answers 304 through If-None-Match), /// so a repo made private, or a reader who lost access, stops being served at once. -pub(crate) const CACHE_PRIVATE: &str = "private, no-cache"; -pub(crate) const CACHE_PUBLIC: &str = "public, no-cache"; -pub(crate) const CACHE_NONE: &str = "no-store"; +pub const CACHE_PRIVATE: &str = "private, no-cache"; +pub const CACHE_PUBLIC: &str = "public, no-cache"; +pub const CACHE_NONE: &str = "no-store"; const TEXT: &str = "text/plain; charset=utf-8"; -pub(crate) const OCTET: &str = "application/octet-stream"; +pub const OCTET: &str = "application/octet-stream"; /// Absolute URL of a file on the raw origin. For private repos it carries a signed `?token=` /// valid for 10 minutes. `rev` is the ref name or commit oid as shown in the app URL. @@ -71,7 +71,7 @@ pub fn raw_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String { } /// Percent-encodes each `/`-separated segment and keeps the separators. -pub(crate) fn encode_path(value: &str) -> String { +pub fn encode_path(value: &str) -> String { value .split('/') .map(encode_segment) @@ -279,7 +279,7 @@ async fn serve(cx: &Cx) -> Response { } /// Result of the blocking lookup. -pub(crate) enum Lookup { +pub enum Lookup { Missing, NotModified { oid: String, @@ -296,7 +296,7 @@ pub(crate) enum Lookup { } /// Resolves `rest` (`/`) to an entry. Trees, submodules and missing paths are `Missing`. -pub(crate) fn lookup( +pub fn lookup( repo_dir: &Path, rest: &str, if_none_match: Option<&str>, @@ -405,14 +405,14 @@ fn etag_matches(header_value: &str, etag: &str) -> bool { }) } -pub(crate) struct Meta { - pub(crate) content_type: &'static str, - pub(crate) attachment: bool, - pub(crate) len: u64, +pub struct Meta { + pub content_type: &'static str, + pub attachment: bool, + pub len: u64, } /// Builds a response with the security and caching headers that every raw response carries. -pub(crate) fn finish( +pub fn finish( status: StatusCode, body: Body, oid: &str, @@ -459,11 +459,7 @@ pub(crate) fn finish( } /// Error or empty response with no ETag and a text body. -pub(crate) fn plain( - status: StatusCode, - cache: &'static str, - body: Option<&'static str>, -) -> Response { +pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>) -> Response { let text = body.unwrap_or(match status { StatusCode::NOT_FOUND => "not found", _ => "internal error", @@ -475,7 +471,7 @@ pub(crate) fn plain( res } -pub(crate) fn now_unix() -> i64 { +pub fn now_unix() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .ok() diff --git a/crates/forge-web/src/raw/snippet_raw.rs b/crates/forge-web-app/src/raw/snippet_raw.rs similarity index 98% rename from crates/forge-web/src/raw/snippet_raw.rs rename to crates/forge-web-app/src/raw/snippet_raw.rs index 6cbee73..b448130 100644 --- a/crates/forge-web/src/raw/snippet_raw.rs +++ b/crates/forge-web-app/src/raw/snippet_raw.rs @@ -47,7 +47,7 @@ pub fn snippet_raw_url(state: &AppState, snippet: &Snippet, file: &str) -> Strin url } -pub(crate) fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { +pub fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> { Box::pin(async move { Ok(serve(cx).await) }) } diff --git a/crates/forge-web/src/release_ops.rs b/crates/forge-web-app/src/release_ops.rs similarity index 100% rename from crates/forge-web/src/release_ops.rs rename to crates/forge-web-app/src/release_ops.rs diff --git a/crates/forge-web/src/replication/mod.rs b/crates/forge-web-app/src/replication/mod.rs similarity index 99% rename from crates/forge-web/src/replication/mod.rs rename to crates/forge-web-app/src/replication/mod.rs index 35c907d..9d7f372 100644 --- a/crates/forge-web/src/replication/mod.rs +++ b/crates/forge-web-app/src/replication/mod.rs @@ -444,11 +444,11 @@ impl StandbyTransport for SshTransport { /// Runs the same shell commands as [`SshTransport`], but with `sh -c` on this machine. The remote /// base is then a local directory. Test only. -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] #[derive(Debug, Clone, Copy, Default)] pub struct LocalTransport; -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] impl StandbyTransport for LocalTransport { fn run(&self, remote_cmd: &str) -> impl Future, String>> + Send { let mut cmd = Command::new("sh"); diff --git a/crates/forge-web/src/replication/worker.rs b/crates/forge-web-app/src/replication/worker.rs similarity index 99% rename from crates/forge-web/src/replication/worker.rs rename to crates/forge-web-app/src/replication/worker.rs index 9d33ca3..a989589 100644 --- a/crates/forge-web/src/replication/worker.rs +++ b/crates/forge-web-app/src/replication/worker.rs @@ -147,7 +147,7 @@ async fn ping(url: &str, report: &ReconcileReport) { /// Records an outcome for `subject` and passes the error on. `refs` is the checksum to store on /// success (repos only). -pub(crate) async fn record( +pub async fn record( store: &Store, subject: &str, result: Result, String>, diff --git a/crates/forge-web/src/self_update.rs b/crates/forge-web-app/src/self_update.rs similarity index 100% rename from crates/forge-web/src/self_update.rs rename to crates/forge-web-app/src/self_update.rs diff --git a/crates/forge-web/src/signatures.rs b/crates/forge-web-app/src/signatures.rs similarity index 100% rename from crates/forge-web/src/signatures.rs rename to crates/forge-web-app/src/signatures.rs diff --git a/crates/forge-web/src/ssh_backend.rs b/crates/forge-web-app/src/ssh_backend.rs similarity index 100% rename from crates/forge-web/src/ssh_backend.rs rename to crates/forge-web-app/src/ssh_backend.rs diff --git a/crates/forge-web/src/state.rs b/crates/forge-web-app/src/state.rs similarity index 97% rename from crates/forge-web/src/state.rs rename to crates/forge-web-app/src/state.rs index 9a6ad2b..49ecded 100644 --- a/crates/forge-web/src/state.rs +++ b/crates/forge-web-app/src/state.rs @@ -62,7 +62,7 @@ pub struct AppState { } /// A settings handle over `config` with no stored overrides and no file keys. For tests. -#[cfg(test)] +#[cfg(any(test, feature = "test-support"))] pub fn settings_for(config: &Arc) -> Arc { Arc::new(forge_core::server_settings::Live::new( config.clone(), @@ -79,7 +79,7 @@ impl AppState { } /// Replaces the config and resets the settings layer over it. For tests. - #[cfg(test)] + #[cfg(any(test, feature = "test-support"))] pub fn set_config(&mut self, config: Config) { self.config = Arc::new(config); self.settings = settings_for(&self.config); diff --git a/crates/forge-web-app/src/test_support/fixture.rs b/crates/forge-web-app/src/test_support/fixture.rs new file mode 100644 index 0000000..77af87b --- /dev/null +++ b/crates/forge-web-app/src/test_support/fixture.rs @@ -0,0 +1,170 @@ +//! Shared test fixture: a store with one owner, a bare repo built through the git CLI, and a +//! router with the app context. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use forge_core::{Store, Visibility}; + +use topcoat::router::request::Request; +use topcoat::router::{Body, Router, to_bytes}; + +pub const OWNER: &str = "tahinli"; +pub const REPO: &str = "demo"; + +pub struct Fixture { + pub router: Router, + pub store: Store, + /// The live hub the router's pages share, to bump topics from a test. + pub live: std::sync::Arc, + /// Root commit: adds `a.txt` and `dir/b.txt`. + pub root: String, + /// Adds `new.txt` and changes `a.txt`. + pub modified: String, + /// Working checkout and bare repo the fixture pushed to. + pub work: PathBuf, + pub bare: PathBuf, + _dir: tempfile::TempDir, +} + +pub fn git(dir: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .args([ + "-c", + "user.name=Tester", + "-c", + "user.email=tester@example.com", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .current_dir(dir) + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_owned() +} + +impl Fixture { + pub async fn new(visibility: Visibility) -> Self { + let tmp = tempfile::tempdir().expect("tempdir"); + let dir = tmp.path().to_path_buf(); + let state = crate::test_support::test_state(&dir).await; + let store = state.store.clone(); + let live = state.live.clone(); + let router = crate::test_support::app_router(state); + + let owner = store + .create_user(OWNER, None, "not-a-real-hash", false) + .await + .unwrap(); + let repo = store + .create_repo(&owner.id, REPO, "", visibility, "main") + .await + .unwrap(); + let bare = repo_dir(&dir, &repo.id); + std::fs::create_dir_all(bare.parent().unwrap()).unwrap(); + git( + &dir, + &[ + "init", + "-q", + "--bare", + "-b", + "main", + &bare.to_string_lossy(), + ], + ); + + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + git(&work, &["init", "-q", "-b", "main"]); + std::fs::write(work.join("a.txt"), "one\ntwo\nthree\n").unwrap(); + std::fs::create_dir_all(work.join("dir")).unwrap(); + std::fs::write(work.join("dir/b.txt"), "b\n").unwrap(); + git(&work, &["add", "-A"]); + git(&work, &["commit", "-q", "-m", "root commit"]); + let root = git(&work, &["rev-parse", "HEAD"]); + + std::fs::write(work.join("a.txt"), "one\nTWO\nthree\nfour\n").unwrap(); + std::fs::write(work.join("new.txt"), "new file\n").unwrap(); + git(&work, &["add", "-A"]); + git( + &work, + &[ + "commit", + "-q", + "-m", + "Modify a.txt and add new.txt", + "-m", + "Body line one.\n\nSecond paragraph.", + ], + ); + let modified = git(&work, &["rev-parse", "HEAD"]); + + // 53 empty commits on top: 55 in all, so history spans two pages. + for n in 1..=53 { + git( + &work, + &[ + "commit", + "-q", + "--allow-empty", + "-m", + &format!("filler {n}"), + ], + ); + } + git( + &work, + &[ + "push", + "-q", + &bare.to_string_lossy(), + "HEAD:refs/heads/main", + ], + ); + + Self { + router, + store, + live, + root, + modified, + work, + bare, + _dir: tmp, + } + } +} + +/// Same layout as `forge_git::repo::repo_path`, computed here so the test can create it. +fn repo_dir(data_dir: &Path, repo_id: &str) -> PathBuf { + let id = repo_id.to_ascii_lowercase(); + data_dir + .join("repos") + .join(&id[0..2]) + .join(&id[2..4]) + .join(format!("{id}.git")) +} + +/// GET through the router: `(status, headers, body)`. +pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec) { + let req = Request::builder() + .method("GET") + .uri(uri) + .body(Body::empty()) + .unwrap(); + let res = router.handle(req).await; + let status = res.status().as_u16(); + let headers = res.headers().clone(); + let body = to_bytes(res.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + (status, headers, body) +} diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web-app/src/test_support/mod.rs similarity index 91% rename from crates/forge-web/src/test_support.rs rename to crates/forge-web-app/src/test_support/mod.rs index cbe6583..2585a86 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web-app/src/test_support/mod.rs @@ -3,6 +3,8 @@ //! Every test that needs a `Config`, an `AppState` or a router builds them here, so a new config //! or state field is added in one place. +pub mod fixture; + use std::path::Path; use std::sync::Arc; use std::time::Duration; @@ -17,6 +19,7 @@ use topcoat::cookie::CookieLayer; use topcoat::router::tower::TowerLayer; use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt}; +#[cfg(not(test))] use crate::layers::RepoMovedLayer; use crate::state::AppState; use crate::throttle::Throttle; @@ -100,18 +103,21 @@ pub async fn test_state(dir: &Path) -> AppState { } } -/// The public router as boot.rs builds it, minus the listeners. +/// The public router as boot.rs builds it, minus the listeners. This crate's own tests have no +/// pages, so the layers scoped to page paths are left out there. pub fn app_router(state: AppState) -> Router { - Router::builder() - .discover() - .with(state) - .layer(crate::layers::AccountWriteLayer) - .layer(CookieLayer::new()) + let builder = Router::builder().discover().with(state); + #[cfg(not(test))] + let builder = builder.layer(crate::layers::AccountWriteLayer); + let builder = builder.layer(CookieLayer::new()); + #[cfg(not(test))] + let builder = builder .layer(RepoMovedLayer) .layer(crate::layers::RepoSettingsWriteLayer) .layer(crate::layers::PullWriteLayer) .layer(crate::layers::DiscussionWriteLayer) - .layer(crate::layers::OrgWriteLayer) + .layer(crate::layers::OrgWriteLayer); + builder .layer(TowerLayer::new(crate::compression::ResponseCompression)) .with(Compression::disable()) .build() diff --git a/crates/forge-web/src/views/commit_line.rs b/crates/forge-web-app/src/views/commit_line.rs similarity index 100% rename from crates/forge-web/src/views/commit_line.rs rename to crates/forge-web-app/src/views/commit_line.rs diff --git a/crates/forge-web/src/views/commit_status.rs b/crates/forge-web-app/src/views/commit_status.rs similarity index 100% rename from crates/forge-web/src/views/commit_status.rs rename to crates/forge-web-app/src/views/commit_status.rs diff --git a/crates/forge-web/src/views/diff.rs b/crates/forge-web-app/src/views/diff.rs similarity index 100% rename from crates/forge-web/src/views/diff.rs rename to crates/forge-web-app/src/views/diff.rs diff --git a/crates/forge-web/src/views/find.rs b/crates/forge-web-app/src/views/find.rs similarity index 100% rename from crates/forge-web/src/views/find.rs rename to crates/forge-web-app/src/views/find.rs diff --git a/crates/forge-web/src/views/heatmap.rs b/crates/forge-web-app/src/views/heatmap.rs similarity index 100% rename from crates/forge-web/src/views/heatmap.rs rename to crates/forge-web-app/src/views/heatmap.rs diff --git a/crates/forge-web/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs similarity index 90% rename from crates/forge-web/src/views/mod.rs rename to crates/forge-web-app/src/views/mod.rs index 443a942..49eec29 100644 --- a/crates/forge-web/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -1648,13 +1648,13 @@ pub async fn ref_selector( /// A stored timestamp shown as an absolute `title` and a relative label. #[derive(Clone)] pub struct When { - pub(crate) iso: String, - pub(crate) absolute: String, - pub(crate) relative: String, + pub iso: String, + pub absolute: String, + pub relative: String, } impl When { - pub(crate) fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self { + pub fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self { let unix = stamp_unix(stamp); Self { iso: iso_time(unix), @@ -2056,220 +2056,4 @@ mod tests { "Private" ); } - - /// Renders `/settings/security` (a page that uses the shell) for a freshly signed-in user. - async fn menu_html( - router: &topcoat::router::Router, - store: &forge_core::Store, - name: &str, - is_admin: bool, - token: &str, - ) -> String { - use crate::auth::SESSION_COOKIE; - use topcoat::router::request::Request; - use topcoat::router::to_bytes; - - let user = store - .create_user(name, None, "x", is_admin) - .await - .expect("user"); - crate::test_support::create_session(store, &user.id, token, "menu-csrf").await; - let req = Request::builder() - .method("GET") - .uri("/settings/security") - .header("cookie", format!("__Host-{SESSION_COOKIE}={token}")) - .body(Body::empty()) - .expect("request"); - let res = router.handle(req).await; - assert_eq!(res.status().as_u16(), 200); - let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); - String::from_utf8_lossy(&bytes).into_owned() - } - - /// A user sees no admin links and an admin sees the one Admin entry. Both render from one - /// fixture. - #[tokio::test] - async fn admin_links_follow_the_role() { - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let store = state.store.clone(); - let router = crate::test_support::app_router(state); - - let html = menu_html(&router, &store, "tahinli", false, "menu-token-user").await; - assert!(html.contains("Log out"), "user menu is rendered"); - assert!(!html.contains("/admin/users"), "no admin link for a user"); - assert!(!html.contains("/admin/audit"), "no audit link for a user"); - - let html = menu_html(&router, &store, "root", true, "menu-token-admin").await; - assert!(html.contains("href=\"/admin/users\"")); - assert!( - !html.contains("Admin:"), - "one Admin entry, no per-page items" - ); - } -} - -#[cfg(test)] -mod shell_tests { - use topcoat::router::request::Request; - use topcoat::router::{Body, to_bytes}; - - use super::NAV_SCRIPT_HREF; - - /// Every `').expect("script tag closes"); - assert!( - tag[..end].contains(" src="), - "inline script: {}", - &tag[..=end] - ); - } - } - - #[tokio::test] - async fn shell_loads_the_deferred_nav_script_without_inline_scripts() { - let dir = tempfile::tempdir().expect("tempdir"); - let state = crate::test_support::test_state(dir.path()).await; - let router = crate::test_support::app_router(state); - let req = Request::builder() - .method("GET") - .uri("/login") - .body(Body::empty()) - .unwrap(); - let res = router.handle(req).await; - assert_eq!(res.status(), 200); - let csp = res.headers()["content-security-policy"] - .to_str() - .unwrap() - .to_owned(); - assert!(csp.contains("default-src 'self'"), "{csp}"); - assert!(!csp.contains("unsafe-inline"), "{csp}"); - let html = String::from_utf8( - to_bytes(res.into_body(), usize::MAX) - .await - .unwrap() - .to_vec(), - ) - .unwrap(); - - let tag_at = html - .find(&format!("