forge
Explore
Log in

Don't you dare go Hollow

Everything below the pages moves from the forge binary into a new forge-web-app crate (state, auth, live, views, CI, mail, backup, replication and the HTTP APIs), so the binary compiles only the pages on top

Browse files at this commit

42a2afe2233a91f7ad6403064c21c88c66c9078eAhmet Kaan GümüşParent: 0e73725
  • refactor
    • everything below the pages moves from the forge binary into a new forge-web-app crate (state, auth, live, views, CI, mail, backup, replication and the HTTP APIs), so the binary compiles only the pages on top
    • route tests that need pages move with the binary
Show full message
♻️ refactor: everything below the pages moves from the forge binary into a new forge-web-app crate (state, auth, live, views, CI, mail, backup, replication and the HTTP APIs), so the binary compiles only the pages on top; route tests that need pages move with the binary

130 changed files +683 -543

Cargo.lockmodified+52 -1
@@ -2115,10 +2115,10 @@ dependencies = [
2115 "forge-git",2115 "forge-git",
2116 "forge-runner",2116 "forge-runner",
2117 "forge-ssh",2117 "forge-ssh",
2118+ "forge-web-app",
2118 "forge-web-base",2119 "forge-web-base",
2119 "form_urlencoded",2120 "form_urlencoded",
2120 "futures-util",2121 "futures-util",
2121- "grass",
2122 "hex",2122 "hex",
2123 "hkdf 0.13.0",2123 "hkdf 0.13.0",
2124 "hmac 0.13.0",2124 "hmac 0.13.0",
@@ -2156,6 +2156,57 @@ dependencies = [
2156 "zip",2156 "zip",
2157 ]2157 ]
2158 2158
2159+[[package]]
2160+name = "forge-web-app"
2161+version = "0.1.0"
2162+dependencies = [
2163+ "aes-gcm 0.11.1",
2164+ "async-compression",
2165+ "base64 0.23.1",
2166+ "bytes",
2167+ "flate2",
2168+ "forge-ci",
2169+ "forge-core",
2170+ "forge-git",
2171+ "forge-ssh",
2172+ "forge-web-base",
2173+ "form_urlencoded",
2174+ "futures-util",
2175+ "grass",
2176+ "hex",
2177+ "hkdf 0.13.0",
2178+ "hmac 0.13.0",
2179+ "http",
2180+ "http-body",
2181+ "http-body-util",
2182+ "image",
2183+ "ipnet",
2184+ "jiff 1.0.3",
2185+ "lettre",
2186+ "multer",
2187+ "nix 0.31.4",
2188+ "p256",
2189+ "rand 0.10.4",
2190+ "reqwest",
2191+ "scraper",
2192+ "serde",
2193+ "serde_json",
2194+ "sha2 0.11.1",
2195+ "similar",
2196+ "subtle",
2197+ "tar",
2198+ "tempfile",
2199+ "time",
2200+ "tokio",
2201+ "tokio-util",
2202+ "topcoat",
2203+ "tracing",
2204+ "tracing-subscriber",
2205+ "ulid",
2206+ "webauthn-authenticator-rs",
2207+ "zip",
2208+]
2209+
2159 [[package]]2210 [[package]]
2160 name = "forge-web-base"2211 name = "forge-web-base"
2161 version = "0.1.0"2212 version = "0.1.0"
Cargo.tomlmodified+2 -0
@@ -6,6 +6,7 @@ members = [
6 "crates/forge-ssh",6 "crates/forge-ssh",
7 "crates/forge-web",7 "crates/forge-web",
8 "crates/forge-web-base",8 "crates/forge-web-base",
9+ "crates/forge-web-app",
9 "crates/forge-ci",10 "crates/forge-ci",
10 "crates/forge-runner",11 "crates/forge-runner",
11 "crates/forge-e2e",12 "crates/forge-e2e",
@@ -34,6 +35,7 @@ forge-git = { path = "crates/forge-git" }
34 forge-ssh = { path = "crates/forge-ssh" }35 forge-ssh = { path = "crates/forge-ssh" }
35 forge-runner = { path = "crates/forge-runner" }36 forge-runner = { path = "crates/forge-runner" }
36 forge-web-base = { path = "crates/forge-web-base" }37 forge-web-base = { path = "crates/forge-web-base" }
38+forge-web-app = { path = "crates/forge-web-app" }
37 39
38 # async runtime and HTTP plumbing40 # async runtime and HTTP plumbing
39 tokio = { version = "1.54.1", features = ["full"] }41 tokio = { version = "1.54.1", features = ["full"] }
crates/forge-web-app/Cargo.tomladded+68 -0
@@ -0,0 +1,68 @@
1+[package]
2+name = "forge-web-app"
3+description = "forge web foundation below the pages: app state, auth, live updates, views, CI, mail, backup and the HTTP APIs"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[features]
10+test-support = ["dep:tempfile"]
11+
12+[dependencies]
13+forge-core.workspace = true
14+ipnet.workspace = true
15+forge-git.workspace = true
16+forge-ssh.workspace = true
17+forge-ci.workspace = true
18+forge-web-base.workspace = true
19+topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
20+tokio.workspace = true
21+futures-util.workspace = true
22+bytes.workspace = true
23+http.workspace = true
24+http-body-util.workspace = true
25+async-compression.workspace = true
26+serde.workspace = true
27+serde_json.workspace = true
28+form_urlencoded.workspace = true
29+jiff.workspace = true
30+base64.workspace = true
31+subtle.workspace = true
32+tracing.workspace = true
33+tracing-subscriber = { workspace = true, features = ["env-filter"] }
34+tokio-util = { workspace = true, features = ["io"] }
35+http-body.workspace = true
36+rand.workspace = true
37+hex.workspace = true
38+nix = { workspace = true }
39+sha2.workspace = true
40+time.workspace = true
41+reqwest = { workspace = true }
42+hmac.workspace = true
43+similar = { workspace = true }
44+multer.workspace = true
45+ulid.workspace = true
46+lettre.workspace = true
47+zip = { workspace = true }
48+tar.workspace = true
49+flate2.workspace = true
50+p256.workspace = true
51+hkdf.workspace = true
52+aes-gcm.workspace = true
53+
54+tempfile = { workspace = true, optional = true }
55+
56+[build-dependencies]
57+grass.workspace = true
58+hex.workspace = true
59+sha2.workspace = true
60+
61+[dev-dependencies]
62+tempfile.workspace = true
63+image = { workspace = true }
64+scraper = { workspace = true }
65+webauthn-authenticator-rs = { version = "0.6.2", features = ["softpasskey"] }
66+
67+[lints]
68+workspace = true
crates/forge-web/build.rs → crates/forge-web-app/build.rsrenamed+3 -2
@@ -198,7 +198,7 @@ fn main() {
198 println!("cargo:rerun-if-changed=../forge-ci/build_identity.rs");198 println!("cargo:rerun-if-changed=../forge-ci/build_identity.rs");
199 emit_identity();199 emit_identity();
200 println!("cargo:rerun-if-changed=../../style");200 println!("cargo:rerun-if-changed=../../style");
201- println!("cargo:rerun-if-changed=assets/nav.js");201+ println!("cargo:rerun-if-changed=../forge-web/assets/nav.js");
202 println!("cargo:rerun-if-changed=../forge-web-base/src/accent_palette.rs");202 println!("cargo:rerun-if-changed=../forge-web-base/src/accent_palette.rs");
203 203
204 let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string());204 let sha = env::var("FORGE_BUILD_SHA").unwrap_or_else(|_| "dev".to_string());
@@ -220,6 +220,7 @@ fn main() {
220 );220 );
221 fs::write(out.join("main.css"), css).expect("writing compiled stylesheet to OUT_DIR");221 fs::write(out.join("main.css"), css).expect("writing compiled stylesheet to OUT_DIR");
222 222
223- let nav = fs::read(manifest.join("assets/nav.js")).expect("reading assets/nav.js");223+ let nav = fs::read(manifest.join("../forge-web/assets/nav.js"))
224+ .expect("reading forge-web/assets/nav.js");
224 println!("cargo:rustc-env=FORGE_NAV_JS_V={}", content_version(&nav));225 println!("cargo:rustc-env=FORGE_NAV_JS_V={}", content_version(&nav));
225 }226 }
crates/forge-web/src/access.rs → crates/forge-web-app/src/access.rsrenamed+0 -0
crates/forge-web/src/admin_client.rs → crates/forge-web-app/src/admin_client.rsrenamed+0 -0
crates/forge-web/src/advisories/mod.rs → crates/forge-web-app/src/advisories/mod.rsrenamed+0 -0
crates/forge-web/src/advisories/scan.rs → crates/forge-web-app/src/advisories/scan.rsrenamed+0 -0
crates/forge-web/src/advisories/worker.rs → crates/forge-web-app/src/advisories/worker.rsrenamed+0 -0
crates/forge-web/src/alerts.rs → crates/forge-web-app/src/alerts.rsrenamed+0 -0
crates/forge-web/src/api/gitea.rs → crates/forge-web-app/src/api/gitea.rsrenamed+0 -0
crates/forge-web/src/api/mod.rs → crates/forge-web-app/src/api/mod.rsrenamed+2 -4
@@ -6,8 +6,6 @@
6 //! use a repo, the same as git, so missing and hidden repos look identical to them.6 //! use a repo, the same as git, so missing and hidden repos look identical to them.
7 7
8 pub mod gitea;8 pub mod gitea;
9-#[cfg(test)]
10-mod gitea_tests;
11 pub mod packages;9 pub mod packages;
12 pub mod releases;10 pub mod releases;
13 pub mod statuses;11 pub mod statuses;
@@ -71,7 +69,7 @@ pub fn internal(message: impl std::fmt::Display) -> Refusal {
71 /// Pulls the token out of `Bearer <token>`, `token <token>` or `Basic base64(user:<token>)`. The69 /// Pulls the token out of `Bearer <token>`, `token <token>` or `Basic base64(user:<token>)`. The
72 /// scheme is matched case-insensitively. A Basic user name is ignored, since the token alone70 /// scheme is matched case-insensitively. A Basic user name is ignored, since the token alone
73 /// names the user. Returns `None` for a missing header and `Some(None)` for any other shape.71 /// names the user. Returns `None` for a missing header and `Some(None)` for any other shape.
74-pub(crate) fn presented_token(headers: &HeaderMap) -> Option<Option<String>> {72+pub fn presented_token(headers: &HeaderMap) -> Option<Option<String>> {
75 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;73 let value = headers.get(AUTHORIZATION)?.to_str().ok()?;
76 let Some((scheme, rest)) = value.split_once(' ') else {74 let Some((scheme, rest)) = value.split_once(' ') else {
77 return Some(None);75 return Some(None);
@@ -120,7 +118,7 @@ pub async fn authenticate(
120 118
121 /// The user a token names, with the token's id and scopes. `None` when the request carries no119 /// The user a token names, with the token's id and scopes. `None` when the request carries no
122 /// Authorization header. The scope is not checked and the token is not touched: the caller does both.120 /// Authorization header. The scope is not checked and the token is not touched: the caller does both.
123-pub(crate) async fn authenticate_token(121+pub async fn authenticate_token(
124 state: &AppState,122 state: &AppState,
125 ip: IpAddr,123 ip: IpAddr,
126 headers: &HeaderMap,124 headers: &HeaderMap,
crates/forge-web/src/api/packages.rs → crates/forge-web-app/src/api/packages.rsrenamed+0 -0
crates/forge-web/src/api/releases.rs → crates/forge-web-app/src/api/releases.rsrenamed+0 -0
crates/forge-web/src/api/statuses.rs → crates/forge-web-app/src/api/statuses.rsrenamed+1 -1
@@ -178,7 +178,7 @@ mod tests {
178 use topcoat::router::{Body, Router, to_bytes};178 use topcoat::router::{Body, Router, to_bytes};
179 179
180 use crate::auth::SESSION_COOKIE;180 use crate::auth::SESSION_COOKIE;
181- use crate::pages::commits::test_support::{Fixture, OWNER, REPO};181+ use crate::test_support::fixture::{Fixture, OWNER, REPO};
182 182
183 /// Sends one request through the router: `(status, json body)`.183 /// Sends one request through the router: `(status, json body)`.
184 async fn send(184 async fn send(
crates/forge-web/src/audit.rs → crates/forge-web-app/src/audit.rsrenamed+0 -0
crates/forge-web/src/auth.rs → crates/forge-web-app/src/auth.rsrenamed+0 -0
crates/forge-web/src/automerge.rs → crates/forge-web-app/src/automerge.rsrenamed+0 -0
crates/forge-web/src/backup/create.rs → crates/forge-web-app/src/backup/create.rsrenamed+0 -0
crates/forge-web/src/backup/fsck.rs → crates/forge-web-app/src/backup/fsck.rsrenamed+0 -0
crates/forge-web/src/backup/healthcheck.rs → crates/forge-web-app/src/backup/healthcheck.rsrenamed+0 -0
crates/forge-web/src/backup/mod.rs → crates/forge-web-app/src/backup/mod.rsrenamed+1 -1
@@ -7,7 +7,7 @@
7 7
8 mod create;8 mod create;
9 mod fsck;9 mod fsck;
10-pub(crate) mod healthcheck;10+pub mod healthcheck;
11 mod restore;11 mod restore;
12 mod retention;12 mod retention;
13 pub mod scheduler;13 pub mod scheduler;
crates/forge-web/src/backup/restore.rs → crates/forge-web-app/src/backup/restore.rsrenamed+0 -0
crates/forge-web/src/backup/retention.rs → crates/forge-web-app/src/backup/retention.rsrenamed+0 -0
crates/forge-web/src/backup/scheduler.rs → crates/forge-web-app/src/backup/scheduler.rsrenamed+0 -0
crates/forge-web/src/backup/tests.rs → crates/forge-web-app/src/backup/tests.rsrenamed+0 -0
crates/forge-web/src/backup/verify.rs → crates/forge-web-app/src/backup/verify.rsrenamed+0 -0
crates/forge-web/src/ci/api.rs → crates/forge-web-app/src/ci/api.rsrenamed+0 -0
crates/forge-web/src/ci/api_tests.rs → crates/forge-web-app/src/ci/api_tests.rsrenamed+1 -1
@@ -11,7 +11,7 @@ use topcoat::router::request::Request;
11 use topcoat::router::{Body, Router, to_bytes};11 use topcoat::router::{Body, Router, to_bytes};
12 12
13 use super::{artifact_key, cache_scope, fit_to_cap, log_path, valid_artifact_name};13 use super::{artifact_key, cache_scope, fit_to_cap, log_path, valid_artifact_name};
14-use crate::pages::commits::test_support::{Fixture, OWNER, REPO};14+use crate::test_support::fixture::{Fixture, OWNER, REPO};
15 use crate::test_support::{app_router, test_state};15 use crate::test_support::{app_router, test_state};
16 16
17 /// A response: status, headers and raw body.17 /// A response: status, headers and raw body.
crates/forge-web/src/ci/live.rs → crates/forge-web-app/src/ci/live.rsrenamed+3 -3
@@ -138,7 +138,7 @@ impl CiLive {
138 138
139 /// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due.139 /// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due.
140 #[derive(Default)]140 #[derive(Default)]
141-pub(crate) struct Signals {141+pub struct Signals {
142 counters: Mutex<HashMap<String, watch::Sender<u64>>>,142 counters: Mutex<HashMap<String, watch::Sender<u64>>>,
143 }143 }
144 144
@@ -147,7 +147,7 @@ impl Signals {
147 self.counters.lock().unwrap_or_else(PoisonError::into_inner)147 self.counters.lock().unwrap_or_else(PoisonError::into_inner)
148 }148 }
149 149
150- pub(crate) fn subscribe(&self, key: &str) -> watch::Receiver<u64> {150+ pub fn subscribe(&self, key: &str) -> watch::Receiver<u64> {
151 self.counters()151 self.counters()
152 .entry(key.to_owned())152 .entry(key.to_owned())
153 .or_insert_with(|| watch::channel(0).0)153 .or_insert_with(|| watch::channel(0).0)
@@ -156,7 +156,7 @@ impl Signals {
156 156
157 /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry157 /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry
158 /// whose last receiver is gone is removed here.158 /// whose last receiver is gone is removed here.
159- pub(crate) fn bump(&self, key: &str) {159+ pub fn bump(&self, key: &str) {
160 let mut counters = self.counters();160 let mut counters = self.counters();
161 let Some(tx) = counters.get(key) else {161 let Some(tx) = counters.get(key) else {
162 return;162 return;
crates/forge-web/src/ci/metrics_chart.rs → crates/forge-web-app/src/ci/metrics_chart.rsrenamed+0 -0
crates/forge-web/src/ci/mod.rs → crates/forge-web-app/src/ci/mod.rsrenamed+1 -1
@@ -84,7 +84,7 @@ pub async fn sync_run_statuses(state: &AppState, run: &CiRun) -> forge_core::Res
84 84
85 /// Writes one commit status for `run`. The creator is the run's actor, or the repo owner for a85 /// Writes one commit status for `run`. The creator is the run's actor, or the repo owner for a
86 /// system run (the status table references users).86 /// system run (the status table references users).
87-pub(crate) async fn publish(87+pub async fn publish(
88 state: &AppState,88 state: &AppState,
89 repo: &Repo,89 repo: &Repo,
90 run: &CiRun,90 run: &CiRun,
crates/forge-web/src/ci/reaper.rs → crates/forge-web-app/src/ci/reaper.rsrenamed+0 -0
crates/forge-web/src/ci/release.rs → crates/forge-web-app/src/ci/release.rsrenamed+0 -0
crates/forge-web/src/ci/runner_log.rs → crates/forge-web-app/src/ci/runner_log.rsrenamed+0 -0
crates/forge-web/src/ci/runner_metrics.rs → crates/forge-web-app/src/ci/runner_metrics.rsrenamed+0 -0
crates/forge-web/src/ci/schedule.rs → crates/forge-web-app/src/ci/schedule.rsrenamed+0 -0
crates/forge-web/src/ci/scheduled.rs → crates/forge-web-app/src/ci/scheduled.rsrenamed+0 -0
crates/forge-web/src/client_ip.rs → crates/forge-web-app/src/client_ip.rsrenamed+1 -1
@@ -38,7 +38,7 @@ pub fn client_addr(cx: &Cx) -> IpAddr {
38 38
39 /// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty.39 /// Pure form of [`client_ip`]: `forwarded` is the combined `X-Forwarded-For` value, or empty.
40 /// Only the tests use the bucketed form; the server takes [`client_ip`], which buckets itself.40 /// Only the tests use the bucketed form; the server takes [`client_ip`], which buckets itself.
41-#[cfg(test)]41+#[cfg(any(test, feature = "test-support"))]
42 pub fn resolve(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {42 pub fn resolve(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
43 bucket(resolve_addr(peer, forwarded, trusted))43 bucket(resolve_addr(peer, forwarded, trusted))
44 }44 }
crates/forge-web/src/exporter.rs → crates/forge-web-app/src/exporter.rsrenamed+0 -0
crates/forge-web/src/exporter/tests.rs → crates/forge-web-app/src/exporter/tests.rsrenamed+0 -0
crates/forge-web/src/git_auth.rs → crates/forge-web-app/src/git_auth.rsrenamed+0 -0
crates/forge-web/src/git_http.rs → crates/forge-web-app/src/git_http.rsrenamed+4 -4
@@ -290,7 +290,7 @@ fn internal_error() -> Response {
290 /// Authenticates the request's credentials under the per-IP git failure limit. Only rejected290 /// Authenticates the request's credentials under the per-IP git failure limit. Only rejected
291 /// credentials count, so anonymous requests and successful logins never do. Returns the response291 /// credentials count, so anonymous requests and successful logins never do. Returns the response
292 /// to send when the request must stop: 429 while the IP is throttled, or the access error.292 /// to send when the request must stop: 429 while the IP is throttled, or the access error.
293-pub(crate) async fn authenticate(293+pub async fn authenticate(
294 state: &AppState,294 state: &AppState,
295 ip: IpAddr,295 ip: IpAddr,
296 headers: &HeaderMap,296 headers: &HeaderMap,
@@ -343,13 +343,13 @@ async fn caller_repo(
343 }343 }
344 344
345 /// Username of a CI job's git credential. The password is `<job id>:<job token>`.345 /// Username of a CI job's git credential. The password is `<job id>:<job token>`.
346-pub(crate) const JOB_GIT_USERNAME: &str = "ci-job";346+pub const JOB_GIT_USERNAME: &str = "ci-job";
347 347
348 /// Read-only git access for a running CI job. Returns `None` unless the request uses the348 /// Read-only git access for a running CI job. Returns `None` unless the request uses the
349 /// `ci-job` username, so other callers take the normal path. The token must belong to a job that349 /// `ci-job` username, so other callers take the normal path. The token must belong to a job that
350 /// is Running (see `job_by_token`), the repo must be that job's repo, and receive-pack is refused.350 /// is Running (see `job_by_token`), the repo must be that job's repo, and receive-pack is refused.
351 /// Failed attempts count against the git failure limit.351 /// Failed attempts count against the git failure limit.
352-pub(crate) async fn job_token_read(352+pub async fn job_token_read(
353 state: &AppState,353 state: &AppState,
354 ip: IpAddr,354 ip: IpAddr,
355 headers: &HeaderMap,355 headers: &HeaderMap,
@@ -436,7 +436,7 @@ fn internal_error_for(error: &forge_core::Error) -> Response {
436 internal_error()436 internal_error()
437 }437 }
438 438
439-pub(crate) fn access_error(error: AccessError) -> Response {439+pub fn access_error(error: AccessError) -> Response {
440 match error {440 match error {
441 AccessError::Unauthorized => {441 AccessError::Unauthorized => {
442 let mut res = text(StatusCode::UNAUTHORIZED, "unauthorized");442 let mut res = text(StatusCode::UNAUTHORIZED, "unauthorized");
crates/forge-web/src/hook_cmd.rs → crates/forge-web-app/src/hook_cmd.rsrenamed+1 -1
@@ -147,7 +147,7 @@ fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
147 }147 }
148 148
149 /// Parses an HTTP/1.1 response with `Content-Length` or chunked framing.149 /// Parses an HTTP/1.1 response with `Content-Length` or chunked framing.
150-pub(crate) fn parse_response(raw: &[u8]) -> io::Result<(u16, Vec<u8>)> {150+pub fn parse_response(raw: &[u8]) -> io::Result<(u16, Vec<u8>)> {
151 let split = find(raw, b"\r\n\r\n").ok_or_else(|| invalid("missing end of HTTP headers"))?;151 let split = find(raw, b"\r\n\r\n").ok_or_else(|| invalid("missing end of HTTP headers"))?;
152 let head =152 let head =
153 std::str::from_utf8(&raw[..split]).map_err(|_| invalid("HTTP headers are not UTF-8"))?;153 std::str::from_utf8(&raw[..split]).map_err(|_| invalid("HTTP headers are not UTF-8"))?;
crates/forge-web/src/importer/api.rs → crates/forge-web-app/src/importer/api.rsrenamed+6 -6
@@ -584,7 +584,7 @@ fn login(u: Option<GhUser>) -> String {
584 u.and_then(|u| u.login).unwrap_or_default()584 u.and_then(|u| u.login).unwrap_or_default()
585 }585 }
586 586
587-#[cfg(test)]587+#[cfg(any(test, feature = "test-support"))]
588 pub fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> {588 pub fn parse_github_labels(json: &[u8]) -> ApiResult<Vec<ExtLabel>> {
589 let raw: Vec<GhLabel> = from_json(json)?;589 let raw: Vec<GhLabel> = from_json(json)?;
590 Ok(raw.into_iter().map(label_of).collect())590 Ok(raw.into_iter().map(label_of).collect())
@@ -598,12 +598,12 @@ fn label_of(l: GhLabel) -> ExtLabel {
598 }598 }
599 }599 }
600 600
601-#[cfg(test)]601+#[cfg(any(test, feature = "test-support"))]
602 fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> {602 fn from_json<T: DeserializeOwned>(json: &[u8]) -> ApiResult<T> {
603 serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string()))603 serde_json::from_slice(json).map_err(|e| ApiError::Parse(e.to_string()))
604 }604 }
605 605
606-#[cfg(test)]606+#[cfg(any(test, feature = "test-support"))]
607 pub fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> {607 pub fn parse_github_issues(json: &[u8]) -> ApiResult<Vec<ExtIssue>> {
608 let raw: Vec<GhIssue> = from_json(json)?;608 let raw: Vec<GhIssue> = from_json(json)?;
609 Ok(raw.into_iter().map(gh_issue).collect())609 Ok(raw.into_iter().map(gh_issue).collect())
@@ -630,7 +630,7 @@ fn gh_issue(i: GhIssue) -> ExtIssue {
630 }630 }
631 }631 }
632 632
633-#[cfg(test)]633+#[cfg(any(test, feature = "test-support"))]
634 pub fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {634 pub fn parse_github_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
635 let raw: Vec<GhRelease> = from_json(json)?;635 let raw: Vec<GhRelease> = from_json(json)?;
636 Ok(raw636 Ok(raw
@@ -952,13 +952,13 @@ fn gl_issue(i: GlIssue, is_pr: bool) -> ExtIssue {
952 }952 }
953 }953 }
954 954
955-#[cfg(test)]955+#[cfg(any(test, feature = "test-support"))]
956 pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> {956 pub fn parse_gitlab_issues(json: &[u8], is_pr: bool) -> ApiResult<Vec<ExtIssue>> {
957 let raw: Vec<GlIssue> = from_json(json)?;957 let raw: Vec<GlIssue> = from_json(json)?;
958 Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect())958 Ok(raw.into_iter().map(|i| gl_issue(i, is_pr)).collect())
959 }959 }
960 960
961-#[cfg(test)]961+#[cfg(any(test, feature = "test-support"))]
962 pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {962 pub fn parse_gitlab_releases(json: &[u8]) -> ApiResult<Vec<ExtRelease>> {
963 let raw: Vec<GlRelease> = from_json(json)?;963 let raw: Vec<GlRelease> = from_json(json)?;
964 Ok(raw.into_iter().map(gl_release).collect())964 Ok(raw.into_iter().map(gl_release).collect())
crates/forge-web/src/importer/mod.rs → crates/forge-web-app/src/importer/mod.rsrenamed+2 -5
@@ -159,7 +159,7 @@ impl JobSpec {
159 #[derive(Clone)]159 #[derive(Clone)]
160 pub enum Transport {160 pub enum Transport {
161 Net,161 Net,
162- #[cfg(test)]162+ #[cfg(any(test, feature = "test-support"))]
163 Local(String),163 Local(String),
164 }164 }
165 165
@@ -504,7 +504,7 @@ async fn fetch_git(
504 .await504 .await
505 .map_err(|e| e.to_string())505 .map_err(|e| e.to_string())
506 }506 }
507- #[cfg(test)]507+ #[cfg(any(test, feature = "test-support"))]
508 Transport::Local(path) => {508 Transport::Local(path) => {
509 forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT)509 forge_git::mirror::mirror_fetch_local(&state.git, &repo_dir, path, GIT_TIMEOUT)
510 .await510 .await
@@ -1106,6 +1106,3 @@ pub async fn on_boot(state: &AppState) {
1106 Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"),1106 Err(e) => tracing::error!(error = %e, "import: could not clean up interrupted jobs"),
1107 }1107 }
1108 }1108 }
1109-
1110-#[cfg(test)]
1111-mod tests;
crates/forge-web/src/importer/remote.rs → crates/forge-web-app/src/importer/remote.rsrenamed+0 -0
crates/forge-web/src/internal.rs → crates/forge-web-app/src/internal.rsrenamed+1 -1
@@ -698,7 +698,7 @@ pub async fn evaluate_pre_receive(
698 /// Whether `actor_id` may push straight to a `restrict_push` branch: an instance admin, the owner698 /// Whether `actor_id` may push straight to a `restrict_push` branch: an instance admin, the owner
699 /// of a person-owned repo, or someone whose effective role is Admin (a collaborator Admin, or an699 /// of a person-owned repo, or someone whose effective role is Admin (a collaborator Admin, or an
700 /// org owner or admin team on an org-owned repo). Pull request merges do not go through here.700 /// org owner or admin team on an org-owned repo). Pull request merges do not go through here.
701-pub(crate) async fn may_push_directly(701+pub async fn may_push_directly(
702 store: &Store,702 store: &Store,
703 repo: &Repo,703 repo: &Repo,
704 actor_id: &str,704 actor_id: &str,
crates/forge-web/src/layers.rs → crates/forge-web-app/src/layers.rsrenamed+0 -0
crates/forge-web/src/lfs/gc.rs → crates/forge-web-app/src/lfs/gc.rsrenamed+0 -0
crates/forge-web/src/lfs/mod.rs → crates/forge-web-app/src/lfs/mod.rsrenamed+0 -0
crates/forge-web/src/lfs/route_tests.rs → crates/forge-web-app/src/lfs/route_tests.rsrenamed+0 -0
crates/forge-web/src/lfs/routes.rs → crates/forge-web-app/src/lfs/routes.rsrenamed+0 -0
crates/forge-web/src/lfs_pointer.rs → crates/forge-web-app/src/lfs_pointer.rsrenamed+0 -0
crates/forge-web-app/src/lib.rsadded+62 -0
@@ -0,0 +1,62 @@
1+//! forge web foundation: everything below the pages.
2+
3+#![recursion_limit = "256"]
4+
5+pub use forge_web_base::{
6+ accent, accent_palette, blobs, compression, custom_colour, i18n, render, repo_stats, templates,
7+ theme, throttle,
8+};
9+
10+pub mod access;
11+pub mod admin_client;
12+pub mod advisories;
13+pub mod alerts;
14+pub mod api;
15+pub mod audit;
16+pub mod auth;
17+pub mod automerge;
18+pub mod backup;
19+pub mod ci;
20+pub mod client_ip;
21+pub mod exporter;
22+pub mod git_auth;
23+pub mod git_http;
24+pub mod hook_cmd;
25+pub mod importer;
26+pub mod internal;
27+pub mod layers;
28+pub mod lfs;
29+pub mod lfs_pointer;
30+pub mod live;
31+pub mod mail;
32+pub mod merge;
33+pub mod merge_queue;
34+pub mod mirrors;
35+pub mod notify;
36+pub mod notify_hub;
37+pub mod oci;
38+pub mod package_ops;
39+pub mod packages_live;
40+pub mod post_update;
41+pub mod prune;
42+pub mod pulls_sync;
43+pub mod raw;
44+pub mod release_ops;
45+pub mod replication;
46+pub mod self_update;
47+pub mod signatures;
48+pub mod ssh_backend;
49+pub mod state;
50+#[cfg(any(test, feature = "test-support"))]
51+pub mod test_support;
52+pub mod views;
53+pub mod web_push;
54+pub mod webhooks;
55+
56+pub mod build_info {
57+ pub const BUILD_SHA: &str = env!("FORGE_BUILD_SHA");
58+ pub const GIT_SHA: &str = env!("FORGE_GIT_SHA");
59+ pub const GIT_DATE: &str = env!("FORGE_GIT_DATE");
60+ pub const GIT_DIRTY: bool = matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1");
61+ pub const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));
62+}
crates/forge-web/src/live.rs → crates/forge-web-app/src/live.rsrenamed+2 -2
@@ -382,7 +382,7 @@ pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) {
382 const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);382 const STREAM_KEEP_ALIVE: Duration = Duration::from_secs(30);
383 383
384 /// A run's or job's status word and whether it is terminal. `None` when the row is gone.384 /// A run's or job's status word and whether it is terminal. `None` when the row is gone.
385-pub(crate) type Status = Option<(String, bool)>;385+pub type Status = Option<(String, bool)>;
386 386
387 /// One `changed` event carrying the status word.387 /// One `changed` event carrying the status word.
388 pub fn changed_event(status: String) -> Result<Event> {388 pub fn changed_event(status: String) -> Result<Event> {
@@ -513,7 +513,7 @@ impl Drop for StreamSlot {
513 513
514 /// How long the browser waits before it reconnects a dropped event stream. The browser's default is514 /// How long the browser waits before it reconnects a dropped event stream. The browser's default is
515 /// a few seconds; one second makes a page come back as soon as a server restart is done.515 /// a few seconds; one second makes a page come back as soon as a server restart is done.
516-pub(crate) const STREAM_RETRY: Duration = Duration::from_secs(1);516+pub const STREAM_RETRY: Duration = Duration::from_secs(1);
517 517
518 /// The response of an event stream: keep-alive comments while idle, no buffering by a reverse518 /// The response of an event stream: keep-alive comments while idle, no buffering by a reverse
519 /// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.519 /// proxy, and a `retry` field first so every stream reconnects after `STREAM_RETRY`.
crates/forge-web/src/mail/account.rs → crates/forge-web-app/src/mail/account.rsrenamed+0 -0
crates/forge-web/src/mail/live.rs → crates/forge-web-app/src/mail/live.rsrenamed+0 -0
crates/forge-web/src/mail/log.rs → crates/forge-web-app/src/mail/log.rsrenamed+0 -0
crates/forge-web/src/mail/mod.rs → crates/forge-web-app/src/mail/mod.rsrenamed+3 -3
@@ -68,14 +68,14 @@ pub async fn enqueue_message(
68 68
69 /// A mailer for tests. It records every message it accepts. [`FakeMailer::fail_next`] makes the69 /// A mailer for tests. It records every message it accepts. [`FakeMailer::fail_next`] makes the
70 /// next sends fail, to exercise the retry path.70 /// next sends fail, to exercise the retry path.
71-#[cfg(test)]71+#[cfg(any(test, feature = "test-support"))]
72 #[derive(Default)]72 #[derive(Default)]
73 pub struct FakeMailer {73 pub struct FakeMailer {
74 sent: std::sync::Mutex<Vec<OutgoingMail>>,74 sent: std::sync::Mutex<Vec<OutgoingMail>>,
75 failures: std::sync::Mutex<std::collections::VecDeque<MailError>>,75 failures: std::sync::Mutex<std::collections::VecDeque<MailError>>,
76 }76 }
77 77
78-#[cfg(test)]78+#[cfg(any(test, feature = "test-support"))]
79 impl FakeMailer {79 impl FakeMailer {
80 /// Messages accepted so far, oldest first.80 /// Messages accepted so far, oldest first.
81 pub fn sent(&self) -> Vec<OutgoingMail> {81 pub fn sent(&self) -> Vec<OutgoingMail> {
@@ -94,7 +94,7 @@ impl FakeMailer {
94 }94 }
95 }95 }
96 96
97-#[cfg(test)]97+#[cfg(any(test, feature = "test-support"))]
98 impl Mailer for FakeMailer {98 impl Mailer for FakeMailer {
99 fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a> {99 fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a> {
100 Box::pin(async move {100 Box::pin(async move {
crates/forge-web/src/mail/smtp.rs → crates/forge-web-app/src/mail/smtp.rsrenamed+0 -0
crates/forge-web/src/mail/templates.rs → crates/forge-web-app/src/mail/templates.rsrenamed+0 -0
crates/forge-web/src/mail/worker.rs → crates/forge-web-app/src/mail/worker.rsrenamed+0 -0
crates/forge-web/src/merge.rs → crates/forge-web-app/src/merge.rsrenamed+0 -0
crates/forge-web/src/merge_queue.rs → crates/forge-web-app/src/merge_queue.rsrenamed+0 -0
crates/forge-web/src/mirrors/mod.rs → crates/forge-web-app/src/mirrors/mod.rsrenamed+0 -0
crates/forge-web/src/mirrors/worker.rs → crates/forge-web-app/src/mirrors/worker.rsrenamed+0 -0
crates/forge-web/src/notify.rs → crates/forge-web-app/src/notify.rsrenamed+0 -0
crates/forge-web/src/notify_hub.rs → crates/forge-web-app/src/notify_hub.rsrenamed+0 -0
crates/forge-web/src/oci/auth.rs → crates/forge-web-app/src/oci/auth.rsrenamed+0 -0
crates/forge-web/src/oci/blobs.rs → crates/forge-web-app/src/oci/blobs.rsrenamed+0 -0
crates/forge-web/src/oci/gc.rs → crates/forge-web-app/src/oci/gc.rsrenamed+0 -0
crates/forge-web/src/oci/manifests.rs → crates/forge-web-app/src/oci/manifests.rsrenamed+0 -0
crates/forge-web/src/oci/mod.rs → crates/forge-web-app/src/oci/mod.rsrenamed+0 -0
crates/forge-web/src/package_ops.rs → crates/forge-web-app/src/package_ops.rsrenamed+0 -0
crates/forge-web/src/packages_live.rs → crates/forge-web-app/src/packages_live.rsrenamed+0 -0
crates/forge-web/src/post_update.rs → crates/forge-web-app/src/post_update.rsrenamed+0 -0
crates/forge-web/src/prune.rs → crates/forge-web-app/src/prune.rsrenamed+0 -0
crates/forge-web/src/pulls_sync.rs → crates/forge-web-app/src/pulls_sync.rsrenamed+0 -0
crates/forge-web/src/raw/media.rs → crates/forge-web-app/src/raw/media.rsrenamed+1 -1
@@ -52,7 +52,7 @@ pub fn media_url(state: &AppState, repo: &Repo, rev: &str, path: &str) -> String
52 url52 url
53 }53 }
54 54
55-pub(crate) fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {55+pub fn media_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {
56 Box::pin(async move { Ok(serve(cx).await) })56 Box::pin(async move { Ok(serve(cx).await) })
57 }57 }
58 58
crates/forge-web/src/raw/mod.rs → crates/forge-web-app/src/raw/mod.rsrenamed+15 -19
@@ -36,17 +36,17 @@ const MAX_INLINE_BYTES: u64 = 8 * 1024 * 1024;
36 /// Bytes inspected to decide text versus binary.36 /// Bytes inspected to decide text versus binary.
37 const SNIFF_BYTES: usize = 8000;37 const SNIFF_BYTES: usize = 8000;
38 /// Lifetime of a signed private raw URL.38 /// Lifetime of a signed private raw URL.
39-pub(crate) const LINK_TTL_SECS: i64 = 600;39+pub const LINK_TTL_SECS: i64 = 600;
40 40
41 const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";41 const CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";
42 const CORP: &str = "cross-origin";42 const CORP: &str = "cross-origin";
43 /// Raw responses revalidate on every use (an unchanged blob answers 304 through If-None-Match),43 /// Raw responses revalidate on every use (an unchanged blob answers 304 through If-None-Match),
44 /// so a repo made private, or a reader who lost access, stops being served at once.44 /// so a repo made private, or a reader who lost access, stops being served at once.
45-pub(crate) const CACHE_PRIVATE: &str = "private, no-cache";45+pub const CACHE_PRIVATE: &str = "private, no-cache";
46-pub(crate) const CACHE_PUBLIC: &str = "public, no-cache";46+pub const CACHE_PUBLIC: &str = "public, no-cache";
47-pub(crate) const CACHE_NONE: &str = "no-store";47+pub const CACHE_NONE: &str = "no-store";
48 const TEXT: &str = "text/plain; charset=utf-8";48 const TEXT: &str = "text/plain; charset=utf-8";
49-pub(crate) const OCTET: &str = "application/octet-stream";49+pub const OCTET: &str = "application/octet-stream";
50 50
51 /// Absolute URL of a file on the raw origin. For private repos it carries a signed `?token=`51 /// Absolute URL of a file on the raw origin. For private repos it carries a signed `?token=`
52 /// valid for 10 minutes. `rev` is the ref name or commit oid as shown in the app URL.52 /// 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 {
71 }71 }
72 72
73 /// Percent-encodes each `/`-separated segment and keeps the separators.73 /// Percent-encodes each `/`-separated segment and keeps the separators.
74-pub(crate) fn encode_path(value: &str) -> String {74+pub fn encode_path(value: &str) -> String {
75 value75 value
76 .split('/')76 .split('/')
77 .map(encode_segment)77 .map(encode_segment)
@@ -279,7 +279,7 @@ async fn serve(cx: &Cx) -> Response {
279 }279 }
280 280
281 /// Result of the blocking lookup.281 /// Result of the blocking lookup.
282-pub(crate) enum Lookup {282+pub enum Lookup {
283 Missing,283 Missing,
284 NotModified {284 NotModified {
285 oid: String,285 oid: String,
@@ -296,7 +296,7 @@ pub(crate) enum Lookup {
296 }296 }
297 297
298 /// Resolves `rest` (`<ref>/<path>`) to an entry. Trees, submodules and missing paths are `Missing`.298 /// Resolves `rest` (`<ref>/<path>`) to an entry. Trees, submodules and missing paths are `Missing`.
299-pub(crate) fn lookup(299+pub fn lookup(
300 repo_dir: &Path,300 repo_dir: &Path,
301 rest: &str,301 rest: &str,
302 if_none_match: Option<&str>,302 if_none_match: Option<&str>,
@@ -405,14 +405,14 @@ fn etag_matches(header_value: &str, etag: &str) -> bool {
405 })405 })
406 }406 }
407 407
408-pub(crate) struct Meta {408+pub struct Meta {
409- pub(crate) content_type: &'static str,409+ pub content_type: &'static str,
410- pub(crate) attachment: bool,410+ pub attachment: bool,
411- pub(crate) len: u64,411+ pub len: u64,
412 }412 }
413 413
414 /// Builds a response with the security and caching headers that every raw response carries.414 /// Builds a response with the security and caching headers that every raw response carries.
415-pub(crate) fn finish(415+pub fn finish(
416 status: StatusCode,416 status: StatusCode,
417 body: Body,417 body: Body,
418 oid: &str,418 oid: &str,
@@ -459,11 +459,7 @@ pub(crate) fn finish(
459 }459 }
460 460
461 /// Error or empty response with no ETag and a text body.461 /// Error or empty response with no ETag and a text body.
462-pub(crate) fn plain(462+pub fn plain(status: StatusCode, cache: &'static str, body: Option<&'static str>) -> Response {
463- status: StatusCode,
464- cache: &'static str,
465- body: Option<&'static str>,
466-) -> Response {
467 let text = body.unwrap_or(match status {463 let text = body.unwrap_or(match status {
468 StatusCode::NOT_FOUND => "not found",464 StatusCode::NOT_FOUND => "not found",
469 _ => "internal error",465 _ => "internal error",
@@ -475,7 +471,7 @@ pub(crate) fn plain(
475 res471 res
476 }472 }
477 473
478-pub(crate) fn now_unix() -> i64 {474+pub fn now_unix() -> i64 {
479 SystemTime::now()475 SystemTime::now()
480 .duration_since(UNIX_EPOCH)476 .duration_since(UNIX_EPOCH)
481 .ok()477 .ok()
crates/forge-web/src/raw/snippet_raw.rs → crates/forge-web-app/src/raw/snippet_raw.rsrenamed+1 -1
@@ -47,7 +47,7 @@ pub fn snippet_raw_url(state: &AppState, snippet: &Snippet, file: &str) -> Strin
47 url47 url
48 }48 }
49 49
50-pub(crate) fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {50+pub fn snippet_file(cx: &Cx, _body: Body) -> RouteFuture<'_> {
51 Box::pin(async move { Ok(serve(cx).await) })51 Box::pin(async move { Ok(serve(cx).await) })
52 }52 }
53 53
crates/forge-web/src/release_ops.rs → crates/forge-web-app/src/release_ops.rsrenamed+0 -0
crates/forge-web/src/replication/mod.rs → crates/forge-web-app/src/replication/mod.rsrenamed+2 -2
@@ -444,11 +444,11 @@ impl StandbyTransport for SshTransport {
444 444
445 /// Runs the same shell commands as [`SshTransport`], but with `sh -c` on this machine. The remote445 /// Runs the same shell commands as [`SshTransport`], but with `sh -c` on this machine. The remote
446 /// base is then a local directory. Test only.446 /// base is then a local directory. Test only.
447-#[cfg(test)]447+#[cfg(any(test, feature = "test-support"))]
448 #[derive(Debug, Clone, Copy, Default)]448 #[derive(Debug, Clone, Copy, Default)]
449 pub struct LocalTransport;449 pub struct LocalTransport;
450 450
451-#[cfg(test)]451+#[cfg(any(test, feature = "test-support"))]
452 impl StandbyTransport for LocalTransport {452 impl StandbyTransport for LocalTransport {
453 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send {453 fn run(&self, remote_cmd: &str) -> impl Future<Output = Result<Vec<u8>, String>> + Send {
454 let mut cmd = Command::new("sh");454 let mut cmd = Command::new("sh");
crates/forge-web/src/replication/worker.rs → crates/forge-web-app/src/replication/worker.rsrenamed+1 -1
@@ -147,7 +147,7 @@ async fn ping(url: &str, report: &ReconcileReport) {
147 147
148 /// Records an outcome for `subject` and passes the error on. `refs` is the checksum to store on148 /// Records an outcome for `subject` and passes the error on. `refs` is the checksum to store on
149 /// success (repos only).149 /// success (repos only).
150-pub(crate) async fn record(150+pub async fn record(
151 store: &Store,151 store: &Store,
152 subject: &str,152 subject: &str,
153 result: Result<Option<String>, String>,153 result: Result<Option<String>, String>,
crates/forge-web/src/self_update.rs → crates/forge-web-app/src/self_update.rsrenamed+0 -0
crates/forge-web/src/signatures.rs → crates/forge-web-app/src/signatures.rsrenamed+0 -0
crates/forge-web/src/ssh_backend.rs → crates/forge-web-app/src/ssh_backend.rsrenamed+0 -0
crates/forge-web/src/state.rs → crates/forge-web-app/src/state.rsrenamed+2 -2
@@ -62,7 +62,7 @@ pub struct AppState {
62 }62 }
63 63
64 /// A settings handle over `config` with no stored overrides and no file keys. For tests.64 /// A settings handle over `config` with no stored overrides and no file keys. For tests.
65-#[cfg(test)]65+#[cfg(any(test, feature = "test-support"))]
66 pub fn settings_for(config: &Arc<Config>) -> Arc<forge_core::server_settings::Live> {66 pub fn settings_for(config: &Arc<Config>) -> Arc<forge_core::server_settings::Live> {
67 Arc::new(forge_core::server_settings::Live::new(67 Arc::new(forge_core::server_settings::Live::new(
68 config.clone(),68 config.clone(),
@@ -79,7 +79,7 @@ impl AppState {
79 }79 }
80 80
81 /// Replaces the config and resets the settings layer over it. For tests.81 /// Replaces the config and resets the settings layer over it. For tests.
82- #[cfg(test)]82+ #[cfg(any(test, feature = "test-support"))]
83 pub fn set_config(&mut self, config: Config) {83 pub fn set_config(&mut self, config: Config) {
84 self.config = Arc::new(config);84 self.config = Arc::new(config);
85 self.settings = settings_for(&self.config);85 self.settings = settings_for(&self.config);
crates/forge-web-app/src/test_support/fixture.rsadded+170 -0
@@ -0,0 +1,170 @@
1+//! Shared test fixture: a store with one owner, a bare repo built through the git CLI, and a
2+//! router with the app context.
3+
4+use std::path::{Path, PathBuf};
5+use std::process::Command;
6+
7+use forge_core::{Store, Visibility};
8+
9+use topcoat::router::request::Request;
10+use topcoat::router::{Body, Router, to_bytes};
11+
12+pub const OWNER: &str = "tahinli";
13+pub const REPO: &str = "demo";
14+
15+pub struct Fixture {
16+ pub router: Router,
17+ pub store: Store,
18+ /// The live hub the router's pages share, to bump topics from a test.
19+ pub live: std::sync::Arc<crate::live::LiveHub>,
20+ /// Root commit: adds `a.txt` and `dir/b.txt`.
21+ pub root: String,
22+ /// Adds `new.txt` and changes `a.txt`.
23+ pub modified: String,
24+ /// Working checkout and bare repo the fixture pushed to.
25+ pub work: PathBuf,
26+ pub bare: PathBuf,
27+ _dir: tempfile::TempDir,
28+}
29+
30+pub fn git(dir: &Path, args: &[&str]) -> String {
31+ let out = Command::new("git")
32+ .args([
33+ "-c",
34+ "user.name=Tester",
35+ "-c",
36+ "user.email=tester@example.com",
37+ "-c",
38+ "commit.gpgsign=false",
39+ ])
40+ .args(args)
41+ .current_dir(dir)
42+ .output()
43+ .expect("git runs");
44+ assert!(
45+ out.status.success(),
46+ "git {args:?} failed: {}",
47+ String::from_utf8_lossy(&out.stderr)
48+ );
49+ String::from_utf8_lossy(&out.stdout).trim().to_owned()
50+}
51+
52+impl Fixture {
53+ pub async fn new(visibility: Visibility) -> Self {
54+ let tmp = tempfile::tempdir().expect("tempdir");
55+ let dir = tmp.path().to_path_buf();
56+ let state = crate::test_support::test_state(&dir).await;
57+ let store = state.store.clone();
58+ let live = state.live.clone();
59+ let router = crate::test_support::app_router(state);
60+
61+ let owner = store
62+ .create_user(OWNER, None, "not-a-real-hash", false)
63+ .await
64+ .unwrap();
65+ let repo = store
66+ .create_repo(&owner.id, REPO, "", visibility, "main")
67+ .await
68+ .unwrap();
69+ let bare = repo_dir(&dir, &repo.id);
70+ std::fs::create_dir_all(bare.parent().unwrap()).unwrap();
71+ git(
72+ &dir,
73+ &[
74+ "init",
75+ "-q",
76+ "--bare",
77+ "-b",
78+ "main",
79+ &bare.to_string_lossy(),
80+ ],
81+ );
82+
83+ let work = dir.join("work");
84+ std::fs::create_dir_all(&work).unwrap();
85+ git(&work, &["init", "-q", "-b", "main"]);
86+ std::fs::write(work.join("a.txt"), "one\ntwo\nthree\n").unwrap();
87+ std::fs::create_dir_all(work.join("dir")).unwrap();
88+ std::fs::write(work.join("dir/b.txt"), "b\n").unwrap();
89+ git(&work, &["add", "-A"]);
90+ git(&work, &["commit", "-q", "-m", "root commit"]);
91+ let root = git(&work, &["rev-parse", "HEAD"]);
92+
93+ std::fs::write(work.join("a.txt"), "one\nTWO\nthree\nfour\n").unwrap();
94+ std::fs::write(work.join("new.txt"), "new file\n").unwrap();
95+ git(&work, &["add", "-A"]);
96+ git(
97+ &work,
98+ &[
99+ "commit",
100+ "-q",
101+ "-m",
102+ "Modify a.txt and add new.txt",
103+ "-m",
104+ "Body line one.\n\nSecond paragraph.",
105+ ],
106+ );
107+ let modified = git(&work, &["rev-parse", "HEAD"]);
108+
109+ // 53 empty commits on top: 55 in all, so history spans two pages.
110+ for n in 1..=53 {
111+ git(
112+ &work,
113+ &[
114+ "commit",
115+ "-q",
116+ "--allow-empty",
117+ "-m",
118+ &format!("filler {n}"),
119+ ],
120+ );
121+ }
122+ git(
123+ &work,
124+ &[
125+ "push",
126+ "-q",
127+ &bare.to_string_lossy(),
128+ "HEAD:refs/heads/main",
129+ ],
130+ );
131+
132+ Self {
133+ router,
134+ store,
135+ live,
136+ root,
137+ modified,
138+ work,
139+ bare,
140+ _dir: tmp,
141+ }
142+ }
143+}
144+
145+/// Same layout as `forge_git::repo::repo_path`, computed here so the test can create it.
146+fn repo_dir(data_dir: &Path, repo_id: &str) -> PathBuf {
147+ let id = repo_id.to_ascii_lowercase();
148+ data_dir
149+ .join("repos")
150+ .join(&id[0..2])
151+ .join(&id[2..4])
152+ .join(format!("{id}.git"))
153+}
154+
155+/// GET through the router: `(status, headers, body)`.
156+pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>) {
157+ let req = Request::builder()
158+ .method("GET")
159+ .uri(uri)
160+ .body(Body::empty())
161+ .unwrap();
162+ let res = router.handle(req).await;
163+ let status = res.status().as_u16();
164+ let headers = res.headers().clone();
165+ let body = to_bytes(res.into_body(), usize::MAX)
166+ .await
167+ .unwrap()
168+ .to_vec();
169+ (status, headers, body)
170+}
crates/forge-web/src/test_support.rs → crates/forge-web-app/src/test_support/mod.rsrenamed+13 -7
@@ -3,6 +3,8 @@
3 //! Every test that needs a `Config`, an `AppState` or a router builds them here, so a new config3 //! Every test that needs a `Config`, an `AppState` or a router builds them here, so a new config
4 //! or state field is added in one place.4 //! or state field is added in one place.
5 5
6+pub mod fixture;
7+
6 use std::path::Path;8 use std::path::Path;
7 use std::sync::Arc;9 use std::sync::Arc;
8 use std::time::Duration;10 use std::time::Duration;
@@ -17,6 +19,7 @@ use topcoat::cookie::CookieLayer;
17 use topcoat::router::tower::TowerLayer;19 use topcoat::router::tower::TowerLayer;
18 use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt};20 use topcoat::router::{Compression, Router, RouterBuilderDiscoverExt};
19 21
22+#[cfg(not(test))]
20 use crate::layers::RepoMovedLayer;23 use crate::layers::RepoMovedLayer;
21 use crate::state::AppState;24 use crate::state::AppState;
22 use crate::throttle::Throttle;25 use crate::throttle::Throttle;
@@ -100,18 +103,21 @@ pub async fn test_state(dir: &Path) -> AppState {
100 }103 }
101 }104 }
102 105
103-/// The public router as boot.rs builds it, minus the listeners.106+/// The public router as boot.rs builds it, minus the listeners. This crate's own tests have no
107+/// pages, so the layers scoped to page paths are left out there.
104 pub fn app_router(state: AppState) -> Router {108 pub fn app_router(state: AppState) -> Router {
105- Router::builder()109+ let builder = Router::builder().discover().with(state);
106- .discover()110+ #[cfg(not(test))]
107- .with(state)111+ let builder = builder.layer(crate::layers::AccountWriteLayer);
108- .layer(crate::layers::AccountWriteLayer)112+ let builder = builder.layer(CookieLayer::new());
109- .layer(CookieLayer::new())113+ #[cfg(not(test))]
114+ let builder = builder
110 .layer(RepoMovedLayer)115 .layer(RepoMovedLayer)
111 .layer(crate::layers::RepoSettingsWriteLayer)116 .layer(crate::layers::RepoSettingsWriteLayer)
112 .layer(crate::layers::PullWriteLayer)117 .layer(crate::layers::PullWriteLayer)
113 .layer(crate::layers::DiscussionWriteLayer)118 .layer(crate::layers::DiscussionWriteLayer)
114- .layer(crate::layers::OrgWriteLayer)119+ .layer(crate::layers::OrgWriteLayer);
120+ builder
115 .layer(TowerLayer::new(crate::compression::ResponseCompression))121 .layer(TowerLayer::new(crate::compression::ResponseCompression))
116 .with(Compression::disable())122 .with(Compression::disable())
117 .build()123 .build()
crates/forge-web/src/views/commit_line.rs → crates/forge-web-app/src/views/commit_line.rsrenamed+0 -0
crates/forge-web/src/views/commit_status.rs → crates/forge-web-app/src/views/commit_status.rsrenamed+0 -0
crates/forge-web/src/views/diff.rs → crates/forge-web-app/src/views/diff.rsrenamed+0 -0
crates/forge-web/src/views/find.rs → crates/forge-web-app/src/views/find.rsrenamed+0 -0
crates/forge-web/src/views/heatmap.rs → crates/forge-web-app/src/views/heatmap.rsrenamed+0 -0
crates/forge-web/src/views/mod.rs → crates/forge-web-app/src/views/mod.rsrenamed+4 -220
@@ -1648,13 +1648,13 @@ pub async fn ref_selector(
1648 /// A stored timestamp shown as an absolute `title` and a relative label.1648 /// A stored timestamp shown as an absolute `title` and a relative label.
1649 #[derive(Clone)]1649 #[derive(Clone)]
1650 pub struct When {1650 pub struct When {
1651- pub(crate) iso: String,1651+ pub iso: String,
1652- pub(crate) absolute: String,1652+ pub absolute: String,
1653- pub(crate) relative: String,1653+ pub relative: String,
1654 }1654 }
1655 1655
1656 impl When {1656 impl When {
1657- pub(crate) fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self {1657+ pub fn new(lang: Lang, stamp: &str, tz: &str, now: i64) -> Self {
1658 let unix = stamp_unix(stamp);1658 let unix = stamp_unix(stamp);
1659 Self {1659 Self {
1660 iso: iso_time(unix),1660 iso: iso_time(unix),
@@ -2056,220 +2056,4 @@ mod tests {
2056 "Private"2056 "Private"
2057 );2057 );
2058 }2058 }
2059-
2060- /// Renders `/settings/security` (a page that uses the shell) for a freshly signed-in user.
2061- async fn menu_html(
2062- router: &topcoat::router::Router,
2063- store: &forge_core::Store,
2064- name: &str,
2065- is_admin: bool,
2066- token: &str,
2067- ) -> String {
2068- use crate::auth::SESSION_COOKIE;
2069- use topcoat::router::request::Request;
2070- use topcoat::router::to_bytes;
2071-
2072- let user = store
2073- .create_user(name, None, "x", is_admin)
2074- .await
2075- .expect("user");
2076- crate::test_support::create_session(store, &user.id, token, "menu-csrf").await;
2077- let req = Request::builder()
2078- .method("GET")
2079- .uri("/settings/security")
2080- .header("cookie", format!("__Host-{SESSION_COOKIE}={token}"))
2081- .body(Body::empty())
2082- .expect("request");
2083- let res = router.handle(req).await;
2084- assert_eq!(res.status().as_u16(), 200);
2085- let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
2086- String::from_utf8_lossy(&bytes).into_owned()
2087- }
2088-
2089- /// A user sees no admin links and an admin sees the one Admin entry. Both render from one
2090- /// fixture.
2091- #[tokio::test]
2092- async fn admin_links_follow_the_role() {
2093- let dir = tempfile::tempdir().expect("tempdir");
2094- let state = crate::test_support::test_state(dir.path()).await;
2095- let store = state.store.clone();
2096- let router = crate::test_support::app_router(state);
2097-
2098- let html = menu_html(&router, &store, "tahinli", false, "menu-token-user").await;
2099- assert!(html.contains("Log out"), "user menu is rendered");
2100- assert!(!html.contains("/admin/users"), "no admin link for a user");
2101- assert!(!html.contains("/admin/audit"), "no audit link for a user");
2102-
2103- let html = menu_html(&router, &store, "root", true, "menu-token-admin").await;
2104- assert!(html.contains("href=\"/admin/users\""));
2105- assert!(
2106- !html.contains("Admin:"),
2107- "one Admin entry, no per-page items"
2108- );
2109- }
2110-}
2111-
2112-#[cfg(test)]
2113-mod shell_tests {
2114- use topcoat::router::request::Request;
2115- use topcoat::router::{Body, to_bytes};
2116-
2117- use super::NAV_SCRIPT_HREF;
2118-
2119- /// Every `<script` tag carries a `src`: an inline script could not run under the CSP.
2120- fn assert_no_inline_scripts(html: &str) {
2121- for (at, _) in html.match_indices("<script") {
2122- let tag = &html[at..];
2123- let end = tag.find('>').expect("script tag closes");
2124- assert!(
2125- tag[..end].contains(" src="),
2126- "inline script: {}",
2127- &tag[..=end]
2128- );
2129- }
2130- }
2131-
2132- #[tokio::test]
2133- async fn shell_loads_the_deferred_nav_script_without_inline_scripts() {
2134- let dir = tempfile::tempdir().expect("tempdir");
2135- let state = crate::test_support::test_state(dir.path()).await;
2136- let router = crate::test_support::app_router(state);
2137- let req = Request::builder()
2138- .method("GET")
2139- .uri("/login")
2140- .body(Body::empty())
2141- .unwrap();
2142- let res = router.handle(req).await;
2143- assert_eq!(res.status(), 200);
2144- let csp = res.headers()["content-security-policy"]
2145- .to_str()
2146- .unwrap()
2147- .to_owned();
2148- assert!(csp.contains("default-src 'self'"), "{csp}");
2149- assert!(!csp.contains("unsafe-inline"), "{csp}");
2150- let html = String::from_utf8(
2151- to_bytes(res.into_body(), usize::MAX)
2152- .await
2153- .unwrap()
2154- .to_vec(),
2155- )
2156- .unwrap();
2157-
2158- let tag_at = html
2159- .find(&format!("<script src=\"{NAV_SCRIPT_HREF}\""))
2160- .expect("the shell loads the nav script");
2161- let tag = &html[tag_at..tag_at + html[tag_at..].find('>').unwrap()];
2162- assert!(tag.contains("defer"), "{tag}");
2163- assert_no_inline_scripts(&html);
2164-
2165- assert!(html.contains("<main tabindex=\"-1\" data-width=\"col\">"));
2166- assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\""));
2167-
2168- // An anonymous page renders the default colours.
2169- let tag = html_tag(&html);
2170- assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
2171- assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
2172- assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
2173- assert!(tag.contains("data-base-dark=\"ink\""), "{tag}");
2174- }
2175-
2176- /// The `<html …>` start tag of a page.
2177- fn html_tag(page: &str) -> &str {
2178- let at = page.find("<html").expect("the page has an html tag");
2179- let len = page[at..].find('>').expect("the html tag closes");
2180- &page[at..at + len + 1]
2181- }
2182-
2183- /// The `<html>` tag of `/settings/security` for a signed-in user whose stored colours are the
2184- /// four ids given, in the order light accent, dark accent, light base, dark base.
2185- async fn html_tag_for_colours(
2186- router: &topcoat::router::Router,
2187- store: &forge_core::Store,
2188- name: &str,
2189- token: &str,
2190- colours: [&str; 4],
2191- ) -> String {
2192- use crate::auth::SESSION_COOKIE;
2193- let user = store
2194- .create_user(name, None, "x", false)
2195- .await
2196- .expect("user");
2197- let [accent_light, accent_dark, base_light, base_dark] = colours;
2198- store
2199- .set_colours(&user.id, accent_light, accent_dark, base_light, base_dark)
2200- .await
2201- .expect("colours");
2202- crate::test_support::create_session(store, &user.id, token, "colour-csrf").await;
2203- let req = Request::builder()
2204- .method("GET")
2205- .uri("/settings/security")
2206- .header("cookie", format!("__Host-{SESSION_COOKIE}={token}"))
2207- .body(Body::empty())
2208- .unwrap();
2209- let res = router.handle(req).await;
2210- assert_eq!(res.status().as_u16(), 200);
2211- let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
2212- html_tag(&String::from_utf8_lossy(&bytes)).to_owned()
2213- }
2214-
2215- /// Every colour case shares one fixture; each has its own user and session.
2216- #[tokio::test]
2217- async fn the_html_tag_carries_the_viewers_colours() {
2218- let dir = tempfile::tempdir().expect("tempdir");
2219- let state = crate::test_support::test_state(dir.path()).await;
2220- let store = state.store.clone();
2221- let router = crate::test_support::app_router(state);
2222-
2223- let tag = html_tag_for_colours(
2224- &router,
2225- &store,
2226- "tahinli",
2227- "colour-token",
2228- ["ocean", "plum", "ink", "dusk"],
2229- )
2230- .await;
2231- assert!(tag.contains("data-accent-light=\"ocean\""), "{tag}");
2232- assert!(tag.contains("data-accent-dark=\"plum\""), "{tag}");
2233- assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
2234- assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}");
2235- assert!(!tag.contains("data-accent="), "{tag}");
2236- // Stored ids that are no longer offered fall back to the defaults, never to nothing.
2237- let removed = html_tag_for_colours(
2238- &router,
2239- &store,
2240- "removed",
2241- "removed-token",
2242- ["removed-palette", "removed-palette", "x", "x"],
2243- )
2244- .await;
2245- assert!(removed.contains("data-accent-light=\"sage\""), "{removed}");
2246- assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");
2247- assert!(removed.contains("data-base-light=\"ink\""), "{removed}");
2248- assert!(removed.contains("data-base-dark=\"ink\""), "{removed}");
2249- // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself.
2250- let retired = html_tag_for_colours(
2251- &router,
2252- &store,
2253- "retired",
2254- "retired-token",
2255- ["ochre", "terracotta", "mist", "stone"],
2256- )
2257- .await;
2258- assert!(retired.contains("data-accent-light=\"sage\""), "{retired}");
2259- assert!(retired.contains("data-accent-dark=\"sage\""), "{retired}");
2260- assert!(retired.contains("data-base-light=\"ink\""), "{retired}");
2261- assert!(retired.contains("data-base-dark=\"ink\""), "{retired}");
2262- let hued = html_tag_for_colours(
2263- &router,
2264- &store,
2265- "hued",
2266- "hued-token",
2267- ["hue-215", "hue-7", "hue-300", "ink"],
2268- )
2269- .await;
2270- assert!(hued.contains("data-accent-light=\"hue-215\""), "{hued}");
2271- assert!(hued.contains("data-accent-dark=\"hue-7\""), "{hued}");
2272- assert!(hued.contains("data-base-light=\"hue-300\""), "{hued}");
2273- assert!(hued.contains("data-base-dark=\"ink\""), "{hued}");
2274- }
2275 }2059 }
crates/forge-web/src/views/parts.rs → crates/forge-web-app/src/views/parts.rsrenamed+0 -0
crates/forge-web/src/views/repo_list.rs → crates/forge-web-app/src/views/repo_list.rsrenamed+0 -0
crates/forge-web/src/views/review_thread.rs → crates/forge-web-app/src/views/review_thread.rsrenamed+0 -0
crates/forge-web/src/views/timeline.rs → crates/forge-web-app/src/views/timeline.rsrenamed+0 -0
crates/forge-web/src/web_push/crypto.rs → crates/forge-web-app/src/web_push/crypto.rsrenamed+0 -0
crates/forge-web/src/web_push/mod.rs → crates/forge-web-app/src/web_push/mod.rsrenamed+0 -0
crates/forge-web/src/webhooks/client.rs → crates/forge-web-app/src/webhooks/client.rsrenamed+0 -0
crates/forge-web/src/webhooks/emit.rs → crates/forge-web-app/src/webhooks/emit.rsrenamed+0 -0
crates/forge-web/src/webhooks/mod.rs → crates/forge-web-app/src/webhooks/mod.rsrenamed+0 -0
crates/forge-web/src/webhooks/payload.rs → crates/forge-web-app/src/webhooks/payload.rsrenamed+0 -0
crates/forge-web/src/webhooks/worker.rs → crates/forge-web-app/src/webhooks/worker.rsrenamed+1 -1
@@ -128,7 +128,7 @@ fn sleep_for(next_due: &str, now: OffsetDateTime) -> Duration {
128 128
129 /// Claims up to [`BATCH`] due deliveries at `now`, sends them, and records each result. Returns129 /// Claims up to [`BATCH`] due deliveries at `now`, sends them, and records each result. Returns
130 /// how many were claimed.130 /// how many were claimed.
131-pub(crate) async fn process_due(131+pub async fn process_due(
132 state: &AppState,132 state: &AppState,
133 client: &HookClient,133 client: &HookClient,
134 policy: &WebhookPolicy,134 policy: &WebhookPolicy,
crates/forge-web/Cargo.tomlmodified+2 -5
@@ -17,6 +17,7 @@ forge-git.workspace = true
17 forge-ssh.workspace = true17 forge-ssh.workspace = true
18 forge-ci.workspace = true18 forge-ci.workspace = true
19 forge-web-base.workspace = true19 forge-web-base.workspace = true
20+forge-web-app.workspace = true
20 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }21 topcoat = { workspace = true, default-features = false, features = ["router", "view", "runtime", "cookie", "asset", "serve", "sse", "discover", "compression", "multipart", "tower"] }
21 tokio.workspace = true22 tokio.workspace = true
22 futures-util.workspace = true23 futures-util.workspace = true
@@ -56,12 +57,8 @@ p256.workspace = true
56 hkdf.workspace = true57 hkdf.workspace = true
57 aes-gcm.workspace = true58 aes-gcm.workspace = true
58 59
59-[build-dependencies]
60-grass.workspace = true
61-hex.workspace = true
62-sha2.workspace = true
63-
64 [dev-dependencies]60 [dev-dependencies]
61+forge-web-app = { workspace = true, features = ["test-support"] }
65 tempfile.workspace = true62 tempfile.workspace = true
66 image = { workspace = true }63 image = { workspace = true }
67 scraper = { workspace = true }64 scraper = { workspace = true }
crates/forge-web/src/importer/forgejo_tests.rs → crates/forge-web/src/forgejo_tests.rsrenamed+1 -1
@@ -100,7 +100,7 @@ fn page_of(target: &str) -> usize {
100 }100 }
101 101
102 fn client(base: &str, token: Option<&str>) -> Forgejo {102 fn client(base: &str, token: Option<&str>) -> Forgejo {
103- let notice: super::super::api::Notice = Arc::new(|_| {});103+ let notice: crate::importer::api::Notice = Arc::new(|_| {});
104 let open =104 let open =
105 crate::webhooks::client::WebhookPolicy::from_config(&forge_core::config::WebhookConfig {105 crate::webhooks::client::WebhookPolicy::from_config(&forge_core::config::WebhookConfig {
106 allow_http: true,106 allow_http: true,
crates/forge-web/src/api/gitea_tests.rs → crates/forge-web/src/gitea_route_tests.rsrenamed+0 -0
crates/forge-web/src/importer/tests.rs → crates/forge-web/src/importer_route_tests.rsrenamed+3 -3
@@ -11,14 +11,14 @@ use forge_core::{IssueState, Visibility};
11 use topcoat::router::request::Request;11 use topcoat::router::request::Request;
12 use topcoat::router::{Body, to_bytes};12 use topcoat::router::{Body, to_bytes};
13 13
14-use super::api::{14+use crate::auth::SESSION_COOKIE;
15+use crate::importer::api::{
15 ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone,16 ApiError, ApiResult, AssetStream, ExtAsset, ExtComment, ExtIssue, ExtLabel, ExtMilestone,
16 ExtRelease, ExtRepo, RemoteApi,17 ExtRelease, ExtRepo, RemoteApi,
17 };18 };
18-use super::{19+use crate::importer::{
19 ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note,20 ImportOptions, JobSpec, Source, Transport, asset_name, origin_note, run_job, with_note,
20 };21 };
21-use crate::auth::SESSION_COOKIE;
22 use crate::state::AppState;22 use crate::state::AppState;
23 use crate::test_support::{app_router, create_session, test_state};23 use crate::test_support::{app_router, create_session, test_state};
24 24
crates/forge-web/src/main.rsmodified+20 -53
@@ -6,66 +6,33 @@
6 6
7 #![recursion_limit = "256"]7 #![recursion_limit = "256"]
8 8
9-// Modules that moved to forge-web-base, so they compile once and are not rebuilt with the pages.9+// Modules that live in forge-web-base and forge-web-app, so they compile once and are not rebuilt with the pages.
10-pub(crate) use forge_web_base::{10+#[cfg(test)]
11- accent, accent_palette, blobs, compression, custom_colour, i18n, render, repo_stats, templates,11+pub(crate) use forge_web_app::test_support;
12- theme, throttle,12+pub(crate) use forge_web_app::{
13+ accent, admin_client, advisories, alerts, api, audit, auth, automerge, backup, blobs, ci,
14+ client_ip, compression, custom_colour, exporter, hook_cmd, i18n, importer, internal, layers,
15+ lfs, lfs_pointer, live, mail, merge, merge_queue, mirrors, notify, notify_hub, oci,
16+ package_ops, packages_live, post_update, prune, raw, release_ops, render, replication,
17+ repo_stats, self_update, signatures, ssh_backend, state, templates, theme, throttle, views,
18+ web_push, webhooks,
13 };19 };
14 20
15-mod access;
16 mod admin_cli;21 mod admin_cli;
17-mod admin_client;
18-mod advisories;
19-mod alerts;
20-mod api;
21-mod audit;
22-mod auth;
23-mod automerge;
24-mod backup;
25 mod boot;22 mod boot;
26-mod ci;
27-mod client_ip;
28 #[cfg(test)]23 #[cfg(test)]
29 mod compression_route_tests;24 mod compression_route_tests;
30-mod exporter;25+#[cfg(test)]
31-mod git_auth;26+mod gitea_route_tests;
32-mod git_http;27+#[cfg(test)]
33-mod hook_cmd;28+mod importer_route_tests;
34-mod importer;
35-mod internal;
36-mod layers;
37-mod lfs;
38-mod lfs_pointer;
39-mod live;
40-mod mail;
41-mod merge;
42-mod merge_queue;
43-mod mirrors;
44-mod notify;
45-mod notify_hub;
46-mod oci;
47-mod package_ops;
48-mod packages_live;
49 mod pages;29 mod pages;
50-mod post_update;
51-mod prune;
52-mod pulls_sync;
53-mod raw;
54-mod release_ops;
55-mod replication;
56 #[cfg(test)]30 #[cfg(test)]
57 mod route_list_tests;31 mod route_list_tests;
58-mod self_update;
59-mod signatures;
60-mod ssh_backend;
61-mod state;
62 #[cfg(test)]32 #[cfg(test)]
63-mod templates_route_tests;33+mod shell_route_tests;
64 #[cfg(test)]34 #[cfg(test)]
65-mod test_support;35+mod templates_route_tests;
66-mod views;
67-mod web_push;
68-mod webhooks;
69 36
70 use std::path::PathBuf;37 use std::path::PathBuf;
71 use std::process::ExitCode;38 use std::process::ExitCode;
@@ -82,7 +49,7 @@ const DEFAULT_CONFIG: &str = "config/forge.toml";
82 49
83 #[route(GET "/healthz")]50 #[route(GET "/healthz")]
84 async fn healthz(cx: &topcoat::context::Cx) -> Result<String, topcoat::Error> {51 async fn healthz(cx: &topcoat::context::Cx) -> Result<String, topcoat::Error> {
85- Ok(format!("ok {}", env!("FORGE_BUILD_SHA")))52+ Ok(format!("ok {}", forge_web_app::build_info::BUILD_SHA))
86 }53 }
87 54
88 async fn serve(config_path: &std::path::Path) -> Result<(), BoxError> {55 async fn serve(config_path: &std::path::Path) -> Result<(), BoxError> {
@@ -166,9 +133,9 @@ fn reexec_with_allocator_env(raw: &[std::ffi::OsString]) {
166 133
167 fn main() -> ExitCode {134 fn main() -> ExitCode {
168 forge_ci::build::set_identity(135 forge_ci::build::set_identity(
169- env!("FORGE_GIT_SHA"),136+ forge_web_app::build_info::GIT_SHA,
170- env!("FORGE_GIT_DATE"),137+ forge_web_app::build_info::GIT_DATE,
171- matches!(env!("FORGE_GIT_DIRTY").as_bytes(), b"1"),138+ forge_web_app::build_info::GIT_DIRTY,
172 );139 );
173 // The sandbox helpers must start before any runtime or subscriber exists.140 // The sandbox helpers must start before any runtime or subscriber exists.
174 if forge_runner::cli::is_sandbox_invocation() {141 if forge_runner::cli::is_sandbox_invocation() {
crates/forge-web/src/pages/archive.rsmodified+1 -1
@@ -153,7 +153,7 @@ mod tests {
153 use forge_core::Visibility;153 use forge_core::Visibility;
154 154
155 use super::{archive_prefix, split_format};155 use super::{archive_prefix, split_format};
156- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get};156+ use crate::test_support::fixture::{Fixture, OWNER, REPO, get};
157 use forge_git::history::ArchiveFormat;157 use forge_git::history::ArchiveFormat;
158 158
159 #[test]159 #[test]
crates/forge-web/src/pages/assets.rsmodified+1 -1
@@ -26,7 +26,7 @@ fn cache_for(cx: &Cx, href: &str) -> topcoat::router::HeaderValue {
26 topcoat::router::HeaderValue::from_static(value)26 topcoat::router::HeaderValue::from_static(value)
27 }27 }
28 28
29-const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css"));29+const CSS: &str = forge_web_app::build_info::MAIN_CSS;
30 30
31 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.31 /// Immutable when the URL carries the current content hash, so a changed file gets a new URL.
32 #[route(GET "/assets/main.css")]32 #[route(GET "/assets/main.css")]
crates/forge-web/src/pages/blame.rsmodified+1 -1
@@ -263,7 +263,7 @@ async fn blame_page(cx: &Cx) -> Result<impl View> {
263 mod tests {263 mod tests {
264 use forge_core::Visibility;264 use forge_core::Visibility;
265 265
266- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get};266+ use crate::test_support::fixture::{Fixture, OWNER, REPO, get};
267 267
268 /// Blame groups each line under the commit that wrote it.268 /// Blame groups each line under the commit that wrote it.
269 async fn scenario_blame_lines(fx: &Fixture) {269 async fn scenario_blame_lines(fx: &Fixture) {
crates/forge-web/src/pages/browse_tests.rsmodified+1 -1
@@ -7,8 +7,8 @@ use topcoat::router::request::Request;
7 use topcoat::router::{Body, Router, to_bytes};7 use topcoat::router::{Body, Router, to_bytes};
8 8
9 use crate::auth::SESSION_COOKIE;9 use crate::auth::SESSION_COOKIE;
10-use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get, git};
11 use crate::test_support::create_session;10 use crate::test_support::create_session;
11+use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};
12 12
13 const CSRF: &str = "browse-csrf";13 const CSRF: &str = "browse-csrf";
14 14
crates/forge-web/src/pages/commit.rsmodified+1 -1
@@ -372,7 +372,7 @@ mod tests {
372 372
373 use super::is_hex_prefix;373 use super::is_hex_prefix;
374 use crate::auth::SESSION_COOKIE;374 use crate::auth::SESSION_COOKIE;
375- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get};375+ use crate::test_support::fixture::{Fixture, OWNER, REPO, get};
376 use topcoat::router::request::Request;376 use topcoat::router::request::Request;
377 use topcoat::router::{Body, to_bytes};377 use topcoat::router::{Body, to_bytes};
378 378
crates/forge-web/src/pages/commits.rsmodified+1 -174
@@ -403,186 +403,13 @@ async fn commits_page(cx: &Cx) -> Result<impl View> {
403 })403 })
404 }404 }
405 405
406-/// Shared test fixture: a store with one owner, a bare repo built through the git CLI, and a
407-/// router with the app context. Used by the commits, commit and archive page tests.
408-#[cfg(test)]
409-pub(crate) mod test_support {
410- use std::path::{Path, PathBuf};
411- use std::process::Command;
412-
413- use forge_core::{Store, Visibility};
414-
415- use topcoat::router::request::Request;
416- use topcoat::router::{Body, Router, to_bytes};
417-
418- pub const OWNER: &str = "tahinli";
419- pub const REPO: &str = "demo";
420-
421- pub struct Fixture {
422- pub router: Router,
423- pub store: Store,
424- /// The live hub the router's pages share, to bump topics from a test.
425- pub live: std::sync::Arc<crate::live::LiveHub>,
426- /// Root commit: adds `a.txt` and `dir/b.txt`.
427- pub root: String,
428- /// Adds `new.txt` and changes `a.txt`.
429- pub modified: String,
430- /// Working checkout and bare repo the fixture pushed to.
431- pub work: PathBuf,
432- pub bare: PathBuf,
433- _dir: tempfile::TempDir,
434- }
435-
436- pub fn git(dir: &Path, args: &[&str]) -> String {
437- let out = Command::new("git")
438- .args([
439- "-c",
440- "user.name=Tester",
441- "-c",
442- "user.email=tester@example.com",
443- "-c",
444- "commit.gpgsign=false",
445- ])
446- .args(args)
447- .current_dir(dir)
448- .output()
449- .expect("git runs");
450- assert!(
451- out.status.success(),
452- "git {args:?} failed: {}",
453- String::from_utf8_lossy(&out.stderr)
454- );
455- String::from_utf8_lossy(&out.stdout).trim().to_owned()
456- }
457-
458- impl Fixture {
459- pub async fn new(visibility: Visibility) -> Self {
460- let tmp = tempfile::tempdir().expect("tempdir");
461- let dir = tmp.path().to_path_buf();
462- let state = crate::test_support::test_state(&dir).await;
463- let store = state.store.clone();
464- let live = state.live.clone();
465- let router = crate::test_support::app_router(state);
466-
467- let owner = store
468- .create_user(OWNER, None, "not-a-real-hash", false)
469- .await
470- .unwrap();
471- let repo = store
472- .create_repo(&owner.id, REPO, "", visibility, "main")
473- .await
474- .unwrap();
475- let bare = repo_dir(&dir, &repo.id);
476- std::fs::create_dir_all(bare.parent().unwrap()).unwrap();
477- git(
478- &dir,
479- &[
480- "init",
481- "-q",
482- "--bare",
483- "-b",
484- "main",
485- &bare.to_string_lossy(),
486- ],
487- );
488-
489- let work = dir.join("work");
490- std::fs::create_dir_all(&work).unwrap();
491- git(&work, &["init", "-q", "-b", "main"]);
492- std::fs::write(work.join("a.txt"), "one\ntwo\nthree\n").unwrap();
493- std::fs::create_dir_all(work.join("dir")).unwrap();
494- std::fs::write(work.join("dir/b.txt"), "b\n").unwrap();
495- git(&work, &["add", "-A"]);
496- git(&work, &["commit", "-q", "-m", "root commit"]);
497- let root = git(&work, &["rev-parse", "HEAD"]);
498-
499- std::fs::write(work.join("a.txt"), "one\nTWO\nthree\nfour\n").unwrap();
500- std::fs::write(work.join("new.txt"), "new file\n").unwrap();
501- git(&work, &["add", "-A"]);
502- git(
503- &work,
504- &[
505- "commit",
506- "-q",
507- "-m",
508- "Modify a.txt and add new.txt",
509- "-m",
510- "Body line one.\n\nSecond paragraph.",
511- ],
512- );
513- let modified = git(&work, &["rev-parse", "HEAD"]);
514-
515- // 53 empty commits on top: 55 in all, so history spans two pages.
516- for n in 1..=53 {
517- git(
518- &work,
519- &[
520- "commit",
521- "-q",
522- "--allow-empty",
523- "-m",
524- &format!("filler {n}"),
525- ],
526- );
527- }
528- git(
529- &work,
530- &[
531- "push",
532- "-q",
533- &bare.to_string_lossy(),
534- "HEAD:refs/heads/main",
535- ],
536- );
537-
538- Self {
539- router,
540- store,
541- live,
542- root,
543- modified,
544- work,
545- bare,
546- _dir: tmp,
547- }
548- }
549- }
550-
551- /// Same layout as `forge_git::repo::repo_path`, computed here so the test can create it.
552- fn repo_dir(data_dir: &Path, repo_id: &str) -> PathBuf {
553- let id = repo_id.to_ascii_lowercase();
554- data_dir
555- .join("repos")
556- .join(&id[0..2])
557- .join(&id[2..4])
558- .join(format!("{id}.git"))
559- }
560-
561- /// GET through the router: `(status, headers, body)`.
562- pub async fn get(router: &Router, uri: &str) -> (u16, http::HeaderMap, Vec<u8>) {
563- let req = Request::builder()
564- .method("GET")
565- .uri(uri)
566- .body(Body::empty())
567- .unwrap();
568- let res = router.handle(req).await;
569- let status = res.status().as_u16();
570- let headers = res.headers().clone();
571- let body = to_bytes(res.into_body(), usize::MAX)
572- .await
573- .unwrap()
574- .to_vec();
575- (status, headers, body)
576- }
577-}
578-
579 #[cfg(test)]406 #[cfg(test)]
580 mod tests {407 mod tests {
581 use forge_core::Visibility;408 use forge_core::Visibility;
582 409
583 use super::iso_time;410 use super::iso_time;
584- use super::test_support::{Fixture, OWNER, REPO, get, git};
585 use crate::i18n::Lang;411 use crate::i18n::Lang;
412+ use crate::test_support::fixture::{Fixture, OWNER, REPO, get, git};
586 use crate::views::relative_time;413 use crate::views::relative_time;
587 use crate::views::url_path;414 use crate::views::url_path;
588 415
crates/forge-web/src/pages/compare.rsmodified+1 -1
@@ -665,7 +665,7 @@ mod tests {
665 use topcoat::router::{Body, Router, to_bytes};665 use topcoat::router::{Body, Router, to_bytes};
666 666
667 use crate::auth::SESSION_COOKIE;667 use crate::auth::SESSION_COOKIE;
668- use crate::pages::commits::test_support::{get, git};668+ use crate::test_support::fixture::{get, git};
669 use crate::test_support::{app_router, test_state};669 use crate::test_support::{app_router, test_state};
670 670
671 const OWNER: &str = "tahinli";671 const OWNER: &str = "tahinli";
crates/forge-web/src/pages/edit_history.rsmodified+1 -1
@@ -339,7 +339,7 @@ mod tests {
339 use topcoat::router::{Body, Router, to_bytes};339 use topcoat::router::{Body, Router, to_bytes};
340 340
341 use crate::auth::SESSION_COOKIE;341 use crate::auth::SESSION_COOKIE;
342- use crate::pages::commits::test_support::{Fixture, OWNER, REPO};342+ use crate::test_support::fixture::{Fixture, OWNER, REPO};
343 343
344 /// Sends one request and returns `(status, body)`.344 /// Sends one request and returns `(status, body)`.
345 async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {345 async fn send(router: &Router, uri: &str, token: Option<&str>) -> (u16, String) {
crates/forge-web/src/pages/issue_view.rsmodified+1 -1
@@ -539,7 +539,7 @@ mod tests {
539 use topcoat::router::{Body, Router, to_bytes};539 use topcoat::router::{Body, Router, to_bytes};
540 540
541 use crate::auth::{SESSION_COOKIE, percent_encode};541 use crate::auth::{SESSION_COOKIE, percent_encode};
542- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get};542+ use crate::test_support::fixture::{Fixture, OWNER, REPO, get};
543 543
544 fn cookie(token: &str) -> String {544 fn cookie(token: &str) -> String {
545 format!("__Host-{SESSION_COOKIE}={token}")545 format!("__Host-{SESSION_COOKIE}={token}")
crates/forge-web/src/pages/pull_files.rsmodified+1 -1
@@ -713,7 +713,7 @@ mod tests {
713 use topcoat::router::{Body, Router, to_bytes};713 use topcoat::router::{Body, Router, to_bytes};
714 714
715 use crate::auth::SESSION_COOKIE;715 use crate::auth::SESSION_COOKIE;
716- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, git};716+ use crate::test_support::fixture::{Fixture, OWNER, REPO, git};
717 717
718 fn cookie(token: &str) -> String {718 fn cookie(token: &str) -> String {
719 format!("__Host-{SESSION_COOKIE}={token}")719 format!("__Host-{SESSION_COOKIE}={token}")
crates/forge-web/src/pages/pull_reviews.rsmodified+1 -1
@@ -839,7 +839,7 @@ mod tests {
839 use topcoat::router::{Body, Router, to_bytes};839 use topcoat::router::{Body, Router, to_bytes};
840 840
841 use crate::auth::{SESSION_COOKIE, percent_encode};841 use crate::auth::{SESSION_COOKIE, percent_encode};
842- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, git};842+ use crate::test_support::fixture::{Fixture, OWNER, REPO, git};
843 843
844 fn cookie(token: &str) -> String {844 fn cookie(token: &str) -> String {
845 format!("__Host-{SESSION_COOKIE}={token}")845 format!("__Host-{SESSION_COOKIE}={token}")
crates/forge-web/src/pages/pull_view.rsmodified+1 -1
@@ -1101,7 +1101,7 @@ mod tests {
1101 use topcoat::router::{Body, Router, to_bytes};1101 use topcoat::router::{Body, Router, to_bytes};
1102 1102
1103 use crate::auth::{SESSION_COOKIE, percent_encode};1103 use crate::auth::{SESSION_COOKIE, percent_encode};
1104- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, git};1104+ use crate::test_support::fixture::{Fixture, OWNER, REPO, git};
1105 1105
1106 fn cookie(token: &str) -> String {1106 fn cookie(token: &str) -> String {
1107 format!("__Host-{SESSION_COOKIE}={token}")1107 format!("__Host-{SESSION_COOKIE}={token}")
crates/forge-web/src/pages/ref_live.rsmodified+1 -1
@@ -54,7 +54,7 @@ mod tests {
54 use topcoat::router::request::Request;54 use topcoat::router::request::Request;
55 55
56 use crate::live::Topic;56 use crate::live::Topic;
57- use crate::pages::commits::test_support::{Fixture, OWNER, REPO};57+ use crate::test_support::fixture::{Fixture, OWNER, REPO};
58 58
59 /// GET `path` through the router, anonymously.59 /// GET `path` through the router, anonymously.
60 async fn open(fx: &Fixture, path: &str) -> topcoat::router::response::Response {60 async fn open(fx: &Fixture, path: &str) -> topcoat::router::response::Response {
crates/forge-web/src/pages/repo_scrub.rsmodified+1 -1
@@ -227,8 +227,8 @@ mod tests {
227 use forge_core::Visibility;227 use forge_core::Visibility;
228 228
229 use crate::auth::SESSION_COOKIE;229 use crate::auth::SESSION_COOKIE;
230- use crate::pages::commits::test_support::{Fixture, OWNER, REPO, get};
231 use crate::test_support::create_session;230 use crate::test_support::create_session;
231+ use crate::test_support::fixture::{Fixture, OWNER, REPO, get};
232 232
233 /// A private repo's scrub page is a 404 for anonymous visitors. The owner gets the root's names.233 /// A private repo's scrub page is a 404 for anonymous visitors. The owner gets the root's names.
234 #[tokio::test]234 #[tokio::test]
crates/forge-web/src/pages/settings_appearance.rsmodified+2 -2
@@ -818,7 +818,7 @@ mod tests {
818 assert_eq!(selected, ["plum"], "accent: selected");818 assert_eq!(selected, ["plum"], "accent: selected");
819 assert_eq!(819 assert_eq!(
820 options[0].value,820 options[0].value,
821- crate::accent_palette::DEFAULT,821+ forge_web_app::accent_palette::DEFAULT,
822 "accent: default first"822 "accent: default first"
823 );823 );
824 824
@@ -832,7 +832,7 @@ mod tests {
832 assert_eq!(bases, ["ink"], "base: selected");832 assert_eq!(bases, ["ink"], "base: selected");
833 assert_eq!(833 assert_eq!(
834 group.bases[0].value,834 group.bases[0].value,
835- crate::accent_palette::BASE_DEFAULT,835+ forge_web_app::accent_palette::BASE_DEFAULT,
836 "base: default first"836 "base: default first"
837 );837 );
838 838
crates/forge-web/src/shell_route_tests.rsadded+214 -0
@@ -0,0 +1,214 @@
1+//! Shell tests that render pages, so they need the page routes linked in.
2+
3+use topcoat::router::request::Request;
4+use topcoat::router::{Body, to_bytes};
5+
6+use crate::views::NAV_SCRIPT_HREF;
7+
8+/// Every `<script` tag carries a `src`: an inline script could not run under the CSP.
9+fn assert_no_inline_scripts(html: &str) {
10+ for (at, _) in html.match_indices("<script") {
11+ let tag = &html[at..];
12+ let end = tag.find('>').expect("script tag closes");
13+ assert!(
14+ tag[..end].contains(" src="),
15+ "inline script: {}",
16+ &tag[..=end]
17+ );
18+ }
19+}
20+
21+#[tokio::test]
22+async fn shell_loads_the_deferred_nav_script_without_inline_scripts() {
23+ let dir = tempfile::tempdir().expect("tempdir");
24+ let state = crate::test_support::test_state(dir.path()).await;
25+ let router = crate::test_support::app_router(state);
26+ let req = Request::builder()
27+ .method("GET")
28+ .uri("/login")
29+ .body(Body::empty())
30+ .unwrap();
31+ let res = router.handle(req).await;
32+ assert_eq!(res.status(), 200);
33+ let csp = res.headers()["content-security-policy"]
34+ .to_str()
35+ .unwrap()
36+ .to_owned();
37+ assert!(csp.contains("default-src 'self'"), "{csp}");
38+ assert!(!csp.contains("unsafe-inline"), "{csp}");
39+ let html = String::from_utf8(
40+ to_bytes(res.into_body(), usize::MAX)
41+ .await
42+ .unwrap()
43+ .to_vec(),
44+ )
45+ .unwrap();
46+
47+ let tag_at = html
48+ .find(&format!("<script src=\"{NAV_SCRIPT_HREF}\""))
49+ .expect("the shell loads the nav script");
50+ let tag = &html[tag_at..tag_at + html[tag_at..].find('>').unwrap()];
51+ assert!(tag.contains("defer"), "{tag}");
52+ assert_no_inline_scripts(&html);
53+
54+ assert!(html.contains("<main tabindex=\"-1\" data-width=\"col\">"));
55+ assert!(html.contains("data-hard=\"true\" method=\"post\" action=\"/login\""));
56+
57+ // An anonymous page renders the default colours.
58+ let tag = html_tag(&html);
59+ assert!(tag.contains("data-accent-light=\"sage\""), "{tag}");
60+ assert!(tag.contains("data-accent-dark=\"sage\""), "{tag}");
61+ assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
62+ assert!(tag.contains("data-base-dark=\"ink\""), "{tag}");
63+}
64+
65+/// The `<html …>` start tag of a page.
66+fn html_tag(page: &str) -> &str {
67+ let at = page.find("<html").expect("the page has an html tag");
68+ let len = page[at..].find('>').expect("the html tag closes");
69+ &page[at..at + len + 1]
70+}
71+
72+/// The `<html>` tag of `/settings/security` for a signed-in user whose stored colours are the
73+/// four ids given, in the order light accent, dark accent, light base, dark base.
74+async fn html_tag_for_colours(
75+ router: &topcoat::router::Router,
76+ store: &forge_core::Store,
77+ name: &str,
78+ token: &str,
79+ colours: [&str; 4],
80+) -> String {
81+ use crate::auth::SESSION_COOKIE;
82+ let user = store
83+ .create_user(name, None, "x", false)
84+ .await
85+ .expect("user");
86+ let [accent_light, accent_dark, base_light, base_dark] = colours;
87+ store
88+ .set_colours(&user.id, accent_light, accent_dark, base_light, base_dark)
89+ .await
90+ .expect("colours");
91+ crate::test_support::create_session(store, &user.id, token, "colour-csrf").await;
92+ let req = Request::builder()
93+ .method("GET")
94+ .uri("/settings/security")
95+ .header("cookie", format!("__Host-{SESSION_COOKIE}={token}"))
96+ .body(Body::empty())
97+ .unwrap();
98+ let res = router.handle(req).await;
99+ assert_eq!(res.status().as_u16(), 200);
100+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
101+ html_tag(&String::from_utf8_lossy(&bytes)).to_owned()
102+}
103+
104+/// Every colour case shares one fixture; each has its own user and session.
105+#[tokio::test]
106+async fn the_html_tag_carries_the_viewers_colours() {
107+ let dir = tempfile::tempdir().expect("tempdir");
108+ let state = crate::test_support::test_state(dir.path()).await;
109+ let store = state.store.clone();
110+ let router = crate::test_support::app_router(state);
111+
112+ let tag = html_tag_for_colours(
113+ &router,
114+ &store,
115+ "tahinli",
116+ "colour-token",
117+ ["ocean", "plum", "ink", "dusk"],
118+ )
119+ .await;
120+ assert!(tag.contains("data-accent-light=\"ocean\""), "{tag}");
121+ assert!(tag.contains("data-accent-dark=\"plum\""), "{tag}");
122+ assert!(tag.contains("data-base-light=\"ink\""), "{tag}");
123+ assert!(tag.contains("data-base-dark=\"dusk\""), "{tag}");
124+ assert!(!tag.contains("data-accent="), "{tag}");
125+ // Stored ids that are no longer offered fall back to the defaults, never to nothing.
126+ let removed = html_tag_for_colours(
127+ &router,
128+ &store,
129+ "removed",
130+ "removed-token",
131+ ["removed-palette", "removed-palette", "x", "x"],
132+ )
133+ .await;
134+ assert!(removed.contains("data-accent-light=\"sage\""), "{removed}");
135+ assert!(removed.contains("data-accent-dark=\"sage\""), "{removed}");
136+ assert!(removed.contains("data-base-light=\"ink\""), "{removed}");
137+ assert!(removed.contains("data-base-dark=\"ink\""), "{removed}");
138+ // A removed preset (`ochre`, `mist`) falls back too, and a hue passes through as itself.
139+ let retired = html_tag_for_colours(
140+ &router,
141+ &store,
142+ "retired",
143+ "retired-token",
144+ ["ochre", "terracotta", "mist", "stone"],
145+ )
146+ .await;
147+ assert!(retired.contains("data-accent-light=\"sage\""), "{retired}");
148+ assert!(retired.contains("data-accent-dark=\"sage\""), "{retired}");
149+ assert!(retired.contains("data-base-light=\"ink\""), "{retired}");
150+ assert!(retired.contains("data-base-dark=\"ink\""), "{retired}");
151+ let hued = html_tag_for_colours(
152+ &router,
153+ &store,
154+ "hued",
155+ "hued-token",
156+ ["hue-215", "hue-7", "hue-300", "ink"],
157+ )
158+ .await;
159+ assert!(hued.contains("data-accent-light=\"hue-215\""), "{hued}");
160+ assert!(hued.contains("data-accent-dark=\"hue-7\""), "{hued}");
161+ assert!(hued.contains("data-base-light=\"hue-300\""), "{hued}");
162+ assert!(hued.contains("data-base-dark=\"ink\""), "{hued}");
163+}
164+
165+/// Renders `/settings/security` (a page that uses the shell) for a freshly signed-in user.
166+async fn menu_html(
167+ router: &topcoat::router::Router,
168+ store: &forge_core::Store,
169+ name: &str,
170+ is_admin: bool,
171+ token: &str,
172+) -> String {
173+ use crate::auth::SESSION_COOKIE;
174+ use topcoat::router::request::Request;
175+ use topcoat::router::to_bytes;
176+
177+ let user = store
178+ .create_user(name, None, "x", is_admin)
179+ .await
180+ .expect("user");
181+ crate::test_support::create_session(store, &user.id, token, "menu-csrf").await;
182+ let req = Request::builder()
183+ .method("GET")
184+ .uri("/settings/security")
185+ .header("cookie", format!("__Host-{SESSION_COOKIE}={token}"))
186+ .body(Body::empty())
187+ .expect("request");
188+ let res = router.handle(req).await;
189+ assert_eq!(res.status().as_u16(), 200);
190+ let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body");
191+ String::from_utf8_lossy(&bytes).into_owned()
192+}
193+
194+/// A user sees no admin links and an admin sees the one Admin entry. Both render from one
195+/// fixture.
196+#[tokio::test]
197+async fn admin_links_follow_the_role() {
198+ let dir = tempfile::tempdir().expect("tempdir");
199+ let state = crate::test_support::test_state(dir.path()).await;
200+ let store = state.store.clone();
201+ let router = crate::test_support::app_router(state);
202+
203+ let html = menu_html(&router, &store, "tahinli", false, "menu-token-user").await;
204+ assert!(html.contains("Log out"), "user menu is rendered");
205+ assert!(!html.contains("/admin/users"), "no admin link for a user");
206+ assert!(!html.contains("/admin/audit"), "no audit link for a user");
207+
208+ let html = menu_html(&router, &store, "root", true, "menu-token-admin").await;
209+ assert!(html.contains("href=\"/admin/users\""));
210+ assert!(
211+ !html.contains("Admin:"),
212+ "one Admin entry, no per-page items"
213+ );
214+}
crates/forge-web/src/templates_route_tests.rsmodified+1 -1
@@ -1,7 +1,7 @@
1 use forge_core::Visibility;1 use forge_core::Visibility;
2 2
3-use crate::pages::commits::test_support::{Fixture, git};
4 use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, send};3 use crate::pages::issues_list::test_util::{CSRF, OWNER, REPO, TOKEN, send};
4+use crate::test_support::fixture::{Fixture, git};
5 5
6 const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n";6 const BUG: &str = "---\nname: Bug report\nabout: Something broke\ntitle: \"[Bug]: \"\nlabels: bug, needs triage\n---\n## Steps to reproduce\n\n1. Do the thing\n";
7 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";7 const FEATURE: &str = "---\nname: Feature request\nabout: Suggest an idea\n---\n## Idea\n";